branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>ajantha-b/bentes6<file_sep>/readme.md # Express.js Babel 7 and TypeScript Setup ## This is a starter project which has configured to use Babel 7, Express.js and TypeScript 3. This project anables the latest technology features you can have. ## Start the developement ### Install dependencies ``` bash npm install ``` ### Start server ```bash npm start ``` <file_sep>/src/server.ts import express from 'express'; const app = express(); app.get('/test', (req, res) => { res.send('Hello Express from typescript and bable 7') }) app.listen(5000, (err: any) => { if (err) { console.log('error starting server', err); return; } console.log('Server is running on port: 5000'); })
7b6b7f299fcc81cde716f2ec9a4876df0c94be91
[ "Markdown", "TypeScript" ]
2
Markdown
ajantha-b/bentes6
89c2fc707787d3e8e95f394b30d2f3baae7daf97
ce93c7ab6456bb1cb076fc5d77cdf03a43542a85
refs/heads/master
<file_sep>import javax.swing.JTextField; import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.File; import java.io.PrintStream; import java.io.IOException; import java.net.MalformedURLException; import java.util.Scanner; public class TurnBias extends JPanel implements ActionListener { public JTextField cardNumber; public JTextField cardCopies; public JTextField cardBias; public JButton calculateButton; public JButton calculateFinal; public double totalCards; public double numCopies; public double numBias; public double i; public double v; public int x; public int y; public GridBagConstraints c = new GridBagConstraints(); JDialog window; public JTextField finalBias; public TurnBias() { super (new GridBagLayout()); c.fill = GridBagConstraints.HORIZONTAL; c.weightx = .5; c.weighty = .5; cardNumber = new JTextField(); cardNumber.setText("0"); finalBias = new JTextField(); cardCopies = new JTextField(); cardCopies.setText("0"); cardBias = new JTextField(); cardBias.setText("0"); calculateButton = new JButton("Add Card"); calculateButton.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { i = i + (((Double.valueOf(cardBias.getText()))*(Double.valueOf(cardCopies.getText())))/(Double.valueOf(cardNumber.getText()))); System.out.println(i); } }); calculateFinal = new JButton("Calculate Bias"); calculateFinal.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { v = i; finalBias.setText(Double.toString(v)); } }); addGB(cardNumber, x = 0, y = 0); addGB(cardCopies, x = 1, y = 0); addGB(cardBias, x = 2, y = 0); addGB(calculateButton, x = 0, y = 1); addGB(calculateFinal, x = 1, y = 1); addGB(finalBias, x = 2, y = 1); } public static void createAndShowGUI() { JFrame frame = new JFrame("We Tell You To Go First!"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.add(new TurnBias()); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent ae) { System.out.println("This is a placeholder method"); } void addGB( Component component, int x, int y ) { c.gridx = x; c.gridy = y; add ( component, c ); } public static void MCOPY() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } <file_sep>A set of tools written in tenth grade for a trading card game. Keeping the code for nostalgia purposes. <file_sep>import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.Random; public class DiceRoll extends JPanel implements ActionListener { public Random rand = new Random(); public JTextField DisplayResult = new JTextField(); public int Result; public JButton Roll = new JButton("ROLL"); public DiceRoll() { super (new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridwidth = GridBagConstraints.REMAINDER; c.fill = GridBagConstraints.HORIZONTAL; c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; add(DisplayResult, c); add(Roll, c); Roll.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { RollDice(); } }); } public void RollDice() { Result = rand.nextInt(6) + 1; DisplayResult.setText(Integer.toString(Result)); } public static void CreateFrame() { JFrame frame = new JFrame("Roll a Die"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.add(new DiceRoll()); frame.pack(); frame.setVisible(true); frame.getContentPane().setBackground(Color.BLACK); } public void actionPerformed(ActionEvent ae) { System.out.println("This is a placeholder method"); } public static void MCOPY() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { CreateFrame(); } }); } }<file_sep> Instructions: 1. Inputting your deck Click on "Set Deck". This will bring up a window with a text field. Input the name of each card in your deck, exactly as they are written on the card, then press "Enter" or "Return" on your keyboard after each card. When you are finished inputting the names of all cards in your deck, 'x' out of the window. This generates an HTML file to the working directory of the app, so don't be alarmed if you see an HTML file appear while using the YGOMT app. 2. Viewing your rulings Click on "Check Your Deck's Rulings". This will bring up a window with a list of your cards and hyperlinks to quickly view the rulings for each. These rulings are very helpful in determining card interactions. 3. Checking Turn Bias Click on "Check Your Deck's Turn Bias". This will bring up a window with several fields. The first field is the total number of cards in your deck. Put this in first, and do not change this number. The second field (from left to right), is the number of copies of a particular card. This field should be a 1, 2, or 3. The final field is the turn bias of a particular card. This will be a 1, 2, or 3: 1 - You want to draw this card when going first. Examples are swarm cards or trap cards. 2 - It does not matter if you go first or second when drawing this card. Examples include cards like Mystical Space Typhoon. 3 - You want to draw this card when going second. Examples are interrupters like Raigeki or Heavy Storm (Aware that HS is banned). Fill all three fields on top for each card, then press "Add Card" to add it to the sum. Change the fields for the second card, third, etc. When finished, press "Calculate Bias". The field at the bottom right will display your deck's turn bias. How to use this information: 1.0 - 1.65 : Your deck should always go first, given the opportunity. 1.66 - 1.72 : Your deck can swing either way, depending on the opponent. 1.73 - 3.0 : Your deck should generally go second, given the opportunity. 4. LP Calculator Click on "LP Calculator". This will bring up a window with four fields, four buttons, and a large text display area. To change LP, enter a number to add or subtract in either of the second field down for either player, then press "+" or "-" to add or subtract. Changes are outputted to the large text area as a log of LP changes. 5. Coin Flip Click on "Flip a Coin". This will bring up a window with a button. Press the button to get a coin flip result; either heads or tails. 6. Dice Roll Click on "Roll a Die". This will bring up a window with a button. Press the button to get a die roll result; 1 through 6. Patch Notes: Version 1.0 - Added base features (Rulings, Bias Calculator, LP Calculator, Deck Manager). Issues: Still need to add LP Calculator. //ADDED BEFORE LAUNCH If card names are not entered exactly, hyperlink will not resolve. Still need to add Coin Flip. Still need to add Dice Roll. <file_sep>import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.JTextField; import javax.swing.JFrame; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class lpCalculator extends JPanel implements ActionListener { JTextArea log = new JTextArea(20,30); JScrollPane pane = new JScrollPane(log); JButton player1Add = new JButton("+"); JButton player2Add = new JButton("+"); JButton player1Sub = new JButton("-"); JButton player2Sub = new JButton("-"); JTextField player1LP = new JTextField("8000"); JTextField player2LP = new JTextField("8000"); JTextField player1AMT = new JTextField("0"); JTextField player2AMT = new JTextField("0"); GridBagConstraints c = new GridBagConstraints(); public String P1LP; //String of player 1s LP amount public int P1LPI; //Int of player 1s LP amount public String P2LP; //String of Player 2s LP amount public int P2LPI; //Int of player 2s LP amount public String P1CH; //String of the change in LP for player 1 public int P1CHI; //Int of the change in LP for player 1 public String P2CH; //String of the change in LP for player 2 public int P2CHI; //Int of the change in LP for player 2 void addGB( Component component, int x, int y ) { c.gridx = x; c.gridy = y; add ( component, c ); } //Get the text from Player1AMT, convert to int, add to P1LP, settext of Player1LP to P1LP. public void AddLpForPlayer1() { P1CH = player1AMT.getText(); //set change LP temp to the value in the textfield. P1CHI = Integer.parseInt(P1CH); //change LP temp value to an integer. P1LP = player1LP.getText(); //get the text from the current LP block. P1LPI = Integer.parseInt(P1LP); //change current LP value to integer. log.append("Player 1 LP From: " + P1LP + "\n"); P1LPI = P1LPI + P1CHI; //set the current LP value to the current value + the change in LP. P1LP = Integer.toString(P1LPI); //change the current LP value back to string. player1LP.setText(P1LP); //set the textField to display the current LP value. log.append("To: " + P1LPI + "\n"); } public void SubLpForPlayer1() { P1CH = player1AMT.getText(); P1CHI = Integer.parseInt(P1CH); P1LP = player1LP.getText(); P1LPI = Integer.parseInt(P1LP); log.append("Player 1 LP From: " + P1LP + "\n"); P1LPI = P1LPI - P1CHI; P1LP = Integer.toString(P1LPI); player1LP.setText(P1LP); log.append("To: " + P1LPI + "\n"); } public void AddLpForPlayer2() { P2CH = player2AMT.getText(); //set change LP temp to the value in the textfield. P2CHI = Integer.parseInt(P2CH); //change LP temp value to an integer. P2LP = player2LP.getText(); //get the text from the current LP block. P2LPI = Integer.parseInt(P2LP); //change current LP value to integer. log.append("Player 2 LP From: " + P2LP + "\n"); P2LPI = P2LPI + P2CHI; //set the current LP value to the current value + the change in LP. P2LP = Integer.toString(P2LPI); //change the current LP value back to string. player2LP.setText(P2LP); //set the textField to display the current LP value. log.append("To: " + P2LPI + "\n"); } public void SubLpForPlayer2() { P2CH = player2AMT.getText(); P2CHI = Integer.parseInt(P2CH); P2LP = player2LP.getText(); P2LPI = Integer.parseInt(P2LP); log.append("Player 2 LP From: " + P2LP + "\n"); P2LPI = P2LPI - P2CHI; P2LP = Integer.toString(P2LPI); player2LP.setText(P2LP); log.append("To: " + P2LPI + "\n"); } public lpCalculator() { super (new GridBagLayout()); int x, y; // for clarity c.weightx = 1.0; c.weighty = 1.0; c.fill = GridBagConstraints.BOTH; c.gridwidth = 3; addGB(pane, x = 0, y = 0); c.fill = GridBagConstraints.HORIZONTAL; c.gridwidth = 1; c.weightx = .1; c.weighty = .1; addGB(player1Add, x = 0, y = 3); addGB(player2Add, x = 2, y = 3); addGB(player1Sub, x = 0, y = 4); addGB(player2Sub, x = 2, y = 4); addGB(player1LP, x = 0, y = 1); addGB(player2LP, x = 2, y = 1); addGB(player1AMT, x = 0, y = 2); addGB(player2AMT, x = 2, y = 2); player1Add.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { AddLpForPlayer1(); } }); player1Sub.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { SubLpForPlayer1(); } }); player2Add.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { AddLpForPlayer2(); } }); player2Sub.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { SubLpForPlayer2(); } }); } public static void createAndShowGUI() { JFrame frame = new JFrame("LP Calculator"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.add(new lpCalculator()); frame.setSize(400,800); frame.pack(); frame.setVisible(true); } public void actionPerformed (ActionEvent evt) { } public static void MCOPY() { javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
da0fbe653a60cd84a6d37c27e9e16406b101b1f4
[ "Markdown", "Java", "Text" ]
5
Java
novafacing/oldcardgame
c79677459e925f4706492f17caab72a96233b772
8b99dd9ed197e1f35cb625c7bb45ebf556b8b3ef
refs/heads/master
<file_sep>package junit; public class Main { public static void main(String[] args) { HelloJUnit hello = new HelloJUnit (); System.out.println(hello.hello()); } } <file_sep>package junit; public class Fibo { /** * fib (n) > Integer.MAX_VALUE * * Computes the Fibonacci sequence numbers. * Special cases: * -fib (0) = 0 * -fib (1) = 1 * -fib (2) = 1 * @param n, 0 or positive integer * @return int, the n-th number in the fibonacci sequence * @throws IllegalArgumentException if n < 0 * @throws IllegalArgumentException if fib(n) > Integer.MAX_VALUE */ public static int fib(int n) { if(n < 0) {throw new IllegalArgumentException ("n must be zero or positive number ");} if(n > 46) {throw new IllegalArgumentException ("nis too big, must be < 46 ");} if(n == 0) { return 0; } if(n <= 2) { return 1; } // 3 = > 2 // 4 => 3 return fib(n - 1) + fib(n - 2); } }
abd2e3e5193ab0b7ed2879e6b063c9e8255a78a9
[ "Java" ]
2
Java
dnoemie/Test-Junit
6915586d648869908d7c3629a317fafed9307936
489914860e5f7ca6a9a51846b351ca4f55edff5c
refs/heads/master
<file_sep>#!/usr/bin/env python3.8 # -*- coding: utf-8 -*- import sys from signal import signal, SIGINT import asyncio import aioxmpp import aioxmpp.dispatcher class Textpuffer: """ A simple jabber client that prints out what it receives. This is meant to be used as a share-to-pc program. One can share text, especially links, with the connected jabber account. That text then is printed out at the pc that runs this python program. """ def __init__(self, jid, password, receive_from): """ Initialize the class by setting JID and password. Adds a dispatcher to receive messages from the defined account. @param jid: the jabber ID of the buffers account @param password: the password of the buffers jabber account @param receiveFrom: the jabber ID of the account that's allowed to send messages to this buffer """ self.running = False self.receive_from = receive_from self.client = aioxmpp.PresenceManagedClient( aioxmpp.JID.fromstr(jid), aioxmpp.make_security_layer(password)) message_dispatcher = self.client.summon( aioxmpp.dispatcher.SimpleMessageDispatcher) message_dispatcher.register_callback( aioxmpp.MessageType.CHAT, aioxmpp.JID.fromstr(receive_from), self.receive) self.loop = asyncio.get_event_loop() def start(self): """ Set self.running to True and start the event loop. """ self.running = True self.loop.run_until_complete(self.run()) async def run(self): """ Run the program. That means connecting, then sending a message to the account that can send text to this buffer, signaling that this buffer is now available. After that an infinite loop is started so the program can receive messages. This loop can be broken when self.running is set to false. """ async with self.client.connected() as stream: msg = aioxmpp.Message( to=aioxmpp.JID.fromstr(self.receive_from), type_=aioxmpp.MessageType.CHAT) msg.body[None] = "Ready to receive now!" await self.client.send(msg) while self.running: await asyncio.sleep(10) msg = aioxmpp.Message( to=aioxmpp.JID.fromstr(self.receive_from), type_=aioxmpp.MessageType.CHAT) msg.body[None] = "Shutting down!" await self.client.send(msg) sys.exit(0) def stop(self, signal_received, frame): """ Set running variable to False. This causes the main loop in run() to break. @param signal_received: @param frame: """ self.running = False def receive(self, message): """ Print out the bare messages body if it has any. @param message: the received message """ if not message.body: return else: print(message.body.any()) def main(argv): """ Initializes with the first three commandline arguments and starts it. Registers the SIGINT signal to call Textpuffer.stop() to end program when CTRL+C is pressed. """ tp = Textpuffer(argv[1], argv[2], argv[3]) signal(SIGINT, tp.stop) tp.start() if __name__ == "__main__": main(sys.argv)
0da23f3dac15539d83e35e12043dbbf2e65e3de4
[ "Python" ]
1
Python
don-philipe/textpuffer
8ca3ec31448f034658db4cc245a9320eab47acc3
26a24897e40ea28087a8ceb3ecf71b78dad5c430
refs/heads/master
<repo_name>josesanc29/server-sockets<file_sep>/sockets/sockets.ts import { Socket } from "socket.io"; import socketIO from 'socket.io'; import { isObject } from "util"; import { UsuariosLista } from "../clases/usuarios-lista"; import { Usuario } from "../clases/usuario"; export const usuariosConectados = new UsuariosLista(); export const conectarCliente = ( cliente: Socket , socketIO: socketIO.Server) => { const usuario = new Usuario ( cliente.id); usuariosConectados.agregarUsuario(usuario); // socketIO.emit('usuarios-activos', usuariosConectados.getLista()); } export const desconectar = ( cliente: Socket , socketIO: socketIO.Server)=>{ cliente.on('disconnect', ()=>{ console.log('Cliente desconectado'); usuariosConectados.borrarUsuario(cliente.id); socketIO.emit('usuarios-activos', usuariosConectados.getLista()); }); } //Escuchar mensaje export const mensaje = ( cliente: Socket , socketIO: socketIO.Server ) =>{ cliente.on('mensaje' , (payload:{ de: string , cuerpo: string})=>{ console.log('Mensaje recibido', payload); socketIO.emit('mensaje-nuevo', payload ); }); } //Configurar-usuario export const configurarUsuario = ( cliente: Socket , socketIO: socketIO.Server ) =>{ cliente.on('configurar-usuario' , (payload:{ nombre: string}, callBack: Function)=>{ usuariosConectados.actualizaNombre(cliente.id , payload.nombre); socketIO.emit('usuarios-activos', usuariosConectados.getLista()); callBack({ ok: true, mensaje : `Usuario ${payload.nombre} configurado`, }) }); } //Obtener Usuarios export const obtenerUsuariosActivos = ( cliente: Socket , socketIO: socketIO.Server) =>{ cliente.on('obtener-usuarios' , ()=>{ socketIO.emit('usuarios-activos', usuariosConectados.getLista()); }) } <file_sep>/clases/usuarios-lista.ts import { Usuario } from "./usuario"; export class UsuariosLista { private lista: Usuario[] = []; constructor () { } // Añade usuario a la lista agregarUsuario (usuario: Usuario){ this.lista.push(usuario); console.log(this.lista); return usuario; } //Modificar el nombre de usuario dentro de la lista actualizaNombre (id: string , nombre: string){ for(let usuario of this.lista){ if(usuario.id === id){ usuario.nombre = nombre; break; } } console.log('ACTUALIZANDO NOMBRE DE USUARIO'); console.log(this.lista); } //GET de la lista de usuarios getLista(){ return this.lista.filter(usuario => usuario.nombre !== 'sin-nombre'); } //Obtener usuario de la lista por su id getUsuario(id: string){ return this.lista.filter( (usuario : any) =>{ return usuario.id === id; })[0]; } //Obtener usuarios en una sala particular getUsuarioEnSala(sala: string) { return this.lista.filter( (usuario:any)=> { return usuario.sala === sala; }); } //Borrar usuario borrarUsuario (id: string){ const usuarioTemp = this.getUsuario(id); this.lista = this.lista.filter( (usuario)=>{ return usuario.id !== id; }); } }<file_sep>/routes/router.ts import {Router, Request, Response} from 'express'; import Server from "../clases/server"; import { resolve } from 'path'; import { Socket } from 'socket.io'; import { usuariosConectados } from '../sockets/sockets'; const router = Router(); router.get('/mensajes', ( req: Request , resp: Response) => { resp.json({ ok: true, mensaje:'El GET ha ido bien!!' }); }); router.post('/mensajes', ( req: Request , resp: Response) => { const cuerpo = req.body.cuerpo; const de = req.body.de; const server = Server.instance; const payload = { de, cuerpo } server.io.emit('mensaje-nuevo', payload); resp.json({ ok: true, mensaje:'El POST ha ido bien!!', cuerpo, de }); }); router.post('/mensajes/:id', ( req: Request , resp: Response) => { const id = req.params.id; const cuerpo = req.body.cuerpo; const de = req.body.de; // const server = Server.instance; const server = Server.instance; const payload = { de, cuerpo } server.io.in( id ).emit('mensajes-privados', payload); resp.json({ ok: true, mensaje:'El POST por ID_Mensaje ha ido bien!!', id, cuerpo, de }); }); // Servicio para obtener todos los ids de los usuarios router.get('/usuarios', ( req: Request , resp: Response) => { // const server = Server.instance; const server = Server.instance; server.io.clients( (err: any , clientes: string[]) =>{ if(err){ return resp.json({ ok: false, message: err }); } resp.json({ ok: true, clientes }); }); }); // Servicio para obtener los id y el nombre de los usuarios conectados [ESTE ES EL SERVICIO QUE USAREMOS] router.get('/usuarios/detail', ( req: Request , resp: Response) => { // const server = Server.instance; const server = Server.instance; usuariosConectados; server.io.clients( (err: any , clientes: string[]) =>{ if(err){ return resp.json({ ok: false, message: err }); } resp.json({ ok: true, clientes: usuariosConectados.getLista() }); }); }); export default router;
f5e7b587c2515ef6c8b4c008f0e21f1131cd2f34
[ "TypeScript" ]
3
TypeScript
josesanc29/server-sockets
5df07b6045cd823f111caa8f192c09c3233043db
5c4bc7e519d04fa2b1fcffb8be0c65f14d2591e2
refs/heads/master
<repo_name>roro89/sld<file_sep>/main.js define(['./parser', './Parser'], function(parser, Parser) { return { parser : parser, Parser : Parser } });
56c5494c35ff3514f718a6a6f13cf66a8f16f0d5
[ "JavaScript" ]
1
JavaScript
roro89/sld
ae51662dec048c0a8377328c9d9c095a73303d63
7c5d30e0fe0655e0837c6370430d487dcfd7b689
refs/heads/master
<repo_name>carloarp/Computer-Vision-CW1<file_sep>/SCRIPTS/random_forest_vary_k.py import numpy as np import seaborn as sns import scipy import matplotlib import matplotlib.pyplot as plt from sklearn import preprocessing import numpy as np import pandas as pd import scipy.io as sc import matplotlib as plt import matplotlib.pyplot as plt import sys import time import os import psutil from sklearn.neighbors import NearestNeighbors from scipy.io import loadmat from sklearn.neighbors import KNeighborsClassifier from sklearn.decomposition import PCA from sklearn.cluster import KMeans from scipy.cluster.vq import * from sklearn.metrics import confusion_matrix def print_image(face_image,title,mode): # function for plotting an image if mode == 'no': return None face_image = np.reshape(face_image, (300,267)) face_image = face_image.T plt.imshow(face_image, cmap='gist_gray') plt.title(title) plt.show() def load_codebook(codebook_name, distortion_name, show): codebook_recall = np.load(codebook_name) distortion_recall = np.load(distortion_name) if show == 'yes': display_codebook(codebook_recall, distortion_recall) return codebook_recall, distortion_recall def display_codebook(codebook, distortion): print("Codebook has shape",codebook.shape) print("Distortion =",distortion) return None os.system('cls') original_working_dir = os.getcwd() dir = os.getcwd() # gets the working directory of the file this python script is in os.chdir (dir) # changes the working directory to the file this python script is in print("") # also change plt.savefig to plt.show np.random.seed(13) ### UNPACK MATLAB FILE data = sc.loadmat('team_6.mat') random_selected_descriptors = data['random_selected_descriptors'] test_desc = data['descriptors_testing'] train_desc = data['descriptors_training'] train_idx = data['training_idx'] test_idx = data['testing_idx'] train_idx = train_idx.squeeze() test_idx = test_idx.squeeze() #print("train_idx:\n", train_idx,"\n") ### ORGANIZE MATLAB DATA ticks_train_images = train_desc[0] # descriptor list for ticks train image trilobite_train_images = train_desc[1] # descriptor list for trilobite train image umbrella_train_images = train_desc[2] watch_train_images = train_desc[3] waterlily_train_images = train_desc[4] wheelchair_train_images = train_desc[5] wildcat_train_images = train_desc[6] windsorchair_train_images = train_desc[7] wrench_train_images = train_desc[8] yinyang_train_images = train_desc[9] ticks_train_idx = train_idx[0].squeeze() # index list for tick train image trilobite_train_idx = train_idx[1].squeeze() # index list for trilobite train image umbrella_train_idx = train_idx[2].squeeze() watch_train_idx = train_idx[3].squeeze() waterlily_train_idx = train_idx[4].squeeze() wheelchair_train_idx = train_idx[5].squeeze() wildcat_train_idx = train_idx[6].squeeze() windsorchair_train_idx = train_idx[7].squeeze() wrench_train_idx = train_idx[8].squeeze() yinyang_train_idx = train_idx[9].squeeze() ticks_test_images = test_desc[0] # descriptor list for ticks test image trilobite_test_images = test_desc[1] # descriptor list for trilobite test image umbrella_test_images = test_desc[2] watch_test_images = test_desc[3] waterlily_test_images = test_desc[4] wheelchair_test_images = test_desc[5] wildcat_test_images = test_desc[6] windsorchair_test_images = test_desc[7] wrench_test_images = test_desc[8] yinyang_test_images = test_desc[9] ticks_test_idx = test_idx[0].squeeze() # index list for tick test image trilobite_test_idx = test_idx[1].squeeze() # index list for trilobite test image umbrella_test_idx = test_idx[2].squeeze() watch_test_idx = test_idx[3].squeeze() waterlily_test_idx = test_idx[4].squeeze() wheelchair_test_idx = test_idx[5].squeeze() wildcat_test_idx = test_idx[6].squeeze() windsorchair_test_idx = test_idx[7].squeeze() wrench_test_idx = test_idx[8].squeeze() yinyang_test_idx = test_idx[9].squeeze() number_of_images = 15 ### LOAD HISTOGRAM DATA print("LOADING HISTOGRAM DATA...") accuracy_list = [] train_time_list = [] test_time_list = [] k_list = [5,10,20,39,56,75,95,120,185,372,550,724,918,1372,1843] #k_list = [5,10,20] for k_number in k_list: #k_number = 120 codeword_list = [f'Codeword{i+1}' for i in range(0, k_number)] # creates a list that contains codeword0...codeword'k' output_dir_histogram_npy = str('histogram_npy_files_k='+str(k_number)) os.chdir(output_dir_histogram_npy) train_histogram = str('train_histogram_array_k='+str(k_number)+'.npy') test_histogram = str('test_histogram_array_k='+str(k_number)+'.npy') class_hist_list_train = np.load(train_histogram) class_hist_list_test = np.load(test_histogram) os.chdir(original_working_dir) print("HISTOGRAM DATA LOADED: K =",k_number,"@",output_dir_histogram_npy,'\n') ### ORGANIZE HISTOGRAM DATA ticks_train_histogram = class_hist_list_train[0] trilobite_train_histogram = class_hist_list_train[1] umbrella_train_histogram = class_hist_list_train[2] watch_train_histogram = class_hist_list_train[3] waterlily_train_histogram = class_hist_list_train[4] wheelchair_train_histogram = class_hist_list_train[5] wildcat_train_histogram = class_hist_list_train[6] windsorchair_train_histogram = class_hist_list_train[7] wrench_train_histogram = class_hist_list_train[8] yinyang_train_histogram = class_hist_list_train[9] ticks_test_histogram = class_hist_list_test[0] trilobite_test_histogram = class_hist_list_test[1] umbrella_test_histogram = class_hist_list_test[2] watch_test_histogram = class_hist_list_test[3] waterlily_test_histogram = class_hist_list_test[4] wheelchair_test_histogram = class_hist_list_test[5] wildcat_test_histogram = class_hist_list_test[6] windsorchair_test_histogram = class_hist_list_test[7] wrench_test_histogram = class_hist_list_test[8] yinyang_test_histogram = class_hist_list_test[9] combined_train_features = ticks_train_histogram.tolist() + trilobite_train_histogram.tolist() + umbrella_train_histogram.tolist() + watch_train_histogram.tolist() + waterlily_train_histogram.tolist() + wheelchair_train_histogram.tolist() + wildcat_train_histogram.tolist() + windsorchair_train_histogram.tolist() + wrench_train_histogram.tolist() + yinyang_train_histogram.tolist() combined_test_features = ticks_test_histogram.tolist() + trilobite_test_histogram.tolist() + umbrella_test_histogram.tolist() + watch_test_histogram.tolist() + waterlily_test_histogram.tolist() + wheelchair_test_histogram.tolist() + wildcat_test_histogram.tolist() + windsorchair_test_histogram.tolist() + wrench_test_histogram.tolist() + yinyang_test_histogram.tolist() ### TRANSFORM TRAIN DATA INTO PANDAS DATAFRAME print("COVERTING TRAIN DATA INTO PANDAS DATAFRAME...") codeword_list = [f'Codeword{i}' for i in range(0, k_number)] ticks_label = ['ticks']*number_of_images trilobite_label = [f'trilobite']*number_of_images umbrella_label = [f'umbrella']*number_of_images watch_label = [f'watch']*number_of_images waterlily_label = [f'waterlily']*number_of_images wheelchair_label = [f'wheelchair']*number_of_images wildcat_label = [f'wildcat']*number_of_images windsorchair_label = [f'windsorchair']*number_of_images wrench_label = [f'wrench']*number_of_images yinyang_label = [f'yinyang']*number_of_images combined_train_label = ticks_label+trilobite_label+umbrella_label+watch_label+waterlily_label+wheelchair_label+wildcat_label+windsorchair_label+wrench_label+yinyang_label df_column = codeword_list train_features_array = combined_train_features combined_train_df_column = codeword_list combined_train_df_column.append("Label") #combined_train_df = pd.DataFrame(columns=combined_train_df_column) combined_train_df = pd.DataFrame(columns=["Codeword0","Codeword1","Codeword2","Label"]) ticks_train_df = pd.DataFrame(columns=df_column) trilobite_train_df = pd.DataFrame(columns=df_column) umbrella_train_df = pd.DataFrame(columns=df_column) watch_train_df = pd.DataFrame(columns=df_column) waterlily_train_df = pd.DataFrame(columns=df_column) wheelchair_train_df = pd.DataFrame(columns=df_column) wildcat_train_df = pd.DataFrame(columns=df_column) windsorchair_train_df = pd.DataFrame(columns=df_column) wrench_train_df = pd.DataFrame(columns=df_column) yinyang_train_df = pd.DataFrame(columns=df_column) for K_train in range(0,k_number): ticks_train_df[codeword_list[K_train]] = ticks_train_histogram[:,K_train] trilobite_train_df[codeword_list[K_train]] = trilobite_train_histogram[:,K_train] umbrella_train_df[codeword_list[K_train]] = umbrella_train_histogram[:,K_train] watch_train_df[codeword_list[K_train]] = watch_train_histogram[:,K_train] waterlily_train_df[codeword_list[K_train]] = waterlily_train_histogram[:,K_train] wheelchair_train_df[codeword_list[K_train]] = wheelchair_train_histogram[:,K_train] wildcat_train_df[codeword_list[K_train]] = wildcat_train_histogram[:,K_train] windsorchair_train_df[codeword_list[K_train]] = windsorchair_train_histogram[:,K_train] wrench_train_df[codeword_list[K_train]] = wrench_train_histogram[:,K_train] yinyang_train_df[codeword_list[K_train]] = yinyang_train_histogram[:,K_train] ticks_train_df["Label"] = ticks_label trilobite_train_df["Label"] = trilobite_label umbrella_train_df["Label"] = umbrella_label watch_train_df["Label"] = watch_label waterlily_train_df["Label"] = waterlily_label wheelchair_train_df["Label"] = wheelchair_label wildcat_train_df["Label"] = wildcat_label windsorchair_train_df["Label"] = windsorchair_label wrench_train_df["Label"] = wrench_label yinyang_train_df["Label"] = yinyang_label combined_train_df = combined_train_df.append(ticks_train_df) combined_train_df = combined_train_df.append(trilobite_train_df) combined_train_df = combined_train_df.append(umbrella_train_df) combined_train_df = combined_train_df.append(watch_train_df) combined_train_df = combined_train_df.append(waterlily_train_df) combined_train_df = combined_train_df.append(wheelchair_train_df) combined_train_df = combined_train_df.append(wildcat_train_df) combined_train_df = combined_train_df.append(windsorchair_train_df) combined_train_df = combined_train_df.append(wrench_train_df) combined_train_df = combined_train_df.append(yinyang_train_df) ### TRANSFORM TEST DATA INTO PANDAS DATAFRAME print("COVERTING TEST DATA INTO PANDAS DATAFRAME...") codeword_list = [f'Codeword{i}' for i in range(0, k_number)] #combined_test_label = ticks_label+trilobite_label+umbrella_label+watch_label+waterlily_label+wheelchair_label+wildcat_label+windsorchair_label+wrench_label+yinyang_label df_column = codeword_list combined_test_df_column = codeword_list combined_test_df = pd.DataFrame(columns=combined_test_df_column) ticks_test_df = pd.DataFrame(columns=df_column) trilobite_test_df = pd.DataFrame(columns=df_column) umbrella_test_df = pd.DataFrame(columns=df_column) watch_test_df = pd.DataFrame(columns=df_column) waterlily_test_df = pd.DataFrame(columns=df_column) wheelchair_test_df = pd.DataFrame(columns=df_column) wildcat_test_df = pd.DataFrame(columns=df_column) windsorchair_test_df = pd.DataFrame(columns=df_column) wrench_test_df = pd.DataFrame(columns=df_column) yinyang_test_df = pd.DataFrame(columns=df_column) for K_test in range(0,k_number): ticks_test_df[codeword_list[K_test]] = ticks_test_histogram[:,K_test] trilobite_test_df[codeword_list[K_test]] = trilobite_test_histogram[:,K_test] umbrella_test_df[codeword_list[K_test]] = umbrella_test_histogram[:,K_test] watch_test_df[codeword_list[K_test]] = watch_test_histogram[:,K_test] waterlily_test_df[codeword_list[K_test]] = waterlily_test_histogram[:,K_test] wheelchair_test_df[codeword_list[K_test]] = wheelchair_test_histogram[:,K_test] wildcat_test_df[codeword_list[K_test]] = wildcat_test_histogram[:,K_test] windsorchair_test_df[codeword_list[K_test]] = windsorchair_test_histogram[:,K_test] wrench_test_df[codeword_list[K_test]] = wrench_test_histogram[:,K_test] yinyang_test_df[codeword_list[K_test]] = yinyang_test_histogram[:,K_test] ticks_test_df["Label"] = ticks_label trilobite_test_df["Label"] = trilobite_label umbrella_test_df["Label"] = umbrella_label watch_test_df["Label"] = watch_label waterlily_test_df["Label"] = waterlily_label wheelchair_test_df["Label"] = wheelchair_label wildcat_test_df["Label"] = wildcat_label windsorchair_test_df["Label"] = windsorchair_label wrench_test_df["Label"] = wrench_label yinyang_test_df["Label"] = yinyang_label combined_test_df = combined_test_df.append(ticks_test_df, sort=True) combined_test_df = combined_test_df.append(trilobite_test_df) combined_test_df = combined_test_df.append(umbrella_test_df) combined_test_df = combined_test_df.append(watch_test_df) combined_test_df = combined_test_df.append(waterlily_test_df) combined_test_df = combined_test_df.append(wheelchair_test_df) combined_test_df = combined_test_df.append(wildcat_test_df) combined_test_df = combined_test_df.append(windsorchair_test_df) combined_test_df = combined_test_df.append(wrench_test_df) combined_test_df = combined_test_df.append(yinyang_test_df) #combined_test_df = combined_test_df.astype(int) combined_df = pd.DataFrame(columns=combined_test_df_column) combined_df = combined_df.append(combined_test_df, sort=True) combined_df = combined_df.append(combined_train_df, sort=True) train_df = combined_train_df test_df = combined_test_df print("") ### =================================================================================================== import numpy as np import pandas as pd import random from pprint import pprint from decision_tree_functions import decision_tree_algorithm, decision_tree_predictions from helper_functions import train_test_split, calculate_accuracy random.seed(0) def bootstrapping(train_df, n_bootstrap): # creates a dataframe consisting of randomly picked training data bootstrap_indices = np.random.randint(low=0, high=len(train_df), size=n_bootstrap) df_bootstrapped = train_df.iloc[bootstrap_indices] return df_bootstrapped def random_forest_algorithm(train_df, n_trees, n_bootstrap, n_features, dt_max_depth): forest = [] for i in range(n_trees): df_bootstrapped = bootstrapping(train_df, n_bootstrap) tree = decision_tree_algorithm(df_bootstrapped, max_depth=dt_max_depth, random_subspace=n_features) forest.append(tree) return forest def random_forest_predictions(test_df, forest): df_predictions = {} for i in range(len(forest)): column_name = "tree_{}".format(i) predictions = decision_tree_predictions(test_df, tree=forest[i]) df_predictions[column_name] = predictions df_predictions = pd.DataFrame(df_predictions) random_forest_predictions = df_predictions.mode(axis=1)[0] return random_forest_predictions df_bootstrapped = bootstrapping(train_df, n_bootstrap=5) N_features = int(0.4*k_number) start_train_time = time.time() forest = random_forest_algorithm(train_df, n_trees=400, n_bootstrap=100, n_features=N_features, dt_max_depth=10) train_time = time.time() - start_train_time #print(train_time) start_test_time = time.time() predictions = random_forest_predictions(test_df, forest) test_time = time.time() - start_test_time #print(test_time) accuracy = calculate_accuracy(predictions,test_df.Label) accuracy_list.append(accuracy) train_time_list.append(train_time) test_time_list.append(test_time) y_true = test_df.Label.values y_pred = predictions cm = confusion_matrix(y_true, y_pred) plt.matshow(cm, cmap = 'Reds') title_name = str('confusion_matrix_'+'acc='+str(accuracy)+'_k'+str(k_number)+'_trees400_bootstrap100_features0.4_depth_10.png') plt.savefig(title_name) #plt.show() plt.close() #title_name = str('accuracy_axis-aligned_traintesttime_trees10_bootstrap100_features0.8_depth10.png') #print(confusion_matrix(y_true, y_pred)) sys.exit() fig = plt.figure() ax = fig.add_subplot(111) lns1 = ax.plot(k_list, train_time_list, '-r', label = 'train_time') lns2 = ax.plot(k_list, test_time_list, '-g', label = 'test_time') ax2 = ax.twinx() lns3 = ax2.plot(k_list, accuracy_list, '-b', label = 'accuracy') # added these three lines lns = lns1+lns2+lns3 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc=0) ax.set_xlabel("k") ax.set_ylabel("Time(s)") ax2.set_ylabel("Accuracy(%)") plt.savefig(title_name) #plt.show() plt.close() sys.exit() <file_sep>/README.md # Computer-Vision-CW1<file_sep>/SCRIPTS/random_forest_vary_nfeatures.py import numpy as np import seaborn as sns import scipy import matplotlib import matplotlib.pyplot as plt from sklearn import preprocessing import numpy as np import pandas as pd import scipy.io as sc import matplotlib as plt import matplotlib.pyplot as plt import sys import time import os import psutil from sklearn.neighbors import NearestNeighbors from scipy.io import loadmat from sklearn.neighbors import KNeighborsClassifier from sklearn.decomposition import PCA from sklearn.cluster import KMeans from scipy.cluster.vq import * def print_image(face_image,title,mode): # function for plotting an image if mode == 'no': return None face_image = np.reshape(face_image, (300,267)) face_image = face_image.T plt.imshow(face_image, cmap='gist_gray') plt.title(title) plt.show() def load_codebook(codebook_name, distortion_name, show): codebook_recall = np.load(codebook_name) distortion_recall = np.load(distortion_name) if show == 'yes': display_codebook(codebook_recall, distortion_recall) return codebook_recall, distortion_recall def display_codebook(codebook, distortion): print("Codebook has shape",codebook.shape) print("Distortion =",distortion) return None os.system('cls') original_working_dir = os.getcwd() dir = os.getcwd() # gets the working directory of the file this python script is in os.chdir (dir) # changes the working directory to the file this python script is in print("") # also change plt.savefig to plt.show np.random.seed(13) ### UNPACK MATLAB FILE data = sc.loadmat('team_6.mat') random_selected_descriptors = data['random_selected_descriptors'] test_desc = data['descriptors_testing'] train_desc = data['descriptors_training'] train_idx = data['training_idx'] test_idx = data['testing_idx'] train_idx = train_idx.squeeze() test_idx = test_idx.squeeze() #print("train_idx:\n", train_idx,"\n") ### ORGANIZE MATLAB DATA ticks_train_images = train_desc[0] # descriptor list for ticks train image trilobite_train_images = train_desc[1] # descriptor list for trilobite train image umbrella_train_images = train_desc[2] watch_train_images = train_desc[3] waterlily_train_images = train_desc[4] wheelchair_train_images = train_desc[5] wildcat_train_images = train_desc[6] windsorchair_train_images = train_desc[7] wrench_train_images = train_desc[8] yinyang_train_images = train_desc[9] ticks_train_idx = train_idx[0].squeeze() # index list for tick train image trilobite_train_idx = train_idx[1].squeeze() # index list for trilobite train image umbrella_train_idx = train_idx[2].squeeze() watch_train_idx = train_idx[3].squeeze() waterlily_train_idx = train_idx[4].squeeze() wheelchair_train_idx = train_idx[5].squeeze() wildcat_train_idx = train_idx[6].squeeze() windsorchair_train_idx = train_idx[7].squeeze() wrench_train_idx = train_idx[8].squeeze() yinyang_train_idx = train_idx[9].squeeze() ticks_test_images = test_desc[0] # descriptor list for ticks test image trilobite_test_images = test_desc[1] # descriptor list for trilobite test image umbrella_test_images = test_desc[2] watch_test_images = test_desc[3] waterlily_test_images = test_desc[4] wheelchair_test_images = test_desc[5] wildcat_test_images = test_desc[6] windsorchair_test_images = test_desc[7] wrench_test_images = test_desc[8] yinyang_test_images = test_desc[9] ticks_test_idx = test_idx[0].squeeze() # index list for tick test image trilobite_test_idx = test_idx[1].squeeze() # index list for trilobite test image umbrella_test_idx = test_idx[2].squeeze() watch_test_idx = test_idx[3].squeeze() waterlily_test_idx = test_idx[4].squeeze() wheelchair_test_idx = test_idx[5].squeeze() wildcat_test_idx = test_idx[6].squeeze() windsorchair_test_idx = test_idx[7].squeeze() wrench_test_idx = test_idx[8].squeeze() yinyang_test_idx = test_idx[9].squeeze() number_of_images = 15 ### LOAD HISTOGRAM DATA print("LOADING HISTOGRAM DATA...") accuracy_list = [] train_time_list = [] test_time_list = [] k_number = 120 codeword_list = [f'Codeword{i+1}' for i in range(0, k_number)] # creates a list that contains codeword0...codeword'k' output_dir_histogram_npy = str('histogram_npy_files_k='+str(k_number)) os.chdir(output_dir_histogram_npy) train_histogram = str('train_histogram_array_k='+str(k_number)+'.npy') test_histogram = str('test_histogram_array_k='+str(k_number)+'.npy') class_hist_list_train = np.load(train_histogram) class_hist_list_test = np.load(test_histogram) os.chdir(original_working_dir) print("HISTOGRAM DATA LOADED: K =",k_number,"@",output_dir_histogram_npy,'\n') ### ORGANIZE HISTOGRAM DATA ticks_train_histogram = class_hist_list_train[0] trilobite_train_histogram = class_hist_list_train[1] umbrella_train_histogram = class_hist_list_train[2] watch_train_histogram = class_hist_list_train[3] waterlily_train_histogram = class_hist_list_train[4] wheelchair_train_histogram = class_hist_list_train[5] wildcat_train_histogram = class_hist_list_train[6] windsorchair_train_histogram = class_hist_list_train[7] wrench_train_histogram = class_hist_list_train[8] yinyang_train_histogram = class_hist_list_train[9] ticks_test_histogram = class_hist_list_test[0] trilobite_test_histogram = class_hist_list_test[1] umbrella_test_histogram = class_hist_list_test[2] watch_test_histogram = class_hist_list_test[3] waterlily_test_histogram = class_hist_list_test[4] wheelchair_test_histogram = class_hist_list_test[5] wildcat_test_histogram = class_hist_list_test[6] windsorchair_test_histogram = class_hist_list_test[7] wrench_test_histogram = class_hist_list_test[8] yinyang_test_histogram = class_hist_list_test[9] combined_train_features = ticks_train_histogram.tolist() + trilobite_train_histogram.tolist() + umbrella_train_histogram.tolist() + watch_train_histogram.tolist() + waterlily_train_histogram.tolist() + wheelchair_train_histogram.tolist() + wildcat_train_histogram.tolist() + windsorchair_train_histogram.tolist() + wrench_train_histogram.tolist() + yinyang_train_histogram.tolist() combined_test_features = ticks_test_histogram.tolist() + trilobite_test_histogram.tolist() + umbrella_test_histogram.tolist() + watch_test_histogram.tolist() + waterlily_test_histogram.tolist() + wheelchair_test_histogram.tolist() + wildcat_test_histogram.tolist() + windsorchair_test_histogram.tolist() + wrench_test_histogram.tolist() + yinyang_test_histogram.tolist() ### TRANSFORM TRAIN DATA INTO PANDAS DATAFRAME print("COVERTING TRAIN DATA INTO PANDAS DATAFRAME...") codeword_list = [f'Codeword{i}' for i in range(0, k_number)] ticks_label = ['ticks']*number_of_images trilobite_label = [f'trilobite']*number_of_images umbrella_label = [f'umbrella']*number_of_images watch_label = [f'watch']*number_of_images waterlily_label = [f'waterlily']*number_of_images wheelchair_label = [f'wheelchair']*number_of_images wildcat_label = [f'wildcat']*number_of_images windsorchair_label = [f'windsorchair']*number_of_images wrench_label = [f'wrench']*number_of_images yinyang_label = [f'yinyang']*number_of_images combined_train_label = ticks_label+trilobite_label+umbrella_label+watch_label+waterlily_label+wheelchair_label+wildcat_label+windsorchair_label+wrench_label+yinyang_label df_column = codeword_list train_features_array = combined_train_features combined_train_df_column = codeword_list combined_train_df_column.append("Label") #combined_train_df = pd.DataFrame(columns=combined_train_df_column) combined_train_df = pd.DataFrame(columns=["Codeword0","Codeword1","Codeword2","Label"]) ticks_train_df = pd.DataFrame(columns=df_column) trilobite_train_df = pd.DataFrame(columns=df_column) umbrella_train_df = pd.DataFrame(columns=df_column) watch_train_df = pd.DataFrame(columns=df_column) waterlily_train_df = pd.DataFrame(columns=df_column) wheelchair_train_df = pd.DataFrame(columns=df_column) wildcat_train_df = pd.DataFrame(columns=df_column) windsorchair_train_df = pd.DataFrame(columns=df_column) wrench_train_df = pd.DataFrame(columns=df_column) yinyang_train_df = pd.DataFrame(columns=df_column) for K_train in range(0,k_number): ticks_train_df[codeword_list[K_train]] = ticks_train_histogram[:,K_train] trilobite_train_df[codeword_list[K_train]] = trilobite_train_histogram[:,K_train] umbrella_train_df[codeword_list[K_train]] = umbrella_train_histogram[:,K_train] watch_train_df[codeword_list[K_train]] = watch_train_histogram[:,K_train] waterlily_train_df[codeword_list[K_train]] = waterlily_train_histogram[:,K_train] wheelchair_train_df[codeword_list[K_train]] = wheelchair_train_histogram[:,K_train] wildcat_train_df[codeword_list[K_train]] = wildcat_train_histogram[:,K_train] windsorchair_train_df[codeword_list[K_train]] = windsorchair_train_histogram[:,K_train] wrench_train_df[codeword_list[K_train]] = wrench_train_histogram[:,K_train] yinyang_train_df[codeword_list[K_train]] = yinyang_train_histogram[:,K_train] ticks_train_df["Label"] = ticks_label trilobite_train_df["Label"] = trilobite_label umbrella_train_df["Label"] = umbrella_label watch_train_df["Label"] = watch_label waterlily_train_df["Label"] = waterlily_label wheelchair_train_df["Label"] = wheelchair_label wildcat_train_df["Label"] = wildcat_label windsorchair_train_df["Label"] = windsorchair_label wrench_train_df["Label"] = wrench_label yinyang_train_df["Label"] = yinyang_label combined_train_df = combined_train_df.append(ticks_train_df) combined_train_df = combined_train_df.append(trilobite_train_df) combined_train_df = combined_train_df.append(umbrella_train_df) combined_train_df = combined_train_df.append(watch_train_df) combined_train_df = combined_train_df.append(waterlily_train_df) combined_train_df = combined_train_df.append(wheelchair_train_df) combined_train_df = combined_train_df.append(wildcat_train_df) combined_train_df = combined_train_df.append(windsorchair_train_df) combined_train_df = combined_train_df.append(wrench_train_df) combined_train_df = combined_train_df.append(yinyang_train_df) ### TRANSFORM TEST DATA INTO PANDAS DATAFRAME print("COVERTING TEST DATA INTO PANDAS DATAFRAME...") codeword_list = [f'Codeword{i}' for i in range(0, k_number)] #combined_test_label = ticks_label+trilobite_label+umbrella_label+watch_label+waterlily_label+wheelchair_label+wildcat_label+windsorchair_label+wrench_label+yinyang_label df_column = codeword_list combined_test_df_column = codeword_list combined_test_df = pd.DataFrame(columns=combined_test_df_column) ticks_test_df = pd.DataFrame(columns=df_column) trilobite_test_df = pd.DataFrame(columns=df_column) umbrella_test_df = pd.DataFrame(columns=df_column) watch_test_df = pd.DataFrame(columns=df_column) waterlily_test_df = pd.DataFrame(columns=df_column) wheelchair_test_df = pd.DataFrame(columns=df_column) wildcat_test_df = pd.DataFrame(columns=df_column) windsorchair_test_df = pd.DataFrame(columns=df_column) wrench_test_df = pd.DataFrame(columns=df_column) yinyang_test_df = pd.DataFrame(columns=df_column) for K_test in range(0,k_number): ticks_test_df[codeword_list[K_test]] = ticks_test_histogram[:,K_test] trilobite_test_df[codeword_list[K_test]] = trilobite_test_histogram[:,K_test] umbrella_test_df[codeword_list[K_test]] = umbrella_test_histogram[:,K_test] watch_test_df[codeword_list[K_test]] = watch_test_histogram[:,K_test] waterlily_test_df[codeword_list[K_test]] = waterlily_test_histogram[:,K_test] wheelchair_test_df[codeword_list[K_test]] = wheelchair_test_histogram[:,K_test] wildcat_test_df[codeword_list[K_test]] = wildcat_test_histogram[:,K_test] windsorchair_test_df[codeword_list[K_test]] = windsorchair_test_histogram[:,K_test] wrench_test_df[codeword_list[K_test]] = wrench_test_histogram[:,K_test] yinyang_test_df[codeword_list[K_test]] = yinyang_test_histogram[:,K_test] ticks_test_df["Label"] = ticks_label trilobite_test_df["Label"] = trilobite_label umbrella_test_df["Label"] = umbrella_label watch_test_df["Label"] = watch_label waterlily_test_df["Label"] = waterlily_label wheelchair_test_df["Label"] = wheelchair_label wildcat_test_df["Label"] = wildcat_label windsorchair_test_df["Label"] = windsorchair_label wrench_test_df["Label"] = wrench_label yinyang_test_df["Label"] = yinyang_label combined_test_df = combined_test_df.append(ticks_test_df, sort=True) combined_test_df = combined_test_df.append(trilobite_test_df) combined_test_df = combined_test_df.append(umbrella_test_df) combined_test_df = combined_test_df.append(watch_test_df) combined_test_df = combined_test_df.append(waterlily_test_df) combined_test_df = combined_test_df.append(wheelchair_test_df) combined_test_df = combined_test_df.append(wildcat_test_df) combined_test_df = combined_test_df.append(windsorchair_test_df) combined_test_df = combined_test_df.append(wrench_test_df) combined_test_df = combined_test_df.append(yinyang_test_df) #combined_test_df = combined_test_df.astype(int) combined_df = pd.DataFrame(columns=combined_test_df_column) combined_df = combined_df.append(combined_test_df, sort=True) combined_df = combined_df.append(combined_train_df, sort=True) train_df = combined_train_df test_df = combined_test_df print("") ### =================================================================================================== import numpy as np import pandas as pd import random from pprint import pprint from decision_tree_functions import decision_tree_algorithm, decision_tree_predictions from helper_functions import train_test_split, calculate_accuracy random.seed(0) def bootstrapping(train_df, n_bootstrap): # creates a dataframe consisting of randomly picked training data bootstrap_indices = np.random.randint(low=0, high=len(train_df), size=n_bootstrap) df_bootstrapped = train_df.iloc[bootstrap_indices] return df_bootstrapped def random_forest_algorithm(train_df, n_trees, n_bootstrap, n_features, dt_max_depth): forest = [] for i in range(n_trees): df_bootstrapped = bootstrapping(train_df, n_bootstrap) tree = decision_tree_algorithm(df_bootstrapped, max_depth=dt_max_depth, random_subspace=n_features) forest.append(tree) return forest def random_forest_predictions(test_df, forest): df_predictions = {} for i in range(len(forest)): column_name = "tree_{}".format(i) predictions = decision_tree_predictions(test_df, tree=forest[i]) df_predictions[column_name] = predictions df_predictions = pd.DataFrame(df_predictions) random_forest_predictions = df_predictions.mode(axis=1)[0] return random_forest_predictions df_bootstrapped = bootstrapping(train_df, n_bootstrap=5) # control: k=120, trees=10, bootstrap=100, features=100, depth=10 N_features_list = [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0] for item in N_features_list: N_features = int(item*k_number) start_train_time = time.time() forest = random_forest_algorithm(train_df, n_trees=10, n_bootstrap=100, n_features=N_features, dt_max_depth=10) train_time = time.time() - start_train_time start_test_time = time.time() predictions = random_forest_predictions(test_df, forest) test_time = time.time() - start_test_time accuracy = calculate_accuracy(predictions,test_df.Label) accuracy_list.append(accuracy) train_time_list.append(train_time) test_time_list.append(test_time) title_name = str('accuracy_k120_axis-aligned_trees10_varybootstrap_features100_depth10.png') fig = plt.figure() ax = fig.add_subplot(111) lns1 = ax.plot(N_features_list, train_time_list, '-r', label = 'train_time') lns2 = ax.plot(N_features_list, test_time_list, '-g', label = 'test_time') ax2 = ax.twinx() lns3 = ax2.plot(N_features_list, accuracy_list, '-b', label = 'accuracy') # added these three lines lns = lns1+lns2+lns3 labs = [l.get_label() for l in lns] ax.legend(lns, labs, loc=0) ax.set_xlabel("#trees = % of k") ax.set_ylabel("Time(s)") ax2.set_ylabel("Accuracy(%)") plt.savefig(title_name) plt.show() plt.close() sys.exit()
06b292b7029f2cb6445f165ec0a9237c21f8f623
[ "Markdown", "Python" ]
3
Python
carloarp/Computer-Vision-CW1
300e284601de46a09c734ebc8aaf95d48eb09a89
121350118e143853d2967d6c5f7d246cb83b3aec
refs/heads/master
<repo_name>mobilemadman2/jetbrains-plugin-graph-database-support<file_sep>/ui/jetbrains/src/main/java/com/neueda/jetbrains/plugin/graphdb/jetbrains/ui/datasource/tree/TreeContextMenuMouseAdapter.java package com.neueda.jetbrains.plugin.graphdb.jetbrains.ui.datasource.tree; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.ui.treeStructure.Tree; import javax.swing.*; import javax.swing.tree.TreePath; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class TreeContextMenuMouseAdapter extends MouseAdapter { private ContextMenuService contextMenuService = new ContextMenuService(); @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { Tree tree = (Tree) e.getComponent(); TreePath pathForLocation = tree.getPathForLocation(e.getX(), e.getY()); DataContext dataContext = DataManager.getInstance().getDataContext(tree); contextMenuService.getContextMenu(pathForLocation) .ifPresent(dto -> dto.showPopup(dataContext)); } } } <file_sep>/ui/jetbrains/src/main/java/com/neueda/jetbrains/plugin/graphdb/jetbrains/ui/datasource/tree/TableContextMenuMouseAdapter.java package com.neueda.jetbrains.plugin.graphdb.jetbrains.ui.datasource.tree; import com.intellij.ide.DataManager; import com.intellij.openapi.actionSystem.DataContext; import com.intellij.ui.table.JBTable; import com.intellij.ui.treeStructure.Tree; import javax.swing.*; import javax.swing.tree.TreePath; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class TableContextMenuMouseAdapter extends MouseAdapter { private ContextMenuService contextMenuService = new ContextMenuService(); @Override public void mouseClicked(MouseEvent e) { if (SwingUtilities.isRightMouseButton(e)) { JBTable table = (JBTable) e.getComponent(); int selectedRow = table.rowAtPoint(e.getPoint()); int selectedColumn = table.columnAtPoint(e.getPoint()); Object value = table.getModel().getValueAt(selectedRow, selectedColumn); if (Tree.class.isAssignableFrom(value.getClass())) { Tree tree = (Tree) value; TreePath path = tree.getPathForLocation(e.getX(), e.getY()); DataContext dataContext = DataManager.getInstance() .getDataContext(table, e.getX(), e.getY()); contextMenuService.getContextMenu(path) .ifPresent(dto -> dto.showPopup(dataContext)); } } } } <file_sep>/ui/jetbrains/src/main/java/com/neueda/jetbrains/plugin/graphdb/jetbrains/ui/console/graph/EntityCopyToClipboardAction.java package com.neueda.jetbrains.plugin.graphdb.jetbrains.ui.console.graph; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.neueda.jetbrains.plugin.graphdb.database.api.data.NoIdGraphEntity; import com.neueda.jetbrains.plugin.graphdb.jetbrains.ui.helpers.SerialisationHelper; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; public class EntityCopyToClipboardAction extends AnAction { private Object node; EntityCopyToClipboardAction(String title, String description, Icon icon, NoIdGraphEntity node) { super(title, description, icon); this.node = node; } @Override public void actionPerformed(@NotNull AnActionEvent e) { StringSelection selection = new StringSelection(SerialisationHelper.convertToCsv(node)); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(selection, selection); } }
f834f117769605460459e1ac1d8087ba7d268ecf
[ "Java" ]
3
Java
mobilemadman2/jetbrains-plugin-graph-database-support
04853786f5767ab8d1a5dd84a186f8432443a7d8
8d02d9e805677f89513c0d785d8f676093768964
refs/heads/main
<repo_name>gchecknandini/fabric-1.4<file_sep>/car_details.go package main import ( "encoding/json" "bytes" "fmt" "github.com/hyperledger/fabric/core/chaincode/shim" sc "github.com/hyperledger/fabric/protos/peer" ) type lancastersmartcontract struct{ } type Cars struct{ CarDescription string `json:"car_description"` CarId string `json:"car_id"` CarRegistrationNo string `json:"car_resgistrationno"` CarType string `json:"car_type"` CarCameraId string `json:"car_cameraid"` CarStatus string `json:"car_status"` CarCreated_At string `json:"car_createdate"` CarUpdated_At string `json:"car_updatedate"` } //Init Function func (s *lancastersmartcontract) Init(stub shim.ChaincodeStubInterface) sc.Response { _, args := stub.GetFunctionAndParameters() var cars = Cars{ CarId: args[0], CarRegistrationNo: args[1], CarDescription: args[2], CarType: args[3], CarCameraId: args[4], CarStatus: args[5], CarCreated_At: args[6], CarUpdated_At: args[7],} carAsBytes, _ := json.Marshal(cars) var uniqueID = args[1] err := stub.PutState(uniqueID, carAsBytes) if err != nil { return shim.Error("Failed to enter data") } return shim.Success([]byte("Chaincode Successfully initialized")) } //CreateCar ... this function is used to create doctors func CreateCar(stub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 5 { return shim.Error("Incorrect number of arguments. Expecting 5") } var cars = Cars{ CarId: args[0], CarRegistrationNo: args[1], CarDescription: args[2], CarType: args[3], CarCameraId: args[4], CarStatus: args[5], CarCreated_At: args[6], CarUpdated_At: args[7],} carAsBytes, _ := json.Marshal(cars) var uniqueID = args[1] err := stub.PutState(uniqueID, carAsBytes) if err != nil { fmt.Println("Error in create car") } return shim.Success(nil) } // Deletes an entity from state func (s *lancastersmartcontract) delete(stub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 1") } // Delete the key from the state in ledger err := stub.DelState(args[0]) if err != nil { return shim.Error("Failed to delete state") } return shim.Success(nil) } func (s *lancastersmartcontract) queryCar(stub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 1") } carAsBytes, _ := stub.GetState(args[0]) return shim.Success(carAsBytes) } //Invoke function func (s *lancastersmartcontract) Invoke(stub shim.ChaincodeStubInterface) sc.Response { fun, args := stub.GetFunctionAndParameters() if fun == "CreateCar" { fmt.Println("Error occured ==> ") //logger.Info("########### create docs ###########") return CreateCar(stub, args) } else if fun == "initLedger" { return s.initLedger(stub) } else if fun == "delete" { // Deletes an entity from its state return s.delete(stub, args) } else if fun == "query" { return s.queryCar(stub, args) } else if fun == "queryAllCars" { return s.queryAllCars(stub) } else if fun == "expiryofCar" { return s.expiryofCar(stub, args) } else if fun == "isExpired" { return s.isExpired(stub, args) } return shim.Error(fmt.Sprintf("Unknown action, check the first argument, must be one of 'delete', 'query', or 'move'. But got: %v", fun)) } func (s *lancastersmartcontract) initLedger(stub shim.ChaincodeStubInterface) sc.Response { cars := []Cars{ Cars{CarId: "1", CarRegistrationNo: "LA7432188", CarDescription: "AUDI Blue", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "2", CarRegistrationNo: "LA1234567", CarDescription: "FORD Red", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "3", CarRegistrationNo: "LA1233398", CarDescription: "HYUNDAI Green", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "4", CarRegistrationNo: "LA7432238", CarDescription: "VOLKSWAGEN Yellow", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "5", CarRegistrationNo: "LA7422188", CarDescription: "TESLA Black", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "6", CarRegistrationNo: "LA7333188", CarDescription: "PEUGEOT Purple", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "7", CarRegistrationNo: "LA7477788", CarDescription: "FIAT Blue", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "8", CarRegistrationNo: "LA7438888", CarDescription: "TATA Indigo", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "9", CarRegistrationNo: "LA7555188", CarDescription: "<NAME>", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, Cars{CarId: "10", CarRegistrationNo: "LA7111188", CarDescription: "AUDI Black", CarType: "Lancastercar", CarCameraId: "C005", CarStatus: "Active", CarCreated_At: "03032020", CarUpdated_At: "03032020"}, } i := 0 for i < len(cars) { fmt.Println("i is ", i) carAsBytes, _ := json.Marshal(cars[i]) fmt.Println("Marshaling done for ", i) uniqueID :=cars[i].CarRegistrationNo err:= stub.PutState(uniqueID, carAsBytes) if err != nil { return shim.Error("Failed to enter data "+ err.Error()) } fmt.Println("Added", cars[i]) i = i + 1 } return shim.Success(nil) } func (s *lancastersmartcontract) queryAllCars(stub shim.ChaincodeStubInterface) sc.Response { startKey := "LA0000000" endKey := "LA9999999" resultsIterator, err := stub.GetStateByRange(startKey, endKey) if err != nil { return shim.Error(err.Error()) } defer resultsIterator.Close() // buffer is a JSON array containing QueryResults var buffer bytes.Buffer buffer.WriteString("[") bArrayMemberAlreadyWritten := false for resultsIterator.HasNext() { queryResponse, err := resultsIterator.Next() if err != nil { return shim.Error(err.Error()) } // Add a comma before array members, suppress it for the first array member if bArrayMemberAlreadyWritten == true { buffer.WriteString(",") } buffer.WriteString("{\"Key\":") buffer.WriteString("\"") buffer.WriteString(queryResponse.Key) buffer.WriteString("\"") buffer.WriteString(", \"Values\":") // Record is a JSON object, so we write as-is buffer.WriteString(string(queryResponse.Value)) buffer.WriteString("}") bArrayMemberAlreadyWritten = true } buffer.WriteString("]") fmt.Printf("- queryAllCars:\n%s\n", buffer.String()) return shim.Success(buffer.Bytes()) } func (s *lancastersmartcontract) expiryofCar(stub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 2") } carAsBytes, _ := stub.GetState(args[0]) car := Cars{} json.Unmarshal(carAsBytes, &car) car.CarStatus = "Inactive" carAsBytes, _ = json.Marshal(car) stub.PutState(args[0], carAsBytes) return shim.Success(nil) } func (s *lancastersmartcontract) isExpired(stub shim.ChaincodeStubInterface, args []string) sc.Response { if len(args) != 1 { return shim.Error("Incorrect number of arguments. Expecting 1") } carAsBytes, _ := stub.GetState(args[0]) car := Cars{} json.Unmarshal(carAsBytes, &car) //StatusAsByte := []byte(car.CarStatus) if (car.CarStatus == "Inactive") { return shim.Success([]byte("Y")) } else { return shim.Success([]byte("N")) } } func main() { err := shim.Start(new(lancastersmartcontract)) if err != nil { fmt.Print(err) } } <file_sep>/camera_data.go package main import ( "encoding/json" "fmt" //"strconv" "github.com/hyperledger/fabric/core/chaincode/shim" "github.com/hyperledger/fabric/protos/peer" ) //SmartContract ... The SmartContract type SmartContract struct { } //const Channel = "twoorgschannel" //const TargetChaincode = "autonomy_chain" type Cameras struct { Filename string `json:"file_name"` CameraId string `json:"camera_id"` IncidentType string `json:"Incident_type"` Latitude string `json:"latitude"` Longitude string `json:"longitude"` SavingTimestamp string `json:"saving_timestamp"` Timestamp string `json:"timestamp"` } type CameraByIdResponse struct { ID string `json:"id"` Request Cameras `json:"camera"` } type Response struct { Status string `json:"status"` Message string `json:"message"` Data CameraByIdResponse `json:"data"` } //var logger = shim.NewLogger("example_cc0") //Init Function func (s *SmartContract) Init(stub shim.ChaincodeStubInterface) peer.Response { _, args := stub.GetFunctionAndParameters() var cameras = Cameras{ Filename: args[0], CameraId: args[1], IncidentType: args[2], Latitude: args[3], Longitude: args[4], SavingTimestamp: args[5], Timestamp: args[6]} cameraAsBytes, _ := json.Marshal(cameras) var uniqueID = args[1] err := stub.PutState(uniqueID, cameraAsBytes) if err != nil { fmt.Println("Error in Init") } return shim.Success([]byte("Chaincode Successfully initialized")) } //Createcamera ... this function is used to create cameras func CreateCamera(stub shim.ChaincodeStubInterface, args []string) peer.Response { if len(args) != 5 { return shim.Error("Incorrect number of arguments. Expecting 5") } var cameras = Cameras{ Filename: args[0], CameraId: args[1], IncidentType: args[2], Latitude: args[3], Longitude: args[4], SavingTimestamp: args[5], Timestamp: args[6]} cameraAsBytes, _ := json.Marshal(cameras) var uniqueID = args[1] //args := make([][]byte, 1) //args[0] = []byte("queryCar") //args[1] = []byte[args[1]] // Gets the value of MyToken in token chaincode (V5) //response := stub.InvokeChaincode(TargetChaincode, args, Channel) //if car.statue = 'Active' err := stub.PutState(uniqueID, cameraAsBytes) //else error if err != nil { fmt.Println("Erro in create camera") } return shim.Success(nil) } //GetCameraByID ... This function will return a particular camera func GetCameraByID(stub shim.ChaincodeStubInterface, args []string) peer.Response { fmt.Println("Before Len") if len(args) != 1 { return shim.Error("Incorrect number of arguments.Expected 1 argument") } fmt.Println("After Len") query := `{ "selector": { "camera_id": { "$eq": "` + args[0] + `" } } }` fmt.Println("Queeryy =>>>> \n" + query) //resultsIterator, err := stub.GetQueryResult("{\"selector\":{\"doc_type\":\"cameras\",\"_id\":{\"$eq\": \"1\"}}}") resultsIterator, err := stub.GetQueryResult(query) if err != nil { fmt.Println("Error fetching reuslts") return shim.Error(err.Error()) } defer resultsIterator.Close() fmt.Println("After results") // counter := 0 //var resultKV for resultsIterator.HasNext() { fmt.Println("Inside hasnext") // Get the next element queryResponse, err := resultsIterator.Next() if err != nil { fmt.Println("Err=" + err.Error()) return shim.Success([]byte("Error in parse: " + err.Error())) } // Increment the counter // counter++ key := queryResponse.GetKey() value := string(queryResponse.GetValue()) // Print the receieved result on the console fmt.Printf("Result# %s %s \n\n", key, value) b, je := json.Marshal(value) if je != nil { return shim.Error(je.Error()) } return shim.Success(b) } // Close the iterator resultsIterator.Close() return shim.Success(nil) // return shim.Error("Could not find any cameras.") } //Invoke function func (s *SmartContract) Invoke(stub shim.ChaincodeStubInterface) peer.Response { fun, args := stub.GetFunctionAndParameters() if fun == "CreateCamera" { fmt.Println("Error occured ==> ") //logger.Info("########### create docs ###########") return CreateCamera(stub, args) } else if fun == "GetCameraByID" { fmt.Println("Calling get ==> ") return GetCameraByID(stub, args) } return shim.Error(fmt.Sprintf("Unknown action, check the first argument, must be one of 'delete', 'query', or 'move'. But got: %v", fun)) } func main() { err := shim.Start(new(SmartContract)) if err != nil { fmt.Print(err) } } <file_sep>/README.md # fabric-1.4
ec98ccf4bc43e9b26ffdabdb7ca0745d7e64f0cb
[ "Markdown", "Go" ]
3
Go
gchecknandini/fabric-1.4
89d2d50ddea4220ed53b0381071ed7e51dd35ca4
d96c9c99d92876ef68de7ae63e68e747dd5754c6
refs/heads/master
<repo_name>SuccessMary/graduation<file_sep>/core/test.py """Test script to classify target data.""" import torch import torch.nn as nn from utils import make_variable import params def eval_tgt(encoder, classifier, data_loader): """Evaluation for target encoder by source classifier on target dataset.""" # set eval state for Dropout and BN layers encoder.eval() classifier.eval() # init loss and accuracy # loss = 0 # acc = 0 loss1 = 0 loss2 = 0 loss3 = 0 acc1 = 0 acc2 = 0 acc3 = 0 # set loss function # criterion = nn.CrossEntropyLoss() #my criterion = nn.MSELoss(reduce=True, size_average=True) # evaluate network for (images, labels) in data_loader: images = make_variable(images, volatile=True) #为True表示不需要反向传播 labels = make_variable(labels) #.squeeze_() # print('标签:',labels) preds = classifier(encoder(images)) # print('预测值是:',preds) # loss += criterion(preds, labels).item() # print('loss:',loss) loss1 += criterion(preds[:,0], labels[:,0]).item() loss2 += criterion(preds[:,1], labels[:,1]).item() loss3 += criterion(preds[:,2], labels[:,2]).item() # pred_cls = preds.data.max(1)[1] # acc += pred_cls.eq(labels.data).cpu().sum() # acc += ((preds - labels) ** 2).cpu().sum() # print('acc:',acc) acc1 += ((preds[:,0] - labels[:,0]) ** 2).cpu().sum() acc2 += ((preds[:,1] - labels[:,1]) ** 2).cpu().sum() acc3 += ((preds[:,2] - labels[:,2]) ** 2).cpu().sum() # loss /= len(data_loader) # acc /= len(data_loader.dataset) loss1 /= len(data_loader) loss2 /= len(data_loader) loss3 /= len(data_loader) acc1 /= len(data_loader.dataset) acc2 /= len(data_loader.dataset) acc3 /= len(data_loader.dataset) # print("Avg Loss = {}, Avg Accuracy = {}".format(loss, acc**0.5)) print('Avg loss1: {}, Avg loss2: {}, Avg loss3: {}'.format(loss1,loss2,loss3)) print('Avg Acc1: {}, Avg Acc2: {}, Avg Acc3: {}'.format(acc1, acc2, acc3)) <file_sep>/params.py """Params for ADDA.""" #params for the size of different data loader 暂时用不到 # n_src_trn_samples = 314 # n_src_eval_samples = 78 # n_tgt_trn_samples = 160 # n_src_eval_samples = 40 # params for dataset and data loader data_root = "data" dataset_mean_value = 0.5 dataset_std_value = 0.5 dataset_mean = (dataset_mean_value, dataset_mean_value, dataset_mean_value) dataset_std = (dataset_std_value, dataset_std_value, dataset_std_value) batch_size = 50 image_size = 64 # params for source dataset src_dataset = "MNIST" src_encoder_restore = "snapshots/ADDA-source-encoder-final.pt" src_classifier_restore = "snapshots/ADDA-source-classifier-final.pt" src_model_trained = True # params for target dataset tgt_dataset = "USPS" tgt_encoder_restore = "snapshots/ADDA-target-encoder-final.pt" tgt_model_trained = True # params for setting up models model_root = "snapshots_0419_3" d_input_dims = 50 #40 d_hidden_dims = 40 d_output_dims = 2 d_model_restore = "snapshots/ADDA-critic-final.pt" # params for training network num_gpu = 1 num_epochs_pre = 500 #####1 log_step_pre = 20 eval_step_pre = 20 save_step_pre = 100 num_epochs = 2000 #####2 log_step = 2 #100 save_step = 100 manual_seed = 2020 #None # params for optimizing models d_learning_rate = 1e-4 #####4 c_learning_rate = 1e-4 #####4 beta1 = 0.9 beta2 = 0.99 <file_sep>/core/__init__.py from .adapt import train_tgt from .pretrain import eval_src, train_src from .test import eval_tgt __all__ = (eval_src, train_src, train_tgt, eval_tgt) <file_sep>/README.md # PyTorch-ADDA A PyTorch implementation for [Adversarial Discriminative Domain Adaptation](https://arxiv.org/abs/1702.05464). ## Environment - Python 3.6 - PyTorch 0.2.0 ## Usage I only test on MNIST -> USPS, you can just run the following command: ```shell python3 main.py ``` ## Network In this experiment, I use three types of network. They are very simple. - LeNet encoder ``` LeNetEncoder ( (encoder): Sequential ( (0): Conv2d(1, 20, kernel_size=(5, 5), stride=(1, 1)) (1): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1)) (2): ReLU () (3): Conv2d(20, 50, kernel_size=(5, 5), stride=(1, 1)) (4): Dropout2d (p=0.5) (5): MaxPool2d (size=(2, 2), stride=(2, 2), dilation=(1, 1)) (6): ReLU () ) (fc1): Linear (800 -> 500) ) ``` - LeNet classifier ``` LeNetClassifier ( (fc2): Linear (500 -> 10) ) ``` - Discriminator ``` Discriminator ( (layer): Sequential ( (0): Linear (500 -> 500) (1): ReLU () (2): Linear (500 -> 500) (3): ReLU () (4): Linear (500 -> 2) (5): LogSoftmax () ) ) ``` ## Result | | MNIST (Source) | USPS (Target) | | :--------------------------------: | :------------: | :-----------: | | Source Encoder + Source Classifier | 99.140000% | 83.978495% | | Target Encoder + Source Classifier | | 97.634409% | Domain Adaptation does work (97% vs 83%).<file_sep>/core/pretrain.py """Pre-train encoder and classifier for source dataset.""" import torch.nn as nn import torch.optim as optim import params from utils import make_variable, save_model #对于源域进行空间映射和分类器训练 def train_src(encoder, classifier, data_loader): """Train classifier for source domain.""" #################### # 1. setup network # #################### # set train state for Dropout and BN layers encoder.train() #train训练模式启用Dropout和BatchNormalization classifier.train() # setup criterion and optimizer # optimizer = optim.Adam( # list(encoder.parameters()) + list(classifier.parameters()), #可能不能一起训练 # lr=params.c_learning_rate, # betas=(params.beta1, params.beta2)) optimizer = optim.RMSprop( list(encoder.parameters()) + list(classifier.parameters()), lr=params.c_learning_rate, alpha=0.9) # criterion = nn.CrossEntropyLoss() #my criterion = nn.MSELoss(reduce=True, size_average=True) #################### # 2. train network # #################### for epoch in range(params.num_epochs_pre): #100 for step, (images, labels) in enumerate(data_loader): # make images and labels variable 将图片变成数据 images = make_variable(images) labels = make_variable(labels) #.squeeze_() labels不需要squeeze() # zero gradients for optimizer optimizer.zero_grad() # compute loss for critic preds = classifier(encoder(images)) # loss = criterion(preds, labels) loss1 = criterion(preds[:,0], labels[:,0]) loss2 = criterion(preds[:,1], labels[:,1]) loss3 = criterion(preds[:,2], labels[:,2]) loss = loss1 + loss2 + loss3 # optimize source classifier loss.backward() optimizer.step() # print step info if ((step + 1) % params.log_step_pre == 0): print("Epoch [{}/{}] Step [{}/{}]: loss={}" .format(epoch + 1, params.num_epochs_pre, step + 1, len(data_loader), loss.data[0])) # eval model on test set if ((epoch + 1) % params.eval_step_pre == 0): #每20个epoch评价一次 print('[epoch:{}/{}]'.format(epoch,params.num_epochs_pre), eval_src(encoder, classifier, data_loader)) # save model parameters if ((epoch + 1) % params.save_step_pre == 0): #每100个epoch保存一次 save_model(encoder, "ADDA-source-encoder-{}.pt".format(epoch + 1)) save_model(classifier, "ADDA-source-classifier-{}.pt".format(epoch + 1)) # # save final model save_model(encoder, "ADDA-source-encoder-final.pt") save_model(classifier, "ADDA-source-classifier-final.pt") return encoder, classifier def eval_src(encoder, classifier, data_loader): """Evaluate classifier for source domain.""" # set eval state for Dropout and BN layers encoder.eval() #eval验证模式不启用Dropout和BatchNormalization classifier.eval() # init loss and accuracy # loss = 0 # acc = 0 loss_1 = 0 loss_2 = 0 loss_3 = 0 acc1 = 0 acc2 = 0 acc3 = 0 #my criterion = nn.MSELoss() # evaluate network for (images, labels) in data_loader: images = make_variable(images, volatile=True) labels = make_variable(labels) # print('标签:',labels) # print('标签:',labels.shape) preds = classifier(encoder(images)) #.squeeze() # print('预测值是:',preds.shape) # print('预测值是:',preds) # loss += criterion(preds, labels).item() #data[0]6 loss_1 += criterion(preds[:,0], labels[:,0]).item() loss_2 += criterion(preds[:,1], labels[:,1]).item() loss_3 += criterion(preds[:,2], labels[:,2]).item() # pred_cls = preds.data.max(1)[1] #返回每一行最大值所在的索引(我的不需要,因为分类器(即我的回归器)直接输出一个结果) # acc += pred_cls.eq(labels.data).cpu().sum() # acc += ((preds - labels) ** 2).cpu().sum() acc1 += ((preds[:,0] - labels[:,0]) ** 2).cpu().sum() acc2 += ((preds[:,1] - labels[:,1]) ** 2).cpu().sum() acc3 += ((preds[:,2] - labels[:,2]) ** 2).cpu().sum() # loss /= len(data_loader) # acc /= len(data_loader.dataset) loss_1 /= len(data_loader) loss_2 /= len(data_loader) loss_3 /= len(data_loader) acc1 /= len(data_loader.dataset) acc2 /= len(data_loader.dataset) acc3 /= len(data_loader.dataset) # print("Avg Loss = {}, Avg Accuracy = {}".format(loss, acc)) print('Avg loss1: {}, Avg loss2: {}, Avg loss3: {}'.format(loss_1,loss_2,loss_3)) print('Avg Acc1: {}, Avg Acc2: {}, Avg Acc3: {}'.format(acc1, acc2, acc3)) <file_sep>/models/__init__.py from .discriminator import Discriminator from .lenet import LeNetRegressor, LeNetEncoder __all__ = (LeNetRegressor, LeNetEncoder, Discriminator) <file_sep>/models/lenet.py """LeNet model for ADDA.""" import torch.nn.functional as F from torch import nn #编码器:映射到相同空间 # class LeNetEncoder(nn.Module): # """LeNet encoder model for ADDA.""" # # def __init__(self): # """Init LeNet encoder.""" # super(LeNetEncoder, self).__init__() # # self.restored = False # # self.encoder = nn.Sequential( # # 1st conv layer # # input [1 x 28 x 28] # # output [20 x 12 x 12] # # #my input[1*1*n] # #my output[20*1/2*n/2] # # nn.Conv2d(1, 20, kernel_size=5), # nn.MaxPool2d(kernel_size=2), # nn.ReLU(), # # 2nd conv layer # # input [20 x 12 x 12] # # output [50 x 4 x 4] # # nn.Conv2d(20, 50, kernel_size=5), # nn.Dropout2d(), # nn.MaxPool2d(kernel_size=2), # nn.ReLU() # ) # #经过全连接层(即分类层)转换后,encoder编码输出大小为500(500是人为设定的) # self.fc1 = nn.Linear(50 * 4 * 4, 500) # def forward(self, input): # """Forward the LeNet.""" # conv_out = self.encoder(input) # feat = self.fc1(conv_out.view(-1, 50 * 4 * 4)) #经过卷积层后,先把conv_out拉平,再输入全连接层 # return feat #我的编码器 class LeNetEncoder(nn.Module): def __init__(self): super(LeNetEncoder, self).__init__() self.restored = False self.encoder = nn.Sequential( #input[B, 1, 12] #output[B, 20, 5] # 第一层1维卷积,卷积核尺寸为3*3,步长为1 nn.Conv1d(1, 20, kernel_size=3), # 池化层,卷积核尺寸为2*2,步长为2(1可否?) # nn.MaxPool1d(kernel_size=2, stride=2), nn.BatchNorm1d(20), nn.LeakyReLU(), # 第二层1维卷积和池化,同上 #input[B, 20, 5] #output[B, 50, 1] nn.Conv1d(20, 50, kernel_size=3), nn.BatchNorm1d(50), # nn.Dropout(), # nn.MaxPool1d(kernel_size=2, stride=2), nn.LeakyReLU(), #第三层卷积 nn.Conv1d(50,100,3), nn.BatchNorm1d(100), nn.Tanh() ) # self.fc1 = nn.Linear(100 * 2,100) self.fc1 = nn.Linear(100 * 2, 50) def forward(self, input): conv_out = self.encoder(input) # print(conv_out.shape) # 进全链接层之前,要先拉平(相当于tensorflow里的flatten),第一维是batchsize feat = self.fc1(conv_out.view(-1,50 * 4)) return feat #分类器:映射后进行分类 # class LeNetClassifier(nn.Module): # """LeNet classifier model for ADDA.""" # # def __init__(self): # """Init LeNet encoder.""" # super(LeNetClassifier, self).__init__() # self.fc2 = nn.Linear(500, 10) # # def forward(self, feat): # """Forward the LeNet classifier.""" # out = F.dropout(F.relu(feat), training=self.training) # out = self.fc2(out) # return out #我的回归器 class LeNetRegressor(nn.Module): """LeNet classifier model for ADDA.""" def __init__(self): super(LeNetRegressor, self).__init__() self.fc2 = nn.Linear(50,3) #输出格式大小为3 def forward(self, feat): # out = F.dropout(F.relu(feat), training=self.training) out = F.relu(feat) out = self.fc2(out) # out2 = self.fc2(out) # out3 = self.fc2(out) return out<file_sep>/core/adapt.py """Adversarial adaptation to train target encoder.""" import os import torch import torch.optim as optim from torch import nn import params from utils import make_variable def train_tgt(src_encoder, tgt_encoder, critic, src_data_loader, tgt_data_loader): """Train encoder for target domain.""" #################### # 1. setup network # #################### # set train state for Dropout and BN layers tgt_encoder.train() #相当于生成器 critic.train() #相当于鉴别器 # setup criterion and optimizer criterion = nn.CrossEntropyLoss() #交叉熵损失函数 # optimizer_tgt = optim.Adam(tgt_encoder.parameters(), # lr=params.c_learning_rate, # betas=(params.beta1, params.beta2)) optimizer_tgt = optim.RMSprop(tgt_encoder.parameters(), lr = params.c_learning_rate, alpha=0.9) # optimizer_critic = optim.Adam(critic.parameters(), # lr=params.d_learning_rate, # betas=(params.beta1, params.beta2)) optimizer_critic = optim.RMSprop(critic.parameters(), lr = params.d_learning_rate, alpha=0.9) len_data_loader = min(len(src_data_loader), len(tgt_data_loader)) #################### # 2. train network # #################### for epoch in range(params.num_epochs): # zip source and target data pair data_zip = enumerate(zip(src_data_loader, tgt_data_loader)) for step, ((images_src, _), (images_tgt, _)) in data_zip: #对于每个样本,先训练辨别器D,再训练生成器G # print(step) ########################### # 2.1 train discriminator # 训练辨别器D(critic) ########################### # make images variable images_src = make_variable(images_src) images_tgt = make_variable(images_tgt) # zero gradients for optimizer 清除上一轮的梯度 optimizer_critic.zero_grad() # extract and concat features feat_src = src_encoder(images_src) feat_tgt = tgt_encoder(images_tgt) feat_concat = torch.cat((feat_src, feat_tgt), 0) #纵向叠加在一起 # print('编码过后的大小为',feat_src.shape,feat_tgt.shape) # predict on discriminator辨别器的预测值 pred_concat = critic(feat_concat.detach()) #域分类器的预测值,不求叠加之前的两个网络梯度,只求叠加之后的critic的梯度 # prepare real and fake label辨别器的期望值 label_src = make_variable(torch.ones(feat_src.size(0)).long()) #对于源域,希望为1,即最小化和1的距离 label_tgt = make_variable(torch.zeros(feat_tgt.size(0)).long()) #对于目标域,希望为0,即最小化和0的距离 label_concat = torch.cat((label_src, label_tgt), 0) #同样纵向叠加 # compute loss for critic 辨别器损失函数D_loss loss_critic = criterion(pred_concat, label_concat) loss_critic.backward() # optimize critic optimizer_critic.step() pred_cls = torch.squeeze(pred_concat.max(1)[1]) #返回每一行中最大值的那个元素的索引(返回最大元素在这一行的列索引) acc = (pred_cls == label_concat).float().mean() ############################ # 2.2 train target encoder # 训练生成器G,即目标域编码器target encoder ############################ # zero gradients for optimizer 再次清除上一轮的残余值 optimizer_critic.zero_grad() #应该要加这一步 optimizer_tgt.zero_grad() # extract and target features feat_tgt = tgt_encoder(images_tgt) # predict on discriminator pred_tgt = critic(feat_tgt) # prepare fake labels label_tgt = make_variable(torch.ones(feat_tgt.size(0)).long()) #生成器想愚弄判别器,被判别为1,及最小化和1的距离 # compute loss for target encoder 生成器损失函数G_loss loss_tgt = criterion(pred_tgt, label_tgt) loss_tgt.backward() # optimize target encoder optimizer_tgt.step() ####################### # 2.3 print step info # ####################### # if ((step + 1) % params.log_step == 0): # print("Epoch [{}/{}] Step [{}/{}]:" # "d_loss={:.5f} g_loss={:.5f} acc={:.5f}" # .format(epoch + 1, # params.num_epochs, # step + 1, # len_data_loader, # loss_critic.item(), # loss_tgt.item(), # acc.item())) #打印每个epoch的loss print("Epoch [{}/{}]: d_loss={:.5f} g_loss={:.5f} acc={:.5f}" .format(epoch + 1, params.num_epochs, loss_critic.item(), loss_tgt.item(), acc.item())) ############################# # 2.4 save model parameters # ############################# if ((epoch + 1) % params.save_step == 0): #每100步保存一次模型 torch.save(critic.state_dict(), os.path.join( params.model_root, "ADDA-critic-{}.pt".format(epoch + 1))) torch.save(tgt_encoder.state_dict(), os.path.join( params.model_root, "ADDA-target-encoder-{}.pt".format(epoch + 1))) torch.save(critic.state_dict(), os.path.join( params.model_root, "ADDA-critic-final.pt")) torch.save(tgt_encoder.state_dict(), os.path.join( params.model_root, "ADDA-target-encoder-final.pt")) return tgt_encoder #输出经过对抗生成训练的目标域编码器 <file_sep>/jf_test.py import pandas as pd source_x = pd.read_csv(r'D:/个人资料/研究生/机器学习/Jupyter/迁移学习练习赛-2/run/data/source_x.csv') print(source_x.head())<file_sep>/main.py import pandas as pd class scale_related(): def __init__(self): self.stats = [] self.input = None def norm(self, x): self.input = x self.stats = self.input.describe().transpose() output = (self.input - self.stats['mean']) / (self.stats['max'] - self.stats['min']) return output # def inverse_norm(self,x): # print(self.stats) # self.input = x # out_put = x * (self.stats['max'] - self.stats['min']) + self.stats['mean'] # return out_put # def Normalize(self,y): # self.norm_y[0,0] = np.average(y) # self.norm_y[0,1] = np.max(y) - np.min(y) # return (y - self.norm[0,0]) / self.norm_y[0,1] import pandas as pd import numpy as np import torch import torch.utils.data as Data from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler #jds def get_target_data_loader(): x = pd.read_excel('F:/毕业实验/a3/modal/a3_feature.xlsx', header=0).astype('float32') x = scale_related().norm(x) y = pd.read_excel(r'F:/毕业实验/a3/modal/a3_modal.xlsx', header=0).iloc[:, 1:4].astype('float32') # y = scale_related().norm(y) trn_x, val_x, trn_y, val_y = train_test_split(x, y, test_size=0.2) trn_x = torch.from_numpy(np.array(trn_x)) trn_y = torch.from_numpy(np.array(trn_y)) val_x = torch.from_numpy(np.array(val_x)) val_y = torch.from_numpy(np.array(val_y)) # x扩充至三维,原来的【314*9】转变为【314*1*9】 trn_x = torch.unsqueeze(trn_x, 1) val_x = torch.unsqueeze(val_x, 1) print(trn_x.shape, trn_y.shape, val_x.shape, val_y.shape) # #y减少至一维 # source_y = torch.squeeze(source_y, 1) # target_y = torch.squeeze(target_y, 1) # 运用批训练,装进loder里 trn_data = Data.TensorDataset(trn_x, trn_y) val_data = Data.TensorDataset(val_x, val_y) trn_data_loder = Data.DataLoader(dataset=trn_data, batch_size=params.batch_size, shuffle=True ) val_data_loder = Data.DataLoader(dataset=val_data, batch_size=params.batch_size, shuffle=True ) return (trn_data_loder, val_data_loder) def get_source_data_loader(): # x = torch.from_numpy(StandardScaler().fit_transform(np.random.rand(200,9))).float() x = pd.read_excel('F:/毕业实验/a1/processed modal/a1_feature.xlsx', header=0).astype('float32') x = scale_related().norm(x) x = torch.from_numpy(np.array(x)) x = torch.unsqueeze(x, 1) y = pd.read_excel('F:/毕业实验/a1/processed modal/a1_modal_15-23-2.xlsx', header=0).iloc[:, 1:].astype('float32') # y = scale_related().norm(y) y = torch.from_numpy(np.array(y)) trn_x, val_x, trn_y, val_y = train_test_split(x, y, test_size=0.2) print(trn_x.shape, trn_x.shape, val_x.shape, val_y.shape) trn_data = Data.TensorDataset(trn_x, trn_y) trn_data_loder = Data.DataLoader(dataset=trn_data, batch_size=50, shuffle=True ) val_data = Data.TensorDataset(val_x, val_y) val_data_loder = Data.DataLoader(dataset=val_data, batch_size=50, shuffle=True ) return (trn_data_loder, val_data_loder) # 主程序 import params from core import eval_src, eval_tgt, train_src, train_tgt from models import Discriminator, LeNetRegressor, LeNetEncoder from utils import get_data_loader, init_model, init_random_seed # 先加载数据 # init random seed init_random_seed(params.manual_seed) # load dataset加载数据 # src_data_loader = get_data_loader(params.src_dataset) # src_data_loader_eval = get_data_loader(params.src_dataset, train=False) # tgt_data_loader = get_data_loader(params.tgt_dataset) # tgt_data_loader_eval = get_data_loader(params.tgt_dataset, train=False) src_data_loader, src_data_loader_eval = get_source_data_loader() tgt_data_loader, tgt_data_loader_eval = get_target_data_loader() print(len(tgt_data_loader), len(tgt_data_loader.dataset)) # 加载各模型 # load models src_encoder = init_model(net=LeNetEncoder(), restore=params.src_encoder_restore) src_classifier = init_model(net=LeNetRegressor(), restore=params.src_classifier_restore) tgt_encoder = init_model(net=LeNetEncoder(), restore=params.tgt_encoder_restore) critic = init_model(Discriminator(input_dims=params.d_input_dims, hidden_dims=params.d_hidden_dims, output_dims=params.d_output_dims), restore=params.d_model_restore) # 训练源域回归器和源域映射器(也称编码器) # train source model print("=== Training classifier for source domain ===") print(">>> Source Encoder <<<") print(src_encoder) print(">>> Source Classifier <<<") print(src_classifier) if not (src_encoder.restored and src_classifier.restored and params.src_model_trained): # 如果都没有存储,意为都没有开始训练,所以先训练源域的分类器和编码器 src_encoder, src_classifier = train_src( src_encoder, src_classifier, src_data_loader) # eval source model 对源域的两个模型做测评 print("=== Evaluating classifier for source domain ===") eval_src(src_encoder, src_classifier, src_data_loader_eval) # 进行对抗生成部分的训练 # 输出的是经过GAN思想训练后的目标域编码器 # train target encoder by GAN print("=== Training encoder for target domain ===") print(">>> Target Encoder <<<") print(tgt_encoder) print(">>> Critic <<<") print(critic) # init weights of target encoder with those of source encoder 源域编码器和目标域编码器共用参数 # 如果目标域分类器没训练,就加载已训练的源域分类器的参数到未训练的目标域分类器 if not tgt_encoder.restored: tgt_encoder.load_state_dict(src_encoder.state_dict()) if not (tgt_encoder.restored and critic.restored and # 如果目标域编码器、域分类器都没训练,就开始训练 params.tgt_model_trained): tgt_encoder = train_tgt(src_encoder, tgt_encoder, critic, src_data_loader, tgt_data_loader) # 测试经过GAN思想训练后的目标域编码器对目标域数据的效果 # eval target encoder on test set of target dataset print("=== Evaluating classifier for encoded target domain ===") print(">>> source encoder only <<<") eval_tgt(src_encoder, src_classifier, tgt_data_loader_eval) # print(">>> domain adaption with train data of target area<<<") # eval_tgt(tgt_encoder, src_classifier, tgt_data_loader) print(">>> domain adaption with valid data of target area<<<") eval_tgt(tgt_encoder, src_classifier, tgt_data_loader_eval) from utils import make_variable print(len(tgt_data_loader_eval.dataset)) predict = [] for (x,y) in tgt_data_loader_eval: x = make_variable(x, volatile=True) # 为True表示不需要反向传播 a = src_classifier(tgt_encoder(x)).cuda().data.cpu().numpy() #预测值 # print(a) b = y.numpy() #真实值 # print(b) predict.extend(np.concatenate([np.array(a),np.array(b)],axis=1)) pd.DataFrame(predict).to_csv('res_0419_3.csv',index=False,header=None)<file_sep>/my-adda.py #!/usr/bin/env python # coding: utf-8 # In[ ]: # """Params for ADDA.""" # # params for dataset and data loader # data_root = "data" # dataset_mean_value = 0.5 # dataset_std_value = 0.5 # dataset_mean = (dataset_mean_value, dataset_mean_value, dataset_mean_value) # dataset_std = (dataset_std_value, dataset_std_value, dataset_std_value) # batch_size = 50 # image_size = 64 # # params for source dataset 源域数据 # src_dataset = "MNIST" # src_encoder_restore = "snapshots/ADDA-source-encoder-final.pt" # src_classifier_restore = "snapshots/ADDA-source-classifier-final.pt" # src_model_trained = True # # params for target dataset 目标域数据 # tgt_dataset = "USPS" # tgt_encoder_restore = "snapshots/ADDA-target-encoder-final.pt" # tgt_model_trained = True # # params for setting up models # model_root = "snapshots" # d_input_dims = 500 # d_hidden_dims = 500 # d_output_dims = 2 # d_model_restore = "snapshots/ADDA-critic-final.pt" # # params for training network # num_gpu = 1 # num_epochs_pre = 100 # log_step_pre = 20 # eval_step_pre = 20 # save_step_pre = 100 # num_epochs = 2000 # log_step = 100 # save_step = 100 # manual_seed = None # # params for optimizing models # d_learning_rate = 1e-4 # c_learning_rate = 1e-4 # beta1 = 0.5 # beta2 = 0.9 # 主程序 # In[1]: import params from core import eval_src, eval_tgt, train_src, train_tgt from models import Discriminator, LeNetRegressor, LeNetEncoder from utils import get_data_loader, init_model, init_random_seed # 先加载数据 # In[2]: # init random seed init_random_seed(params.manual_seed) # load dataset加载数据 # src_data_loader = get_data_loader(params.src_dataset) # src_data_loader_eval = get_data_loader(params.src_dataset, train=False) # tgt_data_loader = get_data_loader(params.tgt_dataset) # tgt_data_loader_eval = get_data_loader(params.tgt_dataset, train=False) src_data_loader, tgt_data_loader = get_data_loader() src_data_loader_eval, tgt_data_loader_eval = get_data_loader() # 加载各模型 # In[3]: # load models src_encoder = init_model(net=LeNetEncoder(), restore=params.src_encoder_restore) src_classifier = init_model(net=LeNetRegressor(), restore=params.src_classifier_restore) tgt_encoder = init_model(net=LeNetEncoder(), restore=params.tgt_encoder_restore) critic = init_model(Discriminator(input_dims=params.d_input_dims, hidden_dims=params.d_hidden_dims, output_dims=params.d_output_dims), restore=params.d_model_restore) # 训练源域回归器 # In[4]: # train source model print("=== Training classifier for source domain ===") print(">>> Source Encoder <<<") print(src_encoder) print(">>> Source Classifier <<<") print(src_classifier) if not (src_encoder.restored and src_classifier.restored and params.src_model_trained): #如果都没有存储,意为都没有开始训练,所以先训练源域的分类器和编码器 src_encoder, src_classifier = train_src( src_encoder, src_classifier, src_data_loader) # eval source model 对源域的两个模型做测评 print("=== Evaluating classifier for source domain ===") eval_src(src_encoder, src_classifier, src_data_loader_eval) # 进行对抗生成部分的训练 # # 输出的是经过GAN思想训练后的目标域编码器 # In[ ]: # train target encoder by GAN print("=== Training encoder for target domain ===") print(">>> Target Encoder <<<") print(tgt_encoder) print(">>> Critic <<<") print(critic) # In[ ]: # init weights of target encoder with those of source encoder 共用参数 #如果目标域分类器没训练,就加载已训练的源域分类器的参数到未训练的目标域分类器 if not tgt_encoder.restored: tgt_encoder.load_state_dict(src_encoder.state_dict()) if not (tgt_encoder.restored and critic.restored and #如果目标域编码器、域分类器都没训练,就开始训练 params.tgt_model_trained): tgt_encoder = train_tgt(src_encoder, tgt_encoder, critic, src_data_loader, tgt_data_loader) # 测试经过GAN思想训练后的目标域编码器对目标域数据的效果 # In[ ]: # eval target encoder on test set of target dataset print("=== Evaluating classifier for encoded target domain ===") print(">>> source data only <<<") eval_tgt(src_encoder, src_classifier, tgt_data_loader_eval) print(">>> domain adaption <<<") eval_tgt(tgt_encoder, src_classifier, tgt_data_loader_eval) # In[40]: import torch test_data = torch.FloatTensor(2,3) # 保存数据 torch.save(test_data, "test_data.pkl") print(test_data) # 提取数据 print(torch.load("test_data.pkl")) # In[ ]:
a9614aff17edc11d2d7977cc47f9a8b379966091
[ "Markdown", "Python" ]
11
Python
SuccessMary/graduation
0c63d21386442b4b4a1c10e7ddf91da73f723ce8
083c58515d319497d953d258320b2f3ab23ae644
refs/heads/master
<repo_name>Arun18297/Java-QSP-Files<file_sep>/qsp/HandlingDropDownMultiple.java package qsp; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; public class HandlingDropDownMultiple { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); WebDriver driver=new ChromeDriver(); //driver.manage().window().maximize(); driver.get("file:///D:/HTML/multidropdown.html"); Thread.sleep(2000); WebElement ddAddr = driver.findElement(By.id("SGH")); Select sel = new Select(ddAddr); if(sel.isMultiple()) { System.out.println("It is a Multi-Select Dropdown"); } else { System.out.println("It is a Single-Select DropDown"); } sel.selectByVisibleText("DOSA"); List<WebElement> allOptions = sel.getOptions(); // for(int i=0; i<=allOptions.size()-1; i++) // { // System.out.println(allOptions.get(i).getText()); // } // for(int i=0; i<=allOptions.size()-1; i++) // { // sel.selectByIndex(i); // Thread.sleep(1000); // } //Thread.sleep(3000); //sel.deselectByVisibleText("DOSA"); //sel.deselectByValue("dosa"); //sel.deselectByIndex(2); //sel.deselectAll(); for(int i=1; i<=4; i++) { sel.selectByIndex(i); } System.out.println(sel.getFirstSelectedOption().getText()); System.out.println(sel.getAllSelectedOptions().size()); System.out.println(sel.getWrappedElement().getText()); } } <file_sep>/qsp/ActiTIMELoginTest.java package qsp; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class ActiTIMELoginTest { public static void main(String[] args) throws InterruptedException { //Set the Property System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); //Open the Browser WebDriver driver=new ChromeDriver(); //Maximize the Browser Window driver.manage().window().maximize(); //Enter the Test URL driver.get("https://demo.actitime.com/login.do"); Thread.sleep(2000); //Verify the Login is page is Displayed String expectedTitle="actiTIME - Login"; String actualTitle = driver.getTitle(); System.out.println("Actual Title : "+actualTitle); if(actualTitle.equals(expectedTitle)) { System.out.println("Login Page is displayed, Pass"); } else { System.out.println("Login Page is not Displayed, Fail"); } Thread.sleep(2000); //Enter Valid Username in Username TextBox driver.findElement(By.xpath("//input[@id='username']")).sendKeys("admin"); Thread.sleep(2000); //Enter the Password in Password TextBox driver.findElement(By.name("pwd")).sendKeys("<PASSWORD>"); Thread.sleep(2000); //Click on Login Button driver.findElement(By.xpath("//div[text()='Login ']")).click(); Thread.sleep(2000); //Verify the Home Page is Displayed String expectedHomeTitle ="actiTIME - Enter Time-Track"; String actualHomeTitle = driver.getTitle(); System.out.println("Actual Home Title : "+actualHomeTitle); if(actualHomeTitle.equals(expectedHomeTitle)) { System.out.println("Home Page is Displayed, Pass"); } else { System.out.println("Home Page is not Displayed, Fail"); } } } <file_sep>/qsp/WebDriverInterfaceMethods.java package qsp; import org.openqa.selenium.Dimension; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class WebDriverInterfaceMethods { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.google.com/"); // String pageUrl = driver.getCurrentUrl(); // System.out.println(pageUrl); // String srcCode = driver.getPageSource(); // System.out.println(srcCode); String title = driver.getTitle(); // System.out.println(title); /* if(title.equals("Google")) { System.out.println("Google page is displayed, PASS"); } else { System.out.println("Google page is not displayed, FAIL"); } */ /* String pageUrl = driver.getCurrentUrl(); if(pageUrl.equals("https://www.monsterindia.com/")) { System.out.println("Monster India is Displayed, PASS"); } else { System.out.println("Monster India is not Displayed, FAIL"); } */ /* String srcCode = driver.getPageSource(); if(srcCode.contains("Gmail")) { System.out.println("Gmail is present on Google, PASS"); } else { System.out.println("Gmail is not Present on Google, FAIL"); } */ // driver.manage().window().maximize(); /* Thread.sleep(3000); Dimension d = new Dimension(200,300); driver.manage().window().setSize(d); Thread.sleep(3000); Point p = new Point(500,400); driver.manage().window().setPosition(p); */ driver.navigate().to("https://www.instagram.com/"); Thread.sleep(2000); driver.navigate().back(); Thread.sleep(2000); driver.navigate().forward(); Thread.sleep(2000); driver.navigate().refresh(); } } <file_sep>/qsp/TataCliq.java package qsp; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class TataCliq { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver1.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.tatacliq.com/"); Thread.sleep(2000); driver.findElement(By.xpath("//button[text()='Ask me later']")).click(); Thread.sleep(2000); //driver.findElement(By.xpath("//span[text()='Login/ Register']")).click(); Actions ac = new Actions(driver); WebElement Login/Register = driver.findElement(By.xpath("//span[text()='Login/ Register']")); ac.moveToElement(Login/Register).perform(); } } <file_sep>/qsp/HandlingWebTable.java package qsp; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class HandlingWebTable { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("file:///D:/HTML/WebTable%201.html"); List<WebElement> alltrs = driver.findElements(By.tagName("tr")); System.out.println("Total rows on WebPage :"+alltrs.size()); WebElement table2 = driver.findElement(By.id("t2")); List<WebElement> table2Rows = table2.findElements(By.tagName("tr")); System.out.println("Table 2 rows :"+table2Rows.size()); } } <file_sep>/qsp/YoutubeTest.java package qsp; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class YoutubeTest { public static void main(String[] args) throws InterruptedException { //Set the Property System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); //Open the Browser WebDriver driver=new ChromeDriver(); //Maximize the Browser Window driver.manage().window().maximize(); //Enter the Test URL driver.get("https://www.youtube.com/"); Thread.sleep(10000); String expectedTitle = "YouTube"; String actualTitle = driver.getTitle(); System.out.println("Actual Title : "+actualTitle); //Verify Home Page is Displayed if(actualTitle.equals(expectedTitle)) { System.out.println("Home Page is Displayed, Pass"); } else { System.out.println("Home Page is not Displayed, Fail"); } Thread.sleep(2000); //Enter the Valid Song Name in Search TextBox driver.findElement(By.xpath("//input[@id='search']")).sendKeys("butta bomma song"); Thread.sleep(2000); //Click on Search Button driver.findElement(By.xpath("//button[@id='search-icon-legacy']")).click(); Thread.sleep(2000); driver.findElement(By.xpath("//yt-formatted-string[text()='#AlaVaikunthapurramuloo - ButtaBomma Full Video Song (4K) | <NAME> | Thaman S | Armaan Malik']/ancestor::div[@id='dismissible']")).click(); //Play the Video in Full-Screen Mode Thread.sleep(2000); driver.findElement(By.xpath("//button[@class='ytp-fullscreen-button ytp-button']")).click(); String exptdTitle="Skip Ads"; String actlTitle = driver.getTitle(); if(actlTitle.equals(exptdTitle)) { System.out.println("Click on Skip Button"); } // else // { // System.out.println("Wait until Add is closed"); // } driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); driver.findElement(By.xpath("//div[text()='Skip Ads']")).click(); } } <file_sep>/qsp/InspectionMethodsWithLocators.java package qsp; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class InspectionMethodsWithLocators { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); WebDriver driver=new ChromeDriver(); // driver.manage().window().maximize(); // driver.get("file:///D:/HTML/link.html"); //on the webpage find the element whose tagname is 'a' // WebElement linkAddress=driver.findElement(By.tagName("a")); //on the address perform click button // linkAddress.click(); //on the webpage find the element whose id is 'i1' and click on address // driver.findElement(By.id("i1")).click(); // driver.findElement(By.name("n1")).click(); // driver.findElement(By.className("c1")).click(); // driver.findElement(By.linkText("Facebook")).click(); // driver.findElement(By.partialLinkText("Fa")).click(); // driver.findElement(By.cssSelector("a[title='t1']")).click(); driver.get("https://www.google.com/"); driver.findElement(By.xpath("//input[@name='q']")).sendKeys("<NAME>"); } } <file_sep>/qsp/FacebookLoginTest.java package qsp; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class FacebookLoginTest { public static void main(String[] args) throws InterruptedException { //Set the Property System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver1.exe"); //Open the Browser WebDriver driver=new ChromeDriver(); //Maximize the Browser Window driver.manage().window().maximize(); //Enter the Test URL driver.get("https://www.facebook.com/"); //Verify the Login Page is Displayed /* String expectedTitle ="Facebook – log in or sign up"; String actualTitle = driver.getTitle(); System.out.println("Actual Title : "+actualTitle); if(actualTitle.equals(expectedTitle)) { System.out.println("Login page is Displayed,Pass"); } else { System.out.println("Login Page is not Displayed,Fail"); } */ Thread.sleep(3000); //Enter the Valid Username in Username TextBox driver.findElement(By.id("email")).sendKeys("<PASSWORD>"); Thread.sleep(3000); //Enter valid Password in password TextBox driver.findElement(By.name("pass")).sendKeys("<PASSWORD>"); Thread.sleep(3000); //Click on Login Button driver.findElement(By.xpath("//button[text()='Log In']")).click(); //driver.findElement(By.xpath("//div[@class='_6ltg']")).click(); //Verify Home Page is Displayed String expectedHomeTitle = "Facebook – log in or sign up"; String actualHomeTitle = driver.getTitle(); System.out.println("Actual Home Title : "+actualHomeTitle); if(actualHomeTitle.equals(expectedHomeTitle)) { System.out.println("Home Page is Displayed, Pass"); } else { System.out.println("Home Page is not Displayed, Fail"); } } } <file_sep>/qsp/HandlingDisabledElement.java package qsp; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class HandlingDisabledElement { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); WebDriver driver=new ChromeDriver(); //driver.manage().window().maximize(); driver.get("file:///D:/HTML/DisabledElement.html"); Thread.sleep(2000); driver.findElement(By.id("i1")).sendKeys("admin"); Thread.sleep(2000); WebElement pwtb = driver.findElement(By.id("i2")); if(pwtb.isEnabled()) { System.out.println("Password textbox is enabled, Handle Normally"); pwtb.sendKeys("<PASSWORD>"); } else { System.out.println("Password textbox is Disabled, Handle through JS"); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("document.getElementById('i2').value=\"manager\""); } } } <file_sep>/qsp/FlipkartTest.java package qsp; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class FlipkartTest { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); //Open the Browser WebDriver driver=new ChromeDriver(); //Maximize the Window driver.manage().window().maximize(); //Enter the Test URL driver.get("https://www.flipkart.com/"); //Give the ImplicitlyWait time driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.findElement(By.xpath("//button[@class='_2KpZ6l _2doB4z']")).click(); driver.findElement(By.xpath("//span[text()='Cart']")).click(); // Thread.sleep(2000); // driver.findElement(By.xpath("//span[text()='Login']")).click(); WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text()='Login']"))); driver.findElement(By.xpath("//span[text()='Login']")).click(); } } <file_sep>/qsp/HandlingMultipleElements.java package qsp; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class HandlingMultipleElements { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("file:///D:/HTML/MultipleElements.html"); List<WebElement> allLinksAddr = driver.findElements(By.tagName("a")); //Count the number of Links int noOfLinks=allLinksAddr.size(); System.out.println("No of Links : "+noOfLinks); //Print the text of all Links for(int i=0; i<=allLinksAddr.size()-1; i++) // oneLinkAddress=allLinksAddr.get(i); // String text = oneLinkAddress.getTagName(); // System.out.println(text); // Or System.out.println(allLinksAddr.get(i).getText()); //Click on last Link allLinksAddr.get(allLinksAddr.size()-1).click(); } } <file_sep>/qsp/HandlingLoveStory.java package qsp; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import com.google.common.io.Files; public class HandlingLoveStory { public static void main(String[] args) throws InterruptedException, AWTException, IOException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver1.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://in.bookmyshow.com/"); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.findElement(By.xpath("//button[text()='Not Now']")).click(); driver.findElement(By.xpath("//img[@alt='HYD']")).click(); WebElement mv = driver.findElement(By.xpath("//span[@id=\"4\"]")); mv.click(); Thread.sleep(2000); //mv.sendKeys("Love Story (Telugu)"); driver.findElement(By.xpath("//input[@class='sc-bqjOQT bEsook']")).sendKeys("Love Story"); Thread.sleep(2000); // Robot r=new Robot(); // r.keyPress(KeyEvent.VK_ENTER); // r.keyRelease(KeyEvent.VK_ENTER); driver.findElement(By.xpath("//div[@class='sc-gleUXh dbWdWs']//strong[text()='Love Story']/ancestor::span[text()=' (Telugu)']")).click(); Thread.sleep(2000); //Capturing director Photo WebElement writer = driver.findElement(By.xpath("//h5[text()='<NAME>']/ancestor::a[@class='styles__CircularItemLink-sc-17p4id8-0 ggVMyG']/descendant::img[@class='style__Image-sc-eykeme-1 dWIxSp']")); Thread.sleep(10000); //TakesScreenshot t = (TakesScreenshot)driver; File src = writer.getScreenshotAs(OutputType.FILE); Thread.sleep(2000); File des = new File("D:\\HTML\\ScreenShot\\picture.jpg"); Files.copy(src, des); Thread.sleep(2000); // Print the reviews Text driver.findElement(By.xpath("//span[text()='31.7K reviews']")).click(); Thread.sleep(3000); List<WebElement> txt = driver.findElements(By.xpath("//div[@class='style__ReviewWrapper-sc-r6zm4d-1 hFVfWf']")); System.out.println("No of links :"+txt.size()); Thread.sleep(2000); for(int i=0; i<=txt.size()-1; i++) { System.out.println(txt.get(i).getText()); System.out.println(" "); } Thread.sleep(2000); // Watch the First Trailer driver.navigate().to("https://in.bookmyshow.com/hyderabad/movies/love-story/ET00124288/user-reviews"); Thread.sleep(2000); driver.navigate().back(); Thread.sleep(2000); driver.findElement(By.xpath("//div[@class='styles__SVGFrame-sc-xta4k3-0 bxWgHp']")).click(); Thread.sleep(5000); driver.findElement(By.xpath("//img[@class='style__Image-sc-eykeme-1 dWIxSp']/ancestor::div[@id='WZUH2QTB-yw']")).click(); } } <file_sep>/qsp/ScrollingDownWebpage.java package qsp; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Point; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.remote.RemoteWebDriver; public class ScrollingDownWebpage { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe"); //Upcasting From ChromeDriver to WebDriver Interface WebDriver driver=new ChromeDriver(); //driver.manage().window().maximize(); driver.get("https://www.selenium.dev/downloads/"); Thread.sleep(2000); // //Thru TypeCasting // JavascriptExecutor js = (JavascriptExecutor)driver; // js.executeScript("window.scrollBy(0,1000)"); // //Thru DownCasting // RemoteWebDriver rwd = (RemoteWebDriver)driver; // rwd.executeScript("window.scrollBy(0,1000)"); WebElement selSpons = driver.findElement(By.xpath("//h2[text()='Selenium Level Sponsors']")); Point loc = selSpons.getLocation(); System.out.println(loc); JavascriptExecutor j = (JavascriptExecutor)driver; j.executeScript("window.scrollBy"+loc); } }
4b13f6995a8bc23c54e162ad7a1165725a6d0c5d
[ "Java" ]
13
Java
Arun18297/Java-QSP-Files
d21f56a23b14c1e7792fc5db29ec4bcfd36f7394
e6443580e9ae28b9574d6677408e419fcb356051
refs/heads/master
<file_sep>;(function(factory){ factory(jQuery); })(function($){ var KenBurns = (function(element, settings){ var instanceUid = 0; var timerId; function _KenBurns(element, settings){ this.defaults = {}; this.settings = $.extend({},this,this.defaults,settings); this.$el = $(element); this.instanceUid = instanceUid++; } return _KenBurns; })(); KenBurns.prototype.start = function(){ var _this = this; _this.update(); this.timerId = setInterval(function(){ _this.update(); }, 5000) } KenBurns.prototype.stop = function(){ clearInterval(this.timerId); } KenBurns.prototype.update = function(){ var panel = this.$el; var slides = panel.find('.ken-burns-image-slide'); var index = slides.index('.active'); if(index < slides.length){ index++; }else{ index = 0; } slides.filter('.active').removeClass('active'); $(slides.get(index)).addClass('active').find('.ken-burns-image').addClass('zoomed'); window.setTimeout(function(){ panel.find('.ken-burns-image-slide').not('.active').find('.ken-burns-image').removeClass('zoomed'); }, 1000); } var methods = { init : function(options) { this.KenBurns = new KenBurns(this, options); }, start : function( ) { this.KenBurns.start(); }, stop : function( ) { this.KenBurns.stop(); } }; $.fn.KenBurns = function(methodOrOptions){ return this.each(function(index,el){ // el.data // el.KenBurns = new KenBurns(el,options); if ( methods[methodOrOptions] ) { return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) { // Default to "init" return methods.init.apply( el, arguments ); } else { $.error( 'Method ' + methodOrOptions + ' does not exist on jQuery.tooltip' ); } }); } });<file_sep>var express = require('express'); var router = express.Router(); router.param('workTitle', function(req, res, next, workTitle) { // sample user, would actually fetch from DB, etc... req.workTitle = workTitle next(); }); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); router.get('/works/:workTitle', function(req, res, next) { res.render('index', { title: req.workTitle, partials: { threads: getPartialPath(req.workTitle, 'threads'), digitalTurbine: getPartialPath(req.workTitle, 'digital-turbine'), xyo: getPartialPath(req.workTitle, 'xyo'), archive: getPartialPath(req.workTitle, 'archive'), } }); }); router.get('/partial/:workTitle', function(req, res, next) { res.render(req.workTitle, { title: req.workTitle }); }); function getPartialPath(workTitle, partial){ if(workTitle == partial){ return workTitle; }else{ return null; } } module.exports = router; <file_sep>var canvas; var context; var proton; var renderer; var emitter; var stats; var _mousedown = false; var mouseObj; var attractionBehaviour, crossZoneBehaviour; var state = 2; var count = 50; var zoneRadius = 300; var lowThreshold = 0.2; var highThreshold = 0.65; function setupProton(){ canvas = document.getElementById("particles"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; context = canvas.getContext('2d'); // context.globalCompositeOperation = "overlay"; createProton(); createRenderer(); tick(); canvas.addEventListener('mousedown', mousedownHandler, false); canvas.addEventListener('mouseup', mouseupHandler, false); canvas.addEventListener('mousemove', mousemoveHandler, false); window.onresize = function(e) { canvas.width = window.innerWidth; canvas.height = window.innerHeight; crossZoneBehaviour.reset(new Proton.RectZone(0, 0, canvas.width, canvas.height), 'cross'); } } function mousedownHandler(e) { _mousedown = true; // attractionBehaviour.reset(mouseObj, 200, 2000); mousemoveHandler(e); state++; state = state%3; console.log(state) } function mousemoveHandler(e) { if (_mousedown) { } var _x, _y; if (e.layerX || e.layerX == 0) { _x = e.layerX; _y = e.layerY; } else if (e.offsetX || e.offsetX == 0) { _x = e.offsetX; _y = e.offsetY; } mouseObj.x = _x; mouseObj.y = _y; } function mouseupHandler(e) { _mousedown = false; // attractionBehaviour.reset(mouseObj, -100, 200); } function createProton() { proton = new Proton; emitter = new Proton.Emitter(); // emitter.damping = 0.2; // emitter.rate = new Proton.Rate(new Proton.Span(1, 1), 0.1); emitter.rate = new Proton.Rate(count) emitter.addInitialize(new Proton.Mass(new Proton.Span(1, 5))); emitter.addInitialize(new Proton.Radius(new Proton.Span(2, 1))); // emitter.addInitialize(new Proton.Life(1, 3)); // emitter.addInitialize(new Proton.Velocity(new Proton.Span(20, 30), 0, 'polar')); // emitter.addInitialize(new Proton.Position(new Proton.RectZone(0, 0, canvas.width, canvas.height))); emitter.addInitialize(new Proton.Position(new Proton.CircleZone(canvas.width / 2, canvas.height / 2, 100))); mouseObj = { x : 1003 / 2, y : 610 / 2 }; attractionBehaviour = new Proton.Attraction(mouseObj, 0.01, 900); window.setInterval(function(){ attractionBehaviour.reset({x:Math.floor(Math.random()*canvas.width), y:Math.floor(Math.random()*canvas.width)}, 0.01, 900); }, 5000); crossZoneBehaviour = new Proton.CrossZone(new Proton.RectZone(0, 0, canvas.width, canvas.height), 'cross'); emitter.addBehaviour(new Proton.Color('57F39C')); emitter.addBehaviour(new Proton.Alpha(new Proton.Span(0.2, 0.5),0)); // emitter.addBehaviour(new Proton.RandomDrift(0.01, 0.01, 1)); // emitter.addBehaviour(attractionBehaviour); emitter.addBehaviour({ initialize : function(particle) { particle.initialRadius = particle.radius; particle.theta = Math.random()*Math.PI*2; // particle.speed = Math.random()*1000; }, applyBehaviour : function(particle, time, index) { // particle.a.y += (0.2*(Math.sin((Date.now()-(particle.p.x*10))/2000)))*0.5; // console.log(particle) // particle.theta += Math.PI/(4000+particle.speed); // if(state == 0){0 // if(particle.radius > 2){ // particle.radius = particle.radius*0.9; // } // }else if(state == 1){ // if(particle.radius < particle.initialRadius){ // particle.radius = particle.radius*1.1; // } // } if(state == 0){ //Ring particle.targetx = (canvas.width/2) + Math.cos(particle.theta)*300; particle.targety = (canvas.height/2) + Math.sin(particle.theta)*300; accelerateToTarget(particle) }else if(state == 1){ //Grid particle.targetx = (index%Math.sqrt(count))*(canvas.width/(count/Math.sqrt(count))); particle.targety = (Math.floor(index/Math.sqrt(count))*(canvas.height/(count/Math.sqrt(count)))); accelerateToTarget(particle) }else if(state == 2){ //Flocking for(var i=0; i<emitter.particles.length; i++){ var particle2 = emitter.particles[i]; if(particle2!=particle){ flockingReact(particle, particle2); } } // particle.targetx = canvas.width/2; // particle.targety = canvas.height/2; } // console.log(particle.a) // console.log(particle.a,"foo") particle.v.add(particle.a); particle.v.multiplyScalar(0.9); if(particle.v.length() > 10){ particle.v.setLength(10); }else if(particle.v.length < 0.1){ particle.v.setLength(0.1); } particle.p.add(particle.v); particle.a.x = 0; particle.a.y = 0; } }); emitter.addBehaviour(crossZoneBehaviour); emitter.emit('once'); proton.addEmitter(emitter); console.log(emitter); } function flockingReact(p1, p2){ var target = new Proton.Vector2D(p2.p.x, p2.p.y); var dir = p1.p.clone().sub(target); dir.normalize(); var distSqrd = p1.p.distanceToSquared(target); var zoneRadiusSqrd = zoneRadius*zoneRadius; // console.log(distSqrd, zoneRadiusSqrd, p1.p) if(distSqrd <= zoneRadiusSqrd){ var percent = distSqrd/zoneRadiusSqrd; if(percent<lowThreshold){ //if within the low threshold, separate the particles var force = (zoneRadiusSqrd/distSqrd - 1) * 0.003; dir = dir.normalize()//.multiplyScalar(force); // console.log('low', dir, force) p1.a = p1.a.add(dir.multiplyScalar(force)); p2.a = p2.a.sub(dir.multiplyScalar(force)); }else if(percent < highThreshold){ //if within the high threshold, align var thresholdDelta = 1-lowThreshold; var adjustedPercent = (percent-lowThreshold)/thresholdDelta; var force = (1-(Math.cos(adjustedPercent * Math.PI*2)* -0.5 +0.5 ) ) * 0.05; dir = dir.normalize()//.multiplyScalar(force); // console.log('mid', dir) p1.a = p1.a.add(dir.multiplyScalar(force)); p2.a = p2.a.sub(dir.multiplyScalar(force)); }else{ //otherwise, attract var thresholdDelta = 1-highThreshold; var adjustedPercent = (percent-highThreshold)/thresholdDelta; var force = (1-(Math.cos(adjustedPercent * Math.PI*2)* -0.5 +0.5 ) ) * 0.5; dir = dir.normalize().multiplyScalar(force); // console.log('high', dir) p1.a = p1.a.add(dir.multiplyScalar(force)); p2.a = p2.a.sub(dir.multiplyScalar(force)); } } } function accelerateToTarget(particle){ var target = new Proton.Vector2D(particle.targetx, particle.targety); var direction = particle.p.clone().sub(target); direction.normalize(); //get dist squared var distSqrd = particle.p.distanceToSquared(target); //calculate force var force = distSqrd*1.2; particle.a = particle.a.sub(direction.multiplyScalar(force)); } function createRenderer() { renderer = new Proton.Renderer('canvas', proton, canvas); renderer.onProtonUpdate = function() { context.fillStyle = "rgba(255, 255, 255, 0.1)"; context.fillRect(0, 0, canvas.width, canvas.height); }; renderer.start(); } function tick() { requestAnimationFrame(tick); proton.update(); } function leave(){ crossZoneBehaviour.reset(new Proton.RectZone(0, 0, canvas.width, canvas.height), 'dead'); }<file_sep>var pageTransitions = false; // var isFirst = true; var lastPage = null; // function async(callback){ window.setTimeout(function(){ callback(); }, 0) } //Page Routes var routes = { onExit:function(context, next){ console.log('onExit'); pageTransitions = true; lastPage = context; context.foobar = "foobar"; // console.log('foo', context) next(); }, onHome:function(){ console.log('showing index page'); showHomepage(); }, onWork:function(context){ console.log('showing work page', context, lastPage); //If this is the first page, we won't need to load, the template should already contain the content. //This logic is all fucked up, I should abstract the transition types and handle w a single function call if(lastPage){ loadWorkDetailIfNeeded($('.work-container#'+context.params.workTitle), context.params.workTitle); //Check what kind of transition we need if(~lastPage.path.indexOf('works')){ console.log('last was a work page'); showSectionFromSection($('.work-container#'+context.params.workTitle), $('.work-container#'+lastPage.params.workTitle), pageTransitions); return; } } showSection($('.work-container#'+context.params.workTitle), pageTransitions); }, onContact:function(){ console.log('showing contact page') } } page.base(); page('/', routes.onHome); page('/works/:workTitle', routes.onWork); page('/contact', routes.onContact); page.exit('*', routes.onExit); page(); function showSection(section, animated){ var duration = 0; if(animated){ duration = 600; section.addClass('animated'); }else{ section.removeClass('animated'); } console.log(Math.min(duration, ($("body").scrollTop()-section.offset().top))) section.removeClass('hovered'); section.addClass('opening'); $("body").animate({ scrollTop: section.offset().top }, Math.min(duration, Math.abs(($("body").scrollTop()-section.offset().top))), 'swing', function(){ $('body').addClass('scrollLock'); console.log('open scroll', $('body').scrollTop(), $('#content-wrapper').height()) window.setTimeout(function(){ section.addClass('opened'); // section.find('.work-desc, .work-link-wrapper').css({'display':'none'}); if(section.find('.work-detail')){ section.find('.work-detail').addClass('showing'); } }, duration) }); } function showSectionFromSection(section, lastSection, animated){ //open the section, and move it off screen. //check if transition should be slide up or down console.log(section.data('index'), lastSection.data('index')) // var transition = 'slide-down' if(section.data('index') > lastSection.data('index')){ section.addClass('offset-down'); showSection(section, false); //delay a tick async(function(){ section.addClass('animated').removeClass('offset-down'); lastSection.addClass('animated offset-up'); //TODO Eugh, nested timeouts - find a better way of doing this window.setTimeout(function(){ //clean up closeSection(lastSection, false); section.removeClass('animated'); lastSection.removeClass('animated'); async(function(){ lastSection.removeClass('offset-up'); }) }, 400); }) }else{ section.addClass('offset-up'); showSection(section, false); //delay a tick async(function(){ section.addClass('animated').removeClass('offset-up'); lastSection.addClass('animated offset-down'); //TODO Eugh, nested timeouts - find a better way of doing this window.setTimeout(function(){ //clean up closeSection(lastSection, false); section.removeClass('animated'); lastSection.removeClass('animated'); async(function(){ lastSection.removeClass('offset-down'); }) }, 400); }) } } function showHomepage(){ if($('.work-container.opened').length == 0){ console.log('on the homepage'); $('body').removeClass('scrollLock'); }else{ $('.work-container.opened').each(function(){ console.log('foobar') closeSection($(this), true); }); } // setupProton(); } function closeSection(section, animated){ console.log('FUCK', section.attr('id')) var duration = 0; if(animated){ duration = 300; section.addClass('animated'); }else{ section.removeClass('animated'); } section.find('.work-detail').removeClass('showing'); // window.setTimeout(function(){ section.find('.work-desc, .work-link-wrapper').css({'display':'block'}); section.animate({ scrollTop: 0}, Math.min(duration, Math.abs(section.scrollTop())), 'linear', function(){ section.removeClass('opening'); section.removeClass('opened'); $("body").scrollTop(section.offset().top); //If all sections are closed, let the body scroll again if($('.opened, .opening').length == 0){ $('body').removeClass('scrollLock'); console.log($("body").scrollTop()) } }); } function loadWorkDetailIfNeeded(section, sectionName){ console.log(section.find('.work-detail')) if(!section.find('.work-detail').children().length > 0){ console.log('need to load work') section.find('.work-detail').load('partial/'+sectionName, function(){ console.log('section loaded'); // section.find('.work-detail').addClass('loaded'); }); } if(!section.find('.work-detail').hasClass('loaded')){ } } $(document).ready(function(){ $('.work-link').hover(function(){ hoverSection($('#'+$(this).data('section'))) }, function(){ unhoverSection($('#'+$(this).data('section'))) }); $('.fixed-scroll-panel').waypoint({ handler:function(direction){ var e = $(this.element); if(direction == 'down'){ e.find('.panel-fixed').addClass('fixed'); }else{ e.find('.panel-fixed').removeClass('fixed').removeClass('bottom').addClass('top'); } }, }); $('.fixed-scroll-panel').waypoint({ handler:function(direction){ var e = $(this.element); if(direction == 'down'){ e.find('.panel-fixed').removeClass('fixed').removeClass('top').addClass('bottom'); }else{ e.find('.panel-fixed').addClass('fixed'); } }, offset: 'bottom-in-view' }); $('.work-container').waypoint({ handler:function(direction){ console.log('top of work section', direction); var e = $(this.element); if(direction == 'down'){ e.addClass('in-view'); inviewPanelStart(e); }else{ e.removeClass('in-view'); inviewPanelEnd(e); } }, offset: '100%' }); $('.work-container').waypoint({ handler:function(direction){ console.log('bottom of work section', direction); var e = $(this.element); if(direction == 'down'){ e.removeClass('in-view'); inviewPanelEnd(e); }else{ e.addClass('in-view'); inviewPanelStart(e); } }, offset: '-150%' }); $('.ken-burns-panel').KenBurns(); }); function inviewPanelStart(panel){ panel.find('.ken-burns-panel').each(function(){ $(this).KenBurns('start'); }); } function inviewPanelEnd(panel){ panel.find('.ken-burns-panel').each(function(){ $(this).KenBurns('stop'); }); } function hoverSection(section){ section.addClass('hovered'); } function unhoverSection(section){ section.removeClass('hovered'); }
c26f0365aeed9692e68bd19425f4cc029c932e56
[ "JavaScript" ]
4
JavaScript
yMasukor/portfolio-2015
92c5b63573efba2b58f85dbe90b37d0280dff586
21fc6a1bfb613e2b51ebdeafc0ca00dad055fa1e
refs/heads/master
<repo_name>ZoomPoppy/Algorithm<file_sep>/src/com/zz/homework/Main.java package com.zz.homework; /** * Created by zz on 2016-08-02. */ public class Main { } <file_sep>/src/com/zz/homework/chapter_1/first/Main_1_1_3.java package com.zz.homework.chapter_1.first; /** * Created by zz on 2016-08-02. */ public class Main_1_1_3 { public static void main(String args[]){ int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); int c = Integer.parseInt(args[2]); if (a==b&&a==c){ System.out.println("equal"); }else { System.out.println("not equal"); } } } <file_sep>/src/com/zz/homework/chapter_1/first/Main_1_1_1.java package com.zz.homework.chapter_1.first; /** * Created by zz on 2016-08-02. */ public class Main_1_1_1 { public static void main(String args[]){ System.out.println((0+15)/2); System.out.println((2.0e-6 * 1000000000.1)); System.out.println((true && false || true && true)); } } <file_sep>/src/com/zz/homework/chapter_1/first/Main_1_1_13.java package com.zz.homework.chapter_1.first; /** * Created by zz on 2016-08-03. */ public class Main_1_1_13 { public static void main(String args[]){ int[][] matrix = randomIntMatrix(5, 5); } private static int[][] randomIntMatrix(int row, int column){ int[][] matrix = new int[row][column]; for (int i = 0; i < row; i++){ for (int j = 0; j < column; j++){ int random = (int) (Math.random()*100000); matrix[i][j] = random; } } return matrix; } } <file_sep>/README.md # Algorithm 记录算法习题,以及平常的面试算法题 ###算法 - 归并:自然,递归,非递归 - 插入:普通,希尔 - 选择 ###面试题 -网易有道面试题 <file_sep>/src/com/zz/homework/chapter_1/first/Main_1_1_5.java package com.zz.homework.chapter_1.first; /** * Created by zz on 2016-08-02. */ public class Main_1_1_5 { public static void main(String args[]){ double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); if (((x-1) > 0) && ((y-1) > 0)){ System.out.println("true"); }else System.out.println("false"); } } <file_sep>/src/com/zz/homework/chapter_2/practice/Main_2_2_14.java package com.zz.homework.chapter_2.practice; import java.util.LinkedList; import java.util.Queue; /** * 归并有序队列 * 将两个有序队列作为参数,返回一个归并后的有序队列 * Created by zz on 2016-08-20. */ public class Main_2_2_14 { public static void main(String args[]){ LinkedList<Integer> integers = new LinkedList<>(); LinkedList<Integer> integers1 = new LinkedList<>(); for (int i = 0; i < 5; i++){ integers.offer((int) (Math.random() * 10)); integers1.offer((int) (Math.random() * 10)); } Queue queue = mergeQueue(integers, integers1); print(queue); } public static void print(Queue a){ int N = a.size(); for (int i = 0; i < N; i++){ System.out.print(a.poll()); } System.out.println(""); } public static <T extends Comparable> Queue mergeQueue(Queue<T> a, Queue<T> b){ int N = a.size() + b.size(); Queue<T> outQueue = new LinkedList<T>(); for (int i = 0; i < N; i++){ if (a.isEmpty()) outQueue.offer(b.poll()); else if (b.isEmpty()) outQueue.offer(a.poll()); else outQueue.offer(getMinElement(a, b)); } return outQueue; } public static <T extends Comparable> T getMinElement(Queue<T> a, Queue<T> b) { if (a.peek().compareTo(b.peek()) == -1) return a.poll(); if (a.peek().compareTo(b.peek()) == 0) return a.poll(); else return b.poll(); } } <file_sep>/src/com/zz/homework/chapter_2/Example/Merge.java package com.zz.homework.chapter_2.Example; /** * Created by zz on 2016-08-16. */ public class Merge { //自顶向上 public static void sort(Comparable[] a, int lo, int hi) { if (hi <= lo) { return; } int mid = (hi - lo) / 2 + lo; sort(a, lo, mid); sort(a, mid + 1, hi); merge(a, lo, mid, hi); } //利用另外的一个数组来进行归并排序 public static void merge(Comparable[] a, int lo, int mid, int hi) { Comparable[] aux = new Comparable[a.length]; int j = mid + 1; int k = lo; for (int i = 0; i < a.length; i++) { aux[i] = a[i]; } for (int i = 0; i <= hi; i++) { if (k > mid) a[i] = aux[j++]; else if (j > hi) a[i] = aux[k++]; else if (less(aux[k], aux[j])) a[i] = aux[k++]; else a[i] = aux[j++]; } } public static boolean less(Comparable a, Comparable b) { return a.compareTo(b) == -1; } }
2d290e1dab97934f1baa9e6d3b55223aaf131dfb
[ "Markdown", "Java" ]
8
Java
ZoomPoppy/Algorithm
1267220f8d9841c91ba1788273a7d12e31c79de5
8fb49ae86ed562ac727e3bd54cf0b2ee58940d36
refs/heads/master
<repo_name>MaximUsss/FraudDetection<file_sep>/Model.py from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report from sklearn.model_selection import StratifiedShuffleSplit def buildModel(X, y): # Define the model model = LogisticRegression() # Define the splitter for splitting the data in a train set and a test set splitter = StratifiedShuffleSplit(n_splits=3, test_size=0.1, random_state=0) # Loop through the splits (only one) for train_index, test_index in splitter.split(X, y): # Select the train and test data X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] # Fit and predict! model.fit(X_train, y_train) y_pred = model.predict(X_test) # show the results print(classification_report(y_test, y_pred)) <file_sep>/DataProcessing.py from sklearn import preprocessing import pandas as pd from fraud_detection_model import buildModel import numpy as np # number of rows in data set # used for testing purposes # n = 1000 # data from kaggle IEEE-CIS Fraud Detection # https://www.kaggle.com/c/ieee-fraud-detection/data # Read the CSV file identity = pd.read_csv("J:/Study/ML/Siraj/Homework/Week 3/data/train_identity.csv") transaction = pd.read_csv("J:/Study/ML/Siraj/Homework/Week 3/data/train_transaction.csv",) test_identity = pd.read_csv("J:/Study/ML/Siraj/Homework/Week 3/data/test_identity.csv",) test_transaction = pd.read_csv("J:/Study/ML/Siraj/Homework/Week 3/data/test_transaction.csv") # let's combine the data and work with the whole dataset train = pd.merge(transaction, identity, on='TransactionID', how='left') test = pd.merge(test_transaction, test_identity, on='TransactionID', how='left') # define if there are columns with more than 90% nulls many_null_cols = [col for col in train.columns if train[col].isnull().sum() / train.shape[0] > 0.9] many_null_cols_test = [col for col in test.columns if test[col].isnull().sum() / test.shape[0] > 0.9] # define columns with only 1 value one_value_cols = [col for col in train.columns if train[col].nunique() <= 1] one_value_cols_test = [col for col in test.columns if test[col].nunique() <= 1] # define top value columns big_top_value_cols = [col for col in train.columns if train[col].value_counts(dropna=False, normalize=True).values[0] > 0.9] big_top_value_cols_test = [col for col in test.columns if test[col].value_counts(dropna=False, normalize=True).values[0] > 0.9] # merging useless columns in a list cols_to_drop = list(set(many_null_cols + many_null_cols_test + big_top_value_cols + big_top_value_cols_test + one_value_cols + one_value_cols_test)) cols_to_drop.remove('isFraud') # dropping useless columns train = train.drop(cols_to_drop, axis=1) test = test.drop(cols_to_drop, axis=1) # Drop missing values train.fillna(value=-99999, inplace=True) # converting the labels into numeric form with LabelEncoder class # so as to convert it into the machine-readable form cat_cols = ['id_12', 'id_13', 'id_14', 'id_15', 'id_16', 'id_17', 'id_18', 'id_19', 'id_20', 'id_21', 'id_22', 'id_23', 'id_24', 'id_25', 'id_26', 'id_27', 'id_28', 'id_29', 'id_30', 'id_31', 'id_32', 'id_33', 'id_34', 'id_35', 'id_36', 'id_37', 'id_38', 'DeviceType', 'DeviceInfo', 'ProductCD', 'card4', 'card6', 'M4', 'P_emaildomain', 'R_emaildomain', 'card1', 'card2', 'card3', 'card5', 'addr1', 'addr2', 'M1', 'M2', 'M3', 'M5', 'M6', 'M7', 'M8', 'M9', 'P_emaildomain_1', 'P_emaildomain_2', 'P_emaildomain_3', 'R_emaildomain_1', 'R_emaildomain_2', 'R_emaildomain_3'] for col in cat_cols: if col in train.columns: le = preprocessing.LabelEncoder() le.fit(list(train[col].astype(str).values) + list(test[col].astype(str).values)) train[col] = le.transform(list(train[col].astype(str).values)) test[col] = le.transform(list(test[col].astype(str).values)) X = train.sort_values('TransactionDT').drop(['isFraud', 'TransactionDT', 'TransactionID'], axis=1) y = train.sort_values('TransactionDT')['isFraud'] # looks like dataset is missing "isFraud" label in test data # X_test = test.sort_values('TransactionDT').drop(['isFraud', 'TransactionDT', 'TransactionID'], axis=1) # y_test = test.sort_values('TransactionDT')['isFraud'] # method from cleaning infinite values to NaN def clean_inf_nan(df): return df.replace([np.inf, -np.inf], np.nan) # Cleaning infinite values to NaN X = clean_inf_nan(X) # X_test = clean_inf_nan(X_test) # Scale the X so that everyone can have the same distribution # https://scikit-learn.org/stable/modules/preprocessing.html X = preprocessing.scale(X) # X_test = preprocessing.scale(X_test) buildModel(X, y)
eaafc8d642fb480cb4120e64050040b905f05c61
[ "Python" ]
2
Python
MaximUsss/FraudDetection
5d121bb0daa9b561bc91612a0a6912cb3b8680a4
d87cbf0882a5a1afee16275c975c88fa7e3d806d
refs/heads/master
<repo_name>dylanjohnsonsfo/messos-docker-compose<file_sep>/send_data.py #!/usr/bin/python -tt import socket import json import sys HOST = '172.16.17.32' PORT = 4560 def send_data(): try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(1) try: sock.connect((HOST, PORT)) except socket.error, msg: sys.stderr.write("[ERROR] %s\n" % msg[1]) sys.exit(2) count += 1 msg = {'@message': 'python test message', '@tags': ['python', 'test']} sock.send(json.dumps(msg)) sock.close() sys.exit(0) def main(): send_data() if __name__ == '__main__': main() <file_sep>/README.md # messos-docker-compose
322d7dcaf87ffc704dc5d60a997ee78097f68c10
[ "Markdown", "Python" ]
2
Python
dylanjohnsonsfo/messos-docker-compose
0a410b8559344f41be802325829bc8279b6c2b66
0035e28ffcd9d4ecf1a04a8bf834a8d832b98f5a
refs/heads/master
<file_sep>'use strict'; //document.ready $(() => { console.log('ready'); //var square_arr = $('.square'); //var row_arr=$('.row'); //console.log(square_arr); //colorSquares(square_arr); createBoard(); addPieces(); $('.piece').click(moveplayer); }); function createBoard() { let $rows = []; // fill it up for(let i = 0; i < 8; i++) { let $row = $('<div>').addClass('row'); // fill it with squares for(let j = 0; j < 8; j++) { let $square = $('<div>').addClass('square'); $row.append($square); if( (i+j) % 2 == 0 ) { $square.addClass('black'); } else { $square.addClass('white'); } } $rows.push($row); } $('.game').append($rows); } function addPieces(){ $('.white').each(function(i){ //console.log(this,i); if(i<12){ var $player1Piece = $('<div>').addClass('player1 piece'); $(this).append($player1Piece); } else if(i>19){ var $player2Piece = $('<div>').addClass('player2 piece'); $(this).append($player2Piece); } }) } function moveplayer(){ // selects the checker $(this).fadeOut("slow"); $(this).fadeIn("slow"); $('.black').click(event,blackClicked); move(); //console.log($(this).keyPre); } function move(){ $('piece').slideUp(); } function blackClicked(event){ if($h3.text()){ $h3.text(" "); } else { console.log("black clicked"); var $h3 =$('<h3>'); $h3.text("black squares are not allowed"); //console.log( $h3.text()); } $("body").append($h3); }
f6f254a9367fcb43a19bbd4adcf716ea5df91a0d
[ "JavaScript" ]
1
JavaScript
annzach/checkerBoard
832f0d9cd5735a3f5d7e3f2ed069d32969a0751a
1adbd30754f1c6102fdaddb9a027a2c21de855c7
refs/heads/master
<repo_name>aletheasimonett/curso-ruby-basico<file_sep>/blocks/blocks_times.rb 5.times {puts "Exec the block"} #irá executar 5x a frase<file_sep>/tipos-de-dados/challenge_one.rb print 'Digite seu nome: ' name = gets.chomp print 'Digite sua idade: ' age = gets.chomp puts "Ola #{name}, voce tem #{age} anos"<file_sep>/tipos-de-dados/entrada_saida_dados.rb #saida de dado print 'Digite seu nome: ' #recebendo uma entrada do teclado name = gets.chomp #saida utilizando puts #use codigo ruby dentro de uma string com #{code} puts "Ola #{name}!"<file_sep>/estruturas_de_dados/if.rb day = 'Sunday' if day == 'Sunday' #Se o dia é Domingo, então o almoço é especial lunch = 'special' end puts "Lunch is #{lunch} today"<file_sep>/estruturas_de_dados/for.rb #usado para percorrer uma coleção de elementos fruits = ['Maçã', 'Uva', 'Morango'] for fruit in fruits #percorrerá todos os elementos da lista fruits. Em cada interação, podemos acessar o elemento atual através da variaveis fruit puts fruit end<file_sep>/tipos-de-dados/challenge_two.rb print "Digite o primeiro número inteiro: " number1 = gets.chomp.to_i print "Digite o segundo numero inteiro: " number2 = gets.chomp.to_i sum = number1 + number2 subtraction = number1 - number2 multiplication = number1*number2 division = number1/number2 puts "Resultado soma: #{sum}" puts "Resultado subtração: #{subtraction}" puts "Resultado multiplicação: #{multiplication}" puts "Resultado divisão: #{division}"<file_sep>/tipos-de-dados/float.rb #Float é o tipo de variável que representa os números reais inexatos float_number = -20.05 puts float_number.class<file_sep>/tipos-de-dados/boolean.rb #Tipo de dado usado para informar a veracidade de algo. Possui apenas dois estados, true e false ruby_free_course = true puts ruby_free_course.class ruby_test = false puts ruby_test.class<file_sep>/estruturas_de_dados/if_elsif.rb day = 'Holiday' if day == 'Sunday' #Se o dia é Domingo, então o almoço é especial. lunch = 'special' elsif day == 'Holiday' #Senão e se o dia é feriado, então o almoço é tarde. lunch = 'later' else #Senão, o almoço é normal. lunch = 'normal' end puts "lunch is #{lunch} today"<file_sep>/blocks/blocks_do.rb foo = {2 => 3, 4 => 5} foo.each do |key, value| puts "key = #{key}" puts "value = #{value}" puts "key + value = #{key * value}" puts '---' end<file_sep>/poo/exemplos/pessoa.rb class Pessoa #quando for declarar uma classe, sempre deve começar com letra maiuscula def initialize(cont = 1) cont.times do |i| puts "Contando...#{i}" end end def falar(nome) #definindo o método falar "Olá, #{nome}!" end def falar2(texto="Olá, pessoal!") texto end def falar3(texto = "olá!", texto2 = "Hello!") "#{texto} - #{texto2}!" end end p1 = Pessoa.new puts p1.falar("Alethea") puts p1.falar2 puts p1.falar3("Palavra foi trocada") p2 = Pessoa.new(5)<file_sep>/poo/tipos_variaveis/local.rb def foo # Pode ser definida como local ou _local local = 'Local é acessada apenas dentro deste metodo' print local end foo puts local #como a variável só existe dentro do metodo foo, quando rodarmos, irá dar um erro, pois a variavel 'local' não está definida fora desse metodo<file_sep>/metodos_gems/challenge1.rb #Crie um programa que possua um método que resolva a potência dado um número base e seu expoente. Estes dois valores devem ser informados pelo usuário. print 'Base: ' base = gets.chomp.to_i print 'Expoente: ' expoente = gets.chomp.to_i def potencia (base, expoente) base ** expoente end result = potencia(base,expoente) puts "Potencia é #{result}"<file_sep>/poo/challenge/challenge.rb class Esportista def competir puts 'Participando de uma competicao' end end class JogadorDeFutebol < Esportista def correr puts 'Correndo atras da bola' end end class Maratonista < Esportista def correr puts 'Percorrendo o circuito' end end #jogador_de_futebol = JogadorDeFutebol.new #maratonista = Maratonista.new esportistas = [JogadorDeFutebol.new, Maratonista.new] esportistas.each do |esportista| esportista.competir esportista.correr end <file_sep>/blocks/blocks_parameter.rb def foo(numbers, &block) if block_given?<file_sep>/blocks/blocks_method.rb def foo #Call the block yield #executa um bloco que foi passado por parametro yield end foo do puts "Exec the block" end<file_sep>/poo/tipos_variaveis/inheritance.rb class Computer #o nome da classe sempre começa com class, o nome dela poderia ser qualquer um, exemplo: cachorro, carro e etc def turn_on 'turn on the computer' end def shutdown 'shutdown the computer' end end computer = Computer.new #'Computer.new' é o objeto da classe puts computer.shutdown<file_sep>/metodos_gems/method.rb #isso é um o método def talk (first_name, last_name) puts "olá #{first_name} #{last_name},como vocês está" end first_name = 'Alethea' last_name = 'Soares' #o que está dentro dos () são chamados de parâmetros talk(first_name, last_name) def signal (color) puts "O sinal está #{color}" end color = 'vermelho' signal(color)<file_sep>/poo/tipos_variaveis/instancia.rb class User #criado uma classe que possui um metodo chamado add e outro chamado hello def add(name) #adicionado o parametro 'name' ao metodo add @name = name puts "User adicionado" hello end def hello puts "Seja bem vindo, #{@name}!" end end user = User.new user.add('Joao')<file_sep>/collections/each_array.rb # O each percorre uma coleção de forma parecida com o for, porem, nao sobrescrevendo o valor de variaveis fora da estrutura de repeticao names = ['Joao', 'Manoela', 'Aurora'] name = 'Leonardo' names.each do |name| puts name end puts name<file_sep>/poo/tipos_variaveis/classe.rb class User @@user_count = 0 def add (name) puts "User #{name} adicionando" @@user_count += 1 puts @@user_count end end first_user = User.new first_user.add('Joao') second_user = User.new second_user.add('Mario')<file_sep>/tipos-de-dados/symbol.rb # símbolo é um tipo de dado semelhante a String, com a diferença de que ele é um objeto imutável # Duas strings idênticas podem ser objetos diferentes, mas um símbolo é apenas um objeto, ocupando sempre o mesmo espaço de memória example_symbol = :ruby_symbol puts example_symbol.object_id #.object_id informa a posição de memoria desse simbolo second_example_symbol = :ruby_symbol puts second_example_symbol.object_id #irá apontar para o mesmo endereço de e-mail que o example_symbol puts example_symbol.class #irá exibir o tipo de variavel<file_sep>/poo/exemplos/string.rb class String def inverter self.reverse #o self é o proprio objeto, que no caso, neste exemplo é o nome end end puts "Alethea".inverter<file_sep>/collections/hash.rb capitais = Hash.new #cria um hash vazio capitais = {acre: 'Rio Branco', sao_paulo: 'Sao Paulo'}#um hasg tambem pode ser iniciado com varios pares de chave-valor #chave de um hash pode ser qualquer tipo de dado hash = {1 => 'Chave do tipo inteiro', true => 'Chave do tipo booleano', [1, 2, 3] => 'Chave do tipo array'} capitais[:minas_gerais] = 'Belo Horizonte' #adiciona um novo item a hash capitais[:minas_gerias] #acessa a capital que acabamos de inserir capitais.keys #para retornar todas as chaves de um hash capitais.values #retorna todos os valores de um hash capitais.delete(:acre) #remova um elemento chave-valor capitais.size #descubre o tamanho do hash capitais.empty? #veriqua se o hash está vazio <file_sep>/poo/exemplos/accessors.rb class Pessoa attr_accessor :nome end p1 = Pessoa.new p1.nome = "Alethea" #setter puts p1.nome #getter<file_sep>/tipos-de-dados/arithmetic.rb print "Digite o primeiro número inteiro: " number1 = gets.chomp.to_i # .to_i transforma a string em um numero inteiro print "Digite o segundo numero inteiro: " number2 = gets.chomp.to_i addition = number1 + number2 puts "O resultado da adição entre os dois números é #{addition}"<file_sep>/tipos-de-dados/array.rb #Um tipo que nos permite armazenar uma lista ordenada de dados em um único objeto. array = [0, 1, 2] puts array[2] puts array.class<file_sep>/estruturas_de_dados/if_else.rb day = 'Saturday' if day == 'Sunday' #Se o dia é Domingo, então o almoço é especial lunch = 'special' else #Senão, o almoço é normal. lunch = 'normal' end puts "Lunch is #{lunch} today"<file_sep>/blocks/blocks_each.rb sum = 0 numbers = [5, 10, 5] numbers.each {|number| sum += number } puts sum<file_sep>/metodos_gems/challenge2.rb #Siga a documentação da Gem CPF_CNPJ para criar um programa que recebe como entrada um número de cpf e em um método verifique se este número é válido require 'cpf_cnpj' puts 'Informe seu cpf: ' numero_cpf = gets.chomp def verifica_cpf (numero_cpf) if CPF.valid?(numero_cpf) 'Numero de cpf valido!' else 'Numero de cpf invalido!' end end puts "#{verifica_cpf (numero_cpf)}" <file_sep>/tipos-de-dados/integer.rb #Intereger é o tipo de variável que representa os números inteiros, positivos e negativos, incluindo o zero integer_number = -20 puts integer_number.class #puts faz com que algum conteudo seja exibido na tela, e o .class diz qual o tipo da variavel<file_sep>/modulos/metodos/modulo/app.rb require_relative 'pagamento' include Pagamento::Master puts pagando<file_sep>/estruturas_de_dados/unless.rb product_status = 'closed' unless product_status == 'open' #A menos que o estado do produto seja aberto, a troca é possível. check_change = 'can' else #Senão, a troca não é possível. check_change = 'can not' end puts "You #{check_change} change the product"<file_sep>/poo/tipos_variaveis/class.rb class Animal #chamasse de classe pai a que passa uma herança def pular puts 'Toing! toim! boim! poim!' end def dormir puts 'ZzZzZz' end end class Cachorro < Animal # esse simbolo < significa que ela está recebendo como herança tudo que a classe anterior tem def latir puts 'Au Au' end end cachorro = Cachorro.new cachorro.pular cachorro.dormir cachorro.latir<file_sep>/collections/array.rb estados = [] #Criando um array vazio estados.push('Espirito Santo') #adicionando item, o push sempre adiciona de forma sequencial estados.push('Minas Gerais', 'Rio de Janeiro', 'São Paulo') #inserindo varios elementos de uma só vez puts estados #exibindo o array puts estados[1] #acessando o segundo elemento do array puts estados[2..5] #acessando indices atraves de intervalos, vai retornar os indices 2, 3, 4 e 5 puts estados[-2] #adquira o penultimo elemento de estados puts estados[-3..1] puts estados.first #recupera o primeiro elemento puts estados.last #recupera o ultimo elemento puts estados.count #conta quantidade de itens do array puts estados.length #conta quantidade de itens do array puts estados.empty? #descobre se o array está vazio, retorna true ou false puts estados.include?('Sao Paulo') #verica se um item especifico está presente, retorna true ou false puts estados.delete_at(2) #remova um item através de seu indice puts estados.pop #exclua o ultimo item do array puts estados.shift #para excluir o primeiro item<file_sep>/blocks/blocks_symbol.rb def foo(name, &block) @name = name block.call end foo('Leonardo') {puts "Hello #{@name}" }<file_sep>/metodos_gems/os.rb require 'os' #require diz que precisamos importar tal gem antes que o método seja iniciado # my_os é um método def my_os if OS.windows? #O OS foi declarado lá na gem "Windows" elsif OS.linux? "Linux" elsif OS.mac? "Mac" else "Não consegui identificar" end end puts "Meu PC possui #{OS.cpu_count} cores, é #{OS.bits} bits e o sistema operacional é #{my_os}"<file_sep>/metodos_gems/return.rb def compare (a,b) a > b end a = 1 b = 2 result = compare(a,b) puts "O resultado da comparação é #{result}"<file_sep>/poo/exemplos/heranca.rb class Pessoa attr_accessor :nome, :email end class PessoaFisica < Pessoa #usa-se o menor '<' para indicar herança attr_accessor :cpf def falar(texto) texto end end class PessoaJuridica < Pessoa attr_accessor :cnpj def pagar_fornecedor "Pagando fornecedor..." end end p1 = Pessoa.new #setter p1.nome = "Alethea" p1.email = "<EMAIL>" #getter puts p1.nome puts p1.email puts "-------------------------" p2 = PessoaFisica.new #setter p2.nome = "Jose" p2.email = "<EMAIL>" p2.cpf = "12345678984" #getter puts p2.nome puts p2.email puts p2.cpf puts "-------------------------" p2.falar("Hello!") p2 = PessoaJuridica.new #setter p2.nome = "<NAME>" p2.email = "<EMAIL>" p2.cnpj = "9191919191-0001" #getter puts p2.nome puts p2.email puts p2.cnpj puts p2.pagar_fornecedor puts "-------------------------" <file_sep>/blocks/blocks_method_verify.rb def foo if block_given? # Call the block yield else puts "Sem parametro do tipo bloco" end end foo foo {puts "Com parâmetro do tipo bloco"}<file_sep>/tipos-de-dados/string.rb #Tipo que representa um texto. Um conjunto de letras, símbolos ou números happiness = "Programming with ruby" puts happiness.class<file_sep>/tipos-de-dados/hash.rb #Tipo que representa uma coleção de dados organizados por chaves únicas e seus respectivos valores example_hash = {course: 'Ruby', language: 'pt-br', locale: 'tecnopuc'} puts example_hash[:locale] puts example_hash.class<file_sep>/poo/exemplos/variavel_instancia.rb class Pessoa def initialize(nome_fornecido = "Alethea") @nome = nome_fornecido end def imprime_nome @nome end end p1 = Pessoa.new puts p1.imprime_nome p2 = Pessoa.new ("Dara") puts p2.imprime_nome<file_sep>/estruturas_de_dados/times.rb #executa uma repetição por um numero especifico de vezes 2.times do #Exibe a frase “Estou aprendendo times” 2 vezes puts 'Estou aprendendo times!' end names = ['Joao', 'Alfredo', 'Juca'] #Igual ao array, o times começa com indice 0 3.times do |index| #Exibe um índice do array name por 3 vezes puts names[index] end <file_sep>/estruturas_de_dados/challenge.rb result = '' loop do print 'Digite o primeiro valor: ' num1 = gets.chomp.to_i print 'Digite o segundo valor: ' num2 = gets.chomp.to_i puts result puts 'Selecione uma das seguintes opções da calculadora: ' puts '4 - Multiplicar' puts '3 - Dividir' puts '2 - Subtrair' puts '1 - Somar' print 'Opção: ' option = gets.chomp.to_i if option == 4 mult = num1 * num2 puts("O resultado da multiplicacao eh: #{mult} ") elsif option == 3 div = num1/num2 puts("O resultado da divisão eh: #{div} ") elsif option == 2 subt = num1-num2 puts("O resultado da subtracao eh: #{subt} ") elsif option == 1 soma = num1 + num2 puts("O resultado da soma eh: #{soma} ") end end
bdbf10540f74bd75a8f4a22837bf2a5f7e37ece0
[ "Ruby" ]
45
Ruby
aletheasimonett/curso-ruby-basico
17a0f353968e3038850cf8c6632ab83bbd6ea45c
578843b3fcc5eb9cebbb327ca53bc3a6031715a7
refs/heads/master
<file_sep>## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class MetasploitModule < Msf::Post include Msf::Post::Common include Msf::Post::Android::System $LocalDir = "#{File.expand_path(File.dirname(__FILE__))}" $ScriptDir = "#{$LocalDir}/Scripts" def initialize(info={}) super(update_info(info, 'Name' => 'android Manage up_and_run_sh_file', 'Description' => %q{ Upload script to save your victoms And Run the uploaded script }, 'License' => MSF_LICENSE, 'Author' => [ 'CorrM' ], 'Platform' => [ 'android' ], 'SessionTypes' => [ 'meterpreter', 'shell' ] )) end def run #print_status(session.android.public_methods.join(', ')) #return # Check Platform if !session.platform.eql?("android") print_error("This Script for android [ONLY].!!") return end # Upload uploadSH() sleep(1.5) # Run runSH() sleep(1.5) # Hide Icon session.android.hide_app_icon() print_good("App Icon now hidden.!") sleep(1.5) print_good("Bye, CorrM.") end def uploadSH if File.file?("#{$ScriptDir}/CorrM.sh") print_good("Start Uploading . . . .") session.fs.file.upload_file('/sdcard/download/001.sh', "#{$ScriptDir}/CorrM.sh") else print_error("Can't Find 'CorrM.sh' !!") end print_good("File Uploaded.") end def runSH print_status("GoTo '/sdcard/download'.") shell_command("cd /sdcard/download", false) print_status("Run shell script :-") buff = shell_command("sh 001.sh", true) if buff.include?("No such file") print_error("\t" + buff) else print_good("\t" + buff) end end def shell_command(cmd, ret_read) buff = "" session.shell_write(cmd + "\n") if ret_read res = session.shell_read() buff << res if res end buff end end <file_sep># Meta-Modules To edit UI go to this path '/usr/share/metasploit-framework/lib/rex/post/meterpreter/ui/console/command_dispatcher'
6394223a1e27df17ee96e91eced07670f0f885b4
[ "Markdown", "Ruby" ]
2
Ruby
CorrM/Meta-Modules
5657734796a1b6eb8e92f79edcb1ec67fbd9c273
c73f83dbe40064c600b07ad8ac826651a2f9ad97
refs/heads/master
<repo_name>petitepirate/jsRecursionSeminar<file_sep>/examples.js var x = 0; while (x < 10) { console.log(x); x = x + 1; } function func1() { console.log('func 1'); func2(); console.log('func 1 continues'); return; } function func2() { console.log('func 2'); func3(); console.log('func 2 continues'); return; } function func3() { console.log('func 3'); return; } func1(); // ????? function func(x) { if (x === 0) { console.log(0); return; } console.log(x); func(x - 1); console.log(x); } func(5); console.log('done!'); /* func(5) func(4) func(3) func(2) func(1) func(0) */ //____________________________________________________________________ var addUntilTen = function(num) { if (num >= 10) { // base case console.log('done!'); } else { // recursive case console.log(`num is ${num} keep going!`); addUntilTen(num + 1); console.log(`back where num is ${num}`); } }; addUntilTen(4); // function expression var isGreaterThan100 = function(number) { if (number > 100) { // do one thing console.log('your number is greater than 100'); } else { // do another thing console.log('your number is less than 100'); } }; // function declaration function isGreaterThan100Again(number) { if (number > 100) { console.log('greater than 100'); } else { console.log('less than 100'); } } isGreaterThan100(150); isGreaterThan100Again(50); function outer() { console.log("I'm the start of the outer function"); middle(); console.log("I'm the end of the outer function"); } function middle() { console.log("I'm the start of the middle function"); inner(); console.log("I'm the end of the middle function"); } function inner() { console.log("I'm the inner function"); } outer(); function sumTo10(number, sum = 0) { // base case if (number >= 10) { return sum + number; } else { // recursive case // console.log('curent sum:', sum) sum = sum + number; return sumTo10(number + 1, sum); } } // console.log('final output:', sumTo10(1, 0)) // console.log('math equation:', 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10) // var myArray = ['hello', 'there', 'my'] // var value = myArray.shift() // console.log(value) // console.log(myArray) // [[3], [4]] // [3, [4]] // [1].concat([2, 3, 4])
29afd85066fe5525717564372cf8dec4aecbfc70
[ "JavaScript" ]
1
JavaScript
petitepirate/jsRecursionSeminar
b4896f3cb3b423affd4da180a1d8b5d0929249f0
c0ff34c332c22c3ee051bb09755f271892b418ff
refs/heads/master
<file_sep>//Class Packer removes pots from the shelf and packs the pots public class Packer extends Thread { //Initialising variables private int totPots; private int count = 0; //Method run is the code which is executed when Main calls start public void run() { System.out.println("Packer has started"); Main m = new Main(); do { setTotPots(); pack(m.shelf, m.empty); } while (totPots > 0 || m.shelf != 0); } //Method pack waits for the shelf variable to be available, sleeps Thread for 400ms and decrements the shelf public void pack(int shelf, boolean empty) { Main m = new Main(); //Synchronized block waits if the shelf is 0 synchronized(this) { while (m.shelf == 0 && totPots > 0) { try { System.out.println("Packer waiting for pots... \n"); notifyAll(); wait(500); } catch (InterruptedException e) {} } } m.empty = false; m.shelfDec(); System.out.println("Packer has removed a pot from the shelf"); //Sleeps Thread for 400ms to simulate time taken to pack try { Thread.sleep(400); } catch (InterruptedException e) {} count++; System.out.println("Packer has packed: " + count + " pots"); System.out.println("There are " + m.shelf + " pots on the shelf\n"); m.empty = true; } //Setter method for totPots private synchronized void setTotPots() { Potter1 p1 = new Potter1(); Potter2 p2 = new Potter2(); totPots = p1.potsRem1 + p2.potsRem2; } }
5fbfed17e0a04b113c185ec1a46743c20cf20b59
[ "Java" ]
1
Java
TGasco/ParallelPotting
21f96dffa8768816de84c475d8e7ce97d5a49418
a865d2ce8919eb06d2c90dbcd75c04c8b0edb914
refs/heads/master
<file_sep>using UnityEngine; using System.Collections; using UnityEngine.UI; public class AIPlayerController : MonoBehaviour { private float turnProbability; private long turnQuanta; private long quantSeen; public GameObject explosion; public Transform playerTransform; public Pose3D devicePose; public Rigidbody bikeBody; public GameObject trailObject; public GameObject trailTurnObject; public AudioClip explodeClip; public GameObject gameOverMenu; private int startingDir; //this will be mod 4. 0 is forward. 1 is right. 2 is back. 3 is left. private bool inTurn; Transform cameraTransform; Vector3 forceDirection; private GameObject currTrailObj; private float currTrailOrigin; private bool gameOver; public AIPlayerController (float probability, long quanta) { turnProbability = probability; turnQuanta = quanta; } void Awake() { forceDirection = playerTransform.right; } void Start () { quantSeen = 0; gameOver = false; startingDir = 0; inTurn = false; } void Update () { bikeBody.velocity = Vector3.zero; bikeBody.rotation = playerTransform.rotation; bikeBody.AddRelativeForce (Vector3.right * 500); } // TODO Interval should honestly vary automatically based on our choice // of player speed, but it is hardcoded for now. int interval = 15; float nextTime = 0.0f; float dropCount = 0; void LateUpdate() { quantSeen++; if (nextTime % 350 == 0 && nextTime > 10 && gameOver == false && inTurn == false) { if (quantSeen >= turnQuanta) { // determine whether or not to make a turn float turnVal = Random.Range (0.0f, 1.0f); if (turnVal >= turnProbability) { // we're going to execute a turn ExecuteRandomTurn (); } quantSeen = 0; } } // The condition dropCount > 25 lets the cycle start moving before we start spawning. //If we are in a turn, we want to spawn more frequent, smaller objects. if (inTurn) { if (dropCount % 10 == 0 && dropCount > 25 && gameOver == false) { //SpawnTrailObject (inTurn); SpawnTrailObjectAlt(inTurn); } } else { //Every <interval> frames, make a block. if (dropCount % 15 == 0 && dropCount > 25 && gameOver == false) { //SpawnTrailObject (inTurn); SpawnTrailObjectAlt(inTurn); } } dropCount++; nextTime++; if (Random.Range (1, 350) == 1) { nextTime = 350; } } void ExecuteRandomTurn () { float turnChoice = Random.Range (0.0f, 1.0f); if (turnChoice > 0.5) { TurnLeft (); } else { TurnRight (); } } //Call it hacky, but this prevents our turning coroutines from being slightly off. void CorrectRotation() { if (playerTransform.eulerAngles.y > 267 && playerTransform.eulerAngles.y < 273) { Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 270; playerTransform.eulerAngles = tempRotation; } if (playerTransform.eulerAngles.y > 357 || playerTransform.eulerAngles.y < 3) { Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 0; playerTransform.eulerAngles = tempRotation; } if (playerTransform.eulerAngles.y > 87 && playerTransform.eulerAngles.y < 93) { Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 90; playerTransform.eulerAngles = tempRotation; } if (playerTransform.eulerAngles.y > 177 && playerTransform.eulerAngles.y < 183) { Debug.Log ("Correcting forward"); Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 180; playerTransform.eulerAngles = tempRotation; } } float nfmod(float a, float b) { return a - b * Mathf.Floor(a / b); } /* perform a left turn */ void TurnLeft () { StartCoroutine (PerformTurn(Vector3.down * 90, 0.5f)); Cardboard.SDK.Recenter (); startingDir = (int)nfmod(startingDir - 1, 4); Debug.Log ("starting dir is now: " + startingDir); } /* perform a right turn */ void TurnRight () { StartCoroutine (PerformTurn (Vector3.up * 90, 0.5f)); Cardboard.SDK.Recenter (); startingDir = (int)nfmod(startingDir + 1, 4); } IEnumerator PerformTurn (Vector3 byAngles, float inTime) { inTurn = true; Quaternion fromAngle = playerTransform.rotation; Quaternion toAngle = Quaternion.Euler (playerTransform.eulerAngles + byAngles); for (float t = 0f; t < 1; t += Time.deltaTime / inTime) { playerTransform.rotation = Quaternion.Lerp (fromAngle, toAngle, t); yield return null; } CorrectRotation (); inTurn = false; } // SpawnTrailObjectAlt spawns trail objects right on the player position, but delays turning on their collider. void SpawnTrailObjectAlt(bool inTurn) { Vector3 tempScale = trailTurnObject.transform.localScale; Debug.Log ("my inturn is: " + inTurn); if (inTurn == false && dropCount % 15 == 0 && dropCount > 25) { if (startingDir == 0) { //trailTurnObject.x -= 6; tempScale.z = .8f; tempScale.x = 5; trailTurnObject.transform.localScale = tempScale; } if (startingDir == 1) { //trailTurnObject.z += 6; tempScale.z = 5; tempScale.x = .8f; trailTurnObject.transform.localScale = tempScale; } if (startingDir == 2) { //trailObjectPos.x += 6; tempScale.z = .8f; tempScale.x = 5; trailTurnObject.transform.localScale = tempScale; } if (startingDir == 3) { //trailObjectPos.z -= 6; tempScale.z = 5; tempScale.x = .8f; trailTurnObject.transform.localScale = tempScale; } Instantiate (trailTurnObject, playerTransform.position, Quaternion.identity); } else { tempScale.z = 1.5f; tempScale.x = 1.5f; trailTurnObject.transform.localScale = tempScale; Instantiate (trailTurnObject, playerTransform.position, Quaternion.identity); } } public void Turn() { float turnAngle = devicePose.Orientation.eulerAngles.y; //Debug.Log(devicePose.Orientation.eulerAngles.y); int turnDirection = -1; if (turnAngle > 0 && turnAngle < 180) { turnDirection = 1; } if (turnAngle >= 180 && turnAngle <= 360) { turnAngle = 360 - turnAngle; } Quaternion turnQuaternion = playerTransform.localRotation; Debug.Log ("Player rotation is" + turnQuaternion); turnQuaternion.y += turnDirection * turnAngle; Debug.Log (turnQuaternion.y); playerTransform.localRotation = turnQuaternion ; Debug.Log ("Player rotation is" + playerTransform.localRotation + " after turn"); } void OnTriggerEnter(Collider other) { AudioSource explosionSound = GetComponent <AudioSource>(); Debug.Log ("feeling triggered"); gameOver = true; GetComponent<Rigidbody>().isKinematic = true; GetComponent<Rigidbody>().detectCollisions = false; explosionSound.PlayOneShot (explodeClip); Instantiate (explosion, playerTransform.position, playerTransform.rotation); GetComponent<Renderer>().enabled = false; gameOverMenu.GetComponent<Renderer> ().enabled = true; } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.Networking; using UnityEngine.UI; //Controls player movement and trail generation. public class playerController : MonoBehaviour { public GameObject explosion; public Transform playerTransform; public Pose3D devicePose; public Rigidbody bikeBody; public Cardboard mainCamera; public GameObject trailObject; public GameObject trailTurnObject; public AudioClip explodeClip; public GameObject gameOverMenu; private int startingDir; //this will be mod 4. 0 is forward. 1 is right. 2 is back. 3 is left. private bool inTurn; private NetworkView nView; private NetworkIdentity netID; private NetworkManager netManager; Transform cameraTransform; Vector3 forceDirection; private GameObject currTrailObj; private float currTrailOrigin; private bool gameOver; void Awake() { forceDirection = playerTransform.right; //These are disabled at first in the scene for network purposes GetComponent<AudioSource> ().enabled = true; } // Use this for initialization void Start () { netManager =GameObject.FindObjectOfType <NetworkManager> (); netID = GetComponent <NetworkIdentity> (); // We need this, so a player knows which camera to turn on (their own). // Without it, all players get 1 shared camera, which is, in fact, awful for gameplay. if (netID.isLocalPlayer) { mainCamera.gameObject.SetActive (true); } nView = GetComponent <NetworkView> (); gameOver = false; devicePose = Cardboard.SDK.HeadPose; startingDir = 0; inTurn = false; } // Update is called once per frame void Update () { Debug.Log ("main cam ID: " + mainCamera.GetInstanceID()); if (!netID.isLocalPlayer) { return; } bikeBody.velocity = Vector3.zero; bikeBody.rotation = playerTransform.rotation; bikeBody.AddRelativeForce (Vector3.right * 400); // Commented this shit out because onCardboardTrigger should // take care of it. if (Input.touchCount > 0 && inTurn == false || (Input.GetKeyDown("space") && inTurn == false)) { ChooseTurn (); } } //public void onCardboardTrigger() { // if (inTurn == false) { // ChooseTurn (); // } //} //Call it hacky, but this prevents our turning coroutines from being slightly off. void CorrectRotation() { if (playerTransform.eulerAngles.y > 267 && playerTransform.eulerAngles.y < 273) { Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 270; playerTransform.eulerAngles = tempRotation; } if (playerTransform.eulerAngles.y > 357 || playerTransform.eulerAngles.y < 3) { Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 0; playerTransform.eulerAngles = tempRotation; } if (playerTransform.eulerAngles.y > 87 && playerTransform.eulerAngles.y < 93) { Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 90; playerTransform.eulerAngles = tempRotation; } if (playerTransform.eulerAngles.y > 177 && playerTransform.eulerAngles.y < 183) { Debug.Log ("Correcting forward"); Vector3 tempRotation = playerTransform.eulerAngles; tempRotation.y = 180; playerTransform.eulerAngles = tempRotation; } } // TODO Interval should honestly vary automatically based on our choice // of player speed, but it is hardcoded for now. int interval = 15; float nextTime = 0; void LateUpdate() { // The condition nextTime > 25 lets the cycle start moving before we start spawning. //If we are in a turn, we want to spawn more frequent, smaller objects. if (inTurn) { if (nextTime % 10 == 0 && nextTime > 25 && gameOver == false) { //SpawnTrailObject (inTurn); SpawnTrailObjectAlt(inTurn); } } else { //Every <interval> frames, make a block. if (nextTime % interval == 0 && nextTime > 25 && gameOver == false) { //SpawnTrailObject (inTurn); SpawnTrailObjectAlt(inTurn); } } nextTime++; } public void ChooseTurn () { float lookAngle = devicePose.Orientation.eulerAngles.y; if (lookAngle > 0 && lookAngle < 90) TurnRight (); else if (lookAngle > 90 && lookAngle < 360) TurnLeft (); } float nfmod(float a, float b) { return a - b * Mathf.Floor(a / b); } /* perform a left turn */ void TurnLeft () { StartCoroutine (PerformTurn(Vector3.down * 90, 0.5f)); Cardboard.SDK.Recenter (); startingDir = (int)nfmod(startingDir - 1, 4); Debug.Log ("starting dir is now: " + startingDir); } /* perform a right turn */ void TurnRight () { StartCoroutine (PerformTurn (Vector3.up * 90, 0.5f)); Cardboard.SDK.Recenter (); startingDir = (int)nfmod(startingDir + 1, 4); } IEnumerator PerformTurn (Vector3 byAngles, float inTime) { inTurn = true; Quaternion fromAngle = playerTransform.rotation; Quaternion toAngle = Quaternion.Euler (playerTransform.eulerAngles + byAngles); for (float t = 0f; t < 1; t += Time.deltaTime / inTime) { playerTransform.rotation = Quaternion.Lerp (fromAngle, toAngle, t); yield return null; } CorrectRotation (); inTurn = false; } //TODO possibly remove this. Replacement for SpawnTrailObject is below. void SpawnTrailObject(bool inTurn) { if (inTurn == false) { Vector3 trailObjectPos = playerTransform.position; Vector3 tempScale = trailObject.transform.localScale; if (startingDir == 0) { trailObjectPos.x -= 6; tempScale.z = .8f; tempScale.x = 5; trailObject.transform.localScale = tempScale; } if (startingDir == 1) { trailObjectPos.z += 6; tempScale.z = 5; tempScale.x = .8f; trailObject.transform.localScale = tempScale; } if (startingDir == 2) { trailObjectPos.x += 6; tempScale.z = .8f; tempScale.x = 5; trailObject.transform.localScale = tempScale; } if (startingDir == 3) { trailObjectPos.z -= 6; tempScale.z = 5; tempScale.x = .8f; trailObject.transform.localScale = tempScale; } Instantiate (trailObject, trailObjectPos, Quaternion.identity); } else { Instantiate (trailTurnObject, playerTransform.position, Quaternion.identity); } } // SpawnTrailObjectAlt spawns trail objects right on the player position, but delays turning on their collider. void SpawnTrailObjectAlt(bool inTurn) { Vector3 tempScale = trailTurnObject.transform.localScale; if (inTurn == false && nextTime % interval == 0 && nextTime > 25) { if (startingDir == 0) { //trailTurnObject.x -= 6; tempScale.z = .8f; tempScale.x = 5; trailTurnObject.transform.localScale = tempScale; } if (startingDir == 1) { //trailTurnObject.z += 6; tempScale.z = 5; tempScale.x = .8f; trailTurnObject.transform.localScale = tempScale; } if (startingDir == 2) { //trailObjectPos.x += 6; tempScale.z = .8f; tempScale.x = 5; trailTurnObject.transform.localScale = tempScale; } if (startingDir == 3) { //trailObjectPos.z -= 6; tempScale.z = 5; tempScale.x = .8f; trailTurnObject.transform.localScale = tempScale; } Instantiate (trailTurnObject, playerTransform.position, Quaternion.identity); } else { tempScale.z = 1.5f; tempScale.x = 1.5f; trailTurnObject.transform.localScale = tempScale; Instantiate (trailTurnObject, playerTransform.position, Quaternion.identity); } } public void Turn() { float turnAngle = devicePose.Orientation.eulerAngles.y; //Debug.Log(devicePose.Orientation.eulerAngles.y); int turnDirection = -1; if (turnAngle > 0 && turnAngle < 180) { turnDirection = 1; } if (turnAngle >= 180 && turnAngle <= 360) { turnAngle = 360 - turnAngle; } Quaternion turnQuaternion = playerTransform.localRotation; Debug.Log ("Player rotation is" + turnQuaternion); turnQuaternion.y += turnDirection * turnAngle; Debug.Log (turnQuaternion.y); playerTransform.localRotation = turnQuaternion ; Debug.Log ("Player rotation is" + playerTransform.localRotation + " after turn"); } void OnTriggerEnter(Collider other) { AudioSource explosionSound = GetComponent <AudioSource>(); Debug.Log ("feeling triggered"); gameOver = true; GetComponent<Rigidbody>().isKinematic = true; GetComponent<Rigidbody>().detectCollisions = false; explosionSound.PlayOneShot (explodeClip); Instantiate (explosion, playerTransform.position, playerTransform.rotation); GetComponent<Renderer>().enabled = false; gameOverMenu.GetComponent<Renderer> ().enabled = true; } } <file_sep>using UnityEngine; using System.Collections; using UnityEngine.Networking; using UnityEngine.SceneManagement; public class MenuHandler : MonoBehaviour { private NetworkManager netManager; float timer = 5.0f; private bool showGUI = false; // Use this for initialization void Start () { netManager =GameObject.FindObjectOfType <NetworkManager> (); } // Update is called once per frame void Update () { if (showGUI == true) { timer -= Time.deltaTime; } } public void startSingleplayer() { StartCoroutine (singleLoader()); } public void start2player() { StartCoroutine (multiplayerLoader()); } public void resetScene() { //SceneManager.UnloadScene(SceneManager.GetActiveScene().buildIndex); StartCoroutine(reset ()); } IEnumerator singleLoader () { showGUI = true; yield return new WaitForSeconds (timer); Application.LoadLevel ("scene1"); } IEnumerator multiplayerLoader () { showGUI = true; yield return new WaitForSeconds (timer); Application.LoadLevel ("2player"); } IEnumerator reset () { netManager.StopHost (); Application.LoadLevel ("2player"); netManager.StartHost (); yield return new WaitForSeconds (1); } void OnGUI() { if (showGUI == true) { GUI.Box (new Rect (100, 175, 150, 100), "" + timer.ToString ("0")); } } } <file_sep>using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; public class TronNetworkManager : MonoBehaviour { public bool isAtStartup = true; private Button bothButton; private Button clientButton; NetworkClient myClient; private NetworkManager netManager; void Awake() { netManager = GetComponent <NetworkManager> (); } void Start() { } void Update () { } void OnGUI() { if (isAtStartup) { if (GUI.Button (new Rect (400, 100, 500, 100), "Start as Host")) { SetupHost (); } if (GUI.Button (new Rect (400, 200, 500, 100), "Start as Client")) { SetupClient (); } } } // Create a server and listen on a port public void SetupHost () { /*NetworkServer.Listen (4444); myClient = new NetworkClient(); myClient.RegisterHandler(MsgType.Connect, OnConnected); myClient.Connect("127.0.0.1", 4444); */ netManager.StartHost (); isAtStartup = false; GameObject tempCam = GameObject.FindWithTag ("tmp"); GameObject.Destroy (tempCam); } // Create a client and connect to the server port public void SetupClient() { /* myClient = new NetworkClient(); myClient.RegisterHandler(MsgType.Connect, OnConnected); myClient.Connect("127.0.0.1", 4444); */ netManager.StartClient (); isAtStartup = false; GameObject tempCam = GameObject.FindWithTag ("tmp"); GameObject.Destroy (tempCam); } // Create a local client and connect to the local server public void SetupLocalClient() { myClient = ClientScene.ConnectLocalServer(); myClient.RegisterHandler(MsgType.Connect, OnConnected); isAtStartup = false; netManager.StartClient (); GameObject tempCam = GameObject.FindWithTag ("tmp"); GameObject.Destroy (tempCam); } // client function public void OnConnected(NetworkMessage netMsg) { Debug.Log("Connected to server"); } } <file_sep>using UnityEngine; using System.Collections; public class colliderDelay : MonoBehaviour { private BoxCollider bCollider; // Use this for initialization void Start () { bCollider = GetComponent<BoxCollider> (); bCollider.enabled = false; } // Update is called once per frame int counter = 0; void Update () { if (counter > 40) { bCollider.enabled = true; bCollider.isTrigger = true; } counter++; } }
8d9a0e9f1d7e7a0d3864dc075c4b0765b6419aa5
[ "C#" ]
5
C#
ryhamz/Tron
68dd3e9dbd60e634680b34037aef174c0ccebd04
5b820dc17248a0cf1d3c8c7dc7196313709757c0
refs/heads/master
<file_sep>define(function(require, module, exports){ var $ = require('jquery'); var _ = require('dtools'); $('.input').click(function(){ }); var CustomPassword = function(options){ this._initCustomPassword(options); } CustomPassword.prototype = { _initCustomPassword: function(options){ this.options = _.mix({ ele: '.input' },options); this.panel = $(this.options.ele); this._initUI(); this._initEvents(); this.length = 0; this.values = []; }, _initUI: function(){}, _initEvents: function(){ var self = this; this.panel.click(function(){ $('.num-keyboard').show(); }); $('.num-keyboard').on('click', 'div[data-value]', function(){ console.log(this.dataset.value); if(this.dataset.value == 'del'){ if(self.length == 0){ return; } self.values.unshift(); self.panel.find('div').eq(self.length - 1).removeClass('active'); self.length--; }else if(this.dataset.value == 'done'){ $('.num-keyboard').hide(); }else{ self.values.push(this.dataset.value); self.length++; self.panel.find('div').eq(self.length - 1).addClass('active'); } }); } } new CustomPassword(); })
dabda6f21a4747f5b3667b9f3e4d5ce5c35c41f6
[ "JavaScript" ]
1
JavaScript
dukai/num-keyboard
9d2f41e6b17d90d11e910003be349252068abc5e
11d45ed618ebedb4642733a715870905e8cb0871
refs/heads/master
<repo_name>grimoh/asdf-k6<file_sep>/bin/download #!/usr/bin/env bash set -e # check ASDF environment variables [ -n "$ASDF_INSTALL_VERSION" ] || (echo 'Missing ASDF_INSTALL_VERSION' >&2 && exit 1) [ -n "$ASDF_DOWNLOAD_PATH" ] || (echo 'Missing ASDF_DOWNLOAD_PATH' >&2 && exit 1) case "$(uname -s)" in "Darwin") DOWNLOAD_URL="https://github.com/grafana/k6/releases/download/v${ASDF_INSTALL_VERSION}/k6-v${ASDF_INSTALL_VERSION}-macos-amd64.zip" curl -fL -o "${ASDF_DOWNLOAD_PATH}/k6.zip" "${DOWNLOAD_URL}" ;; "Linux") DOWNLOAD_URL="https://github.com/grafana/k6/releases/download/v${ASDF_INSTALL_VERSION}/k6-v${ASDF_INSTALL_VERSION}-linux-amd64.tar.gz" curl -fL -o "${ASDF_DOWNLOAD_PATH}/k6.tar.gz" "${DOWNLOAD_URL}" ;; esac <file_sep>/bin/list-all #!/usr/bin/env bash set -e releases_path="https://api.github.com/repos/grafana/k6/releases" cmd="curl -s" if [ -n "$GITHUB_API_TOKEN" ]; then cmd="$cmd -H 'Authorization: token $GITHUB_API_TOKEN'" fi cmd="$cmd $releases_path" versions=$(eval $cmd | sed -nE 's/^ "tag_name": "v(.+)",$/\1/pg' | sed -n -e '1!G;h;$p') echo $versions <file_sep>/bin/install #!/usr/bin/env bash set -e # check ASDF environment variables [ -n "$ASDF_INSTALL_PATH" ] || (echo 'Missing ASDF_INSTALL_PATH' >&2 && exit 1) [ -n "$ASDF_DOWNLOAD_PATH" ] || (echo 'Missing ASDF_DOWNLOAD_PATH' >&2 && exit 1) mkdir -p "${ASDF_INSTALL_PATH}/bin" toolPath="${ASDF_INSTALL_PATH}/bin/k6" cd "${ASDF_DOWNLOAD_PATH}" case "$(uname -s)" in "Darwin") unzip -q k6.zip mv ./k6-v${ASDF_INSTALL_VERSION}-macos-amd64/k6 "${toolPath}" ;; "Linux") tar xzf k6.tar.gz mv ./k6-v${ASDF_INSTALL_VERSION}-linux-amd64/k6 "${toolPath}" ;; esac chmod +x "${toolPath}" <file_sep>/README.md ![GitHub Actions Status](https://github.com/grimoh/asdf-k6/workflows/Main%20workflow/badge.svg?branch=master) # asdf-k6 [k6](https://github.com/grafana/k6) plugin for [asdf](https://github.com/asdf-vm/asdf) version manager ## Install ``` asdf plugin add k6 ```
dec284c7ed4c77548a91a9a829937e7b1b29018c
[ "Markdown", "Shell" ]
4
Shell
grimoh/asdf-k6
8e65b776cd523991d79d3190ae3ed4053b3bdc9b
990510a24afeaedc6fb5c6939b0572416c15382b
refs/heads/master
<file_sep># Kubemq RabbitMQ Target Connector Kubemq rabbitmq target connector allows services using kubemq server to access rabbitmq messaging services. ## Prerequisites The following are required to run the rabbitmq target connector: - kubemq cluster - rabbitmq server - kubemq-targets deployment ## Configuration RabbitMQ target connector configuration properties: | Properties Key | Required | Description | Example | |:--------------------|:---------|:-----------------------------------|:-------------------------------------------| | url | yes | rabbitmq connection string address | "amqp://rabbitmq:rabbitmq@localhost:5672/" | | default_exchange | no | set default exchange routing | "exchange.1" | | default_topic | no | set default topic routing | "topic1" | | default_persistence | no | set default persistence for messages | "true" | | ca_cert | no | SSL CA certificate | pem certificate value | | client_certificate | no | SSL Client certificate (mMTL) | pem certificate value | | client_key | no | SSL Client Key (mTLS) | pem key value | Example: ```yaml bindings: - name: kubemq-query-rabbitmq source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-rabbitmq-connector" auth_token: "" channel: "query.rabbitmq" group: "" concurrency: "1" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: messaging.rabbitmq name: target-rabbitmq properties: url: "amqp://rabbitmq:rabbitmq@localhost:5672/" default_exchange: "exchange" default_topic: "topic1" default_persistence: "true" ``` ## Usage ### Request Request metadata setting: | Metadata Key | Required | Description | Possible values | |:---------------|:---------|:--------------------|:----------------| | queue | yes | set queue name | "queue" | | exchange | no | set exchange name | "exchange" | | mandatory | no | set mandatory | "true","false" | | immediate | no | set immediate | "true","false" | | delivery_mode | no | set delivery mode | "1","2" | | priority | no | set priority | "0"-"9" | | correlation_id | no | set correlation id | "some id" | | reply_to | no | set set reply to | "" | | expiry_seconds | no | set message expiry in seconds| "3600" | Query request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:-------------|:-------------------| | data | yes | data to publish | base64 bytes array | Example: ```json { "metadata": { "queue": "queue", "exchange": "", "confirm": "true", "mandatory": "false", "immediate": "false", "delivery_mode": "1", "priority": "0", "correlation_id": "", "reply_to": "", "expiry_seconds": "3600" }, "data": "U0VMRUNUIGlkLHRpdGxlLGNvbnRlbnQgRlJPTSBwb3N0Ow==" } ``` <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // put Metrics namespace := "Logs" b := []byte(`[{"Counts":null,"Dimensions":null,"MetricName":"New Metric","StatisticValues":null,"StorageResolution":null,"Timestamp":"2020-08-10T17:09:48.3895822+03:00","Unit":"Count","Value":132,"Values":null}]`) putRequest := types.NewRequest(). SetMetadataKeyValue("method", "put_metrics"). SetMetadataKeyValue("namespace", namespace). SetData(b) queryPutResponse, err := client.SetQuery(putRequest.ToQuery()). SetChannel("query.aws.cloudwatch.metrics"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } putResponse, err := types.ParseResponse(queryPutResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("put metrics executed, response: %s", putResponse.Data)) // list metrics listRequest := types.NewRequest(). SetMetadataKeyValue("method", "list_metrics"). SetMetadataKeyValue("namespace", namespace) listReq, err := client.SetQuery(listRequest.ToQuery()). SetChannel("query.aws.cloudwatch.metrics"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } listResponse, err := types.ParseResponse(listReq.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("list metrics executed %v, error: %v", listResponse.Data, listResponse.IsError)) } <file_sep>package firebase import ( "encoding/json" "fmt" "firebase.google.com/go/v4/messaging" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ //------------Token-----------// "custom_token": "custom_token", "verify_token": "verify_token", //------------User------------// "retrieve_user": "retrieve_user", "create_user": "create_user", "update_user": "update_user", "delete_user": "delete_user", "delete_multiple_users": "delete_multiple_users", "list_users": "list_users", //------------DB-------------// "get_db": "get_db", "update_db": "update_db", "delete_db": "delete_db", "set_db": "set_db", //--------Messaging---------// "send_message": "send_message", "send_multi": "send_multi", } var retrieveMap = map[string]string{ "by_uid": "by_uid", "by_email": "by_email", "by_phone": "by_phone", } type metadata struct { method string tokenID string retrieveBy string uid string email string phone string refPath string childRefPath string } const ( // iota is reset to 0 Unassigned = iota // c0 == 0 SendMessage = iota // c1 == 1 SendBatch = iota // c2 == 2 ) func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "retrieve_user" { m.retrieveBy, err = meta.ParseStringMap("retrieve_by", retrieveMap) if err != nil { return metadata{}, fmt.Errorf("error parsing retrieve_by, %w", err) } switch m.retrieveBy { case "by_uid": m.uid, err = meta.MustParseString("uid") if err != nil { return metadata{}, fmt.Errorf("error parsing uid, %w", err) } case "by_email": m.email, err = meta.MustParseString("email") if err != nil { return metadata{}, fmt.Errorf("error parsing email, %w", err) } case "by_phone": m.phone, err = meta.MustParseString("phone") if err != nil { return metadata{}, fmt.Errorf("error parsing phone, %w", err) } } } if m.method == "update_user" || m.method == "delete_user" { m.uid, err = meta.MustParseString("uid") if err != nil { return metadata{}, fmt.Errorf("error parsing uid, %w", err) } } if m.method == "verify_token" || m.method == "custom_token" { m.tokenID, err = meta.MustParseString("token_id") if err != nil { return metadata{}, fmt.Errorf("error parsing token_id, %w", err) } } if m.method == "get_db" || m.method == "update_db" || m.method == "set_db" || m.method == "delete_db" { m.refPath, err = meta.MustParseString("ref_path") if err != nil { return metadata{}, fmt.Errorf("error parsing refPath, %w", err) } m.childRefPath = meta.ParseString("child_ref", "") if err != nil { return metadata{}, fmt.Errorf("error parsing child_ref, %w", err) } } return m, nil } func parseMetadataMessages(data []byte, opts options, metaDatatype int) (*messages, error) { // DeepCopy deepcopies a to b using json marshaling switch metaDatatype { // messaging single case 1: ms := messaging.Message{} if opts.defaultMessaging.single != nil { err := DeepCopy(&opts.defaultMessaging.single, &ms) if err != nil { return opts.defaultMessaging, err } } err := json.Unmarshal([]byte(data), &ms) if err != nil { return opts.defaultMessaging, err } return &messages{single: &ms}, nil case 2: mm := messaging.MulticastMessage{} if opts.defaultMessaging.multicast != nil { err := DeepCopy(&opts.defaultMessaging.multicast, &mm) if err != nil { return opts.defaultMessaging, err } } err := json.Unmarshal([]byte(data), &mm) if err != nil { return opts.defaultMessaging, err } return &messages{multicast: &mm}, nil } return opts.defaultMessaging, nil } // DeepCopy deepcopies a to b using json marshaling func DeepCopy(a, b interface{}) error { byt, _ := json.Marshal(a) return json.Unmarshal(byt, b) } <file_sep>package eventhubs import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { endPoint string sharedAccessKeyName string sharedAccessKey string entityPath string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/azure/eventhubs/endPoint.txt") if err != nil { return nil, err } t.endPoint = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/azure/eventhubs/sharedAccessKeyName.txt") if err != nil { return nil, err } t.sharedAccessKeyName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/azure/eventhubs/sharedAccessKey.txt") if err != nil { return nil, err } t.sharedAccessKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/azure/eventhubs/entityPath.txt") if err != nil { return nil, err } t.entityPath = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init ", cfg: config.Spec{ Name: "azure-eventhubs", Kind: "azure.eventhubs", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, "entity_path": dat.entityPath, }, }, wantErr: false, }, { name: "invalid init - missing end_point", cfg: config.Spec{ Name: "azure-eventhubs", Kind: "azure.eventhubs", Properties: map[string]string{ "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, "entity_path": dat.entityPath, }, }, wantErr: true, }, { name: "invalid init - missing shared_access_key_name", cfg: config.Spec{ Name: "azure-eventhubs", Kind: "azure.eventhubs", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key": dat.sharedAccessKey, "entity_path": dat.entityPath, }, }, wantErr: true, }, { name: "invalid init - missing shared_access_key", cfg: config.Spec{ Name: "azure-eventhubs", Kind: "azure.eventhubs", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "entity_path": dat.entityPath, }, }, wantErr: true, }, { name: "invalid init - missing entity_path", cfg: config.Spec{ Name: "azure-eventhubs", Kind: "azure.eventhubs", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Send(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-eventhubs", Kind: "azure.eventhubs", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, "entity_path": dat.entityPath, }, } body, err := json.Marshal("test") require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid send no properties", request: types.NewRequest(). SetMetadataKeyValue("method", "send"). SetData(body), wantErr: false, }, { name: "valid send with properties", request: types.NewRequest(). SetMetadataKeyValue("properties", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("method", "send"). SetData(body), wantErr: false, }, { name: "invalid send missing body", request: types.NewRequest(). SetMetadataKeyValue("properties", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("method", "send"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_SendBatch(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-eventhubs", Kind: "azure.eventhubs", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, "entity_path": dat.entityPath, }, } var messages []string m1 := "test1" m2 := "test2" m3 := "test3" m4 := "test4" messages = append(messages, m1) messages = append(messages, m2) messages = append(messages, m3) messages = append(messages, m4) body, err := json.Marshal(messages) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid send no properties", request: types.NewRequest(). SetMetadataKeyValue("method", "send_batch"). SetData(body), wantErr: false, }, { name: "valid send with properties", request: types.NewRequest(). SetMetadataKeyValue("properties", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("method", "send_batch"). SetData(body), wantErr: false, }, { name: "invalid send missing body", request: types.NewRequest(). SetMetadataKeyValue("properties", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("method", "send_batch"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package firebase import ( "context" "errors" firebase "firebase.google.com/go/v4" "firebase.google.com/go/v4/auth" "firebase.google.com/go/v4/db" "firebase.google.com/go/v4/messaging" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/option" ) type Client struct { log *logger.Logger opts options clientAuth *auth.Client dbClient *db.Client messagingClient *messaging.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) config := &firebase.Config{ProjectID: c.opts.projectID, DatabaseURL: c.opts.dbURL} app, err := firebase.NewApp(ctx, config, option.WithCredentialsJSON(b)) if err != nil { return err } if c.opts.authClient { client, err := app.Auth(ctx) if err != nil { return err } c.clientAuth = client } if c.opts.dbClient { client, err := app.Database(ctx) if err != nil { return err } c.dbClient = client } if c.opts.messagingClient { c.messagingClient, err = app.Messaging(ctx) if err != nil { return err } } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "custom_token": return c.customToken(ctx, meta, req.Data) case "verify_token": return c.verifyToken(ctx, meta) case "retrieve_user": return c.retrieveUser(ctx, meta) case "create_user": return c.createUser(ctx, req.Data) case "update_user": return c.updateUser(ctx, meta, req.Data) case "delete_user": return c.deleteUser(ctx, meta) case "delete_multiple_users": return c.deleteMultipleUser(ctx, req.Data) case "list_users": return c.listAllUsers(ctx) case "get_db": return c.dbGet(ctx, meta) case "update_db": return c.dbUpdate(ctx, meta, req.Data) case "set_db": return c.dbSet(ctx, meta, req.Data) case "delete_db": return c.dbDelete(ctx, meta) case "send_message": return c.sendMessage(ctx, req, c.opts) case "send_multi": return c.sendMessageMulti(ctx, req, c.opts) } return nil, errors.New("invalid method type") } func (c *Client) Stop() error { return nil } <file_sep>package activemq import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("messaging.activemq"). SetDescription("ActiveMQ Messaging Target"). SetName("ActiveMQ"). SetProvider(""). SetCategory("Messaging"). SetTags("queue", "pub/sub"). AddProperty( common.NewProperty(). SetKind("string"). SetName("host"). SetTitle("Host Address"). SetDescription("Set ActiveMQ host address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set ActiveMQ username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set ActiveMQ password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_destination"). SetDescription("Set ActiveMQ default destination"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("destination"). SetKind("string"). SetDescription("Set ActiveMQ destination"). SetDefault(""). SetMust(true), ) } <file_sep>package openfaas import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { topic string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.topic, err = meta.MustParseString("topic") if err != nil { return metadata{}, fmt.Errorf("error parsing topic func, %w", err) } return m, nil } <file_sep>package minio import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "minio-target", Kind: "", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, wantErr: false, }, { name: "init - no endpoint key", cfg: config.Spec{ Name: "minio-target", Kind: "", Properties: map[string]string{ "secret_access_key": "minio123", "use_ssl": "false", }, }, wantErr: true, }, { name: "init - bad endpoint key", cfg: config.Spec{ Name: "minio-target", Kind: "", Properties: map[string]string{ "endpoint": "badhost", "secret_access_key": "minio123", "use_ssl": "false", }, }, wantErr: true, }, { name: "init - no access key", cfg: config.Spec{ Name: "minio-target", Kind: "", Properties: map[string]string{ "endpoint": "localhost:9001", "secret_access_key": "minio123", "use_ssl": "false", }, }, wantErr: true, }, { name: "init - no secret key", cfg: config.Spec{ Name: "minio-target", Kind: "", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "use_ssl": "false", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantPutErr %v", err, tt.wantErr) return } }) } } func TestClient_Objects(t *testing.T) { tests := []struct { name string cfg config.Spec putRequest *types.Request getRequest *types.Request removeRequest *types.Request wantPutResponse *types.Response wantGetResponse *types.Response wantRemoveResponse *types.Response wantPutErr bool wantGetErr bool wantRemoveErr bool }{ { name: "valid set get remove request", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, putRequest: types.NewRequest(). SetMetadataKeyValue("method", "put"). SetMetadataKeyValue("param1", "bucket"). SetMetadataKeyValue("param2", "test"). SetData([]byte("test data")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("param1", "bucket"). SetMetadataKeyValue("param2", "test"), removeRequest: types.NewRequest(). SetMetadataKeyValue("method", "remove"). SetMetadataKeyValue("param1", "bucket"). SetMetadataKeyValue("param2", "test"), wantPutResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData([]byte("test data")), wantRemoveResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantPutErr: false, wantGetErr: false, wantRemoveErr: false, }, { name: "invalid put request", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, putRequest: types.NewRequest(). SetMetadataKeyValue("method", "put"). SetMetadataKeyValue("param1", ""). SetMetadataKeyValue("param2", "invalid_test"), getRequest: nil, removeRequest: nil, wantPutResponse: nil, wantGetResponse: nil, wantRemoveResponse: nil, wantPutErr: true, wantGetErr: false, wantRemoveErr: false, }, { name: "invalid get request", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, putRequest: nil, getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("param1", ""). SetMetadataKeyValue("param2", "invalid_test"), removeRequest: nil, wantPutResponse: nil, wantGetResponse: nil, wantRemoveResponse: nil, wantPutErr: false, wantGetErr: true, wantRemoveErr: false, }, { name: "invalid get request - 2", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, putRequest: nil, getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("param1", "invalid_bucket"). SetMetadataKeyValue("param2", "invalid_test"), removeRequest: nil, wantPutResponse: nil, wantGetResponse: nil, wantRemoveResponse: nil, wantPutErr: false, wantGetErr: true, wantRemoveErr: false, }, { name: "invalid remove request", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, putRequest: nil, getRequest: nil, removeRequest: types.NewRequest(). SetMetadataKeyValue("method", "remove"). SetMetadataKeyValue("param1", ""). SetMetadataKeyValue("param2", "invalid_test"), wantPutResponse: nil, wantGetResponse: nil, wantRemoveResponse: nil, wantPutErr: false, wantGetErr: false, wantRemoveErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) if tt.putRequest != nil { gotSetResponse, err := c.Do(ctx, tt.putRequest) if tt.wantPutErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantPutResponse, gotSetResponse) } if tt.getRequest != nil { gotGetResponse, err := c.Do(ctx, tt.getRequest) if tt.wantGetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantGetResponse, gotGetResponse) } if tt.removeRequest != nil { gotRemoveResponse, err := c.Do(ctx, tt.removeRequest) if tt.wantRemoveErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotRemoveResponse) require.EqualValues(t, tt.wantRemoveResponse, gotRemoveResponse) } }) } } func TestClient_Buckets(t *testing.T) { tests := []struct { name string cfg config.Spec makeRequest *types.Request listBucketRequest *types.Request existRequest *types.Request removeRequest *types.Request listObjectsRequest *types.Request makeResponse *types.Response listBucketResponse *types.Response existResponse *types.Response removeResponse *types.Response listObjectsResponse *types.Response makeErr bool listBucketErr bool existErr bool removeErr bool listObjectsErr bool }{ { name: "valid make exist list remove request", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, makeRequest: types.NewRequest(). SetMetadataKeyValue("method", "make_bucket"). SetMetadataKeyValue("param1", "testbucket"), listBucketRequest: types.NewRequest(). SetMetadataKeyValue("method", "list_buckets"), existRequest: types.NewRequest(). SetMetadataKeyValue("method", "bucket_exists"). SetMetadataKeyValue("param1", "testbucket"), removeRequest: types.NewRequest(). SetMetadataKeyValue("method", "remove_bucket"). SetMetadataKeyValue("param1", "testbucket"), listObjectsRequest: types.NewRequest(). SetMetadataKeyValue("method", "list_objects"). SetMetadataKeyValue("param1", "testbucket"), makeResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), listBucketResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), existResponse: types.NewResponse(). SetMetadataKeyValue("exist", "true"). SetMetadataKeyValue("result", "ok"), removeResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), listObjectsResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), makeErr: false, listBucketErr: false, existErr: false, removeErr: false, listObjectsErr: false, }, { name: "invalid make", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, makeRequest: types.NewRequest(). SetMetadataKeyValue("method", "make_bucket"). SetMetadataKeyValue("param1", "__bucket"), listBucketRequest: nil, existRequest: nil, removeRequest: nil, listObjectsRequest: nil, makeResponse: nil, listBucketResponse: nil, existResponse: nil, removeResponse: nil, listObjectsResponse: nil, makeErr: true, listBucketErr: false, existErr: false, removeErr: false, listObjectsErr: false, }, { name: "invalid exist", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, makeRequest: nil, listBucketRequest: nil, existRequest: types.NewRequest(). SetMetadataKeyValue("method", "bucket_exists"). SetMetadataKeyValue("param1", "__bucket"), removeRequest: nil, listObjectsRequest: nil, makeResponse: nil, listBucketResponse: nil, existResponse: nil, removeResponse: nil, listObjectsResponse: nil, makeErr: false, listBucketErr: false, existErr: true, removeErr: false, listObjectsErr: false, }, { name: "invalid remove", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, makeRequest: nil, listBucketRequest: nil, existRequest: nil, removeRequest: types.NewRequest(). SetMetadataKeyValue("method", "remove_bucket"). SetMetadataKeyValue("param1", "__bucket"), listObjectsRequest: nil, makeResponse: nil, listBucketResponse: nil, existResponse: nil, removeResponse: nil, listObjectsResponse: nil, makeErr: false, listBucketErr: false, existErr: false, removeErr: true, listObjectsErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) if tt.makeRequest != nil { response, err := c.Do(ctx, tt.makeRequest) if tt.makeErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) require.EqualValues(t, tt.removeResponse, response) } if tt.existRequest != nil { response, err := c.Do(ctx, tt.existRequest) if tt.existErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) require.EqualValues(t, tt.existResponse, response) } if tt.listBucketRequest != nil { response, err := c.Do(ctx, tt.listBucketRequest) if tt.listBucketErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) require.EqualValues(t, tt.listBucketResponse.Metadata, response.Metadata) } if tt.removeRequest != nil { response, err := c.Do(ctx, tt.removeRequest) if tt.removeErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) require.EqualValues(t, tt.removeResponse, response) } if tt.listObjectsRequest != nil { response, err := c.Do(ctx, tt.listObjectsRequest) if tt.listObjectsErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) require.EqualValues(t, tt.listObjectsResponse.Metadata, response.Metadata) } }) } } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid request", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "list_objects"). SetMetadataKeyValue("param1", "bucket"), wantErr: false, }, { name: "invalid metadata request", cfg: config.Spec{ Name: "minio", Kind: "minio", Properties: map[string]string{ "endpoint": "localhost:9001", "access_key_id": "minio", "secret_access_key": "minio123", "use_ssl": "false", }, }, request: types.NewRequest(). SetMetadataKeyValue("param1", "bucket"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) _, err = c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } <file_sep># Kubemq Query Source Kubemq Query source provides rpc query subscriber for processing source queries. ## Prerequisites The following are required to run query source connector: - kubemq cluster - kubemq-targets deployment ## Configuration Query source connector configuration properties: | Properties Key | Required | Description | Example | |:---------------------------|:---------|:--------------------------------------|:----------------| | address | yes | kubemq server address (gRPC interface) | kubemq-cluster:50000 | | client_id | no | set client id | "client_id" | | auth_token | no | set authentication token | jwt token | | channel | yes | set channel to subscribe | | | group | no | set subscriber group | | | sources | no | set how many query sources to subscribe | 1 | | auto_reconnect | no | set auto reconnect on lost connection | "false", "true" | | reconnect_interval_seconds | no | set reconnection seconds | "5" | | max_reconnects | no | set how many times to reconnect | "0" | Example: ```yaml bindings: - name: kubemq-query-elastic-search source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-elastic-search-connector" auth_token: "" channel: "query.elastic-search" group: "" source: "1" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: stores.elastic-search name: target-elastic-search properties: urls: "http://localhost:9200" username: "admin" password: "<PASSWORD>" sniff: "false" ``` <file_sep>package cloudfunctions import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { projectID string cred string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/projectID.txt") if err != nil { return nil, err } t.projectID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") if err != nil { return nil, err } t.cred = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "google-pubsub-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, wantErr: false, }, { name: "invalid init-missing-credentials", cfg: config.Spec{ Name: "google-pubsub-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, }, }, wantErr: true, }, { name: "invalid init-missing-project-id", cfg: config.Spec{ Name: "google-pubsub-target", Kind: "", Properties: map[string]string{ "credentials": dat.cred, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Do(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request want *types.Response wantErr bool }{ { name: "valid google-function sent", cfg: config.Spec{ Name: "target-google-cloudfunctions", Kind: "google.cloudfunctions", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, request: types.NewRequest(). SetMetadataKeyValue("name", "kube-test"). SetData([]byte(`{"data":"dGVzdGluZzEyMy4uLg=="}`)), want: types.NewResponse().SetData([]byte("test")), wantErr: false, }, { name: "valid google-function sent", cfg: config.Spec{ Name: "target-google-cloudfunctions", Kind: "google.cloudfunctions", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, request: types.NewRequest(). SetMetadataKeyValue("name", "kube-test"). SetMetadataKeyValue("project_id", dat.projectID). SetMetadataKeyValue("location", "us-central1").SetData([]byte(`{"data":"dGVzdGluZzEyMy4uLg=="}`)), want: types.NewResponse().SetData([]byte("test")), wantErr: false, }, { name: "invalid google-function location with no match", cfg: config.Spec{ Name: "target-google-cloudfunctions", Kind: "google.cloudfunctions", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "location_match": "false", }, }, request: types.NewRequest(). SetMetadataKeyValue("name", "test-kubemq"). SetData([]byte(`{"message":"test"}`)), want: types.NewResponse().SetData([]byte("test")), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package kafka import ( "strings" "testing" b64 "encoding/base64" kafka "github.com/Shopify/sarama" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestMetadata_parseMeta(t *testing.T) { tests := []struct { name string meta types.Metadata wantMetadata metadata wantErr bool }{ { name: "valid simple", meta: map[string]string{ "key": "_replaceKey_", }, wantMetadata: metadata{ Key: []byte("key"), }, wantErr: false, }, { name: "valid Headers", meta: map[string]string{ "headers": `[{"Key": "_replaceHK_","Value": "_replaceHV_"}]`, "key": "_replaceKey_", }, wantMetadata: metadata{ Headers: []kafka.RecordHeader{ { Key: []byte("meta1"), Value: []byte("dog"), }, }, Key: []byte("key"), }, wantErr: false, }, { name: "invalid Headers_value is not base64", meta: map[string]string{ "headers": `[{"Key": "meta1","Value": "badvalue"}]`, "key": "_replaceKey_", }, wantMetadata: metadata{ Headers: []kafka.RecordHeader{ { Key: []byte("meta1"), Value: []byte("badvalue"), }, }, Key: []byte("key"), }, wantErr: true, }, { name: "invalid Headers_json bad format ", meta: map[string]string{ "headers": `[{"Key": "meta1""Value": "badvalue"}]`, "key": "_replaceKey_", }, wantMetadata: metadata{}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r := strings.NewReplacer( "_replaceHV_", b64.StdEncoding.EncodeToString([]byte("meta1")), "_replaceHK_", b64.StdEncoding.EncodeToString([]byte("dog")), "_replaceKey_", b64.StdEncoding.EncodeToString([]byte("key"))) tt.meta["headers"] = r.Replace(tt.meta["Headers"]) tt.meta["key"] = r.Replace(tt.meta["Key"]) meta, err := parseMetadata(tt.meta, options{}) if tt.wantErr { require.Error(t, err) } else { require.NoError(t, err) } require.EqualValues(t, tt.wantMetadata, meta) }) } } <file_sep>package sources import ( "context" "fmt" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/middleware" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/sources/command" "github.com/kubemq-io/kubemq-targets/sources/events" events_store "github.com/kubemq-io/kubemq-targets/sources/events-store" "github.com/kubemq-io/kubemq-targets/sources/query" "github.com/kubemq-io/kubemq-targets/sources/queue" ) type Source interface { Init(ctx context.Context, cfg config.Spec, bindingName string, log *logger.Logger) error Start(ctx context.Context, target middleware.Middleware) error Stop() error Connector() *common.Connector } func Init(ctx context.Context, cfg config.Spec, bindingName string, log *logger.Logger) (Source, error) { switch cfg.Kind { case "source.command", "kubemq.command": source := command.New() if err := source.Init(ctx, cfg, bindingName, log); err != nil { return nil, err } return source, nil case "source.query", "kubemq.query": target := query.New() if err := target.Init(ctx, cfg, bindingName, log); err != nil { return nil, err } return target, nil case "source.events", "kubemq.events": source := events.New() if err := source.Init(ctx, cfg, bindingName, log); err != nil { return nil, err } return source, nil case "source.events-store", "kubemq.events-store": source := events_store.New() if err := source.Init(ctx, cfg, bindingName, log); err != nil { return nil, err } return source, nil case "source.queue", "kubemq.queue": source := queue.New() if err := source.Init(ctx, cfg, bindingName, log); err != nil { return nil, err } return source, nil default: return nil, fmt.Errorf("invalid kind %s for source", cfg.Kind) } } func Connectors() common.Connectors { return []*common.Connector{ queue.Connector(), query.Connector(), events.Connector(), events_store.Connector(), command.Connector(), } } <file_sep>package blob import ( "bytes" "context" "encoding/json" "errors" "fmt" "net/url" "time" "github.com/Azure/azure-pipeline-go/pipeline" "github.com/Azure/azure-storage-blob-go/azblob" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options pipeLine pipeline.Pipeline } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } // Create a default request pipeline using your storage account name and account key. credential, err := azblob.NewSharedKeyCredential(c.opts.storageAccount, c.opts.storageAccessKey) if err != nil { return fmt.Errorf("failed to create shared key credential on error %s , please check storage access key and acccount are correct", err.Error()) } c.pipeLine = azblob.NewPipeline(credential, azblob.PipelineOptions{ Retry: azblob.RetryOptions{ Policy: c.opts.policy, // Use exponential backoff as opposed to linear MaxTries: c.opts.maxTries, // Try at most x times to perform the operation (set to 1 to disable retries) TryTimeout: time.Millisecond * c.opts.tryTimeout, // Maximum time allowed for any single try RetryDelay: time.Millisecond * c.opts.retryDelay, // Backoff amount for each retry (exponential or linear) MaxRetryDelay: time.Millisecond * c.opts.maxRetryDelay, // Max delay between retries }, }) return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "upload": return c.upload(ctx, meta, req.Data) case "get": return c.get(ctx, meta) case "delete": return c.delete(ctx, meta) } return nil, errors.New("invalid method type") } func (c *Client) upload(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data to upload") } URL, err := url.Parse(meta.serviceUrl) if err != nil { return nil, err } containerURL := azblob.NewContainerURL(*URL, c.pipeLine) blobURL := containerURL.NewBlockBlobURL(meta.fileName) uploadFileOption := azblob.UploadToBlockBlobOptions{ BlockSize: meta.blockSize, Parallelism: meta.parallelism, } if len(meta.blobMetadata) > 0 { uploadFileOption.Metadata = meta.blobMetadata } _, err = azblob.UploadBufferToBlockBlob(ctx, data, blobURL, uploadFileOption) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) get(ctx context.Context, meta metadata) (*types.Response, error) { URL, err := url.Parse(meta.serviceUrl) if err != nil { return nil, err } containerURL := azblob.NewContainerURL(*URL, c.pipeLine) blobURL := containerURL.NewBlobURL(meta.fileName) downloadResponse, err := blobURL.Download(ctx, meta.offset, meta.count, azblob.BlobAccessConditions{}, false) if err != nil { return nil, err } bodyStream := downloadResponse.Body(azblob.RetryReaderOptions{MaxRetryRequests: meta.maxRetryRequests}) defer func() { _ = bodyStream.Close() }() // read the body into a buffer downloadedData := bytes.Buffer{} _, err = downloadedData.ReadFrom(bodyStream) if err != nil { return nil, err } b := downloadedData.Bytes() m := downloadResponse.NewMetadata() if len(m) > 0 { jsonString, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("blob_metadata", string(jsonString)). SetMetadataKeyValue("result", "ok"), nil } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) delete(ctx context.Context, meta metadata) (*types.Response, error) { URL, err := url.Parse(meta.serviceUrl) if err != nil { return nil, err } containerURL := azblob.NewContainerURL(*URL, c.pipeLine) blobURL := containerURL.NewBlobURL(meta.fileName) _, err = blobURL.Delete(ctx, meta.deleteSnapshotsOptionType, azblob.BlobAccessConditions{}) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return nil } <file_sep>package logs import ( "context" "encoding/json" "errors" "fmt" "sort" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudwatchlogs" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *cloudwatchlogs.CloudWatchLogs } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := cloudwatchlogs.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "create_log_event_stream": return c.createLogEventStream(ctx, meta) case "describe_log_event_stream": return c.describeLogEventStream(ctx, meta) case "delete_log_event_stream": return c.deleteLogEventStream(ctx, meta) case "put_log_event": return c.putLogEvent(ctx, meta, req.Data) case "get_log_event": return c.getLogEvent(ctx, meta) case "create_log_group": return c.createLogEventGroup(ctx, meta, req.Data) case "describe_log_group": return c.describeLogGroup(ctx, meta) case "delete_log_group": return c.deleteLogEventGroup(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) createLogEventStream(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.CreateLogStreamWithContext(ctx, &cloudwatchlogs.CreateLogStreamInput{ LogGroupName: aws.String(meta.logGroupName), LogStreamName: aws.String(meta.logStreamName), }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) describeLogEventStream(ctx context.Context, meta metadata) (*types.Response, error) { resp, err := c.client.DescribeLogStreamsWithContext(ctx, &cloudwatchlogs.DescribeLogStreamsInput{ LogGroupName: aws.String(meta.logGroupName), }) if err != nil { return nil, err } b, err := json.Marshal(resp) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) deleteLogEventStream(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.DeleteLogStreamWithContext(ctx, &cloudwatchlogs.DeleteLogStreamInput{ LogGroupName: aws.String(meta.logGroupName), LogStreamName: aws.String(meta.logStreamName), }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) putLogEvent(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { var m map[int64]string err := json.Unmarshal(data, &m) if err != nil { return nil, errors.New("failed to parse messages ,please verify data is map[int64]string int64:timestamp and string: message") } var inputLogs []*cloudwatchlogs.InputLogEvent for k, v := range m { i := cloudwatchlogs.InputLogEvent{ Message: aws.String(v), Timestamp: aws.Int64(k), } inputLogs = append(inputLogs, &i) } sort.Slice(inputLogs, func(i, j int) bool { return *inputLogs[i].Timestamp < *inputLogs[j].Timestamp }) resp, err := c.client.PutLogEventsWithContext(ctx, &cloudwatchlogs.PutLogEventsInput{ LogGroupName: aws.String(meta.logGroupName), LogStreamName: aws.String(meta.logStreamName), SequenceToken: aws.String(meta.sequenceToken), LogEvents: inputLogs, }) if err != nil { return nil, err } if resp.RejectedLogEventsInfo != nil { return nil, fmt.Errorf("%v", resp.RejectedLogEventsInfo) } b, err := json.Marshal(resp) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) getLogEvent(ctx context.Context, meta metadata) (*types.Response, error) { resp, err := c.client.GetLogEventsWithContext(ctx, &cloudwatchlogs.GetLogEventsInput{ LogGroupName: aws.String(meta.logGroupName), LogStreamName: aws.String(meta.logStreamName), Limit: aws.Int64(meta.limit), }) if err != nil { return nil, err } b, err := json.Marshal(resp) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) createLogEventGroup(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { m := make(map[string]*string) var err error if data != nil { err := json.Unmarshal(data, &m) if err != nil { return nil, err } _, err = c.client.CreateLogGroupWithContext(ctx, &cloudwatchlogs.CreateLogGroupInput{ LogGroupName: aws.String(meta.logGroupName), Tags: m, }) if err != nil { return nil, err } } else { _, err = c.client.CreateLogGroupWithContext(ctx, &cloudwatchlogs.CreateLogGroupInput{ LogGroupName: aws.String(meta.logGroupName), }) if err != nil { return nil, err } } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteLogEventGroup(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.DeleteLogGroupWithContext(ctx, &cloudwatchlogs.DeleteLogGroupInput{ LogGroupName: aws.String(meta.logGroupName), }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) describeLogGroup(ctx context.Context, meta metadata) (*types.Response, error) { resp, err := c.client.DescribeLogGroupsWithContext(ctx, &cloudwatchlogs.DescribeLogGroupsInput{ LogGroupNamePrefix: aws.String(meta.logGroupPrefix), }) if err != nil { return nil, err } b, err := json.Marshal(resp) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>package cassandra import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.cassandra"). SetDescription("Cassandra Target"). SetName("Cassandra"). SetProvider(""). SetCategory("Store"). SetTags("db", "sql", "no-sql"). AddProperty( common.NewProperty(). SetKind("string"). SetName("hosts"). SetTitle("Hosts Addresses"). SetDescription("Set Cassandra hosts addresses"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("port"). SetDescription("Set Cassandra port"). SetMust(true). SetMin(0). SetMax(65535). SetDefault("9042"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Cassandra username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Cassandra password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("replication_factor"). SetDescription("Set Cassandra replication factor"). SetMust(false). SetDefault("1"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("consistency"). SetDescription("Set Cassandra consistency"). SetMust(false). SetOptions([]string{"All", "One", "Two", "Three", "Quorum", "LocalQuorum", "EachQuorum", "LocalOne", "Any"}). SetDefault("All"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_table"). SetDescription("Set Cassandra default table"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_keyspace"). SetDescription("Set Cassandra default keyspace"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connect_timeout_seconds"). SetTitle("Connect Timeout (Seconds)"). SetDescription("Set Cassandra connection timeout in seconds"). SetMust(false). SetDefault("60"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("timeout_seconds"). SetTitle("Operation Timeout (Seconds)"). SetDescription("Set Cassandra operation timeout in seconds"). SetMust(false). SetDefault("60"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Cassandra execution method"). SetOptions([]string{"get", "set", "delete", "query", "exec"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("consistency"). SetDescription("Set Cassandra consistency Level"). SetOptions([]string{"strong", "eventual", ""}). SetDefault("strong"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Cassandra key to set get or delete"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("table"). SetKind("string"). SetDescription("Cassandra table name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("keyspace"). SetKind("string"). SetDescription("Cassandra keyspace data container name"). SetDefault(""). SetMust(false), ) } <file_sep>#FROM kubemq/gobuilder as builder FROM kubemq/gobuilder-ubuntu:latest as builder ARG VERSION ARG GIT_COMMIT ARG BUILD_TIME ENV GOPATH=/go ENV PATH=$GOPATH:$PATH ENV ADDR=0.0.0.0 ADD . $GOPATH/github.com/kubemq-io/kubemq-targets WORKDIR $GOPATH/github.com/kubemq-io/kubemq-targets RUN CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -tags container -a -mod=vendor -installsuffix cgo -ldflags="-w -s -X main.version=$VERSION" -o kubemq-targets-run . FROM registry.access.redhat.com/ubi8/ubi-minimal:latest #RUN microdnf install yum \ # && yum -y update-minimal --security --sec-severity=Important --sec-severity=Critical \ # && yum clean all \ # && microdnf remove yum \ # && microdnf clean all MAINTAINER KubeMQ <EMAIL> LABEL name="KubeMQ Target Connectors" \ maintainer="<EMAIL>" \ vendor="kubemq.io" \ version="1.5.0" \ release="stable" \ summary="KubeMQ Targets connects KubeMQ Message Broker with external systems and cloud services" \ description="KubeMQ Targets allows us to build a message-based microservices architecture on Kubernetes with minimal efforts and without developing connectivity interfaces between KubeMQ Message Broker and external systems such as databases, cache, messaging, and REST-base APIs" COPY licenses /licenses ENV GOPATH=/go ENV PATH=$GOPATH/bin:$PATH RUN mkdir -p /opt/mqm/lib64 COPY --from=builder /opt/mqm/lib64 /opt/mqm/lib64 RUN mkdir /kubemq-connector COPY --from=builder $GOPATH/github.com/kubemq-io/kubemq-targets/kubemq-targets-run ./kubemq-connector COPY --from=builder $GOPATH/github.com/kubemq-io/kubemq-targets/default_config.yaml ./kubemq-connector/config.yaml RUN chown -R 1001:root /kubemq-connector && chmod g+rwX /kubemq-connector WORKDIR kubemq-connector USER 1001 CMD ["./kubemq-targets-run"] <file_sep>package nats import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { subject string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.subject, err = meta.MustParseString("subject") if err != nil { return metadata{}, fmt.Errorf("error parsing subject name, %w", err) } return m, nil } <file_sep>package types import "time" type Activity struct { Id int64 `storm:"id,increment"` Binding string `storm:"index"` CreatedAt time.Time Request *Request Response *Response Error error } func NewActivity() *Activity { return &Activity{ CreatedAt: time.Now(), } } //func (a *Activity) SetBindings { // //} <file_sep>package memcached import ( "context" "errors" "fmt" "time" "github.com/bradfitz/gomemcache/memcache" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" ) // Client is a Client state store type Client struct { log *logger.Logger client *memcache.Client opts options } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.client = memcache.New(c.opts.hosts...) c.client.Timeout = time.Duration(c.opts.defaultTimeoutSeconds) * time.Second c.client.MaxIdleConns = c.opts.maxIdleConnections err = c.client.Ping() if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.Get(ctx, meta) case "set": return c.Set(ctx, meta, req.Data) case "delete": return c.Delete(ctx, meta) } return nil, errors.New("invalid method type") } func (c *Client) Get(ctx context.Context, meta metadata) (*types.Response, error) { item, err := c.client.Get(meta.key) if err != nil { // Return nil for status 204 if errors.Is(err, memcache.ErrCacheMiss) { return nil, fmt.Errorf("no data found for this key") } return nil, err } return types.NewResponse(). SetData(item.Value). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) Set(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { err := c.client.Set(&memcache.Item{Key: meta.key, Value: value}) if err != nil { return nil, fmt.Errorf("failed to set key %s: %s", meta.key, err) } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Delete(ctx context.Context, meta metadata) (*types.Response, error) { err := c.client.Delete(meta.key) if err != nil { return nil, fmt.Errorf("failed to delete key '%s',%w", meta.key, err) } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return nil } <file_sep>package couchbase import ( "context" "fmt" "time" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/couchbase/gocb/v2" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" ) const defaultWaitBucketReady = 5 * time.Second type Client struct { log *logger.Logger opts options cluster *gocb.Cluster bucket *gocb.Bucket collection *gocb.Collection } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } clusterOpts := gocb.ClusterOptions{ Authenticator: gocb.PasswordAuthenticator{ Username: c.opts.username, Password: c.opts.password, }, } c.cluster, err = gocb.Connect(c.opts.url, clusterOpts) if err != nil { return fmt.Errorf("couchbase error: unable to connect to couchbase at %s - %v ", c.opts.url, err) } c.bucket = c.cluster.Bucket(c.opts.bucket) err = c.bucket.WaitUntilReady(defaultWaitBucketReady, nil) if err != nil { _ = c.cluster.Close(&gocb.ClusterCloseOptions{}) return fmt.Errorf("couchbase error: unable to connect to bucket %s - %v ", c.opts.bucket, err) } if c.opts.collection == "" { c.collection = c.bucket.DefaultCollection() } else { c.collection = c.bucket.Collection(c.opts.collection) } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.Get(ctx, meta) case "set": return c.Set(ctx, meta, req.Data) case "delete": return c.Delete(ctx, meta) } return nil, nil } func (c *Client) Get(ctx context.Context, meta metadata) (*types.Response, error) { var timeout time.Duration deadline, ok := ctx.Deadline() if ok { timeout = time.Until(deadline) } result, err := c.collection.Get(meta.key, &gocb.GetOptions{ WithExpiry: false, Project: nil, Transcoder: gocb.NewRawBinaryTranscoder(), Timeout: timeout, RetryStrategy: nil, }) if err != nil { return nil, err } var value []byte err = result.Content(&value) if err != nil { return nil, err } return types.NewResponse(). SetData(value). SetMetadataKeyValue("error", "false"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) Set(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { var timeout time.Duration deadline, ok := ctx.Deadline() if ok { timeout = time.Until(deadline) } _, err := c.collection.Upsert(meta.key, data, &gocb.UpsertOptions{ Expiry: meta.expiry, PersistTo: uint(c.opts.numToPersist), ReplicateTo: uint(c.opts.numToReplicate), Transcoder: gocb.NewRawBinaryTranscoder(), Timeout: timeout, RetryStrategy: nil, }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Delete(ctx context.Context, meta metadata) (*types.Response, error) { var timeout time.Duration deadline, ok := ctx.Deadline() if ok { timeout = time.Until(deadline) } _, err := c.collection.Remove(meta.key, &gocb.RemoveOptions{ Cas: gocb.Cas(meta.cas), PersistTo: uint(c.opts.numToPersist), ReplicateTo: uint(c.opts.numToReplicate), DurabilityLevel: 0, Timeout: timeout, RetryStrategy: nil, }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return c.cluster.Close(&gocb.ClusterCloseOptions{}) } <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // listRequest listRequest := types.NewRequest(). SetMetadataKeyValue("method", "list_buckets") queryListResponse, err := client.SetQuery(listRequest.ToQuery()). SetChannel("query.aws.s3"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } listResponse, err := types.ParseResponse(queryListResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("list buckets executed, response: %s", listResponse.Data)) // Create Bucket BucketName := "testmykubemqbucketname" createRequest := types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("bucket_name", BucketName). SetMetadataKeyValue("wait_for_completion", "true") getCreate, err := client.SetQuery(createRequest.ToQuery()). SetChannel("query.aws.s3"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } createResponse, err := types.ParseResponse(getCreate.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("create bucket executed, error: %v", createResponse.IsError)) } <file_sep>package s3 import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string itemName string bucketName string testBucketName string dstBucketName string file []byte } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" dat, err = ioutil.ReadFile("./../../../credentials/aws/s3/itemName.txt") if err != nil { return nil, err } t.itemName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/s3/bucketName.txt") if err != nil { return nil, err } t.bucketName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/s3/testBucketName.txt") if err != nil { return nil, err } t.testBucketName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/s3/srcBucket.txt") if err != nil { return nil, err } t.dstBucketName = string(dat) contents, err := ioutil.ReadFile("./../../../credentials/aws/s3/contents.txt") if err != nil { return nil, err } t.file = contents return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool wantUploader bool wantDownloader bool }{ { name: "init - no uploader - no downloader", cfg: config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, }, wantUploader: false, wantDownloader: false, wantErr: false, }, { name: "init - no uploader", cfg: config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "true", "uploader": "false", }, }, wantUploader: false, wantDownloader: true, wantErr: false, }, { name: "init - no downloader", cfg: config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "true", }, }, wantUploader: true, wantDownloader: false, wantErr: false, }, { name: "init ", cfg: config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "true", "uploader": "true", }, }, wantUploader: true, wantDownloader: true, wantErr: false, }, { name: "invalid init - missing secret key", cfg: config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "region": dat.region, }, }, wantUploader: false, wantDownloader: false, wantErr: true, }, { name: "invalid init - missing key", cfg: config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantUploader: false, wantDownloader: false, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) if tt.wantDownloader { require.NotNil(t, c.downloader) } else { require.Nil(t, c.downloader) } if tt.wantUploader { require.NotNil(t, c.uploader) } else { require.Nil(t, c.uploader) } }) } } func TestClient_List_Buckets(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_buckets"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Bucket_Items(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_bucket_items"). SetMetadataKeyValue("bucket_name", dat.bucketName), wantErr: false, }, { name: "invalid list - missing bucket_name", request: types.NewRequest(). SetMetadataKeyValue("method", "list_bucket_items"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Create_Bucket(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: false, }, { name: "invalid create - missing bucket_name", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"), wantErr: true, }, { name: "invalid create - Already exists", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Upload_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "true", }, } tests := []struct { name string request *types.Request wantErr bool setUploader bool }{ { name: "valid upload item", request: types.NewRequest(). SetMetadataKeyValue("method", "upload_item"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("bucket_name", dat.testBucketName). SetMetadataKeyValue("item_name", dat.itemName). SetData(dat.file), wantErr: false, setUploader: true, }, { name: "invalid upload - missing item", request: types.NewRequest(). SetMetadataKeyValue("method", "upload_item"). SetMetadataKeyValue("bucket_name", dat.testBucketName). SetData(dat.file), wantErr: true, setUploader: true, }, { name: "invalid upload - missing uploader", request: types.NewRequest(). SetMetadataKeyValue("method", "upload_item"). SetMetadataKeyValue("item_name", dat.itemName). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: true, setUploader: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if !tt.setUploader { cfg.Properties["uploader"] = "false" } else { cfg.Properties["uploader"] = "true" } err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Get_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "true", "uploader": "false", }, } tests := []struct { name string request *types.Request wantErr bool setDownloader bool }{ { name: "valid get item", request: types.NewRequest(). SetMetadataKeyValue("method", "get_item"). SetMetadataKeyValue("bucket_name", dat.testBucketName). SetMetadataKeyValue("item_name", dat.itemName), wantErr: false, setDownloader: true, }, { name: "invalid get - missing item", request: types.NewRequest(). SetMetadataKeyValue("method", "get_item"). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: true, setDownloader: true, }, { name: "invalid get - item does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "get_item"). SetMetadataKeyValue("bucket_name", dat.testBucketName). SetMetadataKeyValue("item_name", "fakeItemName"), wantErr: true, setDownloader: true, }, { name: "invalid get - missing bucketName", request: types.NewRequest(). SetMetadataKeyValue("method", "get_item"). SetMetadataKeyValue("item_name", dat.itemName), wantErr: true, setDownloader: true, }, { name: "invalid upload - missing downloader", request: types.NewRequest(). SetMetadataKeyValue("method", "get_item"). SetMetadataKeyValue("bucket_name", dat.testBucketName). SetMetadataKeyValue("item_name", dat.itemName), wantErr: true, setDownloader: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if !tt.setDownloader { cfg.Properties["downloader"] = "false" } else { cfg.Properties["downloader"] = "true" } err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Delete_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete item", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_item_from_bucket"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("bucket_name", dat.testBucketName). SetMetadataKeyValue("item_name", dat.itemName), wantErr: false, }, { name: "invalid delete - missing item", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_item_from_bucket"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: true, }, { name: "invalid delete - missing bucket_name", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_item_from_bucket"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("item_name", dat.itemName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Copy_Items(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid copy items", request: types.NewRequest(). SetMetadataKeyValue("method", "copy_item"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("bucket_name", dat.bucketName). SetMetadataKeyValue("item_name", dat.itemName). SetMetadataKeyValue("copy_source", dat.dstBucketName), wantErr: false, }, { name: "invalid copy items - missing copy_source ", request: types.NewRequest(). SetMetadataKeyValue("method", "copy_item"). SetMetadataKeyValue("bucket_name", dat.testBucketName). SetMetadataKeyValue("item_name", dat.itemName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Delete_All_Items(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete all items", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_all_items_from_bucket"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: false, }, { name: "invalid valid delete all items - missing bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_all_items_from_bucket"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Delete_Bucket(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-s3", Kind: "aws.s3", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "downloader": "false", "uploader": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_bucket"). SetMetadataKeyValue("wait_for_completion", "true"). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: false, }, { name: "invalid delete - missing bucket_name", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"), wantErr: true, }, { name: "invalid delete - bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_bucket"). SetMetadataKeyValue("bucket_name", dat.testBucketName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package bigtable import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { tableName string columnFamily string method string rowKeyPrefix string readColumnName string } var methodsMap = map[string]string{ "write": "write", "write_batch": "write_batch", "get_row": "get_row", "get_all_rows": "get_all_rows", "delete_row": "delete_row", "get_tables": "get_tables", "create_table": "create_table", "delete_table": "delete_table", "create_column_family": "create_column_family", "get_all_rows_by_column": "get_all_rows_by_column", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method != "get_tables" { m.tableName, err = meta.MustParseString("table_name") if err != nil { return metadata{}, fmt.Errorf("table_name is required for method:%s , error parsing table_name, %w", m.method, err) } } if m.method == "write" || m.method == "write_batch" || m.method == "create_column_family" { m.columnFamily, err = meta.MustParseString("column_family") if err != nil { return metadata{}, fmt.Errorf("column_family is required for method:%s ,error parsing column_family, %w", m.method, err) } } else if m.method == "delete_row" || m.method == "get_row" { m.rowKeyPrefix, err = meta.MustParseString("row_key_prefix") if err != nil { return metadata{}, fmt.Errorf("row_key_prefix is required for method:%s ,error parsing row_key_prefix, %w", m.method, err) } } if m.method == "get_all_rows_by_column" { m.readColumnName, err = meta.MustParseString("column_name") if err != nil { return metadata{}, fmt.Errorf("column_name is required for method:%s , error parsing column_name, %w", m.method, err) } } return m, nil } <file_sep>package metrics import ( "net/http" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) var labels = []string{"binding", "source_kind", "target_kind"} type Exporter struct { Store *Store requestsCollector *promCounterMetric responsesCollector *promCounterMetric requestsVolumeCollector *promCounterMetric responsesVolumeCollector *promCounterMetric errorsCollector *promCounterMetric } func (e *Exporter) PrometheusHandler() http.Handler { return promhttp.Handler() } func NewExporter() (*Exporter, error) { e := &Exporter{ Store: NewStore(), requestsCollector: nil, responsesCollector: nil, requestsVolumeCollector: nil, responsesVolumeCollector: nil, errorsCollector: nil, } if err := e.initPromMetrics(); err != nil { return nil, err } return e, nil } func (e *Exporter) initPromMetrics() error { e.requestsCollector = newPromCounterMetric( "requests", "count", "counts requests per binding,source and target types", labels..., ) e.responsesCollector = newPromCounterMetric( "responses", "count", "counts responses per binding,source and target types", labels..., ) e.requestsVolumeCollector = newPromCounterMetric( "requests", "volume", "sum requests volume per binding,source and target types", labels..., ) e.responsesVolumeCollector = newPromCounterMetric( "responses", "volume", "sum responses volume per binding,source and target types", labels..., ) e.errorsCollector = newPromCounterMetric( "errors", "count", "counts error requests per binding,source and target types", labels..., ) err := prometheus.Register(e.requestsCollector.metric) if err != nil { return err } err = prometheus.Register(e.responsesCollector.metric) if err != nil { return err } err = prometheus.Register(e.requestsVolumeCollector.metric) if err != nil { return err } err = prometheus.Register(e.responsesVolumeCollector.metric) if err != nil { return err } err = prometheus.Register(e.errorsCollector.metric) if err != nil { return err } return nil } func (e *Exporter) Report(m *Report) { lbs := m.labels() e.requestsCollector.add(m.RequestCount, lbs) e.requestsVolumeCollector.add(m.RequestVolume, lbs) e.responsesCollector.add(m.ResponseCount, lbs) e.responsesVolumeCollector.add(m.ResponseVolume, lbs) e.errorsCollector.add(m.ErrorsCount, lbs) e.Store.Add(m) } <file_sep>package memcached import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("cache.memcached"). SetDescription("Memcached Target"). SetName("Memcached"). SetProvider(""). SetCategory("Cache"). SetTags("db"). AddProperty( common.NewProperty(). SetKind("string"). SetName("hosts"). SetTitle("Hosts Address"). SetDescription("Set Memcached hosts"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_idle_connections"). SetDescription("Set Memcached max idle connections"). SetDefault("2"). SetMin(1). SetMax(math.MaxInt32). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("default_timeout_seconds"). SetTitle("Default Timeout (Seconds)"). SetDescription("Set Memcached default timeout seconds"). SetDefault("30"). SetMin(1). SetMax(math.MaxInt32). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Memcached execution method"). SetOptions([]string{"get", "set", "delete"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Set Memcached key"). SetMust(true), ) } <file_sep>package athena import ( "context" "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/athena" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *athena.Athena } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := athena.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "list_databases": return c.listDatabases(ctx, meta) case "list_data_catalogs": return c.listDataCatalogs(ctx) case "query": return c.query(ctx, meta) case "get_query_result": return c.getQueryResult(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) listDatabases(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.ListDatabasesWithContext(ctx, &athena.ListDatabasesInput{ CatalogName: aws.String(meta.catalog), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listDataCatalogs(ctx context.Context) (*types.Response, error) { m, err := c.client.ListDataCatalogsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) query(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.StartQueryExecutionWithContext(ctx, &athena.StartQueryExecutionInput{ QueryString: aws.String(meta.query), QueryExecutionContext: &athena.QueryExecutionContext{ Catalog: aws.String(meta.catalog), Database: aws.String(meta.DB), }, ResultConfiguration: &athena.ResultConfiguration{ OutputLocation: aws.String(meta.outputLocation), }, }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("execution_id", *m.QueryExecutionId). SetData(b), nil } func (c *Client) getQueryResult(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.GetQueryResultsWithContext(ctx, &athena.GetQueryResultsInput{ QueryExecutionId: aws.String(meta.executionID), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>//go:build !container // +build !container package main import ( "os" "github.com/kardianos/service" "github.com/kubemq-io/kubemq-targets/pkg/logger" ) type appService struct { serviceExit chan bool errCh chan error svclogger service.Logger } func newAppService() *appService { a := &appService{ serviceExit: make(chan bool, 1), errCh: make(chan error, 5), } return a } func (a *appService) init(action, username, password string) error { options := make(service.KeyValue) options["Restart"] = "on-success" options["SuccessExitStatus"] = "1 2 8 SIGKILL" options["Password"] = <PASSWORD> svcConfig := &service.Config{ Name: "KubeMQ Targets", DisplayName: "KubeMQ Targets", Description: "KubeMQ Targets connects KubeMQ Message Broker with external systems and cloud services.", UserName: username, Arguments: nil, Executable: "", Dependencies: []string{}, WorkingDirectory: "", ChRoot: "", Option: options, } srv, err := service.New(a, svcConfig) if err != nil { return err } a.svclogger, err = srv.Logger(a.errCh) if err != nil { log.Fatal(err) } go func() { for { err := <-a.errCh if err != nil { log.Error(err) } } }() if action != "" { err := service.Control(srv, action) if err != nil { return err } log.Infof("service command %s completed", action) return nil } err = srv.Run() return err } func (a *appService) Start(s service.Service) error { if service.Interactive() { preRun() log.Infof("starting kubemq targets connectors version: %s", version) } else { logger.ServiceLog.SetLogger(a.svclogger) log.Infof("starting kubemq targets connectors as a service version: %s", version) } go func() { err := runInteractive(a.serviceExit) if err != nil { log.Errorf("kubemq targets ended with error: %s", err) os.Exit(1) } else { os.Exit(0) } }() return nil } func (a *appService) Stop(s service.Service) error { a.serviceExit <- true log.Infof("kubemq targets connectors stopped") return nil } <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } randomKey := uuid.New().String() // set request setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", randomKey). SetData([]byte("some-data")) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.memcached"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("set request for key: %s executed, response: %s", randomKey, setResponse.Metadata.String())) // get request getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", randomKey) queryGetResponse, err := client.SetQuery(getRequest.ToQuery()). SetChannel("query.memcached"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(queryGetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get request for key: %s executed, response: %s, data: %s", randomKey, getResponse.Metadata.String(), string(getResponse.Data))) // delete request delRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", randomKey) queryDelResponse, err := client.SetQuery(delRequest.ToQuery()). SetChannel("query.memcached"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } delResponse, err := types.ParseResponse(queryDelResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("delete request for key: %s executed, response: %s", randomKey, delResponse.Metadata.String())) } <file_sep>package dynamodb import ( "context" "fmt" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string tableName string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" dat, err = ioutil.ReadFile("./../../../credentials/aws/dynamodb/tableName.txt") if err != nil { return nil, err } t.tableName = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: false, }, { name: "invalid init - missing aws_key", cfg: config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: true, }, { name: "invalid init - missing region", cfg: config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, }, }, wantErr: true, }, { name: "invalid init - missing aws_secret_key", cfg: config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "region": dat.region, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_List(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_tables"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_CreateTable(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) input := fmt.Sprintf(`{ "AttributeDefinitions": [ { "AttributeName": "Year", "AttributeType": "N" }, { "AttributeName": "Title", "AttributeType": "S" } ], "BillingMode": null, "GlobalSecondaryIndexes": null, "KeySchema": [ { "AttributeName": "Year", "KeyType": "HASH" }, { "AttributeName": "Title", "KeyType": "RANGE" } ], "LocalSecondaryIndexes": null, "ProvisionedThroughput": { "ReadCapacityUnits": 10, "WriteCapacityUnits": 10 }, "SSESpecification": null, "StreamSpecification": null, "TableName": "%s", "Tags": null }`, dat.tableName) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create", request: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetData([]byte(input)), wantErr: false, }, { name: "invalid create - table already exists", request: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetData([]byte(input)), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_InsertItem(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) input := `{ "Plot": { "S": "some plot" }, "Rating": { "N": "10.1" }, "Title": { "S": "KubeMQ test Movie" }, "Year": { "N": "2020" } }` tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid put item", request: types.NewRequest(). SetMetadataKeyValue("method", "insert_item"). SetMetadataKeyValue("table_name", dat.tableName). SetData([]byte(input)), wantErr: false, }, { name: "invalid put item - missing table_name", request: types.NewRequest(). SetMetadataKeyValue("method", "insert_item"). SetData([]byte(input)), wantErr: true, }, { name: "invalid put item - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "insert_item"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_GetItem(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) input := fmt.Sprintf(` { "AttributesToGet": null, "ConsistentRead": null, "ExpressionAttributeNames": null, "Key": { "Title": { "S": "KubeMQ test Movie" }, "Year": { "N": "2020" } }, "ProjectionExpression": null, "ReturnConsumedCapacity": null, "TableName": "%s" }`, dat.tableName) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid put get item", request: types.NewRequest(). SetMetadataKeyValue("method", "get_item"). SetData([]byte(input)), wantErr: false, }, { name: "invalid get item - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "get_item"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_UpdateItem(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) input := fmt.Sprintf(` { "ExpressionAttributeValues": { ":r": { "N": "0.9" } }, "Key": { "Title": { "S": "KubeMQ test Movie" }, "Year": { "N": "2020" } }, "ReturnValues": "UPDATED_NEW", "TableName": "%s", "UpdateExpression": "set Rating = :r" }`, dat.tableName) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid update item", request: types.NewRequest(). SetMetadataKeyValue("method", "update_item"). SetData([]byte(input)), wantErr: false, }, { name: "invalid update item - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "update_item"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_DeleteItem(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) input := fmt.Sprintf( `{ "Key": { "Title": { "S": "KubeMQ test Movie" }, "Year": { "N": "2020" } }, "TableName": "%s" }`, dat.tableName) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete_item item", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_item"). SetData([]byte(input)), wantErr: false, }, { name: "invalid delete_item - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_item"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_DeleteTable(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-dynamodb", Kind: "aws.dynamodb", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete_table ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: false, }, { name: "invalid delete_table - table does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "invalid delete_table - missing table name", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // listRequest listRequest := types.NewRequest(). SetMetadataKeyValue("method", "list_streams") queryListResponse, err := client.SetQuery(listRequest.ToQuery()). SetChannel("query.aws.kinesis"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } listResponse, err := types.ParseResponse(queryListResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("list_streams executed, response: %s", listResponse.Data)) dat, err := ioutil.ReadFile("./credentials/aws/kinesis/streamName.txt") if err != nil { panic(err) } streamName := string(dat) dat, err = ioutil.ReadFile("./credentials/aws/kinesis/partitionKey.txt") if err != nil { panic(err) } partitionKey := string(dat) // putRecord putRequest := types.NewRequest(). SetMetadataKeyValue("method", "put_record"). SetMetadataKeyValue("partition_key", partitionKey). SetMetadataKeyValue("stream_name", streamName). SetData([]byte("{\"my_result\":\"ok\"})")) queryPutResponse, err := client.SetQuery(putRequest.ToQuery()). SetChannel("query.aws.kinesis"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } putResponse, err := types.ParseResponse(queryPutResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("put query executed, response: %s", putResponse.Data)) } <file_sep>package athena import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { method string query string catalog string outputLocation string DB string executionID string } var methodsMap = map[string]string{ "list_databases": "list_databases", "list_data_catalogs": "list_data_catalogs", "query": "query", "get_query_result": "get_query_result", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method != "list_data_catalogs" && m.method != "get_query_result" { m.catalog, err = meta.MustParseString("catalog") if err != nil { return metadata{}, fmt.Errorf("catalog is required for method:%s,error parsing catalog, %w", m.method, err) } if m.method == "query" { m.query, err = meta.MustParseString("query") if err != nil { return metadata{}, fmt.Errorf("query is required for method:%s , error parsing query, %w", m.method, err) } m.DB, err = meta.MustParseString("db") if err != nil { return metadata{}, fmt.Errorf("db is required for method:%s , error parsing db, %w", m.method, err) } m.outputLocation, err = meta.MustParseString("output_location") if err != nil { return metadata{}, fmt.Errorf("output_location is required for method:%s ,error parsing output_location, %w", m.method, err) } } } if m.method == "get_query_result" { m.executionID, err = meta.MustParseString("execution_id") if err != nil { return metadata{}, fmt.Errorf("execution_id is required for method:%s error parsing execution_id, %w", m.method, err) } } return m, nil } <file_sep># Kubemq GCP-Postgres Target Connector Kubemq postgres target connector allows services using kubemq server to access postgres database services. ## Prerequisites The following are required to run the postgres target connector: - kubemq cluster - postgres server - kubemq-targets deployment ## Configuration Postgres target connector configuration properties: | Properties Key | Required | Description | Example | |:--------------------------------|:---------|:--------------------------------------------|:-----------------------------------------------------------------------| | max_idle_connections | no | set max idle connections | "10" | | max_open_connections | no | set max open connections | "100" | | connection_max_lifetime_seconds | no | set max lifetime for connections in seconds | "3600" | | credentials | yes | gcp credentials files | "google json credentials" | | instance_connection_name | yes | set sql instance name | project:us-east1:db-porudction | | db_user | yes | gcp db user name files | "google user" | | db_name | yes | gcp db name | "google instance name" | | db_password | yes | gcp db password | "google db password" | Example: ```yaml bindings: - name: kubemq-query-gcp-postgres source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-postgres-connector" auth_token: "" channel: "query.postgres" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.stores.postgres name: target-gcp-postgres properties: instance_connection_name: "instanceConnectionName" db_user: "user" db_name: "dbName" db_password: "<PASSWORD>" max_idle_connections: "10" max_open_connections: "100" connection_max_lifetime_seconds: "3600" credentials: 'json' ``` ## Usage ### Query Request Query request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | set type of request | "query" | Query request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:-------------|:-------------------| | data | yes | query string | base64 bytes array | Example: Query string: `SELECT id,title,content FROM post;` ```json { "metadata": { "method": "query" }, "data": "U0VMRUNUIGlkLHRpdGxlLGNvbnRlbnQgRlJPTSBwb3N0Ow==" } ``` ### Exec Request Exec request metadata setting: | Metadata Key | Required | Description | Possible values | |:----------------|:---------|:---------------------------------------|:-------------------| | method | yes | set type of request | "exec" | | isolation_level | no | set isolation level for exec operation | "" | | | | | "read_uncommitted" | | | | | "read_committed" | | | | | "repeatable_read" | | | | | "serializable" | | | | | | Exec request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | exec string | base64 bytes array | Example: Exec string: ```sql INSERT INTO post(ID,TITLE,CONTENT) VALUES (1,NULL,'Content One'),(2,'Title Two','Content Two'); ``` ```json { "metadata": { "method": "exec", "isolation_level": "read_uncommitted" }, "data": "SU5TRVJUIElOVE8gcG9zdChJRCxUSVRMRSxDT05URU<KEY>" } ``` ### Transaction Request Transaction request metadata setting: | Metadata Key | Required | Description | Possible values | |:----------------|:---------|:---------------------------------------|:-------------------| | method | yes | set type of request | "transaction" | | isolation_level | no | set isolation level for exec operation | "" | | | | | "read_uncommitted" | | | | | "read_committed" | | | | | "repeatable_read" | | | | | "serializable" | Transaction request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | string string | base64 bytes array | Example: Transaction string: ```sql DROP TABLE IF EXISTS post; CREATE TABLE post ( ID serial, TITLE varchar(40), CONTENT varchar(255), CONSTRAINT pk_post PRIMARY KEY(ID) ); INSERT INTO post(ID,TITLE,CONTENT) VALUES (1,NULL,'Content One'), (2,'Title Two','Content Two'); ``` ```json { "metadata": { "method": "transaction" }, "data": "<KEY> } ``` <file_sep>package blob import ( "context" "fmt" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { storageAccessKey string storageAccount string fileName string fileWithMetadata string serviceURL string file []byte } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../../credentials/azure/storage/blob/storageAccessKey.txt") if err != nil { return nil, err } t.storageAccessKey = string(dat) dat, err = ioutil.ReadFile("./../../../../credentials/azure/storage/blob/storageAccount.txt") if err != nil { return nil, err } t.storageAccount = string(dat) contents, err := ioutil.ReadFile("./../../../../credentials/azure/storage/blob/contents.txt") if err != nil { return nil, err } t.file = contents dat, err = ioutil.ReadFile("./../../../../credentials/azure/storage/blob/fileName.txt") if err != nil { return nil, err } t.fileName = string(dat) dat, err = ioutil.ReadFile("./../../../../credentials/azure/storage/blob/serviceURL.txt") if err != nil { return nil, err } t.fileWithMetadata = fmt.Sprintf("%sWithMetadata", t.fileName) t.serviceURL = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init ", cfg: config.Spec{ Name: "azure-storage-blob", Kind: "azure.storage.blob", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, }, wantErr: false, }, { name: "invalid init - missing storage_access_key ", cfg: config.Spec{ Name: "azure-storage-blob", Kind: "azure.storage.blob", Properties: map[string]string{ "storage_account": dat.storageAccount, }, }, wantErr: true, }, { name: "init - missing storage_account", cfg: config.Spec{ Name: "azure-storage-blob", Kind: "azure.storage.blob", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Upload_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-storage-blob", Kind: "azure.storage.blob", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid upload item", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("service_url", dat.serviceURL). SetData(dat.file), wantErr: false, }, { name: "valid upload item with metadata", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("file_name", dat.fileWithMetadata). SetMetadataKeyValue("blob_metadata", `{"tag":"test","name":"myname"}`). SetMetadataKeyValue("service_url", dat.serviceURL). SetData(dat.file), wantErr: false, }, { name: "invalid upload item - missing file_name", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("service_url", dat.serviceURL). SetData(dat.file), wantErr: true, }, { name: "invalid upload item - missing service url", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("file_name", dat.fileName). SetData(dat.file), wantErr: true, }, { name: "invalid upload item - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Get_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-storage-blob", Kind: "azure.storage.blob", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, } tests := []struct { name string request *types.Request wantErr bool wantBlobMetadata bool }{ { name: "valid get item", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: false, }, { name: "valid get item - with blob metadata", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("file_name", dat.fileWithMetadata). SetMetadataKeyValue("service_url", dat.serviceURL), wantBlobMetadata: true, wantErr: false, }, { name: "valid get item with offset and count", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("offset", "2"). SetMetadataKeyValue("count", "3"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: false, }, { name: "invalid get item - missing file_name", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: true, }, { name: "invalid get item - missing service_url", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("file_name", dat.fileName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got.Data) if tt.wantBlobMetadata { require.NotNil(t, got.Metadata["blob_metadata"]) } else { require.Equal(t, got.Metadata["blob_metadata"], "") } }) } } func TestClient_Delete_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-storage-blob", Kind: "azure.storage.blob", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("service_url", dat.serviceURL). SetMetadataKeyValue("delete_snapshots_option_type", ""), wantErr: false, }, { name: "invalid delete file does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("service_url", dat.serviceURL). SetMetadataKeyValue("delete_snapshots_option_type", ""), wantErr: true, }, { name: "invalid delete- missing file_name", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURL). SetMetadataKeyValue("delete_snapshots_option_type", ""), wantErr: true, }, { name: "invalid delete- fake option", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURL). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("delete_snapshots_option_type", ""), wantErr: true, }, { name: "invalid delete- fake url", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", "fakeURL"). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("delete_snapshots_option_type", ""), wantErr: true, }, { name: "invalid delete- invalid delete_snapshots_option_type", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURL). SetMetadataKeyValue("file_name", dat.fileName). SetMetadataKeyValue("delete_snapshots_option_type", "test"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package bigtable import ( "bytes" "context" "encoding/binary" "encoding/json" "errors" "fmt" "cloud.google.com/go/bigtable" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/option" ) type Client struct { log *logger.Logger opts options adminClient *bigtable.AdminClient client *bigtable.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) adminClient, err := bigtable.NewAdminClient(ctx, c.opts.projectID, c.opts.instance, option.WithCredentialsJSON(b)) if err != nil { return err } c.adminClient = adminClient Client, err := bigtable.NewClient(ctx, c.opts.projectID, c.opts.instance, option.WithCredentialsJSON(b)) if err != nil { return err } c.client = Client return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "write": return c.writeRow(ctx, meta, req.Data) case "write_batch": return c.writeBatch(ctx, meta, req.Data) case "get_row": return c.readRow(ctx, meta) case "get_all_rows": return c.readAllRows(ctx, meta, req.Data) case "get_all_rows_by_column": return c.readAllRowsByColumnFilter(ctx, meta, req.Data) case "create_column_family": return c.createColumnFamily(ctx, meta) case "delete_row": return c.deleteRowRange(ctx, meta) case "get_tables": return c.getTables(ctx) case "create_table": return c.createTable(ctx, meta) case "delete_table": return c.deleteTable(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) getTables(ctx context.Context) (*types.Response, error) { tables, err := c.adminClient.Tables(ctx) if err != nil { return nil, err } if len(tables) <= 0 { return nil, fmt.Errorf("no tables found for this instance") } b, err := json.Marshal(tables) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) createTable(ctx context.Context, meta metadata) (*types.Response, error) { err := c.adminClient.CreateTable(ctx, meta.tableName) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) createColumnFamily(ctx context.Context, meta metadata) (*types.Response, error) { err := c.adminClient.CreateColumnFamily(ctx, meta.tableName, meta.columnFamily) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteTable(ctx context.Context, meta metadata) (*types.Response, error) { err := c.adminClient.DeleteTable(ctx, meta.tableName) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteRowRange(ctx context.Context, meta metadata) (*types.Response, error) { err := c.adminClient.DropRowRange(ctx, meta.tableName, meta.rowKeyPrefix) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) readRow(ctx context.Context, meta metadata) (*types.Response, error) { tbl := c.client.Open(meta.tableName) row, err := tbl.ReadRow(ctx, meta.rowKeyPrefix) if err != nil { return nil, err } b, err := json.Marshal(row) if err != nil { return nil, err } return types.NewResponse(). SetData(b), nil } func (c *Client) readAllRows(ctx context.Context, meta metadata, body []byte) (*types.Response, error) { prefixes, err := c.getRowKeys(body) if err != nil { return nil, err } var rs bigtable.RowSet if len(prefixes) > 0 { rs = bigtable.RowList(prefixes) } else { rs = bigtable.PrefixRange("") } tbl := c.client.Open(meta.tableName) var rows []bigtable.Row err = tbl.ReadRows(ctx, rs, func(row bigtable.Row) bool { rows = append(rows, row) return true }) if err != nil { return nil, err } if len(rows) == 0 { return nil, fmt.Errorf("no rows found for this table") } b, err := json.Marshal(rows) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) readAllRowsByColumnFilter(ctx context.Context, meta metadata, body []byte) (*types.Response, error) { prefixes, err := c.getRowKeys(body) if err != nil { return nil, err } var rs bigtable.RowSet if len(prefixes) > 0 { rs = bigtable.RowList(prefixes) } else { rs = bigtable.PrefixRange("") } tbl := c.client.Open(meta.tableName) var rows []bigtable.Row err = tbl.ReadRows(ctx, rs, func(row bigtable.Row) bool { rows = append(rows, row) return true }, bigtable.RowFilter(bigtable.ColumnFilter(meta.readColumnName))) if err != nil { return nil, err } if len(rows) == 0 { return nil, fmt.Errorf("no rows found for this table") } b, err := json.Marshal(rows) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) writeRow(ctx context.Context, meta metadata, body []byte) (*types.Response, error) { tbl := c.client.Open(meta.tableName) timestamp := bigtable.Now() mut := bigtable.NewMutation() m, err := c.getSingleColumnFromBody(body) if err != nil { return nil, err } rowKey := "" for k, v := range m { if k == "set_row_key" { rowKey = fmt.Sprintf("%s", v) } else { buf := new(bytes.Buffer) b, err := json.Marshal(v) if err != nil { return nil, err } err = binary.Write(buf, binary.BigEndian, b) if err != nil { return nil, err } mut.Set(meta.columnFamily, k, timestamp, buf.Bytes()) } } if len(rowKey) == 0 { return nil, fmt.Errorf("missing set_row_key value") } err = tbl.Apply(ctx, rowKey, mut) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) writeBatch(ctx context.Context, meta metadata, body []byte) (*types.Response, error) { tbl := c.client.Open(meta.tableName) timestamp := bigtable.Now() var muts []*bigtable.Mutation var rowKeys []string s, err := c.getMultipleColumnsFromBody(body) if err != nil { return nil, err } if len(s) == 0 { return nil, fmt.Errorf("column requested must be at least 1") } for _, m := range s { mut := bigtable.NewMutation() for k, v := range m { if k == "set_row_key" { rowKeys = append(rowKeys, fmt.Sprintf("%s", v)) } else { buf := new(bytes.Buffer) b, err := json.Marshal(v) if err != nil { return nil, err } _ = binary.Write(buf, binary.BigEndian, b) mut.Set(meta.columnFamily, k, timestamp, buf.Bytes()) } } muts = append(muts, mut) } if len(s) != len(rowKeys) { return nil, fmt.Errorf("set_row_key count does not match column requested") } _, err = tbl.ApplyBulk(ctx, rowKeys, muts) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) getSingleColumnFromBody(body []byte) (map[string]interface{}, error) { m := make(map[string]interface{}) err := json.Unmarshal(body, &m) if err != nil { return nil, fmt.Errorf("failed to parse body as map[string]interface{} on error %s", err.Error()) } return m, nil } func (c *Client) getRowKeys(body []byte) ([]string, error) { var m []string if body != nil { err := json.Unmarshal(body, &m) if err != nil { return nil, fmt.Errorf("failed to parse body as []string on error %s", err.Error()) } } return m, nil } func (c *Client) getMultipleColumnsFromBody(body []byte) ([]map[string]interface{}, error) { var s []map[string]interface{} err := json.Unmarshal(body, &s) if err != nil { return nil, fmt.Errorf("failed to parse body as slice of map[string]interface{} on error %s", err.Error()) } return s, nil } func (c *Client) Stop() error { err := c.client.Close() if err != nil { return err } return c.adminClient.Close() } <file_sep>package sqs import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.sqs"). SetDescription("AWS SQS Target"). SetName("SQS"). SetProvider("AWS"). SetCategory("Messaging"). SetTags("queue", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set SQS aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set SQS aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set SQS aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set SQS token"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_receive"). SetDescription("Set SQS max receive"). SetMust(false). SetDefault("0"). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("retries"). SetDescription("Set SQS number of retries on failed send request"). SetMust(false). SetDefault("0"). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("default_delay"). SetDescription("Set SQS default delay in seconds"). SetMust(false). SetDefault("10"). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("dead_letter"). SetTitle("Dead Letter Queue"). SetDescription("Set SQS dead letter queue"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_queue"). SetTitle("Default Queue"). SetDescription("Set SQS Default Queue"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("queue"). SetKind("string"). SetDescription("Set EventHubs queue name"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("tags"). SetKind("string"). SetDescription("Set EventHubs tags"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("partition_key"). SetKind("string"). SetDescription("Set EventHubs partition key"). SetDefault(""). SetMust(false), ) } <file_sep>package redshift import ( "context" "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/redshift" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *redshift.Redshift } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := redshift.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "create_tags": return c.createTags(ctx, meta, req.Data) case "delete_tags": return c.deleteTags(ctx, meta, req.Data) case "list_tags": return c.listTags(ctx) case "list_snapshots": return c.listSnapshots(ctx) case "list_snapshots_by_tags_keys": return c.listSnapshotsByTagsKeys(ctx, req.Data) case "list_snapshots_by_tags_values": return c.listSnapshotsTagsValues(ctx, req.Data) case "describe_cluster": return c.describeCluster(ctx, meta) case "list_clusters": return c.listClusters(ctx) case "list_clusters_by_tags_keys": return c.listClustersByTagsKeys(ctx, req.Data) case "list_clusters_by_tags_values": return c.listClustersByTagsValues(ctx, req.Data) } return nil, errors.New("invalid method type") } func (c *Client) createTags(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data,tag list is required") } tags := make(map[string]string) err := json.Unmarshal(data, &tags) if err != nil { return nil, errors.New("data should be map[string]string,tag key(string),tag value(string)") } var redshiftTags []*redshift.Tag for k, v := range tags { t := redshift.Tag{ Key: aws.String(k), Value: aws.String(v), } redshiftTags = append(redshiftTags, &t) } _, err = c.client.CreateTagsWithContext(ctx, &redshift.CreateTagsInput{ ResourceName: aws.String(meta.resourceARN), Tags: redshiftTags, }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteTags(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data , tag list is required") } var tags []*string err := json.Unmarshal(data, &tags) if err != nil { return nil, errors.New("data should be []*string") } _, err = c.client.DeleteTagsWithContext(ctx, &redshift.DeleteTagsInput{ ResourceName: aws.String(meta.resourceARN), TagKeys: tags, }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) listTags(ctx context.Context) (*types.Response, error) { m, err := c.client.DescribeTagsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listSnapshots(ctx context.Context) (*types.Response, error) { m, err := c.client.DescribeClusterSnapshotsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listSnapshotsByTagsKeys(ctx context.Context, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data,tag list keys is required") } var tags []*string err := json.Unmarshal(data, &tags) if err != nil { return nil, errors.New("data should be []*string") } m, err := c.client.DescribeClusterSnapshotsWithContext(ctx, &redshift.DescribeClusterSnapshotsInput{ TagKeys: tags, }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listSnapshotsTagsValues(ctx context.Context, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data,tag list values is required") } var tags []*string err := json.Unmarshal(data, &tags) if err != nil { return nil, errors.New("data should be []*string") } m, err := c.client.DescribeClusterSnapshotsWithContext(ctx, &redshift.DescribeClusterSnapshotsInput{ TagValues: tags, }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) describeCluster(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.DescribeClustersWithContext(ctx, &redshift.DescribeClustersInput{ ClusterIdentifier: aws.String(meta.resourceName), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listClusters(ctx context.Context) (*types.Response, error) { m, err := c.client.DescribeClustersWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listClustersByTagsKeys(ctx context.Context, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data,list of tags keys is required") } var tags []*string err := json.Unmarshal(data, &tags) if err != nil { return nil, errors.New("data should be []*string") } m, err := c.client.DescribeClustersWithContext(ctx, &redshift.DescribeClustersInput{ TagKeys: tags, }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listClustersByTagsValues(ctx context.Context, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data,tag list is required") } var tags []*string err := json.Unmarshal(data, &tags) if err != nil { return nil, errors.New("data should be []*string") } m, err := c.client.DescribeClustersWithContext(ctx, &redshift.DescribeClustersInput{ TagValues: tags, }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>package middleware import ( "fmt" "math" "github.com/kubemq-io/kubemq-targets/pkg/ratelimit" "github.com/kubemq-io/kubemq-targets/types" ) type RateLimitMiddleware struct { rateLimiter ratelimit.Limiter } func NewRateLimitMiddleware(meta types.Metadata) (*RateLimitMiddleware, error) { rpc, err := meta.ParseIntWithRange("rate_per_seconds", 0, 0, math.MaxInt32) if err != nil { return nil, fmt.Errorf("invalid rate limiter rate per second value, %w", err) } rl := &RateLimitMiddleware{} if rpc > 0 { rl.rateLimiter = ratelimit.New(rpc, ratelimit.WithoutSlack) } else { rl.rateLimiter = ratelimit.NewUnlimited() } return rl, nil } func (rl *RateLimitMiddleware) Take() { _ = rl.rateLimiter.Take() } <file_sep>package servicebus import ( "context" "encoding/json" "errors" "fmt" "github.com/Azure/azure-service-bus-go" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *servicebus.Queue } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } ns, err := servicebus.NewNamespace(servicebus.NamespaceWithConnectionString(c.opts.connectionString)) if err != nil { return err } c.client, err = ns.NewQueue(c.opts.queueName) if err != nil { return fmt.Errorf("error connecting to servicebus at %s: %w", c.opts.connectionString, err) } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "send": return c.send(ctx, meta, req.Data) case "send_batch": return c.sendBatch(ctx, meta, req.Data) } return nil, errors.New("invalid method type") } func (c *Client) send(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { m := servicebus.NewMessage(data) if data == nil { return nil, errors.New("missing data") } if meta.label != "" { m.Label = meta.label } if meta.contentType != "" { m.ContentType = meta.contentType } if meta.timeToLive > 0 { m.TTL = &meta.timeToLive } err := c.client.Send(ctx, m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) sendBatch(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { var messages []string err := json.Unmarshal(data, &messages) if err != nil { return nil, err } var sm []*servicebus.Message for _, m := range messages { message := servicebus.NewMessageFromString(m) sm = append(sm, message) } for _, m := range sm { if meta.timeToLive > 0 { m.TTL = &meta.timeToLive } if meta.label != "" { m.Label = meta.label } if meta.contentType != "" { m.ContentType = meta.contentType } } err = c.client.SendBatch(ctx, servicebus.NewMessageBatchIterator(meta.maxBatchSize, sm...)) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.client != nil { return c.client.Close(context.Background()) } return nil } <file_sep># Kubemq sqs target Connector Kubemq aws-sqs target connector allows services using kubemq server to access aws sqs service. ## Prerequisites The following required to run the aws-sqs target connector: - kubemq cluster - aws account with sqs active service - kubemq-targets deployment ## Configuration sqs target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:------------------------------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | retries | no | number of retries on send | 1 (default 0) | | token | no | aws token ("default" empty string | "my token" | | dead_letter | no | dead letter queue name (only relevant to SetQueueAttributes) | "my_dead_letter_queue" | | max_receive | no | max receive of queue (only relevant to SetQueueAttributes) | "0" | | default_queue | no | set SQS default queue | "q1" | Example: ```yaml bindings: - name: kubemq-query-aws-sqs source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-sqs-connector" auth_token: "" channel: "query.aws.sqs" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.sqs name: aws-sqs properties: aws_key: "id" aws_secret_key: 'json' region: "instance" token: "" retries: "1" default_queue: "q1" ``` ## Usage ### Send Message send message to sqs. Send Message: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | queue | yes | name of queue to send | "my_queue" | | delay | yes | message delay | "0" | | tags | no | message tags (key value string string) | "{"tag-1":"test","tag-2":"test2"}" | | data | yes | type of method | "dmFsaWQgYm9keQ==" | Example: ```json { "metadata": { "queue": "my_queue", "delay": "0", "tags": "{\"tag-1\":\"test\",\"tag-2\":\"test2\"}" }, "data": "dmFsaWQgYm9keQ==" } ``` <file_sep>package amazonmq import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.amazonmq"). SetDescription("AWS AmazonMQ Target"). SetName("AmazonMQ"). SetProvider("AWS"). SetCategory("Messaging"). SetTags("queue", "cloud", "mq"). AddProperty( common.NewProperty(). SetKind("string"). SetName("host"). SetTitle("Host Address"). SetDescription("Set AmazonMQ host"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set AmazonMQ username"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set AmazonMQ password"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_destination"). SetDescription("Set AmazonMQ default destination"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("destination"). SetKind("string"). SetDescription("Set AmazonMQ destination"). SetDefault(""). SetMust(true), ) } <file_sep>package redis import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("cache.redis"). SetDescription("Redis Target"). SetName("Redis"). SetProvider(""). SetCategory("Cache"). SetTags("db"). AddProperty( common.NewProperty(). SetKind("string"). SetName("url"). SetTitle("Connection String"). SetDescription("Set Redis url"). SetMust(true). SetDefault("redis://redis.host:6379"), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Redis execution method"). SetOptions([]string{"get", "set", "delete"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Set Redis key"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("etag"). SetKind("int"). SetDescription("Set Redis etag"). SetDefault("0"). SetMin(0). SetMax(math.MaxInt16). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("concurrency"). SetKind("string"). SetDescription("Set Redis write concurrency"). SetOptions([]string{"first-write", "last-write", ""}). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("consistency"). SetKind("string"). SetDescription("Set Redis read consistency"). SetOptions([]string{"strong", "eventual", ""}). SetDefault(""). SetMust(false), ) } <file_sep>package middleware import ( "context" "fmt" "math" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/pkg/metrics" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type mockTarget struct { request *types.Request response *types.Response err error delay time.Duration executed int } func (m *mockTarget) Init(ctx context.Context, cfg config.Spec) error { return nil } func (m *mockTarget) Do(ctx context.Context, request *types.Request) (*types.Response, error) { time.Sleep(m.delay) m.executed++ return m.response, m.err } func (m *mockTarget) Name() string { return "" } func TestClient_RateLimiter(t *testing.T) { tests := []struct { name string mock *mockTarget meta types.Metadata timeToRun time.Duration wantMaxExecution int wantErr bool }{ { name: "100 per seconds", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: nil, delay: 0, executed: 0, }, meta: map[string]string{ "rate_per_seconds": "100", }, timeToRun: time.Second, wantMaxExecution: 110, wantErr: false, }, { name: "unlimited", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: nil, delay: 0, executed: 0, }, meta: map[string]string{}, timeToRun: time.Second, wantMaxExecution: math.MaxInt32, wantErr: false, }, { name: "bad rpc", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: nil, delay: 0, executed: 0, }, meta: map[string]string{ "rate_per_seconds": "-100", }, timeToRun: time.Second, wantMaxExecution: 0, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), tt.timeToRun) defer cancel() rl, err := NewRateLimitMiddleware(tt.meta) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) md := Chain(tt.mock, RateLimiter(rl)) for { select { case <-ctx.Done(): goto done default: } _, _ = md.Do(ctx, tt.mock.request) } done: require.LessOrEqual(t, tt.mock.executed, tt.wantMaxExecution) }) } } func TestClient_Retry(t *testing.T) { log := logger.NewLogger("TestClient_Retry") tests := []struct { name string mock *mockTarget meta types.Metadata wantRetries int wantErr bool }{ { name: "no retry options", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{}, wantRetries: 1, wantErr: false, }, { name: "retry with success", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: nil, delay: 0, executed: 0, }, meta: map[string]string{}, wantRetries: 1, wantErr: false, }, { name: "3 retries fixed delay", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "3", "retry_delay_milliseconds": "100", "retry_delay_type": "fixed", }, wantRetries: 3, wantErr: false, }, { name: "3 retries back-off delay", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "3", "retry_delay_milliseconds": "100", "retry_delay_type": "back-off", }, wantRetries: 3, wantErr: false, }, { name: "3 retries random delay", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "3", "retry_delay_milliseconds": "200", "retry_delay_type": "random", }, wantRetries: 3, wantErr: false, }, { name: "3 retries random with jitter delay", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "3", "retry_delay_milliseconds": "200", "retry_max_jitter_milliseconds": "200", "retry_delay_type": "random", }, wantRetries: 3, wantErr: false, }, { name: "bad rate limiter - attempts", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "-3", "retry_delay_milliseconds": "200", "retry_max_jitter_milliseconds": "200", "retry_delay_type": "random", }, wantRetries: 3, wantErr: true, }, { name: "bad rate limiter - retry_delay_milliseconds", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "3", "retry_delay_milliseconds": "-200", "retry_max_jitter_milliseconds": "200", "retry_delay_type": "random", }, wantRetries: 3, wantErr: true, }, { name: "bad rate limiter - retry_max_jitter_milliseconds", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "3", "retry_delay_milliseconds": "200", "retry_max_jitter_milliseconds": "-200", "retry_delay_type": "random", }, wantRetries: 3, wantErr: true, }, { name: "bad rate limiter - retry_delay_type", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "retry_attempts": "3", "retry_delay_milliseconds": "200", "retry_max_jitter_milliseconds": "200", "retry_delay_type": "bad-type", }, wantRetries: 3, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() r, err := NewRetryMiddleware(tt.meta, log) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) md := Chain(tt.mock, Retry(r)) resp, err := md.Do(ctx, tt.mock.request) if tt.mock.err != nil { require.Error(t, err) require.EqualValues(t, tt.wantRetries, tt.mock.executed) require.Nil(t, resp) } else { require.NoError(t, err) require.NotNil(t, resp) } }) } } func TestClient_Metric(t *testing.T) { exporter, err := metrics.NewExporter() require.NoError(t, err) tests := []struct { name string mock *mockTarget cfg config.BindingConfig wantReport *metrics.Report wantErr bool }{ { name: "no error request", mock: &mockTarget{ request: types.NewRequest().SetData([]byte("data")), response: types.NewResponse().SetData([]byte("data")), err: nil, delay: 0, executed: 0, }, cfg: config.BindingConfig{ Name: "b-1", Source: config.Spec{ Name: "sn", Kind: "sk", Properties: nil, }, Target: config.Spec{ Name: "tn", Kind: "tk", Properties: nil, }, Properties: nil, }, wantReport: &metrics.Report{ Key: "<KEY>", Binding: "b-1", SourceKind: "sk", TargetKind: "tk", RequestCount: 1, RequestVolume: 4, ResponseCount: 1, ResponseVolume: 4, ErrorsCount: 0, }, wantErr: false, }, { name: "error request", mock: &mockTarget{ request: types.NewRequest().SetData([]byte("data")), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, cfg: config.BindingConfig{ Name: "b-2", Source: config.Spec{ Name: "sn", Kind: "sk", Properties: nil, }, Target: config.Spec{ Name: "tn", Kind: "tk", Properties: nil, }, Properties: nil, }, wantReport: &metrics.Report{ Key: "<KEY>", Binding: "b-2", SourceKind: "sk", TargetKind: "tk", RequestCount: 1, RequestVolume: 4, ResponseCount: 0, ResponseVolume: 0, ErrorsCount: 1, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() m, err := NewMetricsMiddleware(tt.cfg, exporter) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) md := Chain(tt.mock, Metric(m)) _, _ = md.Do(ctx, tt.mock.request) storedReport := exporter.Store.Get(tt.wantReport.Key) require.EqualValues(t, tt.wantReport, storedReport) }) } } func TestClient_Log(t *testing.T) { tests := []struct { name string mock *mockTarget meta types.Metadata wantErr bool }{ { name: "no log level", mock: &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{}, wantErr: false, }, { name: "debug level", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "log_level": "debug", }, wantErr: false, }, { name: "info level", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "log_level": "info", }, wantErr: false, }, { name: "info level - 2", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: nil, delay: 0, executed: 0, }, meta: map[string]string{ "log_level": "info", }, wantErr: false, }, { name: "error level", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "log_level": "error", }, wantErr: false, }, { name: "invalid log level", mock: &mockTarget{ request: types.NewRequest(), response: types.NewResponse(), err: fmt.Errorf("some-error"), delay: 0, executed: 0, }, meta: map[string]string{ "log_level": "bad-level", }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() log, err := NewLogMiddleware("test", tt.meta) if tt.wantErr { require.Error(t, err) return } md := Chain(tt.mock, Log(log)) _, _ = md.Do(ctx, tt.mock.request) }) } } func TestClient_Chain(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() mock := &mockTarget{ request: types.NewRequest(), response: nil, err: fmt.Errorf("some-error"), delay: 0, executed: 0, } meta := map[string]string{ "log_level": "debug", "rate_per_seconds": "1", "retry_attempts": "3", "retry_delay_milliseconds": "100", "retry_max_jitter_milliseconds": "100", "retry_delay_type": "fixed", } log, err := NewLogMiddleware("test", meta) require.NoError(t, err) rl, err := NewRateLimitMiddleware(meta) require.NoError(t, err) retry, err := NewRetryMiddleware(meta, logger.NewLogger("retry-logger")) require.NoError(t, err) md := Chain(mock, RateLimiter(rl), Retry(retry), Log(log)) start := time.Now() _, _ = md.Do(ctx, mock.request) d := time.Since(start) require.GreaterOrEqual(t, d.Milliseconds(), 2*time.Second.Milliseconds()) } <file_sep>package http import ( "context" "encoding/json" "fmt" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/labstack/echo/v4" "github.com/stretchr/testify/require" ) type payload struct { Body string `json:"body"` } func newPayload(data string) *payload { return &payload{ Body: data, } } func (p *payload) Marshal() []byte { b, _ := json.Marshal(p) return b } func unmarshalPayload(data []byte) *payload { if len(data) == 0 { return nil } p := &payload{} _ = json.Unmarshal(data, p) return p } type mockHttpServer struct { echo *echo.Echo port string postError bool getError bool } func (m *mockHttpServer) start() { m.echo = echo.New() m.echo.POST("/post", func(c echo.Context) error { if m.postError { return c.String(500, "") } p := &payload{} err := c.Bind(p) if err != nil { panic(err) } return c.JSON(200, p) }) m.echo.GET("/get", func(c echo.Context) error { if m.getError { return c.JSON(500, nil) } return c.JSON(200, nil) }) go func() { _ = m.echo.Start(fmt.Sprintf(":%s", m.port)) }() time.Sleep(time.Second) } func (m *mockHttpServer) stop(ctx context.Context) { _ = m.echo.Shutdown(ctx) } func TestClient_Do(t *testing.T) { tests := []struct { name string mock *mockHttpServer cfg config.Spec request *types.Request want *types.Response wantErr bool }{ { name: "valid request - post", mock: &mockHttpServer{ port: "30000", postError: false, getError: false, }, cfg: config.Spec{ Name: "http", Kind: "http", Properties: map[string]string{ "auth_type": "no_auth", "username": "", "password": "", "token": "", "default_headers": `{"Content-Type":"application/json"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "post"). SetMetadataKeyValue("url", "http://localhost:30000/post"). SetData(newPayload("some-data").Marshal()), want: types.NewResponse(). SetData(newPayload("some-data").Marshal()), wantErr: false, }, { name: "valid request - post error", mock: &mockHttpServer{ port: "30001", postError: true, getError: false, }, cfg: config.Spec{ Name: "http", Kind: "http", Properties: map[string]string{ "auth_type": "no_auth", "username": "", "password": "", "token": "", "default_headers": `{"Content-Type":"application/json"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "post"). SetMetadataKeyValue("url", "http://localhost:30001/post"). SetData(newPayload("some-data").Marshal()), want: types.NewResponse(), wantErr: false, }, { name: "valid request - error on send", mock: &mockHttpServer{ port: "30002", postError: true, getError: false, }, cfg: config.Spec{ Name: "http", Kind: "http", Properties: map[string]string{ "auth_type": "no_auth", "username": "", "password": "", "token": "", "default_headers": `{"Content-Type":"application/json"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "post"). SetMetadataKeyValue("url", "http://localhost:40001/post"). SetData(newPayload("some-data").Marshal()), want: nil, wantErr: true, }, { name: "invalid request - method not supported", mock: &mockHttpServer{ port: "30003", postError: true, getError: false, }, cfg: config.Spec{ Name: "http", Kind: "http", Properties: map[string]string{ "auth_type": "no_auth", "username": "", "password": "", "token": "", "default_headers": `{"Content-Type":"application/json"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "invalid-method"). SetMetadataKeyValue("url", "http://localhost:30003/post"). SetData(newPayload("some-data").Marshal()), want: nil, wantErr: true, }, { name: "invalid request - no method", mock: &mockHttpServer{ port: "30004", postError: true, getError: false, }, cfg: config.Spec{ Name: "http", Kind: "http", Properties: map[string]string{ "auth_type": "no_auth", "username": "", "password": "", "token": "", "default_headers": `{"Content-Type":"application/json"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("url", "http://localhost:30004/post"). SetData(newPayload("some-data").Marshal()), want: nil, wantErr: true, }, { name: "invalid request - no url", mock: &mockHttpServer{ port: "30005", postError: true, getError: false, }, cfg: config.Spec{ Name: "http", Kind: "http", Properties: map[string]string{ "auth_type": "no_auth", "username": "", "password": "", "token": "", "default_headers": `{"Content-Type":"application/json"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "post"). SetMetadataKeyValue("url", "http://localhost:30005/post"). SetMetadataKeyValue("headers", `invalid-format`). SetData(newPayload("some-data").Marshal()), want: nil, wantErr: true, }, { name: "invalid request - bad headers format", mock: &mockHttpServer{ port: "30003", postError: true, getError: false, }, cfg: config.Spec{ Name: "http", Kind: "http", Properties: map[string]string{ "auth_type": "no_auth", "username": "", "password": "", "token": "", "default_headers": `{"Content-Type":"application/json"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "post"). SetData(newPayload("some-data").Marshal()), want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() tt.mock.start() defer tt.mock.stop(ctx) c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) require.EqualValues(t, unmarshalPayload(tt.want.Data), unmarshalPayload(got.Data)) }) } } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "http-target", Kind: "", Properties: map[string]string{ "auth_type": "basic", "username": "username", "password": "<PASSWORD>", "token": "token", "proxy": "proxy", "retry_count": "1", "retry_wait_seconds": "1", "root_certificate": "some-certificate", "client_private_key": "", "client_public_key": "", "default_headers": "", }, }, wantErr: false, }, { name: "init - error on client certificate", cfg: config.Spec{ Name: "http-target", Kind: "", Properties: map[string]string{ "auth_type": "auth_token", "username": "username", "password": "<PASSWORD>", "token": "token", "proxy": "proxy", "retry_count": "1", "retry_wait_seconds": "1", "root_certificate": "some-certificate", "client_private_key": "some-certificate", "client_public_key": "some-certificate", "default_headers": "", }, }, wantErr: true, }, { name: "init - error on bad options 1", cfg: config.Spec{ Name: "http-target", Kind: "", Properties: map[string]string{ "retry_wait_seconds": "-1", }, }, wantErr: true, }, { name: "init - error on bad options 2", cfg: config.Spec{ Name: "http-target", Kind: "", Properties: map[string]string{ "default_headers": "bad format", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantErr %v", err, tt.wantErr) return } }) } } <file_sep>package rethinkdb import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultKey = "" ) var methodsMap = map[string]string{ "get": "get", "update": "update", "insert": "insert", "delete": "delete", } type metadata struct { method string key string dbName string table string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.dbName, err = meta.MustParseString("db_name") if err != nil { return metadata{}, fmt.Errorf("error db_name, %w", err) } m.table, err = meta.MustParseString("table") if err != nil { return metadata{}, fmt.Errorf("error table, %w", err) } m.key = meta.ParseString("key", defaultKey) return m, nil } <file_sep>package amazonmq import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { host string username string password string defaultDestination string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.host, err = cfg.Properties.MustParseString("host") if err != nil { return options{}, fmt.Errorf("error parsing host, %w", err) } o.username, err = cfg.Properties.MustParseString("username") if err != nil { return options{}, fmt.Errorf("error parsing username , %w", err) } o.password, err = cfg.Properties.MustParseString("password") if err != nil { return options{}, fmt.Errorf("error parsing password , %w", err) } o.defaultDestination = cfg.Properties.ParseString("default_destination", "") return o, nil } func (o options) defaultMetadata() (metadata, bool) { if o.defaultDestination != "" { return metadata{ destination: o.defaultDestination, }, true } return metadata{}, false } <file_sep>package hazelcast import ( "context" "crypto/tls" "encoding/json" "fmt" "github.com/hazelcast/hazelcast-go-client" hazelconfig "github.com/hazelcast/hazelcast-go-client/config" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) // Client is a Client state store type Client struct { log *logger.Logger client hazelcast.Client opts options } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } config, err := setConfig(c.opts) if err != nil { return err } client, err := hazelcast.NewClientWithConfig(config) if err != nil { return err } c.client = client return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.get(meta) case "get_list": return c.getList(meta) case "set": return c.set(meta, req.Data) case "delete": return c.delete(meta) } return nil, nil } func (c *Client) get(meta metadata) (*types.Response, error) { Map, err := c.client.GetMap(meta.mapName) if err != nil { return nil, err } v, err := Map.Get(meta.key) if err != nil { return nil, err } if v == nil { return nil, fmt.Errorf("could not fine key for value %s", meta.key) } valueInterface, ok := v.([]byte) if !ok { return nil, fmt.Errorf("failed to cast interface for key %s to byte array", meta.key) } return types.NewResponse(). SetData(valueInterface). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) set(meta metadata, value []byte) (*types.Response, error) { Map, err := c.client.GetMap(meta.mapName) if err != nil { return nil, err } err = Map.Set(meta.key, value) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) getList(meta metadata) (*types.Response, error) { list, err := c.client.GetList(meta.listName) if err != nil { return nil, err } b, err := json.Marshal(list) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) delete(meta metadata) (*types.Response, error) { Map, err := c.client.GetMap(meta.mapName) if err != nil { return nil, err } err = Map.Delete(meta.key) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func setConfig(opts options) (*hazelconfig.Config, error) { c := hazelcast.NewConfig() if opts.username != "" { c.GroupConfig().SetName(opts.username) } if opts.password != "" { c.GroupConfig().SetPassword(opts.password) } if opts.address != "" { c.NetworkConfig().AddAddress(opts.address) } if opts.connectionAttemptLimit > 0 { c.NetworkConfig().SetConnectionAttemptLimit(opts.connectionAttemptLimit) } if opts.connectionAttemptPeriod > 0 { c.NetworkConfig().SetConnectionAttemptPeriod(opts.connectionAttemptPeriod) } if opts.connectionTimeout > 0 { c.NetworkConfig().SetConnectionTimeout(opts.connectionTimeout) } if opts.ssl { cert, err := tls.X509KeyPair([]byte(opts.sslcertificatefile), []byte(opts.sslcertificatekey)) if err != nil { return c, fmt.Errorf("hazelcast: error parsing client certificate: %v", err) } sslConfig := c.NetworkConfig().SSLConfig() sslConfig.SetEnabled(true) sslConfig.Certificates = append(sslConfig.Certificates, cert) if opts.serverName != "" { sslConfig.ServerName = opts.serverName } } return c, nil } func (c *Client) Stop() error { if c.client != nil { c.client.Shutdown() } return nil } <file_sep>package spanner import ( "encoding/base64" "time" "cloud.google.com/go/spanner" sppb "google.golang.org/genproto/googleapis/spanner/v1" ) type Column struct { Name string `json:"name"` Value interface{} `json:"value"` } type Row struct { Columns []*Column `json:"columns"` } func extractDataByType(r *spanner.Row) (*Row, error) { row := &Row{} for i := 0; i < r.Size(); i++ { column := &Column{} var col spanner.GenericColumnValue err := r.Column(i, &col) if err != nil { return row, err } column.Name = r.ColumnName(i) switch col.Type.Code { case sppb.TypeCode_INT64: var v spanner.NullInt64 if err := col.Decode(&v); err != nil { return row, err } column.Value = v.Int64 case sppb.TypeCode_FLOAT64: var v spanner.NullFloat64 if err := col.Decode(&v); err != nil { return row, err } column.Value = v.Float64 case sppb.TypeCode_STRING: var v spanner.NullString if err := col.Decode(&v); err != nil { return row, err } column.Value = v.StringVal case sppb.TypeCode_BYTES: var v spanner.NullString if err := col.Decode(&v); err != nil { return row, err } if v.IsNull() { column.Value = []byte(nil) } else { b, err := base64.StdEncoding.DecodeString(v.StringVal) if err != nil { return row, err } column.Value = b } case sppb.TypeCode_BOOL: var v spanner.NullBool if err := col.Decode(&v); err != nil { return row, err } column.Value = v.Bool case sppb.TypeCode_DATE: var v spanner.NullDate if err := col.Decode(&v); err != nil { return row, err } if v.IsNull() { column.Value = v.Date // typed nil } else { column.Value = v.Date.In(time.Local) } case sppb.TypeCode_TIMESTAMP: var v spanner.NullTime if err := col.Decode(&v); err != nil { return row, err } column.Value = v.Time } row.Columns = append(row.Columns, column) } return row, nil } <file_sep># Kubemq Crate Target Connector Kubemq crate target connector allows services using kubemq server to access crate database services. ## Prerequisites The following are required to run the crate target connector: - kubemq cluster - crate server - kubemq-targets deployment ## Configuration Crate target connector configuration properties: | Properties Key | Required | Description | Example | |:--------------------------------|:---------|:--------------------------------------------|:-----------------------------------------------------------------------| | connection | yes | crate connection string address | "postgresql://crate@localhost:5432/doc?sslmode=disable" | | max_idle_connections | no | set max idle connections | "10" | | max_open_connections | no | set max open connections | "100" | | connection_max_lifetime_seconds | no | set max lifetime for connections in seconds | "3600" | Example: ```yaml bindings: - name: kubemq-query-crate source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-crate-connector" auth_token: "" channel: "query.crate" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: stores.crate name: target-crate properties: connection: ""postgresql://crate@localhost:5432/doc?sslmode=disable"" max_idle_connections: "10" max_open_connections: "100" connection_max_lifetime_seconds: "3600" ``` ## Usage ### Query Request Query request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | set type of request | "query" | Query request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:-------------|:-------------------| | data | yes | query string | base64 bytes array | Example: Query string: `SELECT id,title,content FROM post;` ```json { "metadata": { "method": "query" }, "data": "<KEY> } ``` ### Exec Request Exec request metadata setting: | Metadata Key | Required | Description | Possible values | |:----------------|:---------|:---------------------------------------|:-------------------| | method | yes | set type of request | "exec" | | isolation_level | no | set isolation level for exec operation | "" | | | | | "read_uncommitted" | | | | | "read_committed" | | | | | "repeatable_read" | | | | | "serializable" | | | | | | Exec request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | exec string | base64 bytes array | Example: Exec string: ```sql INSERT INTO post(ID,TITLE,CONTENT) VALUES (1,NULL,'Content One'),(2,'Title Two','Content Two'); ``` ```json { "metadata": { "method": "exec", "isolation_level": "read_uncommitted" }, "data": "<KEY>" } ``` <file_sep>package redshift import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string resourceName string resourceARN string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" dat, err = ioutil.ReadFile("./../../../credentials/aws/redshift-svc/resourceName.txt") if err != nil { return nil, err } t.resourceName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/redshift-svc/resourceARN.txt") if err != nil { return nil, err } t.resourceARN = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init ", cfg: config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: false, }, { name: "init ", cfg: config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: false, }, { name: "invalid init - missing aws_secret_key", cfg: config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "region": dat.region, }, }, wantErr: true, }, { name: "invalid init - missing aws_key", cfg: config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Create_Tags(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } tags := make(map[string]string) tags["test1-key"] = "test1-value" b, err := json.Marshal(tags) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create", request: types.NewRequest(). SetMetadataKeyValue("method", "create_tags"). SetMetadataKeyValue("resource_arn", dat.resourceARN). SetData(b), wantErr: false, }, { name: "invalid create - missing resource_name ", request: types.NewRequest(). SetMetadataKeyValue("method", "create_tags"). SetData(b), wantErr: true, }, { name: "invalid create - missing body", request: types.NewRequest(). SetMetadataKeyValue("method", "create_tags"). SetMetadataKeyValue("resource_arn", dat.resourceARN), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Delete_Tags(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } var keys []*string tag := "test1-key" keys = append(keys, &tag) b, err := json.Marshal(keys) require.NoError(t, err) ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_tags"). SetMetadataKeyValue("resource_arn", dat.resourceName). SetData(b), wantErr: false, }, { name: "invalid delete - missing resource_name ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_tags"). SetData(b), wantErr: true, }, { name: "invalid delete - missing body", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_tags"). SetMetadataKeyValue("resource_arn", dat.resourceName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Tags(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list tags", request: types.NewRequest(). SetMetadataKeyValue("method", "list_tags"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Snapshots(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list snapshots", request: types.NewRequest(). SetMetadataKeyValue("method", "list_snapshots"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Snapshots_By_Tags_Keys(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() var keys []*string tag := "test1-key" keys = append(keys, &tag) b, err := json.Marshal(keys) require.NoError(t, err) err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list snapshots by tags", request: types.NewRequest(). SetMetadataKeyValue("method", "list_snapshots_by_tags_keys"). SetData(b), wantErr: false, }, { name: "invalid list snapshots by tags - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "list_snapshots_by_tags_keys"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Snapshots_By_Tags_Values(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() var keys []*string tag := "test1-value" keys = append(keys, &tag) b, err := json.Marshal(keys) require.NoError(t, err) err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list snapshots by values", request: types.NewRequest(). SetMetadataKeyValue("method", "list_snapshots_by_tags_values"). SetData(b), wantErr: false, }, { name: "invalid list snapshots by values - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "list_snapshots_by_tags_values"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Describe_Clusters(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid describe cluster ", request: types.NewRequest(). SetMetadataKeyValue("method", "describe_cluster"). SetMetadataKeyValue("resource_name", dat.resourceName), wantErr: false, }, { name: "invalid describe cluster - missing resource_name", request: types.NewRequest(). SetMetadataKeyValue("method", "describe_cluster"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Clusters(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_clusters"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Clusters_By_Tags_Keys(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() var keys []*string tag := "test1-key" keys = append(keys, &tag) b, err := json.Marshal(keys) require.NoError(t, err) err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_clusters_by_tags_keys"). SetData(b), wantErr: false, }, { name: "invalid list - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "list_clusters_by_tags_keys"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Clusters_By_Tags_Values(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-rds-redshift", Kind: "aws.rds.redshift", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() var keys []*string tag := "test1-value" keys = append(keys, &tag) b, err := json.Marshal(keys) require.NoError(t, err) err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_clusters_by_tags_values"). SetData(b), wantErr: false, }, { name: "invalid list - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "list_clusters_by_tags_values"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package kafka import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("messaging.kafka"). SetDescription("Kafka Messaging Target"). SetName("Kafka"). SetProvider(""). SetCategory("Messaging"). SetTags("streaming", "pub/sub"). AddProperty( common.NewProperty(). SetKind("string"). SetName("brokers"). SetTitle("Brokers Address"). SetDescription("Set Kafka brokers list"). SetMust(true). SetDefault("localhost:9092"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("sasl_username"). SetTitle("SASL Username"). SetDescription("Set Kafka username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("sasl_password"). SetTitle("SASL Password"). SetDescription("Set Kafka password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("topic"). SetDescription("Set Kafka topic"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("sasl_mechanism"). SetTitle("SASL Mechanism"). SetDescription("SCRAM-SHA-256, SCRAM-SHA-512, plain, 0Auth bearer, or GSS-API"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("security_protocol"). SetTitle("Security Protocol"). SetDescription("plaintext, SASL-plaintext, SASL-SSL, SSL"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("ca_cert"). SetDescription("Set TLS CA Certificate"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("client_certificate"). SetDescription("Set TLS Client PEM data"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("client_key"). SetDescription("Set TLS Client Key PEM data"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("insecure"). SetDescription("Set self-signed SSL Certificate"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetName("headers"). SetKind("string"). SetDescription("Set Kafka headers"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Set Kafka Key"). SetDefault(""). SetMust(false), ) } <file_sep>package logs import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.cloudwatch.logs"). SetDescription("AWS Cloudwatch Logs Target"). SetName("Cloudwatch Logs"). SetProvider("AWS"). SetCategory("Observability"). SetTags("logs", "cloud"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Cloudwatch-Logs aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Cloudwatch-Logs aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Cloudwatch-Logs aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Cloudwatch-Logs aws token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Cloudwatch-Logs execution method"). SetOptions([]string{"create_log_event_stream", "describe_log_event_stream", "delete_log_event_stream", "put_log_event", "get_log_event", "create_log_group", "delete_log_group", "describe_log_group"}). SetDefault("put_log_event"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("sequence_token"). SetKind("string"). SetDescription("Set Cloudwatch-Logs sequence token"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("log_group_name"). SetKind("string"). SetDescription("Set Cloudwatch-Logs log group name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("log_stream_name"). SetKind("string"). SetDescription("Set Cloudwatch-Logs sequence log stream name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("log_group_prefix"). SetKind("string"). SetDescription("Set Cloudwatch-Logs log group prefix"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("limit"). SetDescription("Set Cloudwatch-Logs limit"). SetMust(false). SetDefault("100"). SetMin(0). SetMax(math.MaxInt32), ) } <file_sep>package consulkv import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.consulkv"). SetDescription("consulkv source properties"). SetName("Consul"). SetProvider(""). SetCategory("Store"). SetTags("db", "key-value store", "cache"). AddProperty( common.NewProperty(). SetKind("string"). SetName("address"). SetDescription("Set consulkv address connection"). SetMust(true), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("wait_time"). SetTitle("Wait Time (Milliseconds)"). SetDescription("Set wait time milliseconds "). SetMust(false). SetDefault("36000"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("scheme"). SetDescription("Set consulkv scheme"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("data_center"). SetDescription("Set consulkv data center"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set consulkv token"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token_file"). SetDescription("Set consulkv token_file"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("insecure_skip_verify"). SetDescription("Set if insecure skip verify"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("tls"). SetTitle("Use TLS"). SetDescription("Set if use tls"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("condition"). SetName("tls"). SetTitle("Use TLS"). SetOptions([]string{"true", "false"}). SetDescription("Set tls conditions"). SetMust(true). SetDefault("false"). NewCondition("true", []*common.Property{ common.NewProperty(). SetKind("multilines"). SetName("cert_key"). SetTitle("Certification Key"). SetDescription("Set certificate key"). SetMust(false). SetDefault(""), common.NewProperty(). SetKind("multilines"). SetName("cert_file"). SetTitle("Certification File"). SetDescription("Set certificate file"). SetMust(false). SetDefault(""), }), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("key"). SetDescription("Set key"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("data_center"). SetDescription("Set data center"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("near"). SetDescription("Set near"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("filter"). SetDescription("Set filter"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("prefix"). SetDescription("Set prefix"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("bool"). SetName("allow_stale"). SetDescription("Set if allow stale"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetKind("bool"). SetName("require_consistent"). SetDescription("Set if require consistent"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetKind("bool"). SetName("user_cache"). SetDescription("Set if use user cache"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("max_age"). SetDescription("Set max age milliseconds "). SetMust(false). SetDefault("36000"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("stale_if_error"). SetDescription("Set stale if error time in milliseconds"). SetMust(false). SetDefault("36000"). SetMin(1). SetMax(math.MaxInt32), ) } <file_sep>package main import ( "context" "crypto/rand" "encoding/json" "fmt" "io/ioutil" "log" "math/big" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { dat, err := ioutil.ReadFile("./credentials/tableName.txt") if err != nil { log.Fatal(err) } tableName := string(dat) dat, err = ioutil.ReadFile("./credentials/columnFamily.txt") if err != nil { log.Fatal(err) } columnFamily := string(dat) if err != nil { log.Fatal(err) } client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // write_row singleRow := map[string]interface{}{"set_row_key": fmt.Sprintf("%d", getRandInt64()), "id": 3, "name": "test1"} singleB, err := json.Marshal(singleRow) if err != nil { log.Fatal(err) } writeRequest := types.NewRequest(). SetMetadataKeyValue("method", "write"). SetMetadataKeyValue("table_name", tableName). SetMetadataKeyValue("column_family", columnFamily). SetData(singleB) queryWriteResponse, err := client.SetQuery(writeRequest.ToQuery()). SetChannel("query.gcp.bigtable"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } writeResponse, err := types.ParseResponse(queryWriteResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("set row requests for tableName: %s executed, response: %s", tableName, writeResponse.Data)) // get rows by column getRequest := types.NewRequest(). SetMetadataKeyValue("column_name", "id"). SetMetadataKeyValue("table_name", tableName). SetMetadataKeyValue("method", "get_all_rows") getRows, err := client.SetQuery(getRequest.ToQuery()). SetChannel("query.gcp.bigtable"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getRowsResponse, err := types.ParseResponse(getRows.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get rows executed, response: %s", getRowsResponse.Data)) } func getRandInt64() int64 { nBig, err := rand.Int(rand.Reader, big.NewInt(27)) if err != nil { panic(err) } return nBig.Int64() } <file_sep>package lambda import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultDescription = "" defaultMemorySize = 256 defaultTimeout = 15 ) type metadata struct { method string zipFileName string functionName string handlerName string role string runtime string memorySize int64 timeout int64 description string isDryRun bool } var methodsMap = map[string]string{ "list": "list", "create": "create", "run": "run", "delete": "delete", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "create" { m.zipFileName, err = meta.MustParseString("zip_file_name") if err != nil { return metadata{}, fmt.Errorf("error parsing zip_file_name, %w", err) } m.handlerName, err = meta.MustParseString("handler_name") if err != nil { return metadata{}, fmt.Errorf("error parsing handler_name, %w", err) } m.role, err = meta.MustParseString("role") if err != nil { return metadata{}, fmt.Errorf("error parsing role, %w", err) } m.runtime, err = meta.MustParseString("runtime") if err != nil { return metadata{}, fmt.Errorf("error parsing runtime, %w", err) } i := meta.ParseInt("memory_size", defaultMemorySize) m.memorySize = int64(i) i = meta.ParseInt("timeout", defaultTimeout) m.timeout = int64(i) m.description = meta.ParseString("description", defaultDescription) if err != nil { return metadata{}, fmt.Errorf("error parsing runtime, %w", err) } } if m.method != "list" { m.functionName, err = meta.MustParseString("function_name") if err != nil { return metadata{}, fmt.Errorf("error parsing function_name, %w", err) } } m.isDryRun = meta.ParseBool("dry-run", false) return m, nil } <file_sep>package bigtable import ( "context" "crypto/rand" "encoding/json" "fmt" "io/ioutil" "math/big" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { projectID string instance string tableName string tempTable string columnFamily string rowKeyPrefix string cred string } func getRandInt64() int64 { nBig, err := rand.Int(rand.Reader, big.NewInt(27)) if err != nil { panic(err) } return nBig.Int64() } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/instance.txt") if err != nil { return nil, err } t.instance = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/projectID.txt") if err != nil { return nil, err } t.projectID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/tableName.txt") if err != nil { return nil, err } t.tableName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/tempTable.txt") if err != nil { return nil, err } t.tempTable = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/columnFamily.txt") if err != nil { return nil, err } t.columnFamily = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/rowKeyPrefix.txt") if err != nil { return nil, err } t.rowKeyPrefix = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") if err != nil { return nil, err } t.cred = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, wantErr: false, }, { name: "invalid init-missing-credentials", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, wantErr: true, }, { name: "invalid init-missing-project-id", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "instance": dat.instance, }, }, wantErr: true, }, { name: "invalid init-missing-instance", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } defer func() { _ = c.Stop() }() require.NoError(t, err) err = c.Stop() require.NoError(t, err) }) } } func TestClient_Create_Column_Family(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid create create-column-family", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "create_column_family"). SetMetadataKeyValue("column_family", dat.columnFamily). SetMetadataKeyValue("table_name", dat.tableName), wantErr: false, }, { name: "invalid create-column-family -invalid table_name", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "instance": dat.instance, "project_id": dat.projectID, "credentials": dat.cred, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "create_column_family"). SetMetadataKeyValue("column_family", dat.columnFamily). SetMetadataKeyValue("table_name", "fake table"), wantErr: true, }, { name: "invalid create-column-family - already exists", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "create_column_family"). SetMetadataKeyValue("column_family", dat.columnFamily). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } err = c.Stop() require.NoError(t, err) } func TestClient_Create_Table(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg2 := config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantError bool }{ { name: "valid create table", request: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetMetadataKeyValue("table_name", dat.tempTable), wantError: false, }, { name: "invalid create table- already exists", request: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetMetadataKeyValue("table_name", dat.tempTable), wantError: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantError { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Delete_Table(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg2 := config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantError bool }{ { name: "valid delete table", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("table_name", dat.tempTable), wantError: false, }, { name: "invalid delete table - table does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("table_name", dat.tempTable), wantError: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantError { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_write(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) singleRow := map[string]interface{}{"set_row_key": fmt.Sprintf("%d", getRandInt64()), "id": 1, "name": "test1"} var rows []map[string]interface{} rowOne := map[string]interface{}{"set_row_key": fmt.Sprintf("%d", getRandInt64()), "id": 2, "name": "test2"} rowTwo := map[string]interface{}{"set_row_key": fmt.Sprintf("%d", getRandInt64()), "id": 3, "name": "test3"} rows = append(rows, rowOne) rows = append(rows, rowTwo) singleB, err := json.Marshal(singleRow) require.NoError(t, err) multiB, err := json.Marshal(rows) require.NoError(t, err) tests := []struct { name string cfg config.Spec writeRequest *types.Request wantWriteResponse *types.Response wantWriteErr bool }{ { name: "valid single write", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "write"). SetMetadataKeyValue("table_name", dat.tableName). SetMetadataKeyValue("column_family", dat.columnFamily). SetData(singleB), wantWriteResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantWriteErr: false, }, { name: "valid single write", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "instance": dat.instance, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "write_batch"). SetMetadataKeyValue("table_name", dat.tableName). SetMetadataKeyValue("column_family", dat.columnFamily). SetData(multiB), wantWriteResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantWriteErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.writeRequest) if tt.wantWriteErr { t.Logf("init() error = %v, wantWriteErr %v", err, tt.wantWriteErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantWriteResponse, gotSetResponse) }) } } func TestClient_Delete_Rows(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec deleteRequest *types.Request wantErr bool }{ { name: "valid delete rows", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, deleteRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_row"). SetMetadataKeyValue("table_name", dat.tableName). SetMetadataKeyValue("row_key_prefix", dat.rowKeyPrefix), wantErr: false, }, { name: "invalid delete rows - missing row_key_prefix", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, deleteRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_row"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "invalid delete rows - missing table name", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, deleteRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_row"). SetMetadataKeyValue("row_key_prefix", dat.rowKeyPrefix), wantErr: true, }, { name: "invalid delete rows - table doesnt exists", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, deleteRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_row"). SetMetadataKeyValue("table_name", "fake_table"). SetMetadataKeyValue("row_key_prefix", dat.rowKeyPrefix), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { _ = c.Stop() }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.deleteRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.NotEqual(t, gotSetResponse.Metadata["error"], "true") t.Logf("init() error = %v, response %v", err, string(gotSetResponse.Data)) }) } } func TestClient_Read_Rows(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) keys := []string{ dat.rowKeyPrefix, } bKeys, err := json.Marshal(keys) require.NoError(t, err) tests := []struct { name string cfg config.Spec writeRequest *types.Request wantErr bool }{ { name: "valid read all rows", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_all_rows"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: false, }, { name: "valid read all rows by keys", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "instance": dat.instance, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_all_rows"). SetMetadataKeyValue("table_name", dat.tableName). SetData(bKeys), wantErr: false, }, { name: "valid read all rows - column_filter", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "instance": dat.instance, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_all_rows_by_column"). SetMetadataKeyValue("column_name", "id"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: false, }, { name: "valid read all rows by keys - column_filter", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "instance": dat.instance, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_all_rows_by_column"). SetMetadataKeyValue("column_name", "id"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: false, }, { name: "invalid read all rows - column_filter - missing column_name", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, "credentials": dat.cred, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_all_rows_by_column"). SetMetadataKeyValue("table_name", dat.tableName). SetData(bKeys), wantErr: true, }, { name: "valid read row", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigtable", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, writeRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_row"). SetMetadataKeyValue("table_name", dat.tableName). SetMetadataKeyValue("row_key_prefix", "my_id"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { _ = c.Stop() }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.writeRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) t.Logf("read() error = %v, response %v", err, string(gotSetResponse.Data)) }) } } <file_sep>package firebase import ( "context" "encoding/json" "github.com/kubemq-io/kubemq-targets/types" ) func (c *Client) dbGet(ctx context.Context, meta metadata) (*types.Response, error) { ref := c.dbClient.NewRef(meta.refPath) var data interface{} if err := ref.Get(ctx, &data); err != nil { return nil, err } b, err := json.Marshal(data) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) dbSet(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { ref := c.dbClient.NewRef(meta.refPath) var dat interface{} err := json.Unmarshal(data, &dat) if err != nil { return nil, err } if meta.childRefPath != "" { childRef := ref.Child(meta.childRefPath) if err := childRef.Set(ctx, dat); err != nil { return nil, err } } else { if err := ref.Set(ctx, dat); err != nil { return nil, err } } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) dbUpdate(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { ref := c.dbClient.NewRef(meta.refPath) var dat map[string]interface{} err := json.Unmarshal(data, &dat) if err != nil { return nil, err } if meta.childRefPath != "" { childRef := ref.Child(meta.childRefPath) if err := childRef.Update(ctx, dat); err != nil { return nil, err } } else { if err := ref.Update(ctx, dat); err != nil { return nil, err } } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) dbDelete(ctx context.Context, meta metadata) (*types.Response, error) { ref := c.dbClient.NewRef(meta.refPath) if meta.childRefPath != "" { childRef := ref.Child(meta.childRefPath) if err := childRef.Delete(ctx); err != nil { return nil, err } } else { if err := ref.Delete(ctx); err != nil { return nil, err } } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } <file_sep>package pubsub import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) const ( DefaultRetries = 0 ) type options struct { projectID string retries int credentials string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.projectID, err = cfg.Properties.MustParseString("project_id") if err != nil { return options{}, fmt.Errorf("error parsing project_id, %w", err) } o.retries = cfg.Properties.ParseInt("retries", DefaultRetries) o.credentials, err = cfg.Properties.MustParseString("credentials") if err != nil { return options{}, fmt.Errorf("error parsing credentials, %w", err) } return o, nil } <file_sep>package hdfs import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("storage.hdfs"). SetDescription("Hadoop Target"). SetName("HDFS"). SetProvider(""). SetCategory("Storage"). SetTags("big data"). AddProperty( common.NewProperty(). SetKind("string"). SetName("address"). SetDescription("Set Hadoop address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("user"). SetDescription("Set Hadoop user"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Hadoop execution method"). SetOptions([]string{"write_file", "remove_file", "read_file", "rename_file", "mkdir", "stat"}). SetDefault("read_file"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("file_path"). SetKind("string"). SetDescription("Set Hadoop file path"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("old_file_path"). SetKind("string"). SetDescription("Set Hadoop old file path"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("file_mode"). SetDescription("Set os file mode"). SetMust(false). SetDefault("0777"), ) } <file_sep>module github.com/kubemq-io/kubemq-targets go 1.20 //replace github.com/Azure/azure-service-bus-go => github.com/Azure/azure-service-bus-go v0.10.3 require ( cloud.google.com/go v0.101.1 cloud.google.com/go/bigquery v1.32.0 cloud.google.com/go/bigtable v1.13.0 cloud.google.com/go/firestore v1.6.1 cloud.google.com/go/pubsub v1.21.1 cloud.google.com/go/spanner v1.32.0 cloud.google.com/go/storage v1.22.1 firebase.google.com/go/v4 v4.8.0 github.com/Azure/azure-event-hubs-go/v3 v3.3.0 github.com/Azure/azure-pipeline-go v0.2.3 github.com/Azure/azure-sdk-for-go v46.1.0+incompatible // indirect github.com/Azure/azure-service-bus-go v0.10.3 github.com/Azure/azure-storage-blob-go v0.10.0 github.com/Azure/azure-storage-file-go v0.8.0 github.com/Azure/azure-storage-queue-go v0.0.0-20191125232315-636801874cdd github.com/Azure/go-autorest/autorest v0.11.6 // indirect github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect github.com/Azure/go-autorest/autorest/validation v0.3.0 // indirect github.com/GoogleCloudPlatform/cloudsql-proxy v1.30.1 github.com/Shopify/sarama v1.33.0 github.com/aerospike/aerospike-client-go v4.5.2+incompatible github.com/aws/aws-sdk-go v1.44.19 github.com/bradfitz/gomemcache v0.0.0-20220106215444-fb4bf637b56d github.com/cockroachdb/cockroach-go v2.0.1+incompatible github.com/colinmarc/hdfs/v2 v2.3.0 github.com/couchbase/gocb/v2 v2.5.0 github.com/denisenkom/go-mssqldb v0.12.2 github.com/eclipse/paho.mqtt.golang v1.3.5 github.com/fsnotify/fsnotify v1.5.4 github.com/ghodss/yaml v1.0.0 github.com/go-redis/redis/v7 v7.4.1 github.com/go-resty/resty/v2 v2.7.0 github.com/go-sql-driver/mysql v1.6.0 github.com/go-stomp/stomp v2.1.4+incompatible github.com/gocql/gocql v1.1.0 github.com/golang/protobuf v1.5.2 github.com/googleapis/gax-go/v2 v2.4.0 github.com/hashicorp/consul/api v1.12.0 github.com/hazelcast/hazelcast-go-client v0.6.0 github.com/json-iterator/go v1.1.12 github.com/kardianos/service v1.2.1 github.com/kubemq-hub/builder v0.7.2 github.com/kubemq-hub/ibmmq-sdk v0.3.8 github.com/kubemq-io/kubemq-go v1.7.6 github.com/labstack/echo/v4 v4.9.0 github.com/lib/pq v1.10.6 github.com/minio/minio-go/v7 v7.0.26 github.com/nats-io/nats.go v1.15.0 github.com/olivere/elastic/v7 v7.0.32 github.com/prometheus/client_golang v1.12.2 github.com/spf13/viper v1.11.0 github.com/streadway/amqp v1.0.0 github.com/stretchr/testify v1.7.1 go.mongodb.org/mongo-driver v1.9.1 go.uber.org/atomic v1.9.0 go.uber.org/zap v1.21.0 golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5 google.golang.org/api v0.80.0 google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd google.golang.org/grpc v1.46.2 gopkg.in/rethinkdb/rethinkdb-go.v6 v6.2.1 gopkg.in/yaml.v2 v2.4.0 ) require ( cloud.google.com/go/compute v1.6.1 // indirect cloud.google.com/go/iam v0.3.0 // indirect github.com/AlecAivazis/survey/v2 v2.2.7 // indirect github.com/Azure/go-autorest/tracing v0.6.0 // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver v1.5.0 // indirect github.com/Masterminds/sprig v2.22.0+incompatible // indirect github.com/apache/thrift v0.16.0 // indirect github.com/armon/go-metrics v0.3.10 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/census-instrumentation/opencensus-proto v0.3.0 // indirect github.com/cespare/xxhash/v2 v2.1.2 // indirect github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4 // indirect github.com/cncf/xds/go v0.0.0-20211130200136-a8f946100490 // indirect github.com/couchbase/gocbcore/v10 v10.1.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/devigned/tab v0.1.1 // indirect github.com/dustin/go-humanize v1.0.0 // indirect github.com/eapache/go-resiliency v1.2.0 // indirect github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 // indirect github.com/eapache/queue v1.1.0 // indirect github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1 // indirect github.com/envoyproxy/protoc-gen-validate v0.6.2 // indirect github.com/fatih/color v1.13.0 // indirect github.com/go-stack/stack v1.8.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-jwt/jwt v3.2.2+incompatible // indirect github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe // indirect github.com/golang-sql/sqlexp v0.1.0 // indirect github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/go-cmp v0.5.8 // indirect github.com/google/uuid v1.3.0 // indirect github.com/googleapis/go-type-adapters v1.0.0 // indirect github.com/gookit/color v1.3.1 // indirect github.com/gorilla/websocket v1.5.0 // indirect github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/go-cleanhttp v0.5.2 // indirect github.com/hashicorp/go-hclog v1.2.0 // indirect github.com/hashicorp/go-immutable-radix v1.3.1 // indirect github.com/hashicorp/go-multierror v1.1.1 // indirect github.com/hashicorp/go-rootcerts v1.0.2 // indirect github.com/hashicorp/go-uuid v1.0.2 // indirect github.com/hashicorp/golang-lru v0.5.4 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/hashicorp/serf v0.9.7 // indirect github.com/huandu/xstrings v1.3.2 // indirect github.com/imdario/mergo v0.3.11 // indirect github.com/jcmturner/aescts/v2 v2.0.0 // indirect github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect github.com/jcmturner/gofork v1.0.0 // indirect github.com/jcmturner/goidentity/v6 v6.0.1 // indirect github.com/jcmturner/gokrb5/v8 v8.4.2 // indirect github.com/jcmturner/rpc/v2 v2.0.3 // indirect github.com/jmespath/go-jmespath v0.4.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/jpillora/backoff v1.0.0 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/klauspost/compress v1.15.0 // indirect github.com/klauspost/cpuid v1.3.1 // indirect github.com/kubemq-io/protobuf v1.3.1 // indirect github.com/labstack/gommon v0.3.1 // indirect github.com/magiconair/properties v1.8.6 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.12 // indirect github.com/mattn/go-ieproxy v0.0.1 // indirect github.com/mattn/go-isatty v0.0.14 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect github.com/minio/md5-simd v1.1.0 // indirect github.com/minio/sha256-simd v0.1.1 // indirect github.com/mitchellh/copystructure v1.0.0 // indirect github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/mapstructure v1.4.3 // indirect github.com/mitchellh/reflectwalk v1.0.0 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/nats-io/nats-server/v2 v2.8.2 // indirect github.com/nats-io/nkeys v0.3.0 // indirect github.com/nats-io/nuid v1.0.1 // indirect github.com/opentracing/opentracing-go v1.2.0 // indirect github.com/pelletier/go-toml v1.9.4 // indirect github.com/pelletier/go-toml/v2 v2.0.0-beta.8 // indirect github.com/pierrec/lz4 v2.6.1+incompatible // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.32.1 // indirect github.com/prometheus/procfs v0.7.3 // indirect github.com/rcrowley/go-metrics v0.0.0-20201227073835-cf1acfcdf475 // indirect github.com/rs/xid v1.2.1 // indirect github.com/sirupsen/logrus v1.8.1 // indirect github.com/spf13/afero v1.8.2 // indirect github.com/spf13/cast v1.4.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.2.0 // indirect github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/valyala/fasttemplate v1.2.1 // indirect github.com/xdg-go/pbkdf2 v1.0.0 // indirect github.com/xdg-go/scram v1.1.1 // indirect github.com/xdg-go/stringprep v1.0.3 // indirect github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect github.com/yuin/gopher-lua v0.0.0-20220504180219-658193537a64 // indirect go.opencensus.io v0.23.0 // indirect go.uber.org/multierr v1.6.0 // indirect golang.org/x/crypto v0.0.0-20220411220226-7b82a4e95df4 // indirect golang.org/x/net v0.7.0 // indirect golang.org/x/sync v0.0.0-20210220032951-036812b2e83c // indirect golang.org/x/sys v0.5.0 // indirect golang.org/x/term v0.5.0 // indirect golang.org/x/text v0.7.0 // indirect golang.org/x/time v0.0.0-20220411224347-583f2d630306 // indirect golang.org/x/xerrors v0.0.0-20220411194840-2f41105eb62f // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/appengine/v2 v2.0.1 // indirect google.golang.org/protobuf v1.28.0 // indirect gopkg.in/cenkalti/backoff.v2 v2.2.1 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/ini.v1 v1.66.4 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) require ( github.com/Azure/azure-amqp-common-go/v3 v3.0.0 // indirect github.com/Azure/go-amqp v0.12.6 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest/adal v0.9.4 // indirect github.com/Azure/go-autorest/autorest/date v0.3.0 // indirect github.com/Azure/go-autorest/logger v0.2.0 // indirect github.com/dgrijalva/jwt-go v3.2.0+incompatible // indirect ) <file_sep># Kubemq Queue Stream Source Kubemq Queue source provides a queue subscriber for processing messages from a queue ## Prerequisites The following are required to run queue source connector: - kubemq cluster - kubemq-targets deployment ## Configuration Queue source connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------------------|:------------| | address | yes | kubemq server address (gRPC interface) | kubemq-cluster:50000 | | client_id | no | set client id | "client_id" | | auth_token | no | set authentication token | jwt token | | channel | yes | set channel to subscribe | | | sources | no | set how many concurrent sources to subscribe | 1 | | response_channel | no | set send target response to channel | "response.channel" | | batch_size | no | set how many messages to pull from queue | "1" | | wait_timeout | no | set how long to wait for messages to arrive in seconds | "5" | Example: ```yaml bindings: - name: kubemq-queue-elastic-search source: kind: kubemq.queue-stream name: kubemq-queue properties: address: "kubemq-cluster:50000" client_id: "kubemq-queue-elastic-search-connector" auth_token: "" channel: "queue.elastic-search" sources: "1" response_channel: "queue.response.elastic" batch_size: "1" wait_timeout: "5" target: kind: stores.elastic-search name: target-elastic-search properties: urls: "http://localhost:9200" username: "admin" password: "<PASSWORD>" sniff: "false" ``` <file_sep>package couchbase import ( "context" "encoding/json" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type doc struct { Data string `json:"data"` } func newDoc(data string) *doc { return &doc{Data: data} } func (d *doc) binary() []byte { b, _ := json.Marshal(d) return b } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "couchbase-target", Kind: "", Properties: map[string]string{ "url": "localhost", "username": "Administrator", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "some-collection", }, }, wantErr: false, }, { name: "init - bad url", cfg: config.Spec{ Name: "couchbase-target", Kind: "", Properties: map[string]string{ "url": "couch://localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, wantErr: true, }, { name: "init - no url", cfg: config.Spec{ Name: "couchbase-target", Kind: "", Properties: map[string]string{ "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, wantErr: true, }, { name: "init - bad username and password", cfg: config.Spec{ Name: "couchbase-target", Kind: "", Properties: map[string]string{ "url": "localhost", "username": "bad-couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, wantErr: true, }, { name: "init - no bucket", cfg: config.Spec{ Name: "couchbase-target", Kind: "", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, wantErr: true, }, { name: "init - bad num to replicate", cfg: config.Spec{ Name: "couchbase-target", Kind: "", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "-1", "num_to_persist": "1", "collection": "", }, }, wantErr: true, }, { name: "init - bad num to persist", cfg: config.Spec{ Name: "couchbase-target", Kind: "", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "-1", "collection": "", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSetErr %v", err, tt.wantErr) return } }) } } func TestClient_Set_Get(t *testing.T) { tests := []struct { name string cfg config.Spec setRequest *types.Request getRequest *types.Request wantSetResponse *types.Response wantGetResponse *types.Response wantSetErr bool wantGetErr bool }{ { name: "valid set get request", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-key-2"). SetData(newDoc("some-data").binary()), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "some-key-2"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key-2"). SetMetadataKeyValue("result", "ok"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key-2"). SetMetadataKeyValue("error", "false"). SetData(newDoc("some-data").binary()), wantSetErr: false, wantGetErr: false, }, { name: "valid set , no key get request", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-key-2"). SetData(newDoc("some-data").binary()), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "bad-key"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key-2"). SetMetadataKeyValue("result", "ok"), wantGetResponse: nil, wantSetErr: false, wantGetErr: true, }, { name: "invalid set request", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "100", "num_to_persist": "100", "collection": "", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-key-2"), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "some-key-2"), wantSetResponse: nil, wantGetResponse: nil, wantSetErr: true, wantGetErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.setRequest) if tt.wantSetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantSetResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.getRequest) if tt.wantGetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantGetResponse, gotGetResponse) }) } } func TestClient_Delete(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, nil) key := uuid.New().String() require.NoError(t, err) setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", key). SetData(newDoc("some-data").binary()) _, err = c.Do(ctx, setRequest) require.NoError(t, err) getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", key) gotGetResponse, err := c.Do(ctx, getRequest) require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, newDoc("some-data").binary(), gotGetResponse.Data) delRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", key) _, err = c.Do(ctx, delRequest) require.NoError(t, err) gotGetResponse, err = c.Do(ctx, getRequest) require.Error(t, err) require.Nil(t, gotGetResponse) } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid request", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-key"). SetData(newDoc("some-data").binary()), wantErr: false, }, { name: "invalid request - bad method", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "bad-method"). SetMetadataKeyValue("key", "some-key"). SetData([]byte("some-data")), wantErr: true, }, { name: "invalid request - no key", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetData([]byte("some-data")), wantErr: true, }, { name: "invalid request - bad cas", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("cas", "-1"). SetData(newDoc("some-data").binary()), wantErr: true, }, { name: "invalid request - bad expiry", cfg: config.Spec{ Name: "couchbase", Kind: "couchbase", Properties: map[string]string{ "url": "localhost", "username": "couchbase", "password": "<PASSWORD>", "bucket": "bucket", "num_to_replicate": "1", "num_to_persist": "1", "collection": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("expiry_seconds", "-1"). SetData(newDoc("some-data").binary()), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) _, err = c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } <file_sep>package eventhubs import ( "context" "encoding/json" "errors" "fmt" "github.com/Azure/azure-event-hubs-go/v3" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *eventhub.Hub } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.client, err = eventhub.NewHubFromConnectionString(c.opts.connectionString) if err != nil { return fmt.Errorf("error connecting to eventhub at %s: %w", c.opts.connectionString, err) } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "send": return c.send(ctx, meta, req.Data) case "send_batch": return c.sendBatch(ctx, meta, req.Data) } return nil, errors.New("invalid method type") } func (c *Client) send(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { event := &eventhub.Event{ Data: data, } if meta.partitionKey != "" { event.PartitionKey = &meta.partitionKey } if meta.properties != nil { event.Properties = meta.properties } err := c.client.Send(ctx, event) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) sendBatch(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { var messages []string err := json.Unmarshal(data, &messages) if err != nil { return nil, err } var events []*eventhub.Event for _, message := range messages { event := eventhub.NewEventFromString(message) events = append(events, event) if meta.partitionKey != "" { event.PartitionKey = &meta.partitionKey } } if meta.properties != nil { for _, event := range events { event.Properties = meta.properties } } err = c.client.SendBatch(ctx, eventhub.NewEventBatchIterator(events...)) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.client != nil { return c.client.Close(context.Background()) } return nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { dat, err := ioutil.ReadFile("./credentials/topicID.txt") if err != nil { panic(err) } topicID := string(dat) user := map[string]interface{}{ "first": "test-kubemq", "last": "test-kubemq-last", "id": 123, } bUser, err := json.Marshal(user) if err != nil { panic(err) } client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // add file setRequest := types.NewRequest(). SetMetadataKeyValue("method", "add"). SetMetadataKeyValue("collection", "my_collection"). SetData(bUser) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.gcp.firestore"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("add file request for topic : %s executed, is_error: %v", topicID, setResponse.IsError)) dat, err = ioutil.ReadFile("./credentials/deleteKey.txt") if err != nil { panic(err) } deleteKey := string(dat) // delete file deleteRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete_document_key"). SetMetadataKeyValue("item", deleteKey). SetMetadataKeyValue("collection", "my_collection") queryDeleteResponse, err := client.SetQuery(deleteRequest.ToQuery()). SetChannel("query.gcp.firestore"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } deleteResponse, err := types.ParseResponse(queryDeleteResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("delete_document_key request for topic : %s executed, with id %s , is_error: %v", topicID, deleteKey, deleteResponse.IsError)) } <file_sep>package middleware import "github.com/kubemq-io/kubemq-targets/types" type MetadataMiddleware struct { Metadata map[string]string } func NewMetadataMiddleware(meta types.Metadata) (*MetadataMiddleware, error) { mm := &MetadataMiddleware{} var err error mm.Metadata, err = meta.MustParseJsonMap("metadata") if err != nil { mm.Metadata = map[string]string{} } return mm, nil } <file_sep>package binding import "github.com/kubemq-io/kubemq-targets/types" type Response struct { Metadata map[string]string `json:"metadata"` Data interface{} `json:"data"` IsError bool `json:"is_error"` Error string `json:"error"` } func toResponse(r *types.Response) *Response { return &Response{ Metadata: r.Metadata, Data: types.ParseResponseBody(r.Data), IsError: r.IsError, Error: r.Error, } } <file_sep>package keyspaces import ( "fmt" "math" "time" "github.com/gocql/gocql" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultProtoVersion = 4 defaultReplicationFactor = 1 defaultConsistency = gocql.LocalQuorum defaultPort = 9142 defaultUsername = "" defaultPassword = "" defaultKeyspace = "" defaultTable = "" ) type options struct { hosts []string port int protoVersion int replicationFactor int username string password string consistency gocql.Consistency defaultTable string defaultKeyspace string tls string timeoutSeconds time.Duration connectTimeoutSeconds time.Duration } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.hosts, err = cfg.Properties.MustParseStringList("hosts") if err != nil { return options{}, fmt.Errorf("error parsing hosts, %w", err) } o.port, err = cfg.Properties.ParseIntWithRange("port", defaultPort, 1, 65535) if err != nil { return options{}, fmt.Errorf("error parsing port value, %w", err) } o.protoVersion, err = cfg.Properties.ParseIntWithRange("proto_version", defaultProtoVersion, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing proto version value, %w", err) } o.replicationFactor, err = cfg.Properties.ParseIntWithRange("replication_factor", defaultReplicationFactor, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing replication factor value, %w", err) } o.username = cfg.Properties.ParseString("username", defaultUsername) o.password = cfg.Properties.ParseString("password", defaultPassword) o.consistency, err = getConsistency(cfg.Properties.ParseString("consistency", "LocalQuorum")) if err != nil { return options{}, fmt.Errorf("error parsing consistency value, %w", err) } o.defaultTable = cfg.Properties.ParseString("default_table", defaultTable) o.defaultKeyspace = cfg.Properties.ParseString("default_keyspace", defaultKeyspace) connectTimeout, err := cfg.Properties.ParseIntWithRange("connect_timeout_seconds", 60, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing connect timeout seconds timeout value, %w", err) } o.connectTimeoutSeconds = time.Duration(connectTimeout) * time.Second timeout, err := cfg.Properties.ParseIntWithRange("timeout_seconds", 60, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing timeout seconds value, %w", err) } o.timeoutSeconds = time.Duration(timeout) * time.Second o.tls, err = cfg.Properties.MustParseString("tls") if err != nil { return options{}, fmt.Errorf("error parsing tls, %w", err) } return o, nil } func getConsistency(consistency string) (gocql.Consistency, error) { switch consistency { case "One": return gocql.One, nil case "LocalQuorum": return gocql.LocalQuorum, nil case "LocalOne": return gocql.LocalOne, nil case "": return defaultConsistency, nil } return 0, fmt.Errorf("consistency mode %s not found", consistency) } <file_sep>1. Download kind - to run kubernetes on docker - [https://kind.sigs.k8s.io/] 2. make sure that the ca crt and key extracted and available in the current directory 3. run in command line ``` kubectl create secret generic rabbitmq-certificates --from-file=./ca.crt --from-file=./tls.crt --from-file=./tls.key ``` 4. run in command line ``` helm repo add bitnami https://charts.bitnami.com/bitnami helm install rabbitmq bitnami/rabbitmq --set auth.username=rabbitmq --set auth.password=<PASSWORD> --set auth.tls.enabled=true --set auth.tls.existingSecret=rabbitmq-certificates ``` 5. wait until it will completed and you will see rabbitmq running in the cluster 6. expose rabbitmq service in the cluster with port-forwarding ``` kubectl port-forward svc/rabbitmq 5671:5671 ``` then you can connect to rabbitmq <file_sep>package nats import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("messaging.nats"). SetDescription("nats source properties"). SetName("NATS"). SetProvider(""). SetCategory("Messaging"). SetTags("queue", "pub/sub"). AddProperty( common.NewProperty(). SetKind("string"). SetName("url"). SetTitle("Connection String"). SetDescription("Set nats url connection"). SetMust(true), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set token"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("tls"). SetTitle("Use TLS"). SetDescription("Set if use tls"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("condition"). SetName("tls"). SetOptions([]string{"true", "false"}). SetDescription("Set tls conditions"). SetMust(true). SetDefault("false"). NewCondition("true", []*common.Property{ common.NewProperty(). SetKind("multilines"). SetName("cert_key"). SetTitle("Certification Key"). SetDescription("Set certificate key"). SetMust(false). SetDefault(""), common.NewProperty(). SetKind("multilines"). SetName("Certification File"). SetDescription("Set certificate file"). SetMust(false). SetDefault(""), }), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("subject"). SetDescription("Set subject"). SetMust(true). SetDefault(""), ) } <file_sep>package kafka import ( "encoding/json" "fmt" b64 "encoding/base64" kafka "github.com/Shopify/sarama" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { Headers []kafka.RecordHeader Key []byte } func parseMetadata(meta types.Metadata, opts options) (metadata, error) { m := metadata{} var err error err = m.parseHeaders(meta.ParseString("headers", "")) if err != nil { return metadata{}, fmt.Errorf("error parsing headers, %w", err) } k := meta.ParseString("key", "") err = m.parseKey(k) if err != nil { return metadata{}, fmt.Errorf("error parsing Key, %w", err) } return m, nil } func (meta *metadata) parseHeaders(headers string) error { if len(headers) == 0 { return nil } var h []kafka.RecordHeader err := json.Unmarshal([]byte(headers), &h) if err != nil { return err } meta.Headers = h return nil } func (meta *metadata) parseKey(key string) error { if len(key) == 0 { return nil } var err error meta.Key, err = b64.StdEncoding.DecodeString(key) if err != nil { return err } return nil } <file_sep>package queue import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("kubemq.queue"). SetDescription("Kubemq Queue Source"). SetName("KubeMQ Queue"). SetProvider(""). SetCategory("Queue"). AddProperty( common.NewProperty(). SetKind("string"). SetName("address"). SetTitle("KubeMQ gRPC Service Address"). SetDescription("Set Kubemq grpc endpoint address"). SetMust(true). SetDefault("kubemq-cluster-grpc.kubemq:50000"). SetLoadedOptions("kubemq-address"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("channel"). SetDescription("Set Queue channel"). SetMust(true). SetDefaultFromKey("channel.queue"), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("do_not_parse_payload"). SetTitle("Don't Parse Payload"). SetDescription("Allow payload pass-through"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("response_channel"). SetTitle("Response Channel"). SetDescription("Set Queue response channel"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("sources"). SetTitle("Concurrent Connections"). SetDescription("Set how many concurrent Queue sources to run"). SetMust(false). SetDefault("1"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("client_id"). SetTitle("Client ID"). SetDescription("Set Queue connection clients Id"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("auth_token"). SetTitle("Authentication Token"). SetDescription("Set Queue connection authentication token"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("batch_size"). SetTitle("Poll Batch Size"). SetDescription("Set how many messages will pull in one request"). SetMust(false). SetDefault("1"), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("wait_timeout"). SetTitle("Wait Timeout (Seconds)"). SetDescription("Set how long to wait in seconds for messages during pull of requests"). SetMust(false). SetDefault("5"), ) } <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // listRequest listRequest := types.NewRequest(). SetMetadataKeyValue("method", "list_tables") queryListResponse, err := client.SetQuery(listRequest.ToQuery()). SetChannel("query.aws.dynamodb"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } listResponse, err := types.ParseResponse(queryListResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("list tables executed, response: %s", listResponse.Data)) dat, err := ioutil.ReadFile("./credentials/aws/dynamodb/tableName.txt") if err != nil { panic(err) } tableName := string(dat) // Create Table input := fmt.Sprintf(`{ "AttributeDefinitions": [ { "AttributeName": "Year", "AttributeType": "N" }, { "AttributeName": "Title", "AttributeType": "S" } ], "BillingMode": null, "GlobalSecondaryIndexes": null, "KeySchema": [ { "AttributeName": "Year", "KeyType": "HASH" }, { "AttributeName": "Title", "KeyType": "RANGE" } ], "LocalSecondaryIndexes": null, "ProvisionedThroughput": { "ReadCapacityUnits": 10, "WriteCapacityUnits": 10 }, "SSESpecification": null, "StreamSpecification": null, "TableName": "%s", "Tags": null }`, tableName) createRequest := types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetData([]byte(input)) getCreate, err := client.SetQuery(createRequest.ToQuery()). SetChannel("query.aws.dynamodb"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } createResponse, err := types.ParseResponse(getCreate.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("create table executed, error: %v", createResponse.IsError)) } <file_sep>package s3 import ( "bytes" "context" "encoding/json" "errors" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *s3.S3 uploader *s3manager.Uploader downloader *s3manager.Downloader } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := s3.New(sess) c.client = svc c.downloader = s3manager.NewDownloader(sess) c.uploader = s3manager.NewUploader(sess) return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "list_buckets": return c.listBuckets(ctx) case "list_bucket_items": return c.listBucketItems(ctx, meta) case "create_bucket": return c.createBucket(ctx, meta) case "delete_bucket": return c.deleteBucket(ctx, meta) case "delete_item_from_bucket": return c.deleteItemFromBucket(ctx, meta) case "delete_all_items_from_bucket": return c.deleteAllItemsFromBucket(ctx, meta) case "upload_item": return c.uploadItem(ctx, meta, req.Data) case "copy_item": return c.copyItem(ctx, meta) case "get_item": return c.downloadItem(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) listBuckets(ctx context.Context) (*types.Response, error) { m, err := c.client.ListBucketsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listBucketItems(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.ListObjectsV2WithContext(ctx, &s3.ListObjectsV2Input{Bucket: aws.String(meta.bucketName)}) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) createBucket(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.CreateBucketWithContext(ctx, &s3.CreateBucketInput{ Bucket: aws.String(meta.bucketName), }) if err != nil { return nil, err } if meta.waitForCompletion { err = c.client.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ Bucket: aws.String(meta.bucketName), }) if err != nil { return nil, err } } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) deleteBucket(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.DeleteBucketWithContext(ctx, &s3.DeleteBucketInput{ Bucket: aws.String(meta.bucketName), }) if err != nil { return nil, err } if meta.waitForCompletion { err = c.client.WaitUntilBucketNotExistsWithContext(ctx, &s3.HeadBucketInput{ Bucket: aws.String(meta.bucketName), }) if err != nil { return nil, err } } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteItemFromBucket(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.DeleteObjectWithContext(ctx, &s3.DeleteObjectInput{ Bucket: aws.String(meta.bucketName), Key: aws.String(meta.itemName), }) if err != nil { return nil, err } if meta.waitForCompletion { err = c.client.WaitUntilObjectNotExistsWithContext(ctx, &s3.HeadObjectInput{ Bucket: aws.String(meta.bucketName), Key: aws.String(meta.itemName), }) if err != nil { return nil, err } } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) deleteAllItemsFromBucket(ctx context.Context, meta metadata) (*types.Response, error) { iter := s3manager.NewDeleteListIterator(c.client, &s3.ListObjectsInput{ Bucket: aws.String(meta.bucketName), }) if err := s3manager.NewBatchDeleteWithClient(c.client).Delete(ctx, iter); err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) uploadItem(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if c.uploader == nil { return nil, fmt.Errorf("uploader client is nil, set uploader to true when creating the client") } r := bytes.NewReader(data) m, err := c.uploader.UploadWithContext(ctx, &s3manager.UploadInput{ Bucket: aws.String(meta.bucketName), Key: aws.String(meta.itemName), Body: r, }) if err != nil { return nil, err } if meta.waitForCompletion { err = c.client.WaitUntilObjectExistsWithContext(ctx, &s3.HeadObjectInput{ Bucket: aws.String(meta.bucketName), Key: aws.String(meta.itemName), }) if err != nil { return nil, err } } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) copyItem(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.CopyObjectWithContext(ctx, &s3.CopyObjectInput{ Bucket: aws.String(meta.bucketName), CopySource: aws.String(meta.copySource), Key: aws.String(meta.itemName), }) if err != nil { return nil, err } if meta.waitForCompletion { err = c.client.WaitUntilObjectExistsWithContext(ctx, &s3.HeadObjectInput{ Bucket: aws.String(meta.bucketName), Key: aws.String(meta.itemName), }) if err != nil { return nil, err } } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) downloadItem(ctx context.Context, meta metadata) (*types.Response, error) { if c.downloader == nil { return nil, fmt.Errorf("downloader client is nil, set downloader to true when creating the client") } requestInput := s3.GetObjectInput{ Bucket: aws.String(meta.bucketName), Key: aws.String(meta.itemName), } buf := aws.NewWriteAtBuffer([]byte{}) _, err := c.downloader.DownloadWithContext(ctx, buf, &requestInput) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("bucket", meta.bucketName). SetMetadataKeyValue("key", meta.itemName). SetData(buf.Bytes()), nil } func (c *Client) Stop() error { return nil } <file_sep>package files import ( "context" "fmt" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { storageAccessKey string storageAccount string serviceURL string serviceURLWithMeta string file []byte } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../../credentials/azure/storage/files/storageAccessKey.txt") if err != nil { return nil, err } t.storageAccessKey = string(dat) dat, err = ioutil.ReadFile("./../../../../credentials/azure/storage/files/storageAccount.txt") if err != nil { return nil, err } t.storageAccount = string(dat) contents, err := ioutil.ReadFile("./../../../../credentials/azure/storage/files/contents.txt") if err != nil { return nil, err } t.file = contents dat, err = ioutil.ReadFile("./../../../../credentials/azure/storage/files/serviceURL.txt") if err != nil { return nil, err } t.serviceURL = string(dat) t.serviceURLWithMeta = fmt.Sprintf("%sWithMetadata.txt", t.serviceURL) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init ", cfg: config.Spec{ Name: "azure-storage-files", Kind: "azure.storage.files", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, }, wantErr: false, }, { name: "invalid init - missing storage_account", cfg: config.Spec{ Name: "azure-storage-files", Kind: "azure.storage.files", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, }, }, wantErr: true, }, { name: "invalid init - missing storage_access_key", cfg: config.Spec{ Name: "azure-storage-files", Kind: "azure.storage.files", Properties: map[string]string{ "storage_account": dat.storageAccount, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Create_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-storage-files", Kind: "azure.storage.files", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create item", request: types.NewRequest(). SetMetadataKeyValue("method", "create"). SetMetadataKeyValue("service_url", dat.serviceURL). SetData(dat.file), wantErr: false, }, { name: "valid create item with metadata", request: types.NewRequest(). SetMetadataKeyValue("method", "create"). SetMetadataKeyValue("file_metadata", `{"tag":"test","name":"myname"}`). SetMetadataKeyValue("service_url", dat.serviceURLWithMeta). SetData(dat.file), wantErr: false, }, { name: "invalid create item - missing service url", request: types.NewRequest(). SetMetadataKeyValue("method", "create"). SetData(dat.file), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Upload_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-storage-files", Kind: "azure.storage.files", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid upload item", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("service_url", dat.serviceURL). SetData(dat.file), wantErr: false, }, { name: "valid upload item with metadata", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("blob_metadata", `{"tag":"test","name":"myname"}`). SetMetadataKeyValue("service_url", dat.serviceURL). SetData(dat.file), wantErr: false, }, { name: "invalid upload item - missing service_url", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetData(dat.file), wantErr: true, }, { name: "invalid upload item - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Get_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-storage-files", Kind: "azure.storage.files", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, } tests := []struct { name string request *types.Request wantErr bool wantFileMetadata bool }{ { name: "valid get item", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: false, }, { name: "valid get item - with file metadata", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("service_url", dat.serviceURLWithMeta), wantFileMetadata: true, wantErr: false, }, { name: "valid get item with offset and count", request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("offset", "2"). SetMetadataKeyValue("count", "3"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: false, }, { name: "invalid get item - missing service_url", request: types.NewRequest(). SetMetadataKeyValue("method", "get"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got.Data) if tt.wantFileMetadata { require.NotNil(t, got.Metadata["file_metadata"]) t.Logf("%s", got.Metadata["file_metadata"]) } else { require.Equal(t, got.Metadata["file_metadata"], "") } }) } } func TestClient_Delete_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-storage-files", Kind: "azure.storage.files", Properties: map[string]string{ "storage_access_key": dat.storageAccessKey, "storage_account": dat.storageAccount, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: false, }, { name: "valid delete file with tags", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURLWithMeta), wantErr: false, }, { name: "invalid delete file does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: true, }, { name: "invalid delete- fake option", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: true, }, { name: "invalid delete- fake url", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", "fakeURL"), wantErr: true, }, { name: "invalid delete- invalid delete_snapshots_option_type", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("service_url", dat.serviceURL), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>//go:build container // +build container package ibmmq import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/types" "github.com/kubemq-io/kubemq-targets/config" "github.com/stretchr/testify/require" ) type testStructure struct { applicationChannelName string hostname string listenerPort string queueManagerName string apiKey string mqUsername string password string QueueName string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/ibm/mq/connectionInfo/applicationChannelName.txt") if err != nil { return nil, err } t.applicationChannelName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/ibm/mq/connectionInfo/hostname.txt") if err != nil { return nil, err } t.hostname = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/ibm/mq/connectionInfo/listenerPort.txt") if err != nil { return nil, err } t.listenerPort = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/ibm/mq/connectionInfo/queueManagerName.txt") if err != nil { return nil, err } t.queueManagerName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/ibm/mq/applicationApiKey/apiKey.txt") if err != nil { return nil, err } t.apiKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/ibm/mq/applicationApiKey/mqUsername.txt") if err != nil { return nil, err } t.mqUsername = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/ibm/mq/applicationApiKey/mqPassword.txt") if err != nil { return nil, err } t.password = <PASSWORD>) t.QueueName = "DEV.QUEUE.1" return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, wantErr: false, }, { name: "invalid init incorrect username", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": "fake user name", "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, wantErr: true, }, { name: "invalid init - incorrect password", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": "<PASSWORD>", "queue_name": dat.QueueName, }, }, wantErr: true, }, { name: "invalid init - incorrect host_name", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": "fake host name", "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, wantErr: true, }, { name: "invalid init - missing host_name", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, wantErr: true, }, { name: "invalid init - missing queue_manager_name", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, wantErr: true, }, { name: "invalid init - missing channel_name", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, wantErr: true, }, { name: "invalid init - missing username", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, wantErr: true, }, { name: "invalid init - missing queue_name", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": dat.password, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } defer func() { _ = c.Stop() }() require.NoError(t, err) err = c.Stop() require.NoError(t, err) }) } } func TestClient_Do(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request want *types.Response wantErr bool }{ { name: "valid - send", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, request: types.NewRequest(). SetData([]byte("some-data")), wantErr: false, }, { name: "valid - send override queue", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": "test", }, }, request: types.NewRequest(). SetMetadataKeyValue("dynamic_queue", dat.QueueName). SetData([]byte("some-data")), wantErr: false, }, { name: "invalid - send missing data", cfg: config.Spec{ Name: "messaging-ibmmq", Kind: "messaging.ibmmq", Properties: map[string]string{ "queue_manager_name": dat.queueManagerName, "host_name": dat.hostname, "port_number": dat.listenerPort, "channel_name": dat.applicationChannelName, "username": dat.mqUsername, "key_repository": dat.apiKey, "password": <PASSWORD>, "queue_name": dat.QueueName, }, }, request: types.NewRequest(), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package redshift import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.redshift.service"). SetDescription("AWS Redshift Service Target"). SetName("Redshift Service"). SetProvider("AWS"). SetCategory("Store"). SetTags("sql", "db", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Redshift Service aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Redshift Service aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Redshift Service aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Redshift Service token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Redshift Service execution method"). SetOptions([]string{"create_tags", "delete_tags", "list_tags", "list_snapshots", "list_snapshots_by_tags_keys", "list_snapshots_by_tags_values", "describe_cluster", "list_clusters", "list_clusters_by_tags_keys", "list_clusters_by_tags_values"}). SetDefault("create_tags"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("resource_arn"). SetKind("string"). SetDescription("Set Redshift Service resource arn"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("resource_name"). SetKind("string"). SetDescription("Set Redshift Service resource name"). SetDefault(""). SetMust(false), ) } <file_sep>package ratelimit_test import ( "sync" "testing" "time" "github.com/kubemq-io/kubemq-targets/pkg/ratelimit" "github.com/kubemq-io/kubemq-targets/pkg/ratelimit/internal/clock" "go.uber.org/atomic" "github.com/stretchr/testify/assert" ) func TestUnlimited(t *testing.T) { now := time.Now() rl := ratelimit.NewUnlimited() for i := 0; i < 1000; i++ { rl.Take() } assert.Condition(t, func() bool { return time.Since(now) < 1*time.Millisecond }, "no artificial delay") } func TestRateLimiter(t *testing.T) { var wg sync.WaitGroup wg.Add(1) defer wg.Wait() clock := clock.NewMock() rl := ratelimit.New(100, ratelimit.WithClock(clock), ratelimit.WithoutSlack) count := atomic.NewInt32(0) // Until we're done... done := make(chan struct{}) defer close(done) // Create copious counts concurrently. go job(rl, count, done) go job(rl, count, done) go job(rl, count, done) go job(rl, count, done) clock.AfterFunc(1*time.Second, func() { assert.InDelta(t, 100, count.Load(), 10, "count within rate limit") }) clock.AfterFunc(2*time.Second, func() { assert.InDelta(t, 200, count.Load(), 10, "count within rate limit") }) clock.AfterFunc(3*time.Second, func() { assert.InDelta(t, 300, count.Load(), 10, "count within rate limit") wg.Done() }) clock.Add(4 * time.Second) clock.Add(5 * time.Second) } func TestDelayedRateLimiter(t *testing.T) { var wg sync.WaitGroup wg.Add(1) defer wg.Wait() clock := clock.NewMock() slow := ratelimit.New(10, ratelimit.WithClock(clock)) fast := ratelimit.New(100, ratelimit.WithClock(clock)) count := atomic.NewInt32(0) // Until we're done... done := make(chan struct{}) defer close(done) // Run a slow job go func() { for { slow.Take() fast.Take() count.Inc() select { case <-done: return default: } } }() // Accumulate slack for 10 seconds, clock.AfterFunc(20*time.Second, func() { // Then start working. go job(fast, count, done) go job(fast, count, done) go job(fast, count, done) go job(fast, count, done) }) clock.AfterFunc(30*time.Second, func() { assert.InDelta(t, 1200, count.Load(), 10, "count within rate limit") wg.Done() }) clock.Add(40 * time.Second) } func job(rl ratelimit.Limiter, count *atomic.Int32, done <-chan struct{}) { for { rl.Take() count.Inc() select { case <-done: return default: } } } <file_sep>package nats import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/types" "github.com/kubemq-io/kubemq-targets/config" "github.com/stretchr/testify/require" ) type testStructure struct { url string subject string username string password string token string sslcertificatefile string sslcertificatekey string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/nats/url.txt") if err != nil { return nil, err } t.url = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/nats/subject.txt") if err != nil { return nil, err } t.subject = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/nats/username.txt") if err != nil { return nil, err } t.username = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/nats/password.txt") if err != nil { return nil, err } t.password = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/nats/token.txt") if err != nil { return nil, err } t.token = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/nats/certFile.pem") if err != nil { return nil, err } t.sslcertificatefile = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/nats/certKey.pem") if err != nil { return nil, err } t.sslcertificatekey = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init -without tls", cfg: config.Spec{ Name: "messaging-nats", Kind: "messaging.nats", Properties: map[string]string{ "url": dat.url, "username": dat.username, "password": <PASSWORD>, "token": <PASSWORD>, "tls": "false", }, }, wantErr: false, }, { name: "invalid init - no url", cfg: config.Spec{ Name: "messaging-nats", Kind: "messaging.nats", Properties: map[string]string{ "username": dat.username, "password": <PASSWORD>, "token": <PASSWORD>, "tls": "true", "cert_file": dat.sslcertificatefile, "cert_key": dat.sslcertificatekey, }, }, wantErr: true, }, { name: "invalid init - missing cert key", cfg: config.Spec{ Name: "messaging-nats", Kind: "messaging.nats", Properties: map[string]string{ "url": dat.url, "username": dat.username, "password": <PASSWORD>, "token": <PASSWORD>, "tls": "true", "cert_file": dat.sslcertificatefile, }, }, wantErr: true, }, { name: "invalid init - missing cert file", cfg: config.Spec{ Name: "messaging-nats", Kind: "messaging.nats", Properties: map[string]string{ "url": dat.url, "username": dat.username, "password": <PASSWORD>, "token": <PASSWORD>, "tls": "true", "cert_key": dat.sslcertificatekey, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestClient_Do(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantResponse *types.Response wantErr bool }{ { name: "valid -without tls", cfg: config.Spec{ Name: "messaging-nats", Kind: "messaging.nats", Properties: map[string]string{ "url": dat.url, "username": dat.username, "password": <PASSWORD>, "token": <PASSWORD>, "tls": "false", }, }, request: types.NewRequest(). SetMetadataKeyValue("subject", "foo"). SetData([]byte("some-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotResponse, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotResponse) require.EqualValues(t, tt.wantResponse, gotResponse) }) } } <file_sep># Kubemq firebase target Connector Kubemq gcp-firebase target connector allows services using kubemq server to access google firebase server. ## Prerequisites The following required to run the gcp-firebase target connector: - kubemq cluster - gcp-firebase set up - kubemq-targets deployment ## Configuration firebase target connector configuration properties: | Properties Key | Required | Description | Example | |:----------------|:---------|:-------------------------------------------|:---------------------------| | project_id | yes | gcp firebase project_id | "<googleurl>/myproject" | | credentials | yes | gcp credentials files | "<google json credentials" | | db_client | no | initialize db client if true | true/false | | db_url | no | gcp db full path | <google db url" | | auth_client | no | initialize auth client if true | true/false | | messaging_client | no | initialize messaging client | true/false | | defaultmsg | no | default Firebase Cloud Messaging | json | | defaultmultimsg | no | default Firebase Cloud MulticastMessage | json | *defaultmsg - can be used for common message settings *defaultmultimsg - can be used for common message settings Example: ```yaml bindings: - name: kubemq-query-gcp-firebase source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-firebase-connector" auth_token: "" channel: "query.gcp.firebase" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.firebase name: gcp-firebase properties: project_id: "project_id" credentials: 'json' db_client: "true" db_url: "db_url" auth_client: "true" ``` ## Usage ##DB: ### Get DB Get DB metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | get_db | | ref_path | yes | ref path for the data | valid string | | child_ref | no | path for child ref data | valid string | Example: ```json { "metadata": { "method": "get_db", "ref_path": "string" }, "data": null } ``` ### Set DB Set DB metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | set_db | | ref_path | yes | ref path for the data | valid string | | child_ref | no | path for child ref data | valid string | Example: ```json { "metadata": { "method": "get_db", "ref_path": "string" }, "data": null } ``` ### Update DB Update DB metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | update_db | | ref_path | yes | ref path for the data | valid string | | child_ref | no | path for child ref data | valid string | Example: ```json { "metadata": { "method": "delete_db", "ref_path": "string" }, "data": "updated_string" } ``` ### Delete DB # Kubemq firebase target Connector Kubemq gcp-firebase target connector allows services using kubemq server to access google firebase server. ## Prerequisites The following required to run the gcp-firebase target connector: - kubemq cluster - gcp-firebase set up - kubemq-targets deployment ## Configuration firebase target connector configuration properties: | Properties Key | Required | Description | Example | |:----------------|:---------|:-------------------------------------------|:---------------------------| | project_id | yes | gcp firebase project_id | "<googleurl>/myproject" | | credentials | yes | gcp credentials files | "<google json credentials" | | db_client | no | initialize db client if true | true/false | | db_url | no | gcp db full path | <google db url" | | auth_client | no | initialize auth client if true | true/false | | messaging_client | no | initialize messaging client | true/false | | defaultmsg | no | default Firebase Cloud Messaging | json | | defaultmultimsg | no | default Firebase Cloud MulticastMessage | json | *defaultmsg - can be used for common message settings *defaultmultimsg - can be used for common message settings Example: ```yaml bindings: - name: kubemq-query-gcp-firebase source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-firebase-connector" auth_token: "" channel: "query.gcp.firebase" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind:gcp.firebase name: gcp-firebase properties: project_id: "project_id" credentials: 'json' db_client: "true" db_url: "db_url" auth_client: "true" ``` ## Usage ##DB: ### Get DB Get DB metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | get_db | | ref_path | yes | ref path for the data | valid string | | child_ref | no | path for child ref data | valid string | Example: ```json { "metadata": { "method": "get_db", "ref_path": "string" }, "data": null } ``` ### Set DB Set DB metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | set_db | | ref_path | yes | ref path for the data | valid string | | child_ref | no | path for child ref data | valid string | Example: ```json { "metadata": { "method": "get_db", "ref_path": "string" }, "data": null } ``` ### Update DB Update DB metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | update_db | | ref_path | yes | ref path for the data | valid string | | child_ref | no | path for child ref data | valid string | Example: ```json { "metadata": { "method": "update_db", "ref_path": "string" }, "data": "dXBkYXRlIGRiIHN0cmluZw==" } ``` ### Delete DB Delete DB metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | delete_db | | ref_path | yes | ref path for the data | valid string | | child_ref | no | path for child ref data | valid string | Example: ```json { "metadata": { "method": "delete_db", "ref_path": "string" }, "data": null } ``` ## User: ### Create User Create User metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | create_user | Example: ```json { "metadata": { "method": "create_user" }, "data": "<KEY> } ``` ### Retrieve User Retrieve User metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:--------------------------| | method | yes | method type | retrieve_user | | retrieve_by | yes | type of retrieval | by_email ,by_uid,by_phone | | uid | no | valid unique string | string | | phone | no | valid phone number | string | | email | no | valid email | string | Example: ```json { "metadata": { "method": "retrieve_user", "retrieve_by": "uid", "uid": "1223131" }, "data": null } ``` ### Delete User Delete User metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | delete_user | | uid | yes | valid unique string | string | Example: ```json { "metadata": { "method": "delete_user", "uid": "1223131" }, "data": null } ``` ### Delete Multiple Users Delete Multiple Users metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | delete_multiple_users | Example: ```json { "metadata": { "method": "delete_multiple_users" }, "data": "WyAidXNlcjEiLCAidXNlcjIiLCAidXNlcjMiIF0=" } ``` ### Update User Update User metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | update_user | | uid | yes | valid unique string | string | Example: ```json { "metadata": { "method": "update_user", "uid": "1223131" }, "data": "<KEY> } ``` ### List Users List User metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | list_users | Example: ```json { "metadata": { "method": "list_users" }, "data": null } ``` ## Token: ### Custom Token Custom Token metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | custom_token | | | | uid | yes | valid unique string | string | | Example: ```json { "metadata": { "method": "custom_token", "token_id": "some-uid" }, "data": null } ``` ### Verify Token Verify Token metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | method | yes | method type | verify_token | | | | uid | yes | valid unique string | string | | Example: ```json { "metadata": { "method": "verify_token", "token_id": "some-uid" }, "data": null } ``` ## Messaging: Firebase messaging will send a FCM message or send the message to multiple devices. * message https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages * multi https://firebase.google.com/docs/cloud-messaging/send-message#go_1 ### Send Message Create User metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:------------------------| | method | yes | method type | send_message/send_multi | Example: send_message ```json { "metadata": { "method": "send_message" }, "data": "<KEY>" } * data value is base64 { "Topic":"test", "data": {"key1":"value1"} } ``` Example: send_multi ```json { "metadata": { "method": "send_multi" }, "data": "<KEY>" } * data value is base64 { "topic":"app_topic", "data":{"Tokens":["123","456"],"Data":{"key":"val"},"Notification":{"title":"title"}} } ``` <file_sep># Kubemq CloudWatch Events Target Connector Kubemq cloudwatch-events target connector allows services using kubemq server to access aws cloudwatch-events service. ## Prerequisites The following required to run the aws-cloudwatch-events target connector: - kubemq cluster - aws account with cloudwatch-events active service (IAM Permission under EventBridge) - kubemq-targets deployment ## Configuration cloudwatch-events target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-cloudwatch-events source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-cloudwatch-events" auth_token: "" channel: "query.aws.cloudwatch.events" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.cloudwatch.events name: aws-cloudwatch-events properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### Put Target Put Target: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "put_targets" | | rule | yes | aws existing rule name | "string" | | data | yes | Key value pair of target ARN and ID | `{"my_arn_id":"arn:aws:test:number:function:id"}` | Example: ```json { "metadata": { "method": "put_targets", "rule": "my_rule" }, "data": "<KEY>" } ``` ### List Event Buses List Event Buses: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_buses" | | limit | no | limit of return buses | "int" | Example: ```json { "metadata": { "method": "list_buses", "limit": "1" }, "data": null } ``` ### Send Event Send Event: | Metadata Key | Required | Description | Possible values | |:-----------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "send_event" | | detail | no | general details on the event | "string" | | detail_type | no | event type | "string" | | source | no | aws source to assign the message to | "string" | | data | yes | aws resources to assign the event to | slice of strings ("arn:string") | Example: ```json { "metadata": { "method": "send_event", "detail": "{ some detail }", "detail_type": "appRequestSubmitted", "source": "kubemq_testing" }, "data": "<KEY> } ``` <file_sep>package minio import ( "bytes" "context" "encoding/json" "fmt" "io/ioutil" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "github.com/minio/minio-go/v7" "github.com/minio/minio-go/v7/pkg/credentials" ) type Client struct { log *logger.Logger opts options s3Client *minio.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.s3Client, err = minio.New(c.opts.endpoint, &minio.Options{ Creds: credentials.NewStaticV4(c.opts.accessKeyId, c.opts.secretAccessKey, ""), Secure: c.opts.useSSL, }) if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "make_bucket": return c.MakeBucket(ctx, meta) case "list_buckets": return c.ListBuckets(ctx) case "bucket_exists": return c.BucketExist(ctx, meta) case "remove_bucket": return c.RemoveBucket(ctx, meta) case "list_objects": return c.ListObjects(ctx, meta) case "put": return c.Put(ctx, meta, req.Data) case "get": return c.Get(ctx, meta) case "remove": return c.Remove(ctx, meta) } return nil, nil } func (c *Client) MakeBucket(ctx context.Context, meta metadata) (*types.Response, error) { bucketOptions := minio.MakeBucketOptions{ Region: meta.param2, ObjectLocking: false, } err := c.s3Client.MakeBucket(ctx, meta.param1, bucketOptions) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) ListBuckets(ctx context.Context) (*types.Response, error) { buckets, err := c.s3Client.ListBuckets(ctx) if err != nil { return nil, err } data, err := json.Marshal(&buckets) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(data), nil } func (c *Client) BucketExist(ctx context.Context, meta metadata) (*types.Response, error) { found, err := c.s3Client.BucketExists(ctx, meta.param1) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("exist", fmt.Sprintf("%t", found)). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) RemoveBucket(ctx context.Context, meta metadata) (*types.Response, error) { err := c.s3Client.RemoveBucket(ctx, meta.param1) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) ListObjects(ctx context.Context, meta metadata) (*types.Response, error) { var objects []minio.ObjectInfo for object := range c.s3Client.ListObjects(ctx, meta.param1, minio.ListObjectsOptions{Recursive: true}) { objects = append(objects, object) } data, err := json.Marshal(&objects) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(data), nil } func (c *Client) Get(ctx context.Context, meta metadata) (*types.Response, error) { object, err := c.s3Client.GetObject(ctx, meta.param1, meta.param2, minio.GetObjectOptions{}) if err != nil { return nil, err } defer func() { _ = object.Close() }() data, err := ioutil.ReadAll(object) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(data), nil } func (c *Client) Put(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { r := bytes.NewReader(value) _, err := c.s3Client.PutObject(ctx, meta.param1, meta.param2, r, int64(r.Len()), minio.PutObjectOptions{ ContentType: "application/octet-stream", }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Remove(ctx context.Context, meta metadata) (*types.Response, error) { err := c.s3Client.RemoveObject(ctx, meta.param1, meta.param2, minio.RemoveObjectOptions{ GovernanceBypass: false, VersionID: "", Internal: minio.AdvancedRemoveOptions{}, }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return nil } <file_sep>package dynamodb import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { method string tableName string } var methodsMap = map[string]string{ "list_tables": "list_tables", "create_table": "create_table", "delete_table": "delete_table", "insert_item": "insert_item", "get_item": "get_item", "delete_item": "delete_item", "update_item": "update_item", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "insert_item" || m.method == "delete_table" { m.tableName, err = meta.MustParseString("table_name") if err != nil { return metadata{}, fmt.Errorf("table_name is requeired for method:%s, error parsing table_name, %w", m.method, err) } } return m, nil } <file_sep>package mongodb import ( "fmt" "math" "time" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { host string username string password string database string collection string writeConcurrency string readConcurrency string params string operationTimeout time.Duration } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.host, err = cfg.Properties.MustParseString("host") if err != nil { return options{}, fmt.Errorf("error parsing host, %w", err) } o.username = cfg.Properties.ParseString("username", "") o.password = cfg.Properties.ParseString("password", "") o.database, err = cfg.Properties.MustParseString("database") if err != nil { return options{}, fmt.Errorf("error parsing database name, %w", err) } o.collection, err = cfg.Properties.MustParseString("collection") if err != nil { return options{}, fmt.Errorf("error parsing collection name, %w", err) } o.writeConcurrency = cfg.Properties.ParseString("write_concurrency", "") o.readConcurrency = cfg.Properties.ParseString("read_concurrency", "") o.params = cfg.Properties.ParseString("params", "") operationTimeoutSeconds, err := cfg.Properties.ParseIntWithRange("operation_timeout_seconds", 60, 0, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error operation timeout seconds, %w", err) } o.operationTimeout = time.Duration(operationTimeoutSeconds) * time.Second return o, nil } <file_sep>//go:build container // +build container package ibmmq import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultCertificateLabel = "" defaultPassword = "" defaultKeyRepository = "" defaultTimeToLive = 3600000 defaultPort = 1414 defaultTransportType = 0 defaultTlsClientAuth = "NONE" ) type options struct { qMName string hostname string portNumber int channelName string userName string keyRepository string certificateLabel string queueName string Password string transportType int timeToLive int tlsClientAuth string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.qMName, err = cfg.Properties.MustParseString("queue_manager_name") if err != nil { return options{}, fmt.Errorf("error parsing queue_manager_name, %w", err) } o.hostname, err = cfg.Properties.MustParseString("host_name") if err != nil { return options{}, fmt.Errorf("error parsing host_name, %w", err) } o.channelName, err = cfg.Properties.MustParseString("channel_name") if err != nil { return options{}, fmt.Errorf("error parsing channel_name, %w", err) } o.userName, err = cfg.Properties.MustParseString("username") if err != nil { return options{}, fmt.Errorf("error parsing username, %w", err) } o.queueName, err = cfg.Properties.MustParseString("queue_name") if err != nil { return options{}, fmt.Errorf("error parsing queue_name, %w", err) } o.certificateLabel = cfg.Properties.ParseString("certificate_label", defaultCertificateLabel) o.timeToLive = cfg.Properties.ParseInt("ttl", defaultTimeToLive) o.transportType = cfg.Properties.ParseInt("transport_type", defaultTransportType) o.portNumber = cfg.Properties.ParseInt("port_number", defaultPort) o.Password = cfg.Properties.ParseString("password", defaultPassword) o.tlsClientAuth = cfg.Properties.ParseString("tls_client_auth", defaultTlsClientAuth) o.keyRepository = cfg.Properties.ParseString("key_repository", defaultKeyRepository) return o, nil } <file_sep>package rabbitmq import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", }, }, wantErr: false, }, { name: "init - bad url", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:6000/", }, }, wantErr: true, }, { name: "init - no url", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "", Properties: map[string]string{}, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantExecErr %v", err, tt.wantErr) return } }) } } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantResponse *types.Response wantErr bool }{ { name: "valid publish request without confirmation", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", }, }, request: types.NewRequest(). SetMetadataKeyValue("queue", "some-queue"). SetMetadataKeyValue("exchange", ""). SetMetadataKeyValue("confirm", "false"). SetMetadataKeyValue("delivery_mode", "1"). SetData([]byte("some-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantErr: false, }, { name: "invalid publish request - no queue", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", }, }, request: types.NewRequest(). SetMetadataKeyValue("exchange", ""). SetData([]byte("some-data")), wantResponse: nil, wantErr: true, }, { name: "invalid publish request - bad delivery mode", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", }, }, request: types.NewRequest(). SetMetadataKeyValue("queue", "some-queue"). SetMetadataKeyValue("exchange", ""). SetMetadataKeyValue("confirm", "false"). SetMetadataKeyValue("delivery_mode", "3"), wantResponse: nil, wantErr: true, }, { name: "invalid publish request - bad priority", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", }, }, request: types.NewRequest(). SetMetadataKeyValue("queue", "some-queue"). SetMetadataKeyValue("exchange", ""). SetMetadataKeyValue("confirm", "false"). SetMetadataKeyValue("priority", "12"), wantResponse: nil, wantErr: true, }, { name: "invalid publish request - bad expiry", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", }, }, request: types.NewRequest(). SetMetadataKeyValue("queue", "some-queue"). SetMetadataKeyValue("exchange", ""). SetMetadataKeyValue("confirm", "false"). SetMetadataKeyValue("expiry_seconds", "-1"), wantResponse: nil, wantErr: true, }, { name: "sending with default topic", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", "default_topic": "q1", }, }, request: types.NewRequest(). SetData([]byte("some-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantErr: false, }, { name: "sending with default exchange", cfg: config.Spec{ Name: "messaging-rabbitmq", Kind: "messaging.rabbitmq", Properties: map[string]string{ "url": "amqp://rabbitmq:rabbitmq@localhost:5672/", "default_exchange": "exchange", "default_topic": "weqwe", }, }, request: types.NewRequest(). SetData([]byte("some-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotResponse, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotResponse) require.EqualValues(t, tt.wantResponse, gotResponse) time.Sleep(2 * time.Second) }) } } <file_sep>package events import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.cloudwatch.events"). SetDescription("AWS Cloudwatch Events Target"). SetName("Cloudwatch Events"). SetProvider("AWS"). SetCategory("Observability"). SetTags("events", "cloud"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Cloudwatch-Events aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Cloudwatch-Events aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Cloudwatch-Events aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Cloudwatch-Events aws token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Cloudwatch-Events execution method"). SetOptions([]string{"put_targets", "send_event", "list_buses"}). SetDefault("send_event"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("rule"). SetKind("string"). SetDescription("Set Cloudwatch-Events rule"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("detail"). SetKind("string"). SetDescription("Set Cloudwatch-Events detail"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("detail_type"). SetKind("string"). SetDescription("Set Cloudwatch-Events detail type"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("source"). SetKind("string"). SetDescription("Set Cloudwatch-Events source"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("limit"). SetDescription("Set Cloudwatch-Events limit"). SetMust(false). SetDefault("100"). SetMin(0). SetMax(math.MaxInt32), ) } <file_sep>package rethinkdb import ( "fmt" "math" "time" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultUsername = "" defaultPassword = "" defaultAuthKey = "" defaultUseSSL = false defaultSSL = "" defaultTimeout = 5 defaultHandShakeVersion = 0 ) type options struct { host string username string password string timeout time.Duration keepAlivePeriod time.Duration authKey string ssl bool certFile string certKey string handShakeVersion int numberOfRetries int initialCap int maxOpen int } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.host, err = cfg.Properties.MustParseString("host") if err != nil { return options{}, fmt.Errorf("error parsing host, %w", err) } o.username = cfg.Properties.ParseString("username", defaultUsername) o.password = cfg.Properties.ParseString("password", defaultPassword) timeout, err := cfg.Properties.ParseIntWithRange("timeout", defaultTimeout, 0, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing operation timeout, %w", err) } o.timeout = time.Duration(timeout) * time.Second keepAlivePeriod, err := cfg.Properties.ParseIntWithRange("keep_alive_period", defaultTimeout, 0, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing keep_alive_period, %w", err) } o.keepAlivePeriod = time.Duration(keepAlivePeriod) * time.Second o.authKey = cfg.Properties.ParseString("auth_key", defaultAuthKey) o.ssl = cfg.Properties.ParseBool("ssl", defaultUseSSL) o.certFile = cfg.Properties.ParseString("cert_file", defaultSSL) o.certKey = cfg.Properties.ParseString("cert_key", defaultSSL) o.numberOfRetries = cfg.Properties.ParseInt("number_of_retries", 0) o.initialCap = cfg.Properties.ParseInt("initial_cap", 0) o.maxOpen = cfg.Properties.ParseInt("max_open", 0) o.handShakeVersion, err = cfg.Properties.ParseIntWithRange("hand_shake_version", defaultHandShakeVersion, 0, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing hand_shake_version, %w", err) } return o, nil } <file_sep>package servicebus import ( "time" "github.com/Azure/azure-service-bus-go" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultTimeToLive = 1000000000 DefaultContentType = "" DefaultLabel = "" DefaultMaxBatchSize = 1024 ) var methodsMap = map[string]string{ "send": "send", "send_batch": "send_batch", } type metadata struct { method string label string contentType string maxBatchSize servicebus.MaxMessageSizeInBytes timeToLive time.Duration } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { m.method = "send" } m.timeToLive = meta.ParseTimeDuration("time_to_live", DefaultTimeToLive) m.contentType = meta.ParseString("content_type", DefaultContentType) m.label = meta.ParseString("label", DefaultLabel) maxBatchSize := meta.ParseInt("max_batch_size", DefaultMaxBatchSize) m.maxBatchSize = servicebus.MaxMessageSizeInBytes(maxBatchSize) return m, nil } <file_sep>package redis import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { url string } func parseOptions(cfg config.Spec) (options, error) { o := options{ url: "", } var err error o.url, err = cfg.Properties.MustParseString("url") if err != nil { return options{}, fmt.Errorf("error parsing url, %w", err) } return o, nil } <file_sep>package echo import ( "context" "fmt" "os" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { host string } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Do(ctx context.Context, request *types.Request) (*types.Response, error) { m, _ := parseMetadata(request.Metadata) if m.isError { return types.NewResponse(). SetError(fmt.Errorf("echo error")). SetMetadata(request.Metadata). SetMetadataKeyValue("host", c.host). SetData(request.Data), nil } return types.NewResponse(). SetMetadata(request.Metadata). SetMetadataKeyValue("host", c.host). SetData(request.Data), nil } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { var err error c.host, err = os.Hostname() if err != nil { c.host = "unknown" } return nil } func (c *Client) Stop() error { return nil } <file_sep>package http import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { authType string username string password string token string proxy string rootCertificate string clientPrivateKey string clientPublicKey string defaultHeaders map[string]string } func parseOptions(cfg config.Spec) (options, error) { o := options{ authType: "", username: "", password: "", token: "", proxy: "", rootCertificate: "", clientPublicKey: "", clientPrivateKey: "", defaultHeaders: map[string]string{}, } var err error o.authType = cfg.Properties.ParseString("auth_type", "no_auth") o.username = cfg.Properties.ParseString("username", "") o.password = cfg.Properties.ParseString("password", "") o.token = cfg.Properties.ParseString("token", "") o.proxy = cfg.Properties.ParseString("proxy", "") o.rootCertificate = cfg.Properties.ParseString("root_certificate", "") o.clientPrivateKey = cfg.Properties.ParseString("client_private_key", "") o.clientPublicKey = cfg.Properties.ParseString("client_public_key", "") o.defaultHeaders, err = cfg.Properties.MustParseJsonMap("default_headers") if err != nil { return options{}, fmt.Errorf("error parsing default_headers value, %w", err) } return o, nil } <file_sep># Kubemq OpenFaas Target Connector Kubemq OpenFaas target connector allows services using kubemq server to invoke OpensFaas's functions. ## Prerequisites The following are required to run the OpenFaas target connector: - kubemq cluster - OpenFaas platform - kubemq-targets deployment ## Configuration OpenFaas target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:--------------------------|:-------------------------| | gateway | yes | OpenFaas gateway address | "http://localhost:31112" | | username | yes | Openfaas gateway username | "admin" | | password | yes | OpenFaas gateway password | "<PASSWORD>" | Example: ```yaml bindings: - name: kubemq-query-OpenFaas source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-OpenFaas-connector" auth_token: "" channel: "query.OpenFaas" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: serverless.openfaas name: target-serverless-openfaas properties: gateway: "http://localhost:31112" username: "admin" password: "<PASSWORD>" ``` ## Usage ### Request Request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:------------------------|:-------------------------| | topic | yes | OpenFaas function topic | "function/nslookup" | Request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:-------------------------------------|:--------------------| | data | yes | data to set for the OpenFaas request | base64 bytes array | Example: ```json { "metadata": { "topic": "function/nslookup" }, "data": "a3ViZW1xLmlv" } ``` <file_sep>package http import ( "context" "crypto/tls" "fmt" "io/ioutil" "net/http" "strings" "github.com/go-resty/resty/v2" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger client *resty.Client opts options } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.client = resty.New() c.client.SetDoNotParseResponse(true) switch c.opts.authType { case "basic": c.client.SetBasicAuth(c.opts.username, c.opts.password) case "auth_token": c.client.SetAuthToken(c.opts.token) } c.client.SetHeaders(c.opts.defaultHeaders) if c.opts.proxy != "" { c.client.SetProxy(c.opts.proxy) } if c.opts.rootCertificate != "" { c.client.SetRootCertificateFromString(c.opts.rootCertificate) } if c.opts.clientPrivateKey != "" && c.opts.clientPublicKey != "" { cert, err := tls.X509KeyPair([]byte(c.opts.clientPublicKey), []byte(c.opts.clientPrivateKey)) if err != nil { return fmt.Errorf("error loading client certificate: %w", err) } c.client.SetCertificates(cert) } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } httpReq := c.client.R(). SetHeaders(meta.headers). SetContext(ctx) if req.Data != nil { httpReq.SetBody(req.Data) } httpReq.URL = meta.url httpReq.Method = strings.ToUpper(meta.method) resp, err := httpReq.Send() if err != nil { return nil, err } tr, err := newResultFromHttpResponse(resp.RawResponse) if err != nil { return nil, err } return tr, resp.RawResponse.Body.Close() } func newResultFromHttpResponse(hr *http.Response) (*types.Response, error) { resp := types.NewResponse(). SetMetadataKeyValue("code", fmt.Sprintf("%d", hr.StatusCode)). SetMetadataKeyValue("status", hr.Status) headers := types.NewMetadata() for name, values := range hr.Header { headers[name] = strings.Join(values, ",") } resp.SetMetadataKeyValue("headers", headers.String()) var err error if hr.Body == nil { return resp, nil } resp.Data, err = ioutil.ReadAll(hr.Body) if err != nil { return nil, err } return resp, nil } func (c *Client) Stop() error { return nil } <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { dat, err := ioutil.ReadFile("./credentials/topicID.txt") if err != nil { panic(err) } topicID := string(dat) client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // add request setRequest := types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("topic_id", topicID) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.gcp.pubsub"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("set request with tags for topic : %s executed, is_error: %v", topicID, setResponse.IsError)) } <file_sep>package echo import ( "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { isError bool } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} m.isError = meta.ParseBool("is-error", false) return m, nil } <file_sep>package couchbase import ( "fmt" "math" "time" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultCas = 0 defaultExpirySeconds = 0 ) var methodsMap = map[string]string{ "get": "get", "set": "set", "delete": "delete", } type metadata struct { method string key string cas int expiry time.Duration } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.key, err = meta.MustParseString("key") if err != nil { return metadata{}, fmt.Errorf("error on parsing key value, %w", err) } m.cas, err = meta.ParseIntWithRange("cas", defaultCas, 0, math.MaxInt32) if err != nil { return metadata{}, fmt.Errorf("error on cas value, %w", err) } expirySeconds, err := meta.ParseIntWithRange("expiry_seconds", defaultExpirySeconds, 0, math.MaxInt32) if err != nil { return metadata{}, fmt.Errorf("error on expiry seconds value, %w", err) } m.expiry = time.Duration(expirySeconds) * time.Second return m, nil } <file_sep>package sns import ( "encoding/json" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sns" ) type Attributes struct { Name string `json:"name"` DataType string `json:"data_type"` StringValue string `json:"string_value"` } func (c *Client) createSNSMessage(meta metadata, data []byte) (*sns.PublishInput, error) { var s []Attributes if data != nil { err := json.Unmarshal(data, &s) if err != nil { return nil, err } } i := &sns.PublishInput{ Message: aws.String(meta.message), } if meta.topic != "" { i.TopicArn = aws.String(meta.topic) } else { i.TargetArn = aws.String(meta.targetArn) } if meta.phoneNumber != "" { i.PhoneNumber = aws.String(meta.phoneNumber) } if meta.subject != "" { i.Subject = aws.String(meta.subject) } a := make(map[string]*sns.MessageAttributeValue) for _, i := range s { if _, ok := a[i.Name]; ok { return nil, fmt.Errorf("duplicate name value in attibutes") } a[i.Name] = &sns.MessageAttributeValue{ DataType: aws.String(i.DataType), StringValue: aws.String(i.StringValue), } } if len(a) > 0 { i.MessageAttributes = a } return i, nil } <file_sep>package filesystem import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "filesystem-target", Kind: "", Properties: map[string]string{ "base_path": "./", }, }, wantErr: false, }, { name: "init", cfg: config.Spec{ Name: "filesystem-target", Kind: "", Properties: map[string]string{ "base_path": "", }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSaveErr %v", err, tt.wantErr) return } }) } } func TestClient_Files(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() cfg := config.Spec{ Name: "filesystem-target", Kind: "", Properties: map[string]string{ "base_path": "../../../test-fs", }, } c := New() err := c.Init(ctx, cfg, nil) require.NoError(t, err) save := types.NewRequest(). SetMetadataKeyValue("method", "save"). SetMetadataKeyValue("path", "test"). SetMetadataKeyValue("filename", "test.txt"). SetData([]byte("test")) resp, err := c.Do(ctx, save) require.NoError(t, err) require.Equal(t, false, resp.IsError) load := types.NewRequest(). SetMetadataKeyValue("method", "load"). SetMetadataKeyValue("path", "test"). SetMetadataKeyValue("filename", "test.txt") resp, err = c.Do(ctx, load) require.NoError(t, err) require.Equal(t, false, resp.IsError) require.Equal(t, []byte("test"), resp.Data) del := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("path", "test"). SetMetadataKeyValue("filename", "test.txt") resp, err = c.Do(ctx, del) require.NoError(t, err) require.Equal(t, false, resp.IsError) saveErr := types.NewRequest(). SetMetadataKeyValue("method", "save"). SetMetadataKeyValue("path", "*"). SetMetadataKeyValue("filename", "bad-filename") resp, err = c.Do(ctx, saveErr) require.NoError(t, err) require.Equal(t, true, resp.IsError) loadErr := types.NewRequest(). SetMetadataKeyValue("method", "load"). SetMetadataKeyValue("path", "test"). SetMetadataKeyValue("filename", "bad-filename") resp, err = c.Do(ctx, loadErr) require.NoError(t, err) require.Equal(t, true, resp.IsError) delErr := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("path", "test"). SetMetadataKeyValue("filename", "bad-filename") resp, err = c.Do(ctx, delErr) require.NoError(t, err) require.Equal(t, true, resp.IsError) } <file_sep>package hdfs import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { address string file []byte user string } func getTestStructure() (*testStructure, error) { t := &testStructure{} t.address = "localhost:9000" contents, err := ioutil.ReadFile("./../../../examples/storage/hdfs/exampleFile.txt") if err != nil { return nil, err } t.file = contents t.user = "test_user" return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init ", cfg: config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": dat.address, "user": dat.user, }, }, wantErr: false, }, { name: "invalid init - incorrect port", cfg: config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": "localhost:123123", "user": dat.address, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Mkdir(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": dat.address, "user": dat.user, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid mkdir", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test"). SetMetadataKeyValue("file_mode", "0777"). SetMetadataKeyValue("method", "mkdir"), wantErr: false, }, { name: "invalid mkdir already exists", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test"). SetMetadataKeyValue("file_mode", "0777"). SetMetadataKeyValue("method", "mkdir"), wantErr: true, }, { name: "invalid mkdir - missing path", request: types.NewRequest(). SetMetadataKeyValue("file_mode", "0755"). SetMetadataKeyValue("method", "mkdir"), wantErr: true, }, { name: "invalid mkdir invalid file_mode", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test"). SetMetadataKeyValue("file_mode", "99999"). SetMetadataKeyValue("method", "mkdir"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Upload(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": dat.address, "user": dat.user, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid upload", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo2.txt"). SetData(dat.file). SetMetadataKeyValue("file_mode", "0777"). SetMetadataKeyValue("method", "write_file"), wantErr: false, }, { name: "invalid upload", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo2.txt"). SetData(dat.file). SetMetadataKeyValue("method", "write_file"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_ReadFile(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": dat.address, "user": dat.user, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid read", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo2.txt"). SetMetadataKeyValue("method", "read_file"), wantErr: false, }, { name: "invalid read missing file_path", request: types.NewRequest(). SetMetadataKeyValue("method", "read_file"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Remove_File(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": dat.address, "user": dat.user, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid Remove item", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo2.txt"). SetMetadataKeyValue("method", "remove_file"), wantErr: false, }, { name: "invalid Remove item - file does not exists", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo2.txt"). SetMetadataKeyValue("method", "remove_file"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Stat(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": dat.address, "user": dat.user, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid stat", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo.txt"). SetMetadataKeyValue("method", "stat"), wantErr: false, }, { name: "invalid stat - file does not exists", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/fake.txt"). SetMetadataKeyValue("method", "stat"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Rename(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "storage-hdfs", Kind: "storage.hdfs", Properties: map[string]string{ "address": dat.address, "user": dat.user, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid rename", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo3.txt"). SetMetadataKeyValue("old_file_path", "/test/foo2.txt"). SetMetadataKeyValue("method", "rename_file"), wantErr: false, }, { name: "invalid rename - file does not exists", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo3.txt"). SetMetadataKeyValue("old_file_path", "/test/foo2.txt"). SetMetadataKeyValue("method", "rename_file"), wantErr: true, }, { name: "invalid rename - missing old file path", request: types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo3.txt"). SetMetadataKeyValue("method", "rename_file"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } // //func TestClient_Get_Item(t *testing.T) { // dat, err := getTestStructure() // require.NoError(t, err) // cfg := config.Spec{ // Name: "storage-hdfs", // Kind: "storage.hdfs", // Properties: map[string]string{ // "aws_key": dat.awsKey, // "aws_secret_key": dat.awsSecretKey, // "region": dat.region, // "downloader": "true", // "uploader": "false", // }, // } // tests := []struct { // name string // request *types.Request // wantErr bool // setDownloader bool // }{ // { // name: "valid get item", // request: types.NewRequest(). // SetMetadataKeyValue("method", "get_item"). // SetMetadataKeyValue("bucket_name", dat.testBucketName). // SetMetadataKeyValue("item_name", dat.itemName), // wantErr: false, // setDownloader: true, // }, // { // name: "invalid get - missing item", // request: types.NewRequest(). // SetMetadataKeyValue("method", "get_item"). // SetMetadataKeyValue("bucket_name", dat.testBucketName), // wantErr: true, // setDownloader: true, // }, { // name: "invalid get - item does not exists", // request: types.NewRequest(). // SetMetadataKeyValue("method", "get_item"). // SetMetadataKeyValue("bucket_name", dat.testBucketName). // SetMetadataKeyValue("item_name", "fakeItemName"), // wantErr: true, // setDownloader: true, // }, // { // name: "invalid get - missing bucketName", // request: types.NewRequest(). // SetMetadataKeyValue("method", "get_item"). // SetMetadataKeyValue("item_name", dat.itemName), // wantErr: true, // setDownloader: true, // }, { // name: "invalid upload - missing downloader", // request: types.NewRequest(). // SetMetadataKeyValue("method", "get_item"). // SetMetadataKeyValue("bucket_name", dat.testBucketName). // SetMetadataKeyValue("item_name", dat.itemName), // wantErr: true, // setDownloader: false, // }, // } // for _, tt := range tests { // t.Run(tt.name, func(t *testing.T) { // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // c := New() // // if !tt.setDownloader { // cfg.Properties["downloader"] = "false" // } else { // cfg.Properties["downloader"] = "true" // } // err = c.Init(ctx, cfg) // require.NoError(t, err) // got, err := c.Do(ctx, tt.request) // if tt.wantErr { // require.Error(t, err) // t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) // return // } // require.NoError(t, err) // require.NotNil(t, got) // }) // } //} // //func TestClient_Delete_Item(t *testing.T) { // dat, err := getTestStructure() // require.NoError(t, err) // cfg := config.Spec{ // Name: "storage-hdfs", // Kind: "storage.hdfs", // Properties: map[string]string{ // "aws_key": dat.awsKey, // "aws_secret_key": dat.awsSecretKey, // "region": dat.region, // "downloader": "false", // "uploader": "false", // }, // } // tests := []struct { // name string // request *types.Request // wantErr bool // }{ // { // name: "valid delete item", // request: types.NewRequest(). // SetMetadataKeyValue("method", "delete_item_from_bucket"). // SetMetadataKeyValue("wait_for_completion", "true"). // SetMetadataKeyValue("bucket_name", dat.testBucketName). // SetMetadataKeyValue("item_name", dat.itemName), // wantErr: false, // }, // { // name: "invalid delete - missing item", // request: types.NewRequest(). // SetMetadataKeyValue("method", "delete_item_from_bucket"). // SetMetadataKeyValue("wait_for_completion", "true"). // SetMetadataKeyValue("bucket_name", dat.testBucketName), // wantErr: true, // }, // { // name: "invalid delete - missing bucket_name", // request: types.NewRequest(). // SetMetadataKeyValue("method", "delete_item_from_bucket"). // SetMetadataKeyValue("wait_for_completion", "true"). // SetMetadataKeyValue("item_name", dat.itemName), // wantErr: true, // }, // } // for _, tt := range tests { // t.Run(tt.name, func(t *testing.T) { // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // c := New() // // err = c.Init(ctx, cfg) // require.NoError(t, err) // got, err := c.Do(ctx, tt.request) // if tt.wantErr { // require.Error(t, err) // t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) // return // } // require.NoError(t, err) // require.NotNil(t, got) // }) // } //} // //func TestClient_Copy_Items(t *testing.T) { // dat, err := getTestStructure() // require.NoError(t, err) // cfg := config.Spec{ // Name: "storage-hdfs", // Kind: "storage.hdfs", // Properties: map[string]string{ // "aws_key": dat.awsKey, // "aws_secret_key": dat.awsSecretKey, // "region": dat.region, // "downloader": "false", // "uploader": "false", // }, // } // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // c := New() // // err = c.Init(ctx, cfg) // require.NoError(t, err) // tests := []struct { // name string // request *types.Request // wantErr bool // }{ // { // name: "valid copy items", // request: types.NewRequest(). // SetMetadataKeyValue("method", "copy_item"). // SetMetadataKeyValue("wait_for_completion", "true"). // SetMetadataKeyValue("bucket_name", dat.bucketName). // SetMetadataKeyValue("item_name", dat.itemName). // SetMetadataKeyValue("copy_source", dat.dstBucketName), // wantErr: false, // }, // { // name: "invalid copy items - missing copy_source ", // request: types.NewRequest(). // SetMetadataKeyValue("method", "copy_item"). // SetMetadataKeyValue("bucket_name", dat.testBucketName). // SetMetadataKeyValue("item_name", dat.itemName), // wantErr: true, // }, // } // for _, tt := range tests { // t.Run(tt.name, func(t *testing.T) { // got, err := c.Do(ctx, tt.request) // if tt.wantErr { // require.Error(t, err) // t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) // return // } // require.NoError(t, err) // require.NotNil(t, got) // }) // } //} // //func TestClient_Delete_All_Items(t *testing.T) { // dat, err := getTestStructure() // require.NoError(t, err) // cfg := config.Spec{ // Name: "storage-hdfs", // Kind: "storage.hdfs", // Properties: map[string]string{ // "aws_key": dat.awsKey, // "aws_secret_key": dat.awsSecretKey, // "region": dat.region, // "downloader": "false", // "uploader": "false", // }, // } // ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // defer cancel() // c := New() // // err = c.Init(ctx, cfg) // require.NoError(t, err) // tests := []struct { // name string // request *types.Request // wantErr bool // }{ // { // name: "valid delete all items", // request: types.NewRequest(). // SetMetadataKeyValue("method", "delete_all_items_from_bucket"). // SetMetadataKeyValue("wait_for_completion", "true"). // SetMetadataKeyValue("bucket_name", dat.testBucketName), // wantErr: false, // }, // { // name: "invalid valid delete all items - missing bucket", // request: types.NewRequest(). // SetMetadataKeyValue("method", "delete_all_items_from_bucket"), // wantErr: true, // }, // } // for _, tt := range tests { // t.Run(tt.name, func(t *testing.T) { // got, err := c.Do(ctx, tt.request) // if tt.wantErr { // require.Error(t, err) // t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) // return // } // require.NoError(t, err) // require.NotNil(t, got) // }) // } //} // //func TestClient_Delete_Bucket(t *testing.T) { // dat, err := getTestStructure() // require.NoError(t, err) // cfg := config.Spec{ // Name: "storage-hdfs", // Kind: "storage.hdfs", // Properties: map[string]string{ // "aws_key": dat.awsKey, // "aws_secret_key": dat.awsSecretKey, // "region": dat.region, // "downloader": "false", // "uploader": "false", // }, // } // ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) // defer cancel() // c := New() // // err = c.Init(ctx, cfg) // require.NoError(t, err) // tests := []struct { // name string // request *types.Request // wantErr bool // }{ // { // name: "valid delete", // request: types.NewRequest(). // SetMetadataKeyValue("method", "delete_bucket"). // SetMetadataKeyValue("wait_for_completion", "true"). // SetMetadataKeyValue("bucket_name", dat.testBucketName), // wantErr: false, // }, // { // name: "invalid delete - missing bucket_name", // request: types.NewRequest(). // SetMetadataKeyValue("method", "create_bucket"), // wantErr: true, // }, // { // name: "invalid delete - bucket does not exists", // request: types.NewRequest(). // SetMetadataKeyValue("method", "delete_bucket"). // SetMetadataKeyValue("bucket_name", dat.testBucketName), // wantErr: true, // }, // } // for _, tt := range tests { // t.Run(tt.name, func(t *testing.T) { // got, err := c.Do(ctx, tt.request) // if tt.wantErr { // require.Error(t, err) // t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) // return // } // require.NoError(t, err) // require.NotNil(t, got) // }) // } //} <file_sep>package logs import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultLimit = 100 defaultSequenceToken = "" ) type metadata struct { method string sequenceToken string logGroupName string logStreamName string logGroupPrefix string limit int64 } var methodsMap = map[string]string{ "create_log_event_stream": "create_log_event_stream", "describe_log_event_stream": "describe_log_event_stream", "delete_log_event_stream": "delete_log_event_stream", "put_log_event": "put_log_event", "get_log_event": "get_log_event", "create_log_group": "create_log_group", "delete_log_group": "delete_log_group", "describe_log_group": "describe_log_group", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "describe_log_group" { m.logGroupPrefix, err = meta.MustParseString("log_group_prefix") if err != nil { return metadata{}, fmt.Errorf(" log_group_prefix is required for method :%s error parsing log_group_prefix, %w", m.method, err) } } else { m.logGroupName, err = meta.MustParseString("log_group_name") if err != nil { return metadata{}, fmt.Errorf("log_group_name is required for method %s,error parsing log_group_name, %w", m.method, err) } if m.method == "put_log_event" || m.method == "get_log_event" || m.method == "create_log_event_stream" || m.method == "delete_log_event_stream" { m.logStreamName, err = meta.MustParseString("log_stream_name") if err != nil { return metadata{}, fmt.Errorf("log_stream_name is required for method %s,error parsing log_stream_name, %w", m.method, err) } if m.method == "put_log_event" { m.sequenceToken = meta.ParseString("sequence_token", defaultSequenceToken) } } } m.limit = int64(meta.ParseInt("limit", defaultLimit)) return m, nil } <file_sep>package lambda import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string zipFileName string functionName string handlerName string role string runtime string description string lambdaExp []byte } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" dat, err = ioutil.ReadFile("./../../../credentials/aws/lambda/zipFileName.txt") if err != nil { return nil, err } t.zipFileName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/lambda/functionName.txt") if err != nil { return nil, err } t.functionName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/lambda/handlerName.txt") if err != nil { return nil, err } t.handlerName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/lambda/role.txt") if err != nil { return nil, err } t.role = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/lambda/runtime.txt") if err != nil { return nil, err } t.runtime = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/lambda/description.txt") if err != nil { return nil, err } t.description = string(dat) contents, err := ioutil.ReadFile("./../../../credentials/aws/lambda/lambdaCode.zip") if err != nil { return nil, err } t.lambdaExp = contents return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: false, }, { name: "invalid init - missing aws_key", cfg: config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: true, }, { name: "invalid init - missing region", cfg: config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, }, }, wantErr: true, }, { name: "invalid init - missing aws_secret_key", cfg: config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_key": dat.awsKey, "region": dat.region, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_List(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Create(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create", request: types.NewRequest(). SetMetadataKeyValue("method", "create"). SetMetadataKeyValue("zip_file_name", dat.zipFileName). SetMetadataKeyValue("description", dat.description). SetMetadataKeyValue("handler_name", dat.handlerName). SetMetadataKeyValue("memorySize", "256"). SetMetadataKeyValue("timeout", "15"). SetMetadataKeyValue("role", dat.role). SetMetadataKeyValue("function_name", dat.functionName). SetMetadataKeyValue("runtime", dat.runtime). SetData(dat.lambdaExp), wantErr: false, }, { name: "invalid create- already exists", request: types.NewRequest(). SetMetadataKeyValue("method", "create"). SetMetadataKeyValue("zip_file_name", dat.zipFileName). SetMetadataKeyValue("description", dat.description). SetMetadataKeyValue("handler_name", dat.handlerName). SetMetadataKeyValue("role", dat.role). SetMetadataKeyValue("function_name", dat.functionName). SetMetadataKeyValue("runtime", dat.runtime). SetData(dat.lambdaExp), wantErr: true, }, { name: "invalid create- missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "create"). SetMetadataKeyValue("zip_file_name", dat.zipFileName). SetMetadataKeyValue("description", dat.description). SetMetadataKeyValue("handler_name", dat.handlerName). SetMetadataKeyValue("role", dat.role). SetMetadataKeyValue("function_name", dat.functionName). SetMetadataKeyValue("runtime", dat.runtime), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Delete(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("function_name", dat.functionName), wantErr: false, }, { name: "invalid delete - does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("function_name", dat.functionName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Run(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-lambda", Kind: "aws.lambda", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) b, err := json.Marshal("my object") require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid run", request: types.NewRequest(). SetMetadataKeyValue("method", "run"). SetMetadataKeyValue("function_name", dat.functionName). SetData(b), wantErr: false, }, { name: "invalid run - function does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "run"). SetMetadataKeyValue("function_name", "not_a_real_function"). SetData(b), wantErr: true, }, { name: "invalid run - missing function name", request: types.NewRequest(). SetMetadataKeyValue("method", "run"). SetData(b), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_isJson(t *testing.T) { tests := []struct { name string data []byte want bool }{ { name: "empty", data: nil, want: true, }, { name: "not-valid", data: []byte("bXkgb2JqZWN0"), want: false, }, { name: "not-valid", data: []byte("<KEY>"), want: false, }, { name: "valid", data: []byte("<KEY>=="), want: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := isJson(tt.data); got != tt.want { t.Errorf("isJson() = %v, want %v", got, tt.want) } }) } } <file_sep>package pubsub import ( "context" "encoding/json" "fmt" "cloud.google.com/go/pubsub" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/iterator" "google.golang.org/api/option" ) type Client struct { log *logger.Logger opts options client *pubsub.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) client, err := pubsub.NewClient(ctx, c.opts.projectID, option.WithCredentialsJSON(b)) if err != nil { return err } c.client = client return nil } func (c *Client) Do(ctx context.Context, request *types.Request) (*types.Response, error) { eventMetadata, err := parseMetadata(request.Metadata, c.opts) if err != nil { return nil, err } t := c.client.Topic(eventMetadata.topicID) result := t.Publish(ctx, &pubsub.Message{ Data: request.Data, Attributes: eventMetadata.tags, }) tries := 0 for tries <= c.opts.retries { id, err := result.Get(ctx) if err == nil { return types.NewResponse(). SetMetadataKeyValue("event_id", id), nil } if tries >= c.opts.retries { return nil, err } tries++ } return nil, fmt.Errorf("retries must be a zero or greater") } func (c *Client) list(ctx context.Context) (*types.Response, error) { var topics []string it := c.client.Topics(ctx) for { topic, err := it.Next() if err == iterator.Done { break } if err != nil { return nil, err } topics = append(topics, topic.ID()) } if len(topics) <= 0 { return nil, fmt.Errorf("no topics found for this project") } data, err := json.Marshal(topics) if err != nil { return nil, err } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.client != nil { return c.client.Close() } return nil } <file_sep>package elasticsearch import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultJson = "" DefaultService = "es" ) type metadata struct { method string region string json string domain string index string endpoint string service string id string } var httpMethodsMap = map[string]string{ "GET": "GET", "POST": "POST", "PUT": "PUT", "DELETE": "DELETE", "OPTIONS": "OPTIONS", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", httpMethodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(httpMethodsMap) } m.region, err = meta.MustParseString("region") if err != nil { return metadata{}, fmt.Errorf("error failed to parse region , %w", err) } m.domain, err = meta.MustParseString("domain") if err != nil { return metadata{}, fmt.Errorf("error failed to parse domain , %w", err) } m.index, err = meta.MustParseString("index") if err != nil { return metadata{}, fmt.Errorf("error failed to parse index , %w", err) } m.endpoint, err = meta.MustParseString("endpoint") if err != nil { return metadata{}, fmt.Errorf("error failed to parse endpoint , %w", err) } m.id, err = meta.MustParseString("id") if err != nil { return metadata{}, fmt.Errorf("error failed to parse id , %w", err) } if m.method == "GET" { m.json = meta.ParseString("json", DefaultJson) } else { m.json, err = meta.MustParseString("json") if err != nil { return metadata{}, fmt.Errorf("error failed to parse json , %w", err) } } m.service = meta.ParseString("service", DefaultService) return m, nil } <file_sep>package api import ( "context" "fmt" "time" "github.com/kubemq-io/kubemq-targets/binding" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" ) type Server struct { echoWebServer *echo.Echo bindingService *binding.Service } func Start(ctx context.Context, port int, bs *binding.Service) (*Server, error) { s := &Server{ echoWebServer: echo.New(), bindingService: bs, } s.echoWebServer.Use(middleware.Recover()) s.echoWebServer.Use(middleware.CORS()) s.echoWebServer.HideBanner = true s.echoWebServer.GET("/health", func(c echo.Context) error { return c.String(200, "ok") }) s.echoWebServer.GET("/ready", func(c echo.Context) error { return c.String(200, "ready") }) s.echoWebServer.GET("/metrics", echo.WrapHandler(s.bindingService.PrometheusHandler())) s.echoWebServer.GET("/bindings", func(c echo.Context) error { return c.JSONPretty(200, s.bindingService.GetStatus(), "\t") }) s.echoWebServer.GET("/bindings/stats", func(c echo.Context) error { return c.JSONPretty(200, s.bindingService.Stats(), "\t") }) s.echoWebServer.POST("/bindings/request", func(c echo.Context) error { req := &binding.Request{} err := c.Bind(req) if err != nil { return c.JSONPretty(400, struct { Error string }{ Error: fmt.Sprintf("invalid request, %s", err.Error()), }, "\t") } return c.JSONPretty(200, s.bindingService.SendRequest(c.Request().Context(), req), "\t") }) errCh := make(chan error, 1) go func() { errCh <- s.echoWebServer.Start(fmt.Sprintf("0.0.0.0:%d", port)) }() select { case err := <-errCh: if err != nil { return nil, err } return s, nil case <-time.After(1 * time.Second): return s, nil case <-ctx.Done(): return nil, fmt.Errorf("error strarting api server, %w", ctx.Err()) } } func (s *Server) Stop() error { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() return s.echoWebServer.Shutdown(ctx) } <file_sep>package firestore import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.firestore"). SetDescription("GCP Firestore Target"). SetName("Firestore"). SetProvider("GCP"). SetCategory("Store"). SetTags("db", "no-sql", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("project_id"). SetTitle("Project ID"). SetDescription("Set GCP project ID"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set GCP Firestore execution method"). SetOptions([]string{"documents_all", "document_key", "delete_document_key", "add"}). SetDefault("add"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("collection"). SetKind("string"). SetDescription("Set Firestore collection name"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("item"). SetKind("string"). SetDescription("Set Firestore item name"). SetDefault(""). SetMust(false), ) } <file_sep>package couchbase import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.couchbase"). SetDescription("Couchbase Target"). SetName("Couchbase"). SetProvider(""). SetCategory("Store"). SetTags("db", "sql"). // AddProperty( common.NewProperty(). SetKind("string"). SetName("url"). SetTitle("Connection URL"). SetDescription("Set Couchbase url"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Couchbase username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Couchbase password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("bucket"). SetDescription("Set Couchbase bucket"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("collection"). SetDescription("Set Couchbase collection"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("num_to_replicate"). SetTitle("Replication Nodes"). SetDescription("Set Couchbase number of nodes to replicate"). SetMust(false). SetDefault("1"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("num_to_persist"). SetTitle("Persistence Nodes"). SetDescription("Set Couchbase number of node to persist"). SetMust(false). SetDefault("1"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Couchbase execution method"). SetOptions([]string{"get", "set", "delete"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Couchbase key to set get or delete"). SetMust(true), ) } <file_sep>package filesystem import ( "context" "fmt" "io/ioutil" "os" "path/filepath" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { opts options absPath string } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { var err error c.opts, err = parseOptions(cfg) if err != nil { return err } if _, err := os.Stat(c.opts.basePath); os.IsNotExist(err) { return fmt.Errorf("base path does not exist") } c.absPath, err = filepath.Abs(c.opts.basePath) if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "save": return c.Save(ctx, meta, req.Data) case "load": return c.Load(ctx, meta) case "delete": return c.Delete(ctx, meta) case "list": return c.List(ctx, meta) } return nil, nil } func (c *Client) Save(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if _, err := os.Stat(filepath.Join(c.absPath, meta.path)); os.IsNotExist(err) { err := os.MkdirAll(filepath.Join(c.absPath, meta.path), 0o600) if err != nil { return types.NewResponse().SetError(err), nil } } fullPath := filepath.Join(c.absPath, meta.path, meta.filename) err := ioutil.WriteFile(fullPath, data, 0o600) if err != nil { return types.NewResponse().SetError(err), nil } return types.NewResponse().SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Delete(ctx context.Context, meta metadata) (*types.Response, error) { fullPath := filepath.Join(c.absPath, meta.path, meta.filename) err := os.Remove(fullPath) if err != nil { return types.NewResponse().SetError(err), nil } return types.NewResponse().SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Load(ctx context.Context, meta metadata) (*types.Response, error) { fullPath := filepath.Join(c.absPath, meta.path, meta.filename) data, err := ioutil.ReadFile(fullPath) if err != nil { return types.NewResponse().SetError(err), nil } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(data), nil } func (c *Client) List(ctx context.Context, meta metadata) (*types.Response, error) { var list FileInfoList err := filepath.Walk(c.absPath, func(path string, info os.FileInfo, err error) error { if err != nil { return err } list = append(list, newFromOSFileInfo(info, path)) return nil }) if err != nil { return types.NewResponse().SetError(err), nil } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(list.Marshal()), nil } func (c *Client) Stop() error { return nil } <file_sep>//go:build container // +build container package ibmmq import ( "context" "errors" "fmt" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-hub/ibmmq-sdk/mq-golang-jms20/jms20subset" "github.com/kubemq-hub/ibmmq-sdk/mq-golang-jms20/mqjms" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options queue jms20subset.Queue jmsContext jms20subset.JMSContext producer jms20subset.JMSProducer } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } c.log = logger.NewLogger(cfg.Name) var err error c.opts, err = parseOptions(cfg) if err != nil { return err } cf := mqjms.ConnectionFactoryImpl{ QMName: c.opts.qMName, Hostname: c.opts.hostname, PortNumber: c.opts.portNumber, ChannelName: c.opts.channelName, UserName: c.opts.userName, TransportType: c.opts.transportType, TLSClientAuth: c.opts.tlsClientAuth, KeyRepository: c.opts.keyRepository, Password: c.opts.Password, CertificateLabel: c.opts.certificateLabel, } jmsContext, jmsErr := cf.CreateContext() if jmsErr != nil { return fmt.Errorf("failed to create context on error %s", jmsErr.GetReason()) } c.jmsContext = jmsContext c.queue = c.jmsContext.CreateQueue(c.opts.queueName) c.producer = c.jmsContext.CreateProducer().SetDeliveryMode(c.opts.transportType).SetTimeToLive(c.opts.timeToLive) return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } if meta.dynamicQueue != "" { c.queue = c.jmsContext.CreateQueue(meta.dynamicQueue) } if req.Data == nil { return nil, errors.New("missing body") } jmsErr := c.producer.SendString(c.queue, fmt.Sprintf("%s", req.Data)) if jmsErr != nil { return nil, fmt.Errorf("failed to create context on error %s", jmsErr.GetReason()) } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.jmsContext != nil { c.jmsContext.Close() } return nil } <file_sep>package hazelcast import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "hazelcast-target", Kind: "hazelcast.target", Properties: map[string]string{ "address": "localhost:5701", }, }, wantErr: false, }, { name: "init - incorrect address", cfg: config.Spec{ Name: "hazelcast-target", Kind: "hazelcast.target", Properties: map[string]string{ "address": "localhost:5702", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } func TestClient_Set_Get(t *testing.T) { tests := []struct { name string cfg config.Spec setRequest *types.Request getRequest *types.Request wantSetResponse *types.Response wantGetResponse *types.Response wantSetErr bool wantGetErr bool }{ { name: "valid set get request", cfg: config.Spec{ Name: "hazelcast-target", Kind: "hazelcast.target", Properties: map[string]string{ "address": "localhost:5701", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("map_name", "my_map"). SetData([]byte("some-data")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("map_name", "my_map"). SetMetadataKeyValue("key", "some-key"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("result", "ok"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("result", "ok"). SetData([]byte("some-data")), wantSetErr: false, wantGetErr: false, }, { name: "invalid get - key does not exists", cfg: config.Spec{ Name: "hazelcast-target", Kind: "hazelcast.target", Properties: map[string]string{ "address": "localhost:5701", }, }, getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "fake_key"). SetMetadataKeyValue("map_name", "my_map"), wantSetErr: true, wantGetErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) if tt.setRequest != nil { gotSetResponse, err := c.Do(ctx, tt.setRequest) if tt.wantSetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantSetResponse, gotSetResponse) } gotGetResponse, err := c.Do(ctx, tt.getRequest) if tt.wantGetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantGetResponse, gotGetResponse) }) } } func TestClient_Delete(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request getRequest *types.Request wantResponse *types.Response wantErr bool }{ { name: "valid delete request", cfg: config.Spec{ Name: "hazelcast-target", Kind: "hazelcast.target", Properties: map[string]string{ "address": "localhost:5701", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("map_name", "my_map"), wantResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("result", "ok"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantResponse, gotSetResponse) }) } } <file_sep>package msk import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.msk"). SetDescription("AWS MSK Target"). SetName("MSK"). SetProvider("AWS"). SetCategory("Messaging"). SetTags("kafka", "streaming", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("brokers"). SetTitle("Brokers Address"). SetDescription("Set MSK brokers list"). SetMust(true). SetDefault("localhost:9092"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("sasl_username"). SetTitle("SASL Username"). SetDescription("Set MSK username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("sasl_password"). SetTitle("SASL Password"). SetDescription("Set MSK password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("topic"). SetDescription("Set MSK topic"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("headers"). SetKind("string"). SetDescription("Set Kafka headers"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Set Kafka Key"). SetDefault(""). SetMust(false), ) } <file_sep>package filesystem import ( "fmt" "strings" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { basePath string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.basePath, err = cfg.Properties.MustParseString("base_path") if err != nil { return options{}, fmt.Errorf("error parsing base_path, %w", err) } o.basePath = unixNormalize(o.basePath) return o, nil } func unixNormalize(in string) string { return strings.Replace(in, `\`, "/", -1) } <file_sep>docker-comopse up "access_key_id": "minio", "secret_access_key": "minio123", <file_sep># Kubemq KeySpaces Target Connector Kubemq keyspaces target connector allows services using kubemq server to access keyspaces database services. ## Prerequisites The following are required to run the keyspaces target connector: - kubemq cluster - IAM user keyspaces credentials - aws keyspaces server/cluster - kubemq-targets deployment ## Configuration keyspaces target connector configuration properties: | Properties Key | Required | Description | Example | |:--------------------------|:---------|:---------------------------------------|:------------------------------------| | hosts | yes | aws end point | "localhost" | | port | yes | keyspaces port | "9142" | | proto_version | no | keyspaces proto version | "4" | | replication_factor | no | set replication factor | "1" | | username | no | set keyspaces username | "keyspaces" | | password | no | set keyspaces password | "<PASSWORD>" | | consistency | no | set keyspaces consistency | "One","LocalOne","LocalQuorum" see https://docs.aws.amazon.com/keyspaces/latest/devguide/consistency.html | | default_table | no | set table name | "test" | | default_keyspace | no | set keyspace name | "test" | | tls | yes | aws keyspace certificate | aws tls link see https://docs.aws.amazon.com/keyspaces/latest/devguide/using_go_driver.html | | timeout_seconds | no | set default timeout seconds | "60" | | connect_timeout_seconds | no | set default connect timeout seconds | "60" | Example: ```yaml bindings: - name: kubemq-query-keyspaces source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-keyspaces-connector" auth_token: "" channel: "aws.query.keyspaces" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.keyspaces name: aws-keyspaces properties: hosts: "cassandra.us-east-2.amazonaws.com" port: "9142" username: "keyspaces" password: "<PASSWORD>" proto_version: "4" replication_factor: "1" consistency: "LocalQuorum" default_table: "test" default_keyspace: "test" tls: "https://www.amazontrust.com/repository/AmazonRootCA1.pem" ``` ## Usage ### Get Request Get request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------|:----------------------| | key | yes | keyspaces key string | any string | | method | yes | get | "get" | | consistency | yes | set consistency | "",strong","eventual" | | table | yes | table name | "table | | keyspace | yes | key space name | "keyspace" | Example: ```json { "metadata": { "key": "your-keyspaces-key", "method": "get", "consistency": "", "table": "table", "keyspace": "keyspace" }, "data": null } ``` ### Set Request Set request metadata setting: | Metadata Key | Required | Description | Possible values | |:---------------|:---------|:--------------------------|:-----------------| | key | yes | keyspaces key string | any string | | method | yes | method name set | "set" | | consistency | yes | set consistency | "",strong","eventual" | | table | yes | table name | "table | | keyspace | yes | key space name | "keyspace" | Set request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | data to set for the keyspaces key | base64 bytes array | Example: ```json { "metadata": { "key": "your-keyspaces-key", "method": "set", "consistency": "", "table": "table", "keyspace": "keyspace" }, "data": "c29tZS1kYXRh" } ``` ### Delete Request Delete request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------|:----------------| | key | yes | keyspaces key string | any string | | method | yes | method name delete | "delete" | | table | yes | table name | "table | | keyspace | yes | key space name | "keyspace" | Example: ```json { "metadata": { "key": "your-keyspaces-key", "method": "set", "table": "table", "keyspace": "keyspace" }, "data": null } ``` ### Query Request Query request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | method name query | "query" | | consistency | yes | set consistency | "",strong","eventual" | Query request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:-------------|:-------------------| | data | yes | query string | base64 bytes array | Example: Query string: `SELECT value FROM test.test WHERE key = 'some-key` ```json { "metadata": { "method": "query", "consistency": "strong" }, "data": "U0VMRUNUIHZhbHVlIEZST00gdGVzdC50ZXN0IFdIRVJFIGtleSA9ICdzb21lLWtleQ==" } ``` ### Exec Request Exec request metadata setting: | Metadata Key | Required | Description | Possible values | |:----------------|:---------|:---------------------------------------|:-------------------| | method | yes | set type of request | "exec" | | consistency | yes | set consistency | "",strong","eventual" | Exec request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | exec string | base64 bytes array | Example: Exec string: ```sql INSERT INTO test.test (key, value) VALUES ('some-key',textAsBlob('some-data')) ``` ```json { "metadata": { "method": "exec", "consistency": "strong" }, "data": "<KEY>" } ``` <file_sep>package metrics import "sync" type Store struct { store sync.Map } func NewStore() *Store { return &Store{ store: sync.Map{}, } } func (s *Store) Add(report *Report) { val, ok := s.store.Load(report.Key) if ok { loaded := val.(*Report) loaded.ErrorsCount += report.ErrorsCount loaded.ResponseVolume += report.ResponseVolume loaded.ResponseCount += report.ResponseCount loaded.RequestVolume += report.RequestVolume loaded.RequestCount += report.RequestCount } else { s.store.Store(report.Key, report.Clone()) } } func (s *Store) Get(key string) *Report { val, ok := s.store.Load(key) if ok { return val.(*Report) } return nil } func (s *Store) List() []*Report { var list []*Report s.store.Range(func(key, value interface{}) bool { list = append(list, value.(*Report)) return true }) return list } <file_sep># Kubemq redshift target Connector (Service admin) Kubemq aws-redshift target connector allows services using kubemq server to access aws redshift service. ## Prerequisites The following required to run the aws-redshift service target connector: - kubemq cluster - aws account with redshift active service(Not rds, see rds/redshift) - kubemq-targets deployment ## Configuration redshift target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-redshift-service source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-redshift-connector-svc" auth_token: "" channel: "query.aws.redshift.service" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.redshift.service name: aws-redshift-service properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### Create Tags create a tag for a resource ,must be accessible to redshift cluster. Create Tags: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_tags" | | resource_arn | yes | aws resource ARN | "arn:aws:redshift:region:account_id:cluster:cluster_name" | | data | yes | key value of string string(tag-value) | "<KEY>" | Example: ```json { "metadata": { "method": "create_tags", "resource_arn": "arn:aws:redshift:region:account_id:cluster:cluster_name" }, "data": "<KEY>" } ``` ### Delete Tags delete tag from resource,must be accessible to redshift cluster. Delete Tags: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "delete_tags" | | resource_arn | yes | aws resource ARN | "arn:aws:redshift:region:account_id:cluster:cluster_name" | | data | yes | key slice of tags to remove(by keys) | "WyJ0ZXN0MS1rZXkiXQ==" | Example: ```json { "metadata": { "method": "delete_tags", "resource_arn": "arn:aws:redshift:region:account_id:cluster:cluster_name" }, "data": "WyJ0ZXN0MS1rZXkiXQ==" } ``` ### List Tags list all tags on the redshift cluster List Tags: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_tags" | | Example: ```json { "metadata": { "method": "list_tags" }, "data": null } ``` ### List Snapshots list all redshift snapshots. List Snapshots: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_snapshots" | | Example: ```json { "metadata": { "method": "list_snapshots" }, "data": null } ``` ### List Snapshots By Tag Keys list all redshift snapshots with the matching tag keys. List Snapshots By Tag Keys: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_snapshots_by_tags_keys" | | | data | yes | key slice of tags to search by(by keys) | "WyJ0ZXN0MS1rZXkiXQ==" | Example: ```json { "metadata": { "method": "list_snapshots_by_tags_keys" }, "data": "WyJ0ZXN0MS1rZXkiXQ==" } ``` ### List Snapshots By Tag Values list all redshift snapshots with the matching tag Values. List Snapshots By Tag Values: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:------------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_snapshots_by_tags_values" | | | data | yes | key slice of tags to search by(by values) | "WyJ0ZXN0MS1rZXkiXQ==" | Example: ```json { "metadata": { "method": "list_snapshots_by_tags_keys" }, "data": "WyJ0ZXN0MS1rZXkiXQ==" } ``` ### Describe Clusters Describe Clusters: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:------------------------------------------|:-------------------------------------------| | method | yes | type of method | "describe_cluster" | | | resource_name | yes | aws resource name | "my_cluster_name" | Example: ```json { "metadata": { "method": "list_snapshots_by_tags_keys", "resource_name": "my_cluster_name", }, "data": null } ``` ### List Clusters list clusters under redshift service List Clusters: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_clusters" | | Example: ```json { "metadata": { "method": "list_clusters" }, "data": null } ``` ### List Clusters By Tag Keys list clusters under redshift service by tag keys List Clusters By Tag Keys: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_clusters_by_tags_keys" | | | data | yes | key slice of tags to search by(by keys) | "WyJ0ZXN0MS1rZXkiXQ==" | Example: ```json { "metadata": { "method": "list_clusters_by_tags_keys" }, "data": "WyJ0ZXN0MS1rZXkiXQ==" } ``` ### List Clusters By Tag Values list clusters under redshift service by tag values List Clusters By Tag Values: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:------------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_clusters_by_tags_values" | | | data | yes | key slice of tags to search by(by values) | "WyJ0ZXN0MS1rZXkiXQ==" | Example: ```json { "metadata": { "method": "list_clusters_by_tags_values" }, "data": "WyJ0ZXN0MS1rZXkiXQ==" } ``` <file_sep>package rethinkdb import ( "context" "crypto/tls" "encoding/json" "errors" "fmt" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" rethink "gopkg.in/rethinkdb/rethinkdb-go.v6" ) type Client struct { log *logger.Logger opts options session *rethink.Session } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } opts, err := c.setUpConnectOpts(c.opts) if err != nil { return err } c.session, err = rethink.Connect(opts) if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.get(ctx, meta) case "update": return c.update(ctx, meta, req.Data) case "insert": return c.insert(ctx, meta, req.Data) case "delete": return c.delete(ctx, meta) } return nil, nil } func (c *Client) get(ctx context.Context, meta metadata) (*types.Response, error) { cursor, err := rethink.DB(meta.dbName).Table(meta.table).Get(meta.key).Run(c.session, rethink.RunOpts{Context: ctx}) if err != nil { return nil, err } defer cursor.Close() var resp []interface{} var item interface{} for cursor.Next(&item) { if item != nil { resp = append(resp, item) } } if len(resp) == 0 { return nil, fmt.Errorf("failed to find value for request on table %s", meta.table) } b, err := json.Marshal(resp) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) insert(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data") } var args map[string]interface{} err := json.Unmarshal(data, &args) if err != nil { return nil, err } _, err = rethink.DB(meta.dbName).Table(meta.table).Insert(args).Run(c.session, rethink.RunOpts{Context: ctx}) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("table", meta.table), nil } func (c *Client) update(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data") } var args map[string]interface{} err := json.Unmarshal(data, &args) if err != nil { return nil, err } _, err = rethink.DB(meta.dbName).Table(meta.table).Get(meta.key).Update(args).Run(c.session, rethink.RunOpts{Context: ctx}) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) delete(ctx context.Context, meta metadata) (*types.Response, error) { _, err := rethink.DB(meta.dbName).Table(meta.table).Get(meta.key).Delete().Run(c.session, rethink.RunOpts{Context: ctx}) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) setUpConnectOpts(opts options) (rethink.ConnectOpts, error) { co := rethink.ConnectOpts{ Address: opts.host, } if opts.username != "" { co.Username = opts.username } if opts.password != "" { co.Password = <PASSWORD> } if opts.authKey != "" { co.AuthKey = opts.authKey } if opts.timeout != 0 { co.Timeout = opts.timeout } if opts.keepAlivePeriod != 0 { co.KeepAlivePeriod = opts.keepAlivePeriod } if opts.ssl { cert, err := tls.X509KeyPair([]byte(opts.certFile), []byte(opts.certKey)) if err != nil { return co, fmt.Errorf("rethinkdb: error parsing session certificate: %v", err) } co.TLSConfig.Certificates = append(co.TLSConfig.Certificates, cert) } if opts.handShakeVersion != 0 { co.HandshakeVersion = rethink.HandshakeVersion(opts.handShakeVersion) } if opts.numberOfRetries != 0 { co.NumRetries = opts.numberOfRetries } if opts.initialCap != 0 { co.InitialCap = opts.initialCap } if opts.maxOpen != 0 { co.MaxOpen = opts.maxOpen } return co, nil } func (c *Client) Stop() error { return c.session.Close(rethink.CloseOpts{}) } <file_sep>package sqs import ( "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/sqs" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { delay int tags map[string]*sqs.MessageAttributeValue queueURL string } func parseMetadata(meta types.Metadata, opts options) (metadata, error) { m := metadata{} m.tags = make(map[string]*sqs.MessageAttributeValue) var err error m.queueURL, err = meta.MustParseString("queue") if err != nil { return metadata{}, fmt.Errorf("error parsing queue, %w", err) } m.delay = meta.ParseInt("delay", opts.defaultDelay) tags, err := meta.MustParseJsonMap("tags") if err != nil { return metadata{}, fmt.Errorf("error parsing tags, %w", err) } for k, v := range tags { attributeValue := &sqs.MessageAttributeValue{ DataType: aws.String("String"), StringValue: aws.String(v), } m.tags[k] = attributeValue } return m, nil } <file_sep>package spanner import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.spanner"). SetDescription("GCP Spanner Target"). SetName("Spanner"). SetProvider("GCP"). SetCategory("Store"). SetTags("db", "sql", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("db"). SetTitle("Database name"). SetDescription("Set GCP Spanner DB"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Spanner execution method"). SetOptions([]string{"query", "read", "update_database_ddl", "insert", "update", "insert_or_update"}). SetDefault("query"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("query"). SetKind("string"). SetDescription("Set Spanner query request"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("table_name"). SetKind("string"). SetDescription("Set Spanner table_name"). SetDefault(""). SetMust(false), ) } <file_sep># Kubemq Mongodb Target Connector Kubemq mongodb target connector allows services using kubemq server to access mongodb database services. ## Prerequisites The following are required to run the mongodb target connector: - kubemq cluster - mongodb server - kubemq-targets deployment ## Configuration Mongodb target connector configuration properties: | Properties Key | Required | Description | Example | |:--------------------------|:---------|:-------------------------------------|:--------------------------| | host | yes | mongodb host address | "localhost:27017" | | username | no | mongodb username | "admin" | | password | no | mongodb password | "<PASSWORD>" | | database | no | set database name | "admin" | | collection | no | set database collection | "test" | | params | no | set connection additional parameters | "" | | write_concurrency | no | set write concurrency | "","majority","1","2" | | read_concurrency | no | set read concurrency | "","local" | | | | | "","local" | | | | | "majority","available" | | | | | "linearizable","snapshot" | | operation_timeout_seconds | no | set operation timeout in seconds | "30" | Example: ```yaml bindings: - name: kubemq-query-mongodb source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-mongodb-connector" auth_token: "" channel: "query.mongodb" group: "" concurrency: "1" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: stores.mongodb name: target-mongodb properties: host: "localhost:27017" username: "admin" password: "<PASSWORD>" database: "admin" collection: "test" write_concurrency: "majority" read_concurrency: "" params: "" operation_timeout_seconds: "2" ``` ## Usage ### Find Request Find document by filter request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | find document by set filter | "find" | | filter | yes | filter json object | '{"_id":"some-id"}' | Example: ```json { "metadata": { "method": "find", "filter": "{\"_id\":\"e7141dc8-d793-4f3b-8290-bc9d9a3f9fda\"}" }, "data": null } ``` ### Find Many Request Find many documents by filter request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | find document by set filter | "find_many" | | filter | yes | filter json object | '{"color":"white"}' | Example: ```json { "metadata": { "method": "find_many", "filter": "{\"color\":\"white\"}" }, "data": null } ``` ### Insert Request Insert single document request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | insert document | "insert" | insert request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | json document to insert | base64 bytes array | Example: ```json { "metadata": { "method": "insert" }, "data":"<KEY>ifQ==" } ``` ### Insert Many Request Insert multiple documents request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | insert document | "insert_many" | Insert multiple request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | array of json documents to insert | base64 bytes array | Example: ```json { "metadata": { "method": "insert_many" }, "data":"<KEY>" } ``` ### Update Request Update single document request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | update document | "update" | | filter | yes | filter json object | '{"_id":"some-id"}' | | set_upsert | no | perform insert if not found | true | Update request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | updated json document | base64 bytes array | Example: ```json { "metadata": { "method": "update", "filter": "{\"_id\":\"e7141dc8-d793-4f3b-8290-bc9d9a3f9fda\"}", "set_upsert": "true" }, "data":"<KEY> } ``` ### Update Many Request Update many documents request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | update document | "update_many" | | filter | yes | filter json object | '{"color":"blue"}' | | set_upsert | no | perform insert if not found | true | Update many request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | updated json document | base64 bytes array | Example: ```json { "metadata": { "method": "update_many", "filter": "{\"color\":\"blue\"}", "set_upsert": "true" }, "data":"<KEY> } ``` ### Delete Request Delete document by filter request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | delete document by set filter | "delete" | | filter | yes | filter json object | '{"_id":"some-id"}' | Example: ```json { "metadata": { "method": "delete", "filter": "{\"_id\":\"e7141dc8-d793-4f3b-8290-bc9d9a3f9fda\"}" }, "data": null } ``` ### Delete Many Request Delete many documents by filter request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | delete many documents by set filter | "delete_many" | | filter | yes | filter json object | '{"color":"white"}' | Example: ```json { "metadata": { "method": "delete_many", "filter": "{\"color\":\"white\"}" }, "data": null } ``` ### Aggregate Request Aggregate documents by pipeline request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | aggregate documents by set pipeline | "aggregate" | Aggregate pipeline request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | pipeline json data | base64 bytes array | Example: ```json { "metadata": { "method": "aggregate" }, "data": "<KEY> } ``` ### Distinct Request Distinct documents by filter and field name request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | get distinct documents by set filter | "distinct" | | filter | yes | filter json object | '{"_id":"some-id"}' | | field_name | yes | distinct field name | "id" | Example: ```json { "metadata": { "method": "distinct", "filter": "{\"_id\":\"e7141dc8-d793-4f3b-8290-bc9d9a3f9fda\"}", "field_name": "id" }, "data": null } ``` ### Get By Key Request Get request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | key | yes | mongodb key string | any string | | method | yes | get document by key | "get_by_key" | Example: ```json { "metadata": { "key": "key", "method": "get_by_key" }, "data": null } ``` ### Set By Key Request Set request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | key | yes | mongodb key string | any string | | method | yes | set document by key | "set_by_key" | Set request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | data to set for the mongodb key | base64 bytes array | Example: ```json { "metadata": { "key": "key", "method": "set_by_key" }, "data": "c<KEY>" } ``` ### Delete By Key Request Delete request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | key | yes | mongodb key string | any string | | method | yes | delete document by key | "delete_by_key" | Example: ```json { "metadata": { "key": "key", "method": "delete_by_key" }, "data": null } ``` <file_sep>package postgres import ( "database/sql" "fmt" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "query": "query", "exec": "exec", "transaction": "transaction", } var isolationLevelsMap = map[string]string{ "read_uncommitted": "ReadUncommitted", "read_committed": "ReadCommitted", "repeatable_read": "RepeatableRead", "serializable": "Serializable", "": "Default", } type metadata struct { method string isolationLevel sql.IsolationLevel } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } isolationLevel, err := meta.ParseStringMap("isolation_level", isolationLevelsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing isolation_level, %w", err) } m.isolationLevel = convertToSqlIsolationLevel(isolationLevel) return m, nil } func convertToSqlIsolationLevel(value string) sql.IsolationLevel { switch value { case "ReadUncommitted": return sql.LevelReadCommitted case "ReadCommitted": return sql.LevelReadCommitted case "RepeatableRead": return sql.LevelRepeatableRead case "Serializable": return sql.LevelSerializable default: return sql.LevelDefault } } <file_sep>package s3 import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { method string waitForCompletion bool bucketName string copySource string itemName string } var methodsMap = map[string]string{ "list_buckets": "list_buckets", "list_bucket_items": "list_bucket_items", "create_bucket": "create_bucket", "delete_bucket": "delete_bucket", "delete_item_from_bucket": "delete_item_from_bucket", "delete_all_items_from_bucket": "delete_all_items_from_bucket", "upload_item": "upload_item", "copy_item": "copy_item", "get_item": "get_item", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method != "list_buckets" { m.bucketName, err = meta.MustParseString("bucket_name") if err != nil { return metadata{}, fmt.Errorf("error parsing bucket_name, %w", err) } m.waitForCompletion = meta.ParseBool("wait_for_completion", false) if m.method == "upload_item" || m.method == "copy" || m.method == "delete_item_from_bucket" || m.method == "copy_item" || m.method == "get_item" { m.itemName, err = meta.MustParseString("item_name") if err != nil { return metadata{}, fmt.Errorf("item_name is required when using %s , error parsing item_name, %w", m.method, err) } if m.method == "copy_item" { m.copySource, err = meta.MustParseString("copy_source") if err != nil { return metadata{}, fmt.Errorf("error parsing copy_source, %w", err) } } } } return m, nil } <file_sep>package kinesis import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string shardCount string streamName string partitionKey string shardPosition string shardID string limit string streamARN string shardIterator string consumerName string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/shardCount.txt") if err != nil { return nil, err } t.shardCount = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/streamName.txt") if err != nil { return nil, err } t.streamName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/partitionKey.txt") if err != nil { return nil, err } t.partitionKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/shardPosition.txt") if err != nil { return nil, err } t.shardPosition = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/shardID.txt") if err != nil { return nil, err } t.shardID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/limit.txt") if err != nil { return nil, err } t.limit = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/streamARN.txt") if err != nil { return nil, err } t.streamARN = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/kinesis/shardIterator.txt") if err != nil { return nil, err } t.shardIterator = string(dat) t.consumerName = "my_consumer" return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: false, }, { name: "invalid init - missing aws_key", cfg: config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: true, }, { name: "invalid init - missing region", cfg: config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, }, }, wantErr: true, }, { name: "invalid init - missing aws_secret_key", cfg: config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "region": dat.region, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_ListStreams(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list_streams", request: types.NewRequest(). SetMetadataKeyValue("method", "list_streams"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_ListStreamConsumers(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list_streams", request: types.NewRequest(). SetMetadataKeyValue("method", "list_stream_consumers"). SetMetadataKeyValue("stream_arn", dat.streamARN), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_CreateStream(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create_stream", request: types.NewRequest(). SetMetadataKeyValue("method", "create_stream"). SetMetadataKeyValue("stream_name", dat.streamName). SetMetadataKeyValue("shard_count", dat.shardCount), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_CreateStreamConsumer(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create_stream_consumer", request: types.NewRequest(). SetMetadataKeyValue("method", "create_stream_consumer"). SetMetadataKeyValue("stream_arn", dat.streamARN). SetMetadataKeyValue("consumer_name", dat.consumerName), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_ListShards(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list_shards", request: types.NewRequest(). SetMetadataKeyValue("method", "list_shards"). SetMetadataKeyValue("stream_name", dat.streamName), wantErr: false, }, { name: "invalid list_shards - missing stream name", request: types.NewRequest(). SetMetadataKeyValue("method", "list_shards"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_GetShardIterator(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid get_shard_iterator", request: types.NewRequest(). SetMetadataKeyValue("method", "get_shard_iterator"). SetMetadataKeyValue("stream_name", dat.streamName). SetMetadataKeyValue("shard_iterator_type", "LATEST"). SetMetadataKeyValue("shard_id", dat.shardID), wantErr: false, }, { name: "invalid get_shard_iterator - missing stream", request: types.NewRequest(). SetMetadataKeyValue("method", "get_shard_iterator"). SetMetadataKeyValue("shard_iterator_type", "LATEST"). SetMetadataKeyValue("shard_id", dat.shardID), wantErr: true, }, { name: "invalid get_shard_iterator - missing type", request: types.NewRequest(). SetMetadataKeyValue("method", "get_shard_iterator"). SetMetadataKeyValue("stream_name", dat.streamName). SetMetadataKeyValue("shard_id", dat.shardID), wantErr: true, }, { name: "invalid get_shard_iterator - missing shard_id", request: types.NewRequest(). SetMetadataKeyValue("method", "get_shard_iterator"). SetMetadataKeyValue("stream_name", dat.streamName). SetMetadataKeyValue("shard_iterator_type", "LATEST"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) require.NotNil(t, got.Metadata["shard_iterator"]) t.Logf("got iterator: %s", got.Metadata["shard_iterator"]) }) } } func TestClient_PutRecord(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() data := `{"my_result":"ok"}` err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid put_record", request: types.NewRequest(). SetMetadataKeyValue("method", "put_record"). SetMetadataKeyValue("partition_key", dat.partitionKey). SetMetadataKeyValue("stream_name", dat.streamName). SetData([]byte(data)), wantErr: false, }, { name: "invalid put_record - missing partition_key", request: types.NewRequest(). SetMetadataKeyValue("method", "put_record"). SetMetadataKeyValue("stream_name", dat.streamName). SetData([]byte(data)), wantErr: true, }, { name: "invalid put_record - missing stream_name ", request: types.NewRequest(). SetMetadataKeyValue("method", "put_record"). SetMetadataKeyValue("partition_key", dat.partitionKey). SetData([]byte(data)), wantErr: true, }, { name: "invalid put_record - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "put_record"). SetMetadataKeyValue("partition_key", dat.partitionKey). SetMetadataKeyValue("stream_name", dat.streamName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_PutRecords(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() rm := make(map[string][]byte) data := `{"my_result":"ok"}` data2 := `{"my_result2":"ok!"}` rm["1"] = []byte(data) rm["2"] = []byte(data2) b, err := json.Marshal(rm) require.NoError(t, err) err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid putRecords", request: types.NewRequest(). SetMetadataKeyValue("method", "put_record"). SetMetadataKeyValue("partition_key", dat.partitionKey). SetMetadataKeyValue("stream_name", dat.streamName). SetData(b), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_GetRecords(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-kinesis", Kind: "aws.kinesis", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid get records", request: types.NewRequest(). SetMetadataKeyValue("method", "get_records"). SetMetadataKeyValue("stream_name", dat.streamName). SetMetadataKeyValue("shard_iterator_id", dat.shardIterator), wantErr: false, }, { name: "invalid get records - missing stream name", request: types.NewRequest(). SetMetadataKeyValue("method", "get_records"). SetMetadataKeyValue("shard_iterator_id", dat.shardIterator), wantErr: true, }, { name: "invalid get records - missing iterator", request: types.NewRequest(). SetMetadataKeyValue("method", "get_records"). SetMetadataKeyValue("stream_name", dat.streamName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package minio import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "make_bucket": "make_bucket", "list_buckets": "list_buckets", "bucket_exists": "bucket_exists", "remove_bucket": "remove_bucket", "list_objects": "list_objects", "put": "put", "get": "get", "remove": "remove", } type metadata struct { method string param1 string param2 string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.param1 = meta.ParseString("param1", "") m.param2 = meta.ParseString("param2", "") return m, nil } <file_sep># Kubemq CloudWatch Logs Target Connector Kubemq cloudwatch-logs target connector allows services using kubemq server to access aws cloudwatch-logs service. ## Prerequisites The following required to run the aws-cloudwatch-logs target connector: - kubemq cluster - aws account with cloudwatch-logs active service - some action will need cloudwatch-logs permission (IAM User) - kubemq-targets deployment ## Configuration cloudwatch-logs target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-cloudwatch-logs source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-cloudwatch-logs" auth_token: "" channel: "query.aws.cloudwatch.logs" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.cloudwatch.logs name: aws-cloudwatch-logs properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### Create log Stream create a new log stream Create log Stream: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_log_event_stream" | | log_stream_name | yes | aws log stream name | "string" | | log_group_name | yes | aws log group name | "string" | Example: ```json { "metadata": { "method": "create_log_event_stream", "log_stream_name": "my_stream_name", "log_group_name": "my_group_name" }, "data": null } ``` ### Describe log Stream describe a selected log stream by group_name Describe log Stream: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "describe_log_event_stream" | | log_group_name | yes | aws log group name | "string" | Example: ```json { "metadata": { "method": "describe_log_event_stream", "log_group_name": "my_group_name" }, "data": null } ``` ### Delete log Stream delete log stream Delete log Stream: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "delete_log_event_stream" | | log_stream_name | yes | aws log stream name | "string" | | log_group_name | yes | aws log group name | "string" | Example: ```json { "metadata": { "method": "delete_log_event_stream", "log_stream_name": "my_stream_name", "log_group_name": "my_group_name" }, "data": null } ``` ### Get log Event get log event Get log Stream: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:-----------------------------------------------|:-------------------------------------------| | method | yes | type of method | "get_log_event" | | log_stream_name | yes | aws log stream name | "string" | | log_group_name | yes | aws log group name | "string" | Example: ```json { "metadata": { "method": "get_log_event", "log_stream_name": "my_stream_name", "log_group_name": "my_group_name" }, "data": null } ``` ### Create Log Event Group create a new log event group Create Log Event Group: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:-----------------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_log_group" | | log_group_name | yes | aws log group name | "string" | | data | no | aws tags | key value pair string string | Example: ```json { "metadata": { "method": "create_log_group", "log_group_name": "my_group_name" }, "data": null } ``` ### Put Log put a log in log stream Put Log Event: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:---------------------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "put_log_event" | | log_stream_name | yes | aws log stream name | "string" | | log_group_name | yes | aws log group name | "string" | | sequence_token | yes | aws stream sequence token | "string" | | data | yes | key value pair of int-string int-time - string-Message | "string" | Example: ```json { "metadata": { "method": "put_log_event", "log_group_name": "my_group_name", "sequence_token": "my_token_from_aws" }, "data": "eyIxNTk3MjM1NTU4NTEyIjoibXkgZmlyc3QgbWV<KEY> } ``` ### Describe Log Event Group describe log event group Describe Log Event Group: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:-----------------------------------------------|:-------------------------------------------| | method | yes | type of method | "describe_log_group" | | log_group_prefix | yes | aws log group prefix | "string" | Example: ```json { "metadata": { "method": "describe_log_group", "log_group_name": "my_group_name" }, "data": null } ``` ### Delete Log Event Group delete log event group Delete Log Event Group: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:-----------------------------------------------|:-------------------------------------------| | method | yes | type of method | "delete_log_group" | | log_group_name | yes | aws log group name | "string" | Example: ```json { "metadata": { "method": "delete_log_group", "log_group_name": "my_group_name" }, "data": null } ``` <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) type testStructure struct { region string json string domain string index string endpoint string service string id string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) dat, err = ioutil.ReadFile("./credentials/aws/elasticsearch/signer/json.txt") if err != nil { return nil, err } t.json = string(dat) dat, err = ioutil.ReadFile("./credentials/aws/elasticsearch/signer/domain.txt") if err != nil { return nil, err } t.domain = string(dat) dat, err = ioutil.ReadFile("./credentials/aws/elasticsearch/signer/index.txt") if err != nil { return nil, err } t.index = string(dat) dat, err = ioutil.ReadFile("./credentials/aws/elasticsearch/signer/endpoint.txt") if err != nil { return nil, err } t.endpoint = string(dat) dat, err = ioutil.ReadFile("./credentials/aws/elasticsearch/signer/service.txt") if err != nil { return nil, err } t.service = string(dat) dat, err = ioutil.ReadFile("./credentials/aws/elasticsearch/signer/id.txt") if err != nil { return nil, err } t.id = string(dat) return t, nil } func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } dat, err := getTestStructure() if err != nil { log.Fatal(err) } // POST request := types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id) queryResponse, err := client.SetQuery(request.ToQuery()). SetChannel("query.aws.elasticsearch"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } response, err := types.ParseResponse(queryResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("executed, response: %s", response.Data)) } <file_sep># Kubemq DynamoDb Target Connector Kubemq dynamodb target connector allows services using kubemq server to access aws dynamodb service. ## Prerequisites The following required to run the aws-dynamodb target connector: - kubemq cluster - aws account with dynamodb active service - kubemq-targets deployment ## Configuration dynamodb target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-dynamodb source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-dynamodb" auth_token: "" channel: "query.aws.dynamodb" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.dynamodb name: aws-dynamodb properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### List Tables list all tables under dynamodb. List Tables: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_tables" | Example: ```json { "metadata": { "method": "list_tables" }, "data": null } ``` ### Create Table create a new table under dynamodb. Create Table: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_table" | | data | yes | dynamodb.CreateTableInput as json | "string" | Example: ```json { "metadata": { "method": "create_table" }, "data": "<KEY> } ``` ### Delete Table delete a table under dynamodb. Delete Table: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "delete_table" | | table_name | yes | table name to delete | "string" | Example: ```json { "metadata": { "method": "delete_table", "table_name": "my_table_name" }, "data": null } ``` ### Insert Item insert item to table under dynamodb. Insert Item : | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "insert_item" | | table_name | yes | table name to delete | "string" | | data | yes | dynamodb.AttributeValue as json | "string" | Example: ```json { "metadata": { "method": "insert_item", "table_name": "my_table_name" }, "data": "<KEY> } ``` ### Get Item get an item from a table under dynamodb. Get Item : | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "get_item" | | data | yes | dynamodb.GetItemInput as json | "string" | Example: ```json { "metadata": { "method": "get_item" }, "data": "<KEY> } ``` ### Update Item update an item from a table under dynamodb. Update Item : | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "update_item" | | data | yes | dynamodb.UpdateItemInput as json | "string" | Example: ```json { "metadata": { "method": "update_item" }, "data": "<KEY> } ``` ### Delete Item delete an item from a table under dynamodb. Delete Item : | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "delete_item" | | data | yes | dynamodb.DeleteItemInput as json | "string" | Example: ```json { "metadata": { "method": "delete_item" }, "data": "<KEY>" } ``` <file_sep>package storage import ( "github.com/kubemq-io/kubemq-targets/config" ) type options struct { credentials string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.credentials, err = cfg.Properties.MustParseString("credentials") if err != nil { return options{}, err } return o, nil } <file_sep>package redis import ( "fmt" "math" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "get": "get", "set": "set", "delete": "delete", } var concurrencyMap = map[string]string{ "first-write": "first-write", "last-write": "last-write", "": "", } var consistencyMap = map[string]string{ "strong": "strong", "eventual": "eventual", "": "", } type metadata struct { method string key string etag int concurrency string consistency string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.key, err = meta.MustParseString("key") if err != nil { return metadata{}, fmt.Errorf("error on parsing key value, %w", err) } m.etag, err = meta.ParseIntWithRange("etag", 0, 0, math.MaxInt32) if err != nil { return metadata{}, fmt.Errorf("error on parsing etag value, %w", err) } m.concurrency, err = meta.ParseStringMap("concurrency", concurrencyMap) if err != nil { return metadata{}, fmt.Errorf("error on parsing concurrency, %w", err) } m.consistency, err = meta.ParseStringMap("consistency", consistencyMap) if err != nil { return metadata{}, fmt.Errorf("error on parsing consistency, %w", err) } return m, nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "log" "time" aero "github.com/aerospike/aerospike-client-go" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/targets/stores/aerospike" "github.com/kubemq-io/kubemq-targets/types" ) func main() { k := aerospike.PutRequest{ UserKey: "user_key1", KeyName: "some-key", Namespace: "test", BinMap: // define some bins with data aero.BinMap{ "bin1": 42, "bin2": "An elephant is a mouse with an operating system", "bin3": []interface{}{"Go", 2009}, }, } req, err := json.Marshal(k) if err != nil { log.Fatal(err) } client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } randomKey := uuid.New().String() // set request setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set"). SetData(req) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.aerospike"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("set request for key: %s executed, response: %s", randomKey, setResponse.Metadata.String())) // get request getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("namespace", "test"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("user_key", "user_key1") queryGetResponse, err := client.SetQuery(getRequest.ToQuery()). SetChannel("query.aerospike"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(queryGetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get request for key: %s executed, response: %s, data: %s", randomKey, getResponse.Metadata.String(), string(getResponse.Data))) } <file_sep># Kubemq pubsub target Connector Kubemq gcp-pubsub target connector allows services using kubemq server to access google pubsub server. ## Prerequisites The following required to run the gcp-pubsub target connector: - kubemq cluster - gcp-pubsub set up - kubemq-targets deployment ## Configuration pubsub target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:---------------------------| | project_id | yes | gcp firestore project_id | "<googleurl>/myproject" | | credentials | yes | gcp credentials files | "<google json credentials" | | retries | no | number of sending retires | retries number | Example: ```yaml bindings: - name: kubemq-query-gcp-pubsub source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-pubsub-connector" auth_token: "" channel: "query.gcp.pubsub" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.pubsub name: gcp-pubsub properties: project_id: "projectID" retries: "0" credentials: 'json' ``` ## Usage ### Send Message send a message to pub sub Send Message metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:----------------------| | topicID | yes | the name of the topicID to sent to | valid topicID | | tags | no | type of method | key value string | Example with tags: ```json { "metadata": { "topic_id": "my_topic", "tags": "{\"tag-1\":\"test\",\"tag-2\":\"test2\"}" }, "data": "c3RyaW5n" } ``` Example without tags: ```json { "metadata": { "topic_id": "my_topic" }, "data": "c3RyaW5n" } ``` <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } request := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("url", "https://httpbin.org/get") queryResponse, err := client.SetQuery(request.ToQuery()). SetChannel("query.http"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } response, err := types.ParseResponse(queryResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get request response headers:\n%s", response.Metadata.String())) } <file_sep>package mongodb import ( "context" "fmt" "strconv" jsoniter "github.com/json-iterator/go" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" monogOptions "go.mongodb.org/mongo-driver/mongo/options" "go.mongodb.org/mongo-driver/mongo/readconcern" "go.mongodb.org/mongo-driver/mongo/writeconcern" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary const ( id = "_id" value = "value" connectionURIFormat = "mongodb://%s:%s@%s/%s%s" ) type Item struct { Key string `bson:"_id"` Value string `bson:"value"` } type Client struct { log *logger.Logger opts options client *mongo.Client collection *mongo.Collection } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.client, err = c.getMongoDBClient(ctx) if err != nil { return fmt.Errorf("error in creating mongodb client: %s", err) } wc, err := c.getWriteConcernObject(c.opts.writeConcurrency) if err != nil { _ = c.client.Disconnect(context.Background()) return fmt.Errorf("error in getting write concern object: %s", err) } rc, err := c.getReadConcernObject(c.opts.readConcurrency) if err != nil { _ = c.client.Disconnect(context.Background()) return fmt.Errorf("error in getting read concern object: %s", err) } opts := monogOptions.Collection().SetWriteConcern(wc).SetReadConcern(rc) collection := c.client.Database(c.opts.database).Collection(c.opts.collection, opts) c.collection = collection return nil } func (c *Client) getWriteConcernObject(cn string) (*writeconcern.WriteConcern, error) { var wc *writeconcern.WriteConcern if cn != "" { if cn == "majority" { wc = writeconcern.New(writeconcern.WMajority(), writeconcern.J(true), writeconcern.WTimeout(c.opts.operationTimeout)) } else { w, err := strconv.Atoi(cn) wc = writeconcern.New(writeconcern.W(w), writeconcern.J(true), writeconcern.WTimeout(c.opts.operationTimeout)) return wc, err } } else { wc = writeconcern.New(writeconcern.W(1), writeconcern.J(true), writeconcern.WTimeout(c.opts.operationTimeout)) } return wc, nil } func (c *Client) getReadConcernObject(cn string) (*readconcern.ReadConcern, error) { switch cn { case "local": return readconcern.Local(), nil case "majority": return readconcern.Majority(), nil case "available": return readconcern.Available(), nil case "linearizable": return readconcern.Linearizable(), nil case "snapshot": return readconcern.Snapshot(), nil case "": return readconcern.Local(), nil } return nil, fmt.Errorf("readConcern %s not found", cn) } func (c *Client) getMongoDBClient(ctx context.Context) (*mongo.Client, error) { var uri string if c.opts.username != "" && c.opts.password != "" { uri = fmt.Sprintf(connectionURIFormat, c.opts.username, c.opts.password, c.opts.host, c.opts.database, c.opts.params) } clientOptions := monogOptions.Client().ApplyURI(uri) client, err := mongo.Connect(ctx, clientOptions) if err != nil { return nil, err } err = client.Ping(ctx, nil) if err != nil { return nil, err } return client, nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get_by_key": return c.Get(ctx, meta) case "set_by_key": return c.Set(ctx, meta, req.Data) case "delete_by_key": return c.Delete(ctx, meta) case "find": return c.FindOne(ctx, meta) case "find_many": return c.Find(ctx, meta) case "insert": return c.Insert(ctx, req.Data) case "insert_many": return c.InsertMany(ctx, req.Data) case "update": return c.UpdateOne(ctx, meta, req.Data) case "update_many": return c.UpdateMany(ctx, meta, req.Data) case "delete": return c.DeleteOne(ctx, meta) case "delete_many": return c.DeleteMany(ctx, meta) case "aggregate": return c.Aggregate(ctx, req.Data) case "distinct": return c.Distinct(ctx, meta) } return nil, nil } func (c *Client) FindOne(ctx context.Context, meta metadata) (*types.Response, error) { if len(meta.filter) == 0 { return nil, fmt.Errorf("find one document filter is invalid") } result := map[string]interface{}{} ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() err := c.collection.FindOne(ctx, meta.filter).Decode(&result) if err != nil { return nil, fmt.Errorf("find one error, %s", err.Error()) } data, err := json.Marshal(result) if err != nil { return nil, fmt.Errorf("find one json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Find(ctx context.Context, meta metadata) (*types.Response, error) { if len(meta.filter) == 0 { return nil, fmt.Errorf("find documents filter is invalid") } results := []map[string]interface{}{} ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() cursor, err := c.collection.Find(ctx, meta.filter) if err != nil { return nil, fmt.Errorf("find error, %s", err.Error()) } err = cursor.All(ctx, &results) if err != nil { return nil, fmt.Errorf("find results parsing error, %s", err.Error()) } data, err := json.Marshal(results) if err != nil { return nil, fmt.Errorf("find json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Insert(ctx context.Context, reqData []byte) (*types.Response, error) { var doc interface{} err := json.Unmarshal(reqData, &doc) if err != nil { return nil, fmt.Errorf("insert document json parsing error, %s", err.Error()) } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() result, err := c.collection.InsertOne(ctx, doc) if err != nil { return nil, fmt.Errorf("insert error, %s", err.Error()) } data, err := json.Marshal(result.InsertedID) if err != nil { return nil, fmt.Errorf("insert result json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) InsertMany(ctx context.Context, reqData []byte) (*types.Response, error) { var docs []interface{} err := json.Unmarshal(reqData, &docs) if err != nil { return nil, fmt.Errorf("insert many documents json parsing error, %s", err.Error()) } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() results, err := c.collection.InsertMany(ctx, docs) if err != nil { return nil, fmt.Errorf("insert many error, %s", err.Error()) } data, err := json.Marshal(results.InsertedIDs) if err != nil { return nil, fmt.Errorf("insert many results json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) UpdateOne(ctx context.Context, meta metadata, reqData []byte) (*types.Response, error) { var doc interface{} err := json.Unmarshal(reqData, &doc) if err != nil { return nil, fmt.Errorf("update one document json parsing error, %s", err.Error()) } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() update := bson.M{"$set": &doc} result, err := c.collection.UpdateOne(ctx, meta.filter, update, monogOptions.Update().SetUpsert(meta.setUpsert)) if err != nil { return nil, fmt.Errorf("update one document error, %s", err.Error()) } data, err := json.Marshal(result.UpsertedID) if err != nil { return nil, fmt.Errorf("update one document result json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) UpdateMany(ctx context.Context, meta metadata, reqData []byte) (*types.Response, error) { var doc interface{} err := json.Unmarshal(reqData, &doc) if err != nil { return nil, fmt.Errorf("update many document json parsing error, %s", err.Error()) } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() update := bson.M{"$set": &doc} result, err := c.collection.UpdateMany(ctx, meta.filter, update, monogOptions.Update().SetUpsert(meta.setUpsert)) if err != nil { return nil, fmt.Errorf("update many documents error, %s", err.Error()) } data, err := json.Marshal(result.UpsertedID) if err != nil { return nil, fmt.Errorf("update many documents result json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) DeleteOne(ctx context.Context, meta metadata) (*types.Response, error) { if len(meta.filter) == 0 { return nil, fmt.Errorf("delete one document filter is invalid") } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() result, err := c.collection.DeleteOne(ctx, meta.filter) if err != nil { return nil, fmt.Errorf("delete one document error, %s", err.Error()) } return types.NewResponse(). SetMetadataKeyValue("deleted_count", fmt.Sprintf("%d", result.DeletedCount)). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) DeleteMany(ctx context.Context, meta metadata) (*types.Response, error) { if len(meta.filter) == 0 { return nil, fmt.Errorf("delete many documents filter is invalid") } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() result, err := c.collection.DeleteMany(ctx, meta.filter) if err != nil { return nil, fmt.Errorf("delete many documents error, %s", err.Error()) } return types.NewResponse(). SetMetadataKeyValue("deleted_count", fmt.Sprintf("%d", result.DeletedCount)). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Aggregate(ctx context.Context, reqData []byte) (*types.Response, error) { var pipeline interface{} err := json.Unmarshal(reqData, &pipeline) if err != nil { return nil, fmt.Errorf("aggregate pipeline json parsing error, %s", err.Error()) } results := []map[string]interface{}{} ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() cursor, err := c.collection.Aggregate(ctx, pipeline) if err != nil { return nil, fmt.Errorf("aggregate error, %s", err.Error()) } err = cursor.All(ctx, &results) if err != nil { return nil, fmt.Errorf("aggregate results parsing error, %s", err.Error()) } data, err := json.Marshal(results) if err != nil { return nil, fmt.Errorf("aggregate json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Distinct(ctx context.Context, meta metadata) (*types.Response, error) { if meta.fieldName == "" { return nil, fmt.Errorf("distinct field name missing") } if len(meta.filter) == 0 { return nil, fmt.Errorf("distinct filter is invalid") } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() results, err := c.collection.Distinct(ctx, meta.fieldName, meta.filter) if err != nil { return nil, fmt.Errorf("distinct error, %s", err.Error()) } data, err := json.Marshal(results) if err != nil { return nil, fmt.Errorf("distinct json parsing error, %s", err.Error()) } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Get(ctx context.Context, meta metadata) (*types.Response, error) { if meta.key == "" { return nil, fmt.Errorf("get by key error, invalid key") } var result Item ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() filter := bson.M{id: meta.key} err := c.collection.FindOne(ctx, filter).Decode(&result) if err != nil { return nil, fmt.Errorf("no data found for this key") } return types.NewResponse(). SetData([]byte(result.Value)). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) Set(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if meta.key == "" { return nil, fmt.Errorf("set by key error, invalid key") } if data == nil { return nil, fmt.Errorf("set by key error, invalid document") } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() filter := bson.M{id: meta.key} update := bson.M{"$set": bson.M{id: meta.key, value: string(data)}} _, err := c.collection.UpdateOne(ctx, filter, update, monogOptions.Update().SetUpsert(true)) if err != nil { return nil, fmt.Errorf("failed to set key %s: %s", meta.key, err) } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Delete(ctx context.Context, meta metadata) (*types.Response, error) { if meta.key == "" { return nil, fmt.Errorf("delete by key error, invalid key") } ctx, cancel := context.WithTimeout(ctx, c.opts.operationTimeout) defer cancel() filter := bson.M{id: meta.key} _, err := c.collection.DeleteOne(ctx, filter) if err != nil { return nil, fmt.Errorf("failed to delete key %s: %s", meta.key, err) } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return c.client.Disconnect(context.Background()) } <file_sep>package query import ( "context" "fmt" "testing" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/middleware" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/targets/null" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" "github.com/kubemq-io/kubemq-targets/targets" ) func setupClient(ctx context.Context, target middleware.Middleware) (*Client, error) { c := New() err := c.Init(ctx, config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "<PASSWORD>", "channel": "query", "group": "group", "auto_reconnect": "true", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "2", }, }, "", nil) if err != nil { return nil, err } err = c.Start(ctx, target) if err != nil { return nil, err } time.Sleep(time.Second) return c, nil } func sendQuery(ctx context.Context, req *types.Request, sendChannel string, timeout time.Duration) (*types.Response, error) { client, err := kubemq.NewClient(ctx, kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { return nil, err } queryResponse, err := client.SetQuery(req.ToQuery()).SetChannel(sendChannel).SetTimeout(timeout).Send(ctx) if err != nil { return nil, err } return types.ParseResponse(queryResponse.Body) } func TestClient_processQuery(t *testing.T) { tests := []struct { name string target targets.Target req *types.Request wantResp *types.Response timeout time.Duration sendCh string wantErr bool }{ { name: "request", target: &null.Client{ Delay: 0, DoError: nil, ResponseError: nil, }, req: types.NewRequest().SetData([]byte("some-data")), wantResp: types.NewResponse().SetData([]byte("some-data")), timeout: 5 * time.Second, sendCh: "query", wantErr: false, }, { name: "request with target error", target: &null.Client{ Delay: 0, DoError: nil, ResponseError: fmt.Errorf("error"), }, req: types.NewRequest().SetData([]byte("some-data")), wantResp: types.NewResponse().SetError(fmt.Errorf("error")), timeout: 5 * time.Second, sendCh: "query", wantErr: false, }, { name: "request with target do error", target: &null.Client{ Delay: 0, DoError: fmt.Errorf("error"), ResponseError: nil, }, req: types.NewRequest().SetData([]byte("some-data")), wantResp: types.NewResponse().SetError(fmt.Errorf("error")), timeout: 5 * time.Second, sendCh: "query", wantErr: false, }, { name: "request with timeout error", target: &null.Client{ Delay: 3 * time.Second, DoError: nil, ResponseError: nil, }, req: types.NewRequest().SetData([]byte("some-data")), wantResp: types.NewResponse(), timeout: 2 * time.Second, sendCh: "query", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c, err := setupClient(ctx, tt.target) require.NoError(t, err) defer func() { _ = c.Stop() }() gotResp, err := sendQuery(ctx, tt.req, tt.sendCh, tt.timeout) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.EqualValues(t, tt.wantResp, gotResp) }) } } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "some-auth token", "channel": "some-channel", "group": "", "auto_reconnect": "true", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "2", }, }, wantErr: false, }, { name: "init - error", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "host": "localhost", "port": "-1", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, "", nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestClient_Start(t *testing.T) { tests := []struct { name string target targets.Target cfg config.Spec wantErr bool }{ { name: "start", target: &null.Client{ Delay: 0, DoError: nil, ResponseError: nil, }, cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "some-auth token", "channel": "some-channel", "group": "", "auto_reconnect": "false", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "2", }, }, wantErr: false, }, { name: "start - bad target", target: nil, cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "some-auth token", "channel": "some-channel", "group": "", "auto_reconnect": "true", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "2", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() _ = c.Init(ctx, tt.cfg, "", nil) if err := c.Start(ctx, tt.target); (err != nil) != tt.wantErr { t.Errorf("Start() error = %v, wantErr %v", err, tt.wantErr) } }) } } <file_sep>package http import ( "fmt" "strings" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "post": "POST", "get": "GET", "head": "HEAD", "put": "PUT", "delete": "DELETE", "patch": "PATCH", "options": "OPTIONS", } type metadata struct { method string url string headers map[string]string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{ method: "", url: "", headers: map[string]string{}, } var err error m.method, err = meta.MustParseString("method") if err != nil { return metadata{}, fmt.Errorf("error parsing method func, %w", err) } _, ok := methodsMap[strings.ToLower(m.method)] if !ok { return metadata{}, fmt.Errorf("method %s not supported", m.method) } m.url, err = meta.MustParseString("url") if err != nil { return metadata{}, fmt.Errorf("error parsing url, %w", err) } m.headers, err = meta.MustParseJsonMap("headers") if err != nil { return metadata{}, fmt.Errorf("error parsing headers, %w", err) } return m, nil } <file_sep>package rethinkdb import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.rethinkdb"). SetDescription("Rethinkdb Target"). SetName("RethinkDB"). SetProvider(""). SetCategory("Store"). SetTags("db", "sql"). AddProperty( common.NewProperty(). SetKind("string"). SetName("host"). SetTitle("Host Address"). SetDescription("Set Rethinkdb host address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Rethinkdb username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Rethinkdb password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("timeout"). SetDescription("Set Rethinkdb operation timeout seconds"). SetMust(false). SetDefault("5"). SetMin(0). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("keep_alive_period"). SetDescription("Set Rethinkdb operation keep alive period seconds"). SetMust(false). SetDefault("5"). SetMin(0). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("auth_key"). SetTitle("Authentication Key"). SetDescription("Set Rethinkdb auth key"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("condition"). SetName("tls"). SetTitle("Use TLS"). SetOptions([]string{"true", "false"}). SetDescription("Set tls conditions"). SetMust(true). SetDefault("false"). NewCondition("true", []*common.Property{ common.NewProperty(). SetKind("multilines"). SetName("cert_key"). SetTitle("Certification Key"). SetDescription("Set certificate key"). SetMust(false). SetDefault(""), common.NewProperty(). SetKind("multilines"). SetName("cert_file"). SetTitle("Certification File"). SetDescription("Set certificate file"). SetMust(false). SetDefault(""), }), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("hand_shake_version"). SetDescription("Set Rethinkdb hand shake version"). SetMust(false). SetDefault("0"). SetMin(0). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("number_of_retries"). SetDescription("Set Rethinkdb number of retries"). SetMust(false). SetDefault("0"). SetMin(0). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("initial_cap"). SetDescription("Set Rethinkdb initial cap"). SetMust(false). SetDefault("0"). SetMin(0). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_open"). SetDescription("Set Rethinkdb max open connections"). SetMust(false). SetDefault("0"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Rethinkdb execution method"). SetOptions([]string{"get", "update", "delete", "insert"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Set Rethinkdb key"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("table"). SetKind("string"). SetDescription("Set Rethinkdb table name"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("db_name"). SetKind("string"). SetDescription("Set Rethinkdb db name"). SetMust(true), ) } <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { dat, err := ioutil.ReadFile("./credentials/query.txt") if err != nil { panic(err) } query := string(dat) client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // query setRequest := types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("query", query) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.gcp.bigquery"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get query request for query: %s executed, response: %s", query, setResponse.Data)) // get data sets delRequest := types.NewRequest(). SetMetadataKeyValue("method", "get_data_sets") getDataSets, err := client.SetQuery(delRequest.ToQuery()). SetChannel("query.gcp.bigquery"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getSetsResponse, err := types.ParseResponse(getDataSets.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get data sets executed, response: %s", getSetsResponse.Data)) } <file_sep>package servicebus import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { endPoint string sharedAccessKey string sharedAccessKeyName string data []byte queue string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/azure/servicebus/endPoint.txt") if err != nil { return nil, err } t.endPoint = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/azure/servicebus/sharedAccessKey.txt") if err != nil { return nil, err } t.sharedAccessKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/azure/servicebus/sharedAccessKeyName.txt") if err != nil { return nil, err } t.sharedAccessKeyName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/azure/servicebus/message.txt") if err != nil { return nil, err } t.data = dat t.queue = "myqueue" return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "azure-servicebus", Kind: "azure.servicebus", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, "queue_name": dat.queue, }, }, wantErr: false, }, { name: "invalid init - missing shared_access_key_name", cfg: config.Spec{ Name: "azure-servicebus", Kind: "azure.servicebus", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key": dat.sharedAccessKey, "queue_name": dat.queue, }, }, wantErr: true, }, { name: "invalid init - missing shared_access_key", cfg: config.Spec{ Name: "azure-servicebus", Kind: "azure.servicebus", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "queue_name": dat.queue, }, }, wantErr: true, }, { name: "invalid init - missing queue_name", cfg: config.Spec{ Name: "azure-servicebus", Kind: "azure.servicebus", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Send_Item(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "azure-servicebus", Kind: "azure.servicebus", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, "queue_name": dat.queue, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid send item", request: types.NewRequest(). SetMetadataKeyValue("method", "send"). SetData(dat.data), wantErr: false, }, { name: "invalid send item missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "send"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Send_Batch_Items(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) var data []string data = append(data, "message1") data = append(data, "message2") b, err := json.Marshal(data) cfg := config.Spec{ Name: "azure-servicebus", Kind: "azure.servicebus", Properties: map[string]string{ "end_point": dat.endPoint, "shared_access_key_name": dat.sharedAccessKeyName, "shared_access_key": dat.sharedAccessKey, "queue_name": dat.queue, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid send batch item with label", request: types.NewRequest(). SetMetadataKeyValue("method", "send_batch"). SetMetadataKeyValue("label", "my_label"). SetMetadataKeyValue("content_type", "content_type"). SetData(b), wantErr: false, }, { name: "valid send batch item", request: types.NewRequest(). SetMetadataKeyValue("method", "send_batch"). SetMetadataKeyValue("content_type", "content_type"). SetData(b), wantErr: false, }, { name: "invalid send batch item missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "send_batch"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>//go:build container // +build container package ibmmq import ( "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { dynamicQueue string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} m.dynamicQueue = meta.ParseString("dynamic_queue", "") return m, nil } <file_sep>package mongodb import ( "context" "fmt" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testDocument struct { Id string `json:"_id,omitempty"` String string `json:"string,omitempty"` Integer string `json:"integer,omitempty"` } func (t *testDocument) data() []byte { data, _ := json.Marshal(t) return data } func (t *testDocument) dataString() string { data, _ := json.MarshalToString(t) return data } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "majority", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, wantErr: false, }, { name: "init - error connection", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "host": "bad-host:32017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "majority", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, wantErr: true, }, { name: "init - bad host", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, wantErr: true, }, { name: "init - bad database", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, wantErr: true, }, { name: "init - bad collection", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, wantErr: true, }, { name: "init - bad write concurrency", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "bad-concurrency", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, wantErr: true, }, { name: "init - bad read concurrency", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "bad-concurrency", "params": "", "operation_timeout_seconds": "2", }, }, wantErr: true, }, { name: "init - bad operation timeout", cfg: config.Spec{ Name: "mongodb-target", Kind: "", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "-2", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSetErr %v", err, tt.wantErr) return } }) } } func TestClient_Set_Get(t *testing.T) { tests := []struct { name string cfg config.Spec setRequest *types.Request getRequest *types.Request wantSetResponse *types.Response wantGetResponse *types.Response wantSetErr bool wantGetErr bool }{ { name: "valid set get request", cfg: config.Spec{ Name: "mongodb", Kind: "mongodb", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set_by_key"). SetMetadataKeyValue("key", "some-key"). SetData([]byte("some-data")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_by_key"). SetMetadataKeyValue("key", "some-key"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("result", "ok"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key"). SetData([]byte("some-data")), wantSetErr: false, wantGetErr: false, }, { name: "valid set , no key get request", cfg: config.Spec{ Name: "mongodb", Kind: "mongodb", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set_by_key"). SetMetadataKeyValue("key", "some-key"). SetData([]byte("some-data")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_by_key"). SetMetadataKeyValue("key", "bad-key"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("result", "ok"), wantGetResponse: nil, wantSetErr: false, wantGetErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.setRequest) if tt.wantSetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantSetResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.getRequest) if tt.wantGetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantGetResponse, gotGetResponse) }) } } func TestClient_Delete(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, config.Spec{ Name: "mongodb", Kind: "mongodb", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, nil) key := uuid.New().String() require.NoError(t, err) setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set_by_key"). SetMetadataKeyValue("key", key). SetData([]byte("some-data")) _, err = c.Do(ctx, setRequest) require.NoError(t, err) getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get_by_key"). SetMetadataKeyValue("key", key) gotGetResponse, err := c.Do(ctx, getRequest) require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, []byte("some-data"), gotGetResponse.Data) delRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete_by_key"). SetMetadataKeyValue("key", key) _, err = c.Do(ctx, delRequest) require.NoError(t, err) gotGetResponse, err = c.Do(ctx, getRequest) require.Error(t, err) require.Nil(t, gotGetResponse) } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid request", cfg: config.Spec{ Name: "mongodb", Kind: "mongodb", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "set_by_key"). SetMetadataKeyValue("key", "some-key"). SetData([]byte("some-data")), wantErr: false, }, { name: "invalid request - bad method", cfg: config.Spec{ Name: "mongodb", Kind: "mongodb", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "bad-method"). SetMetadataKeyValue("key", "some-key"). SetData([]byte("some-data")), wantErr: true, }, { name: "invalid request - no key", cfg: config.Spec{ Name: "mongodb", Kind: "mongodb", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "set_by_key"). SetData([]byte("some-data")), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) _, err = c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } func TestClient_Insert_Find_Update_Delete(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, config.Spec{ Name: "mongodb", Kind: "mongodb", Properties: map[string]string{ "host": "localhost:27017", "username": "admin", "password": "<PASSWORD>", "database": "admin", "collection": "test", "write_concurrency": "", "read_concurrency": "", "params": "", "operation_timeout_seconds": "2", }, }, nil) require.NoError(t, err) doc := &testDocument{ Id: uuid.New().String(), String: "s", Integer: "1", } var docs []*testDocument docs = append(docs, doc) docsData, err := json.Marshal(&docs) require.NoError(t, err) insertRequest := types.NewRequest(). SetMetadataKeyValue("method", "insert_many"). SetData(docsData) fmt.Println(insertRequest.String()) _, err = c.Do(ctx, insertRequest) require.NoError(t, err) findFilter := &testDocument{ Id: doc.Id, } findRequest := types.NewRequest(). SetMetadataKeyValue("method", "find"). SetMetadataKeyValue("filter", findFilter.dataString()) findResponse, err := c.Do(ctx, findRequest) require.NoError(t, err) require.NotNil(t, findResponse) receivedDoc := &testDocument{} err = json.Unmarshal(findResponse.Data, receivedDoc) require.NoError(t, err) require.EqualValues(t, doc, receivedDoc) updateFilter := &testDocument{ Id: doc.Id, } updateDoc := &testDocument{ Id: doc.Id, String: "b", Integer: "2", } updateRequest := types.NewRequest(). SetMetadataKeyValue("method", "update"). SetMetadataKeyValue("filter", updateFilter.dataString()).SetData(updateDoc.data()) updateResponse, err := c.Do(ctx, updateRequest) require.NoError(t, err) require.NotNil(t, updateResponse) findResponse, err = c.Do(ctx, findRequest) require.NoError(t, err) require.NotNil(t, findResponse) receivedDoc2 := &testDocument{} err = json.Unmarshal(findResponse.Data, receivedDoc2) require.NoError(t, err) require.EqualValues(t, updateDoc, receivedDoc2) upsertDoc := &testDocument{ Id: uuid.New().String(), String: "c", Integer: "3", } upsertFilter := &testDocument{ Id: upsertDoc.Id, } upsertRequest := types.NewRequest(). SetMetadataKeyValue("method", "update"). SetMetadataKeyValue("set_upsert", "true"). SetMetadataKeyValue("filter", upsertFilter.dataString()).SetData(upsertDoc.data()) upsertResponse, err := c.Do(ctx, upsertRequest) require.NoError(t, err) require.NotNil(t, upsertResponse) findUpsertFilter := &testDocument{ Id: upsertDoc.Id, } findUpsertRequest := types.NewRequest(). SetMetadataKeyValue("method", "find"). SetMetadataKeyValue("filter", findUpsertFilter.dataString()) findUpsertResponse, err := c.Do(ctx, findUpsertRequest) require.NoError(t, err) require.NotNil(t, findUpsertResponse) receivedUpsertDoc2 := &testDocument{} err = json.Unmarshal(findUpsertResponse.Data, receivedUpsertDoc2) require.NoError(t, err) require.EqualValues(t, upsertDoc, receivedUpsertDoc2) delFilter := &testDocument{ Id: upsertDoc.Id, } delRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("filter", delFilter.dataString()) delResponse, err := c.Do(ctx, delRequest) require.NoError(t, err) require.NotNil(t, delResponse) delFilter.Id = doc.Id delRequest = types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("filter", delFilter.dataString()) delResponse, err = c.Do(ctx, delRequest) require.NoError(t, err) require.NotNil(t, delResponse) } <file_sep>package memcached import ( "fmt" "math" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { hosts []string maxIdleConnections int defaultTimeoutSeconds int } func parseOptions(cfg config.Spec) (options, error) { o := options{ hosts: nil, maxIdleConnections: 0, defaultTimeoutSeconds: 0, } var err error o.hosts, err = cfg.Properties.MustParseStringList("hosts") if err != nil { return options{}, fmt.Errorf("error parsing host, %w", err) } o.maxIdleConnections, err = cfg.Properties.ParseIntWithRange("max_idle_connections", 2, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing max idle connections, %w", err) } o.defaultTimeoutSeconds, err = cfg.Properties.ParseIntWithRange("default_timeout_seconds", 1, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing default timeout seconds, %w", err) } return o, nil } <file_sep>package elasticsearch import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string json string domain string index string endpoint string service string id string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" dat, err = ioutil.ReadFile("./../../../credentials/aws/elasticsearch/signer/json.txt") if err != nil { return nil, err } t.json = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/elasticsearch/signer/domain.txt") if err != nil { return nil, err } t.domain = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/elasticsearch/signer/index.txt") if err != nil { return nil, err } t.index = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/elasticsearch/signer/endpoint.txt") if err != nil { return nil, err } t.endpoint = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/elasticsearch/signer/service.txt") if err != nil { return nil, err } t.service = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/elasticsearch/signer/id.txt") if err != nil { return nil, err } t.id = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.elasticsearch", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, }, }, wantErr: false, }, { name: "invalid init - missing aws_key", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.elasticsearch", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, }, }, wantErr: true, }, { name: "invalid init - missing aws_secret_key", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.elasticsearch", Properties: map[string]string{ "aws_key": dat.awsKey, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Do(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-elasticsearch", Kind: "aws.elasticsearch", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid post", request: types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: false, }, { name: "invalid post - missing method", request: types.NewRequest(). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: true, }, { name: "invalid post - incorrect method", request: types.NewRequest(). SetMetadataKeyValue("method", "MADE_UP"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: true, }, { name: "invalid post - missing region", request: types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: true, }, { name: "invalid post - missing json", request: types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: true, }, { name: "invalid post - missing domain", request: types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: true, }, { name: "invalid post - missing endpoint", request: types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: true, }, { name: "invalid post - missing index", request: types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("service", dat.service). SetMetadataKeyValue("id", dat.id), wantErr: true, }, { name: "invalid post - missing id", request: types.NewRequest(). SetMetadataKeyValue("method", "POST"). SetMetadataKeyValue("region", dat.region). SetMetadataKeyValue("json", dat.json). SetMetadataKeyValue("domain", dat.domain). SetMetadataKeyValue("endpoint", dat.endpoint). SetMetadataKeyValue("index", dat.index). SetMetadataKeyValue("service", dat.service), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package kafka import ( "strings" kafka "github.com/Shopify/sarama" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { brokers []string topic string saslUsername string saslPassword string saslMechanism string securityProtocol string cacert string clientCert string clientKey string insecure bool } func parseOptions(cfg config.Spec) (options, error) { m := options{} var err error m.brokers, err = cfg.Properties.MustParseStringList("brokers") if err != nil { return m, err } m.topic, err = cfg.Properties.MustParseString("topic") if err != nil { return m, err } m.saslUsername = cfg.Properties.ParseString("sasl_username", "") m.saslPassword = cfg.Properties.ParseString("sasl_password", "") m.saslMechanism = cfg.Properties.ParseString("sasl_mechanism", "") m.securityProtocol = cfg.Properties.ParseString("security_protocol", "") m.cacert = cfg.Properties.ParseString("ca_cert", "") m.clientCert = cfg.Properties.ParseString("client_certificate", "") m.clientKey = cfg.Properties.ParseString("client_key", "") m.insecure = cfg.Properties.ParseBool("insecure", false) return m, nil } func (m *options) parseASLMechanism() kafka.SASLMechanism { switch strings.ToLower(m.saslMechanism) { case "plain": return kafka.SASLTypePlaintext case "scram-sha-256": return kafka.SASLTypeSCRAMSHA256 case "scram-sha-512": return kafka.SASLTypeSCRAMSHA512 case "gssapi", "gss-api", "gss_api": return kafka.SASLTypeGSSAPI case "oauth", "0auth bearer": return kafka.SASLTypeOAuth case "external", "ext": return kafka.SASLExtKeyAuth default: return kafka.SASLTypePlaintext } } func (m *options) parseSecurityProtocol() (bool, bool) { switch strings.ToLower(m.securityProtocol) { case "plaintext": return false, false case "ssl": return true, false case "sasl_plaintext": return false, true case "sasl_ssl": return true, true default: return false, false } } <file_sep>package consulkv import ( "context" "crypto/tls" "encoding/json" "errors" "fmt" "net" "strings" consul "github.com/hashicorp/consul/api" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) // Client is a Client state store type Client struct { log *logger.Logger client *consul.Client opts options } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } config, err := setConfig(c.opts) if err != nil { return err } client, err := consul.NewClient(config) if err != nil { return err } c.client = client return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.get(ctx, meta) case "list": return c.list(ctx, meta) case "put": return c.put(ctx, meta, req.Data) case "delete": return c.delete(ctx, meta) } return nil, nil } func (c *Client) get(ctx context.Context, meta metadata) (*types.Response, error) { if meta.key == "" { return nil, errors.New("missing key") } kv := c.client.KV() o := c.createQueryOptions(ctx, meta) kvp, qm, err := kv.Get(meta.key, o) if err != nil { return nil, err } if kvp == nil { return nil, fmt.Errorf("failed to find key %s", meta.key) } b, err := json.Marshal(kvp) if err != nil { return nil, err } qmeta, err := json.Marshal(qm) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("query_metadata", string(qmeta)). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) put(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data") } kvp := &consul.KVPair{} err := json.Unmarshal(data, kvp) if err != nil { return nil, err } kv := c.client.KV() o := c.createWriteOptions(ctx) wm, err := kv.Put(kvp, o) if err != nil { return nil, err } b, err := json.Marshal(wm) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) delete(ctx context.Context, meta metadata) (*types.Response, error) { if meta.key == "" { return nil, errors.New("missing key") } kv := c.client.KV() o := c.createWriteOptions(ctx) wm, err := kv.Delete(meta.key, o) if err != nil { return nil, err } b, err := json.Marshal(wm) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) list(ctx context.Context, meta metadata) (*types.Response, error) { kv := c.client.KV() o := c.createQueryOptions(ctx, meta) kvp, qm, err := kv.List(meta.prefix, o) if err != nil { return nil, err } b, err := json.Marshal(kvp) if err != nil { return nil, err } qmeta, err := json.Marshal(qm) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("query_metadata", string(qmeta)). SetMetadataKeyValue("key", meta.key), nil } func setConfig(opts options) (*consul.Config, error) { c := &consul.Config{} if opts.address != "" { c.Address = opts.address } if opts.scheme != "" { c.Scheme = opts.scheme } if opts.datacenter != "" { c.Datacenter = opts.datacenter } if opts.waitTime > 0 { c.WaitTime = opts.waitTime } if opts.token != "" { c.Token = opts.token } if opts.tokenFile != "" { c.TokenFile = opts.tokenFile } if opts.tls { tlsClientConfig := &tls.Config{} tlsClientConfig.InsecureSkipVerify = opts.insecureSkipVerify if opts.address != "" { server := opts.address hasPort := strings.LastIndex(server, ":") > strings.LastIndex(server, "]") if hasPort { var err error server, _, err = net.SplitHostPort(server) if err != nil { return nil, err } } tlsClientConfig.ServerName = server } cert, err := tls.X509KeyPair([]byte(opts.tlscertificatefile), []byte(opts.tlscertificatekey)) if err != nil { return c, fmt.Errorf("consulkv: error parsing client certificate: %v", err) } tlsClientConfig.Certificates = []tls.Certificate{cert} } return c, nil } func (c *Client) Stop() error { return nil } func (c *Client) createWriteOptions(ctx context.Context) *consul.WriteOptions { o := &consul.WriteOptions{} o.WithContext(ctx) if c.opts.datacenter != "" { o.Datacenter = c.opts.datacenter } if c.opts.token != "" { o.Token = c.opts.token } return o } func (c *Client) createQueryOptions(ctx context.Context, meta metadata) *consul.QueryOptions { o := &consul.QueryOptions{} o.WithContext(ctx) if c.opts.datacenter != "" { o.Datacenter = c.opts.datacenter } o.AllowStale = meta.allowStale o.RequireConsistent = meta.requireConsistent o.UseCache = meta.useCache if meta.maxAge != 0 { o.MaxAge = meta.maxAge } if meta.staleIfError != 0 { o.StaleIfError = meta.staleIfError } o.WaitTime = c.opts.waitTime if c.opts.token != "" { o.Token = c.opts.token } o.Near = meta.near o.Filter = meta.filter return o } <file_sep>package firebase import ( "context" "encoding/json" "fmt" "strconv" "firebase.google.com/go/v4/auth" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/iterator" ) func (c *Client) createUser(ctx context.Context, data []byte) (*types.Response, error) { p, err := getCreateData(data) if err != nil { return nil, err } u, err := c.clientAuth.CreateUser(ctx, p) if err != nil { return nil, err } b, err := json.Marshal(u) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) retrieveUser(ctx context.Context, meta metadata) (*types.Response, error) { var b []byte switch meta.retrieveBy { case "by_uid": u, err := c.clientAuth.GetUser(ctx, meta.uid) if err != nil { return nil, err } b, err = json.Marshal(u) if err != nil { return nil, err } case "by_email": u, err := c.clientAuth.GetUserByEmail(ctx, meta.email) if err != nil { return nil, err } b, err = json.Marshal(u) if err != nil { return nil, err } case "by_phone": u, err := c.clientAuth.GetUserByPhoneNumber(ctx, meta.phone) if err != nil { return nil, err } b, err = json.Marshal(u) if err != nil { return nil, err } } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) updateUser(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { p, err := getUpdateData(data) if err != nil { return nil, err } u, err := c.clientAuth.UpdateUser(ctx, meta.uid, p) if err != nil { return nil, err } b, err := json.Marshal(u) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) deleteUser(ctx context.Context, meta metadata) (*types.Response, error) { err := c.clientAuth.DeleteUser(ctx, meta.uid) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteMultipleUser(ctx context.Context, data []byte) (*types.Response, error) { var l []string err := json.Unmarshal(data, &l) if err != nil { return nil, err } r, err := c.clientAuth.DeleteUsers(ctx, l) if err != nil { return nil, err } b, err := json.Marshal(r) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listAllUsers(ctx context.Context) (*types.Response, error) { var users []*auth.ExportedUserRecord iter := c.clientAuth.Users(ctx, "") for { user, err := iter.Next() if err == iterator.Done { break } if err != nil { return nil, err } users = append(users, user) } b, err := json.Marshal(users) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func getUpdateData(data []byte) (*auth.UserToUpdate, error) { u := &auth.UserToUpdate{} m := make(map[string]interface{}) err := json.Unmarshal(data, &m) if err != nil { return u, err } for k, v := range m { switch k { case "custom_claims": c := make(map[string]interface{}) err := json.Unmarshal(data, &c) if err != nil { return u, err } u.CustomClaims(c) case "disabled": b, err := strconv.ParseBool(fmt.Sprintf("%v", v)) if err != nil { return u, err } u.Disabled(b) case "display_name": u.DisplayName(fmt.Sprintf("%v", v)) case "email": u.Email(fmt.Sprintf("%v", v)) case "email_verified": b, err := strconv.ParseBool(fmt.Sprintf("%v", v)) if err != nil { return u, err } u.EmailVerified(b) case "password": u.Password(fmt.Sprintf("%v", v)) case "phone_number": u.PhoneNumber(fmt.Sprintf("%v", v)) case "photo_url": u.PhotoURL(fmt.Sprintf("%v", v)) } } return u, nil } func getCreateData(data []byte) (*auth.UserToCreate, error) { u := &auth.UserToCreate{} m := make(map[string]interface{}) err := json.Unmarshal(data, &m) if err != nil { return u, err } for k, v := range m { switch k { case "disabled": b, err := strconv.ParseBool(fmt.Sprintf("%v", v)) if err != nil { return u, err } u.Disabled(b) case "display_name": u.DisplayName(fmt.Sprintf("%v", v)) case "email": u.Email(fmt.Sprintf("%v", v)) case "email_verified": b, err := strconv.ParseBool(fmt.Sprintf("%v", v)) if err != nil { return u, err } u.EmailVerified(b) case "password": u.Password(fmt.Sprintf("%s", v)) case "phone_number": u.PhoneNumber(fmt.Sprintf("%v", v)) case "photo_url": u.PhotoURL(fmt.Sprintf("%v", v)) case "local_id": u.UID(fmt.Sprintf("%v", v)) } } return u, nil } <file_sep># Kubemq Minio/S3 Target Connector Kubemq Minio/S3 target connector allows services using kubemq server to access minio/s3 storage functions. ## Prerequisites The following are required to run the minio target connector: - kubemq cluster - minio cluster / AWS s3 service - kubemq-targets deployment ## Configuration Minio target connector configuration properties: | Properties Key | Required | Description | Example | |:------------------|:---------|:-----------------------------------------|:-----------------| | endpoint | yes | minio host address | "localhost:9001" | | use_ssl | no | set connection ssl | "true" | | access_key_id | yes | set access key id | "minio" | | secret_access_key | yes | set secret access key | "minio123" | Example: ```yaml bindings: - name: kubemq-query-minio source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-minio-connector" auth_token: "" channel: "query.minio" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: storage.minio name: target-minio properties: endpoint: "localhost:9000" use_ssl: "false" access_key_id: "minio" secret_access_key: "minio123" ``` ## Usage ### Make Bucket Request Make bucket request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "make_bucket" | | param1 | yes | set bucket name | "bucket" | | param2 | no | set bucket location | "" | Example: ```json { "metadata": { "method": "make_bucket", "param1": "bucket", "param2": "" }, "data": null } ``` ### List Buckets Request List Buckets request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | method | yes | method name | "list_buckets" | Example: ```json { "metadata": { "method": "list_buckets" }, "data": null } ``` ### Bucket Exists Request Bucket exists request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "bucket_exists" | | param1 | yes | set bucket name | "bucket" | Example: ```json { "metadata": { "method": "make_bucket", "param1": "bucket" }, "data": null } ``` ### Remove Bucket Request Remove bucket request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "remove_bucket" | | param1 | yes | set bucket name | "bucket" | Example: ```json { "metadata": { "method": "remove_bucket", "param1": "bucket" }, "data": null } ``` ### List Objects Request List objects request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "list_objects" | | param1 | yes | set bucket name | "bucket" | Example: ```json { "metadata": { "method": "list_objects", "param1": "bucket" }, "data": null } ``` ### Put Object Request Put object request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "put" | | param1 | yes | set bucket name | "bucket" | | param2 | yes | set object name | "object" | Put request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | data to put for object | base64 bytes array | Example: ```json { "metadata": { "method": "put", "param1": "bucket", "param2": "object-name" }, "data": "c29tZS1kYXRh" } ``` ### Get Object Request Get object request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "get" | | param1 | yes | set bucket name | "bucket" | | param2 | yes | set object name | "object" | Example: ```json { "metadata": { "method": "get", "param1": "bucket", "param2": "object" }, "data": null } ``` ### Remove Object Request Remove object request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "remove" | | param1 | yes | set bucket name | "bucket" | | param2 | yes | set object name | "object" | Example: ```json { "metadata": { "method": "remove", "param1": "bucket", "param2": "object" }, "data": null } ``` <file_sep>package http import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("http"). SetDescription("HTTP/Rest Target"). SetName("HTTP"). SetProvider(""). SetCategory("General"). SetTags("rest", "api"). AddProperty( common.NewProperty(). SetKind("condition"). SetName("auth_type"). SetTitle("Authentication Type"). SetDescription("Set Auth type"). SetMust(true). SetOptions([]string{"No Auth", "Basic", "Token"}). SetDefault("No Auth"). NewCondition("No Auth", []*common.Property{ common.NewProperty(). SetKind("null"). SetName("auth_type"). SetTitle("Authentication Type"). SetDescription("Set Auth type"). SetMust(true). SetDefault("no_auth"), }). NewCondition("Basic", []*common.Property{ common.NewProperty(). SetKind("null"). SetName("auth_type"). SetTitle("Authentication Type"). SetDescription("Set Auth type"). SetMust(true). SetDefault("basic"), common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Basic auth username"). SetMust(true). SetDefault(""), common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Basic auth password"). SetMust(true). SetDefault(""), }). NewCondition("Token", []*common.Property{ common.NewProperty(). SetKind("null"). SetName("auth_type"). SetTitle("Authentication Type"). SetDescription("Set Auth type"). SetMust(true). SetDefault("auth_token"), common.NewProperty(). SetKind("multilines"). SetName("token"). SetDescription("Set Auth token"). SetMust(true). SetDefault(""), }), ). AddProperty( common.NewProperty(). SetKind("map"). SetName("default_headers"). SetDescription("Set Default headers (key1=value1;key2=value2;...)"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("proxy"). SetDescription("Set Proxy address"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("root_certificate"). SetDescription("Set Root Certificate"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("client_private_key"). SetDescription("Set Client private key"). SetMust(false). SetDefault(""), ).AddProperty( common.NewProperty(). SetKind("multilines"). SetName("client_public_key"). SetDescription("Set Client public key"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set method"). SetOptions([]string{"post", "get", "head", "put", "delete", "patch", "options"}). SetDefault("post"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("url"). SetKind("string"). SetDescription("Set HTTP URL bucket name"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("headers"). SetKind("string"). SetDescription("Set HTTP headers"). SetDefault(""). SetMust(false), ) } <file_sep>package filesystem import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "save": "save", "load": "load", "delete": "delete", "list": "list", } type metadata struct { method string path string filename string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.filename, err = meta.MustParseString("filename") if err != nil { return metadata{}, fmt.Errorf("error parsing filename, %w", err) } m.path = meta.ParseString("path", "") m.path = unixNormalize(m.path) return m, nil } <file_sep>package sqs import ( "context" "encoding/json" "fmt" "strconv" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sqs" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *sqs.SQS } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.sqsKey, c.opts.sqsSecretKey, c.opts.token), }) if err != nil { return err } svc := sqs.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, request *types.Request) (*types.Response, error) { eventMetadata, ok := c.opts.defaultMetadata() if !ok { var err error eventMetadata, err = parseMetadata(request.Metadata, c.opts) if err != nil { return nil, err } } m := &sqs.SendMessageInput{} c.setMessageMeta(m, eventMetadata) m.SetMessageBody(string(request.Data)) tries := 0 for tries <= c.opts.retries { r, err := c.client.SendMessageWithContext(ctx, m) if err == nil { return types.NewResponse(). SetMetadataKeyValue("event_id", *r.MessageId), nil } if tries >= c.opts.retries { return nil, err } tries++ } return nil, fmt.Errorf("retries must be a zero or greater") } func (c *Client) setMessageMeta(m *sqs.SendMessageInput, eventMetadata metadata) *sqs.SendMessageInput { m.SetQueueUrl(eventMetadata.queueURL) m.SetDelaySeconds(int64(eventMetadata.delay)) if len(eventMetadata.tags) > 0 { m.SetMessageAttributes(eventMetadata.tags) } return m } func (c *Client) SetQueueAttributes(ctx context.Context, QueueUrl string) error { if c.opts.maxReceiveCount > 0 && len(c.opts.deadLetterQueue) > 0 { policy := map[string]string{ "deadLetterTargetArn": c.opts.deadLetterQueue, "maxReceiveCount": strconv.Itoa(c.opts.maxReceiveCount), } b, err := json.Marshal(policy) if err != nil { return fmt.Errorf("failed to marshal policy on err :%s", err.Error()) } _, err = c.client.SetQueueAttributesWithContext(ctx, &sqs.SetQueueAttributesInput{ Attributes: map[string]*string{ sqs.QueueAttributeNameRedrivePolicy: aws.String(string(b)), }, QueueUrl: aws.String(QueueUrl), }) if err != nil { return fmt.Errorf("failed to SetQueueAttributesWithContext err :%s", err.Error()) } return nil } return fmt.Errorf("failed to SetQueueAttributesWithContext need to verify max_receive and dead_letter exists") } func (c *Client) Stop() error { return nil } <file_sep>package s3 import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.s3"). SetDescription("AWS S3 Target"). SetName("S3"). SetProvider("AWS"). SetCategory("Storage"). SetTags("filesystem", "object", "db", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set S3 aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set S3 aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set S3 aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set S3 token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set S3 execution method"). SetOptions([]string{"list_buckets", "list_bucket_items", "create_bucket", "delete_bucket", "delete_item_from_bucket", "delete_all_items_from_bucket", "upload_item", "copy_item", "get_item"}). SetDefault("upload_item"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("bucket_name"). SetKind("string"). SetDescription("Set S3 bucket name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("copy_source"). SetKind("string"). SetDescription("Set S3 copy source"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("bool"). SetName("wait_for_completion"). SetDescription("Set S3 wait for completion until retuning response"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("item_name"). SetDescription("Set S3 item name"). SetMust(false). SetDefault(""), ) } <file_sep>package rabbitmq import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { url string defaultExchange string defaultTopic string defaultPersistence bool caCert string insecure bool } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.url, err = cfg.Properties.MustParseString("url") if err != nil { return options{}, fmt.Errorf("error parsing url, %w", err) } o.defaultExchange = cfg.Properties.ParseString("default_exchange", "") o.defaultTopic = cfg.Properties.ParseString("default_topic", "") o.defaultPersistence = cfg.Properties.ParseBool("default_persistence", true) o.caCert = cfg.Properties.ParseString("ca_cert", "") o.insecure = cfg.Properties.ParseBool("skip_insecure", false) return o, nil } func (o options) defaultMetadata() (metadata, bool) { if o.defaultTopic != "" || o.defaultExchange != "" { delMode := 2 if !o.defaultPersistence { delMode = 1 } return metadata{ queue: o.defaultTopic, exchange: o.defaultExchange, mandatory: false, immediate: false, deliveryMode: delMode, priority: 0, correlationId: "", replyTo: "", expiration: 0, }, true } return metadata{}, false } <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // listRequest statRequest := types.NewRequest(). SetMetadataKeyValue("file_path", "/test/foo.txt"). SetMetadataKeyValue("method", "stat") queryStatResponse, err := client.SetQuery(statRequest.ToQuery()). SetChannel("query.hdfs"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } statResponse, err := types.ParseResponse(queryStatResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("stat executed, response: %s", statResponse.Data)) } <file_sep>package binding import ( "context" "fmt" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/middleware" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/pkg/metrics" "github.com/kubemq-io/kubemq-targets/sources" "github.com/kubemq-io/kubemq-targets/targets" ) type Binder struct { name string log *logger.Logger source sources.Source target targets.Target md middleware.Middleware } func NewBinder() *Binder { return &Binder{} } func (b *Binder) buildMiddleware(cfg config.BindingConfig, exporter *metrics.Exporter, log *middleware.LogMiddleware) (middleware.Middleware, error) { retry, err := middleware.NewRetryMiddleware(cfg.Properties, b.log) if err != nil { return nil, err } rateLimiter, err := middleware.NewRateLimitMiddleware(cfg.Properties) if err != nil { return nil, err } met, err := middleware.NewMetricsMiddleware(cfg, exporter) if err != nil { return nil, err } meta, err := middleware.NewMetadataMiddleware(cfg.Properties) if err != nil { return nil, err } md := middleware.Chain(b.target, middleware.RateLimiter(rateLimiter), middleware.Retry(retry), middleware.Metric(met), middleware.Log(log), middleware.Metadata(meta)) return md, nil } func (b *Binder) Init(ctx context.Context, cfg config.BindingConfig, exporter *metrics.Exporter) error { b.name = cfg.Name log, err := middleware.NewLogMiddleware(cfg.Name, cfg.Properties) if err != nil { return err } b.log = log.Logger b.target, err = targets.Init(ctx, cfg.Target, b.log) if err != nil { return fmt.Errorf("error loading target conntector on binding %s, %w", b.name, err) } b.log.Infof("binding: %s target: initialized successfully", b.name) b.md, err = b.buildMiddleware(cfg, exporter, log) if err != nil { return fmt.Errorf("error loading middlewares on binding %s, %w", b.name, err) } b.source, err = sources.Init(ctx, cfg.Source, cfg.Name, b.log) if err != nil { return fmt.Errorf("error loading source conntector on binding %s, %w", b.name, err) } b.log.Infof("binding: %s source initialized successfully", b.name) b.log.Infof("binding: %s, initialized successfully", b.name) return nil } func (b *Binder) Start(ctx context.Context) error { if b.md == nil { return fmt.Errorf("error starting binding connector %s,no valid initialzed target middleware found", b.name) } if b.source == nil { return fmt.Errorf("error starting binding connector %s,no valid initialzed source found", b.name) } err := b.source.Start(ctx, b.md) if err != nil { return err } b.log.Infof("binding: %s, started successfully", b.name) return nil } func (b *Binder) Stop() error { err := b.source.Stop() if err != nil { return err } err = b.target.Stop() if err != nil { return err } b.log.Infof("binding: %s, stopped successfully", b.name) return nil } <file_sep>package kinesis import ( "context" "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/kinesis" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *kinesis.Kinesis } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := kinesis.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "list_streams": return c.listStreams(ctx) case "list_stream_consumers": return c.listStreamConsumers(ctx, meta) case "create_stream": return c.createStream(ctx, meta) case "create_stream_consumer": return c.createStreamConsumer(ctx, meta) case "delete_stream": return c.deleteStream(ctx, meta) case "put_record": return c.putRecord(ctx, meta, req.Data) case "put_records": return c.putRecords(ctx, meta, req.Data) case "get_records": return c.getRecord(ctx, meta) case "get_shard_iterator": return c.getShardIterator(ctx, meta) case "list_shards": return c.listShards(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) listStreams(ctx context.Context) (*types.Response, error) { m, err := c.client.ListStreamsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listStreamConsumers(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.ListStreamConsumersWithContext(ctx, &kinesis.ListStreamConsumersInput{ StreamARN: aws.String(meta.streamARN), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) createStream(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.CreateStreamWithContext(ctx, &kinesis.CreateStreamInput{ ShardCount: aws.Int64(meta.shardCount), StreamName: aws.String(meta.streamName), }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteStream(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.DeleteStreamWithContext(ctx, &kinesis.DeleteStreamInput{ StreamName: aws.String(meta.streamName), }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) listShards(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.ListShardsWithContext(ctx, &kinesis.ListShardsInput{ StreamName: aws.String(meta.streamName), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) putRecord(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { m, err := c.client.PutRecordWithContext(ctx, &kinesis.PutRecordInput{ Data: data, StreamName: aws.String(meta.streamName), PartitionKey: aws.String(meta.partitionKey), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) getShardIterator(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.GetShardIteratorWithContext(ctx, &kinesis.GetShardIteratorInput{ ShardId: aws.String(meta.shardID), StreamName: aws.String(meta.streamName), ShardIteratorType: aws.String(meta.shardIteratorType), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("shard_iterator", *m.ShardIterator). SetData(b), nil } func (c *Client) putRecords(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { rm := make(map[string][]byte) err := json.Unmarshal(data, &rm) if err != nil { return nil, err } var r []*kinesis.PutRecordsRequestEntry for k, v := range rm { r = append(r, &kinesis.PutRecordsRequestEntry{Data: v, PartitionKey: aws.String(k)}) } m, err := c.client.PutRecordsWithContext(ctx, &kinesis.PutRecordsInput{ Records: r, StreamName: aws.String(meta.streamName), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) getRecord(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.GetRecordsWithContext(ctx, &kinesis.GetRecordsInput{ ShardIterator: aws.String(meta.shardIteratorID), Limit: aws.Int64(meta.limit), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) createStreamConsumer(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.RegisterStreamConsumerWithContext(ctx, &kinesis.RegisterStreamConsumerInput{ ConsumerName: aws.String(meta.consumerName), StreamARN: aws.String(meta.streamARN), }) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>package lambda import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.lambda"). SetDescription("AWS Lambda Target"). SetName("Lambda"). SetProvider("AWS"). SetCategory("Serverless"). SetTags("faas", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Lambda aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Lambda aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Lambda aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Lambda token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Lambda execution method"). SetOptions([]string{"list", "create", "run", "delete"}). SetDefault("run"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("zip_file_name"). SetKind("string"). SetDescription("Set Lambda zip file name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("handler_name"). SetKind("string"). SetDescription("Set Lambda handler name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("role"). SetKind("string"). SetDescription("Set Lambda role"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("runtime"). SetKind("string"). SetDescription("Set Lambda runtime version"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("function_name"). SetKind("string"). SetDescription("Set Lambda function name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("description"). SetKind("string"). SetDescription("Set Lambda description"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("memory_size"). SetDescription("Set Lambda memory size"). SetMust(false). SetDefault("256"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("timeout"). SetDescription("Set Lambda timeout"). SetMust(false). SetDefault("15"). SetMin(0). SetMax(math.MaxInt32), ) } <file_sep>package mysql import ( "fmt" "math" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultMaxIdleConnections = 10 defaultMaxOpenConnections = 100 defaultConnectionMaxLifetimeSeconds = 3600 defaultToken = "" defaultDBPort = 3306 ) type options struct { awsKey string awsSecretKey string region string token string dbPort int dbName string dbUser string endPoint string // maxIdleConnections sets the maximum number of connections in the idle connection pool maxIdleConnections int // maxOpenConnections sets the maximum number of open connections to the database. maxOpenConnections int // connectionMaxLifetimeSeconds sets the maximum amount of time a connection may be reused. connectionMaxLifetimeSeconds int } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.awsKey, err = cfg.Properties.MustParseString("aws_key") if err != nil { return options{}, fmt.Errorf("error parsing aws_key , %w", err) } o.awsSecretKey, err = cfg.Properties.MustParseString("aws_secret_key") if err != nil { return options{}, fmt.Errorf("error parsing aws_secret_key , %w", err) } o.region, err = cfg.Properties.MustParseString("region") if err != nil { return options{}, fmt.Errorf("error parsing region , %w", err) } o.token = cfg.Properties.ParseString("token", defaultToken) o.dbName, err = cfg.Properties.MustParseString("db_name") if err != nil { return options{}, fmt.Errorf("error parsing db_name , %w", err) } o.dbUser, err = cfg.Properties.MustParseString("db_user") if err != nil { return options{}, fmt.Errorf("error parsing db_user , %w", err) } o.endPoint, err = cfg.Properties.MustParseString("end_point") if err != nil { return options{}, fmt.Errorf("error parsing end_point , %w", err) } o.dbPort = cfg.Properties.ParseInt("db_port", defaultDBPort) if err != nil { return options{}, fmt.Errorf("error parsing end_point , %w", err) } o.maxIdleConnections, err = cfg.Properties.ParseIntWithRange("max_idle_connections", defaultMaxIdleConnections, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing max_idle_connections value, %w", err) } o.maxOpenConnections, err = cfg.Properties.ParseIntWithRange("max_open_connections", defaultMaxOpenConnections, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing max_open_connections value, %w", err) } o.connectionMaxLifetimeSeconds, err = cfg.Properties.ParseIntWithRange("connection_max_lifetime_seconds", defaultConnectionMaxLifetimeSeconds, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing connection_max_lifetime_seconds value, %w", err) } return o, nil } <file_sep>package mqtt import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { topic string qos int } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.topic, err = meta.MustParseString("topic") if err != nil { return metadata{}, fmt.Errorf("error parsing topic name, %w", err) } m.qos, err = meta.ParseIntWithRange("qos", 0, 0, 2) if err != nil { return metadata{}, fmt.Errorf("error parsing qos, %w", err) } return m, nil } <file_sep>package elastic import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.elasticsearch"). SetDescription("Elastic Search Target"). SetName("Elasticsearch"). SetProvider(""). SetCategory("Store"). SetTags("db", "logs"). AddProperty( common.NewProperty(). SetKind("string"). SetName("urls"). SetTitle("Connection URLs"). SetDescription("Set Elastic Search Urls"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Elastic Search username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Elastic Search password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("sniff"). SetTitle("Use Sniff"). SetDescription("Set Elastic Search sniff mode"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Elastic execution method"). SetOptions([]string{"get", "set", "delete", "index.exists", "index.create", "index.delete"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("index"). SetKind("string"). SetDescription("Select Elastic index"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("id"). SetKind("string"). SetDescription("Select Elastic document id"). SetMust(true), ) } <file_sep>package echo import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("echo"). SetDescription("target for echo each request"). SetName("Echo"). SetProvider(""). SetCategory("Testing") } <file_sep>package hazelcast import ( "fmt" "time" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultUsername = "" defaultPassword = "" defaultUseSSL = false defaultServerName = "" defaultConnectionAttemptLimit = 1 defaultConnectionAttemptPeriod = 36000 defaultConnectionTimeout = 36000 ) type options struct { address string username string password string connectionAttemptLimit int32 connectionAttemptPeriod time.Duration connectionTimeout time.Duration ssl bool sslcertificatefile string sslcertificatekey string serverName string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.address, err = cfg.Properties.MustParseString("address") if err != nil { return options{}, fmt.Errorf("error parsing address, %w", err) } o.username = cfg.Properties.ParseString("username", defaultUsername) o.password = cfg.Properties.ParseString("password", <PASSWORD>) connectionAttemptLimit, err := cfg.Properties.ParseIntWithRange("connection_attempt_limit", defaultConnectionAttemptLimit, 0, 2147483647) if err != nil { return options{}, fmt.Errorf("error parsing connection_attempt_limit, %w", err) } o.connectionAttemptLimit = int32(connectionAttemptLimit) connectionAttemptPeriod, err := cfg.Properties.ParseIntWithRange("connection_attempt_period", defaultConnectionAttemptPeriod, 0, 2147483647) if err != nil { return options{}, fmt.Errorf("error parsing connection_attempt_period, %w", err) } o.connectionAttemptPeriod = time.Duration(connectionAttemptPeriod) * time.Millisecond connectionTimeout, err := cfg.Properties.ParseIntWithRange("connection_timeout", defaultConnectionTimeout, 0, 2147483647) if err != nil { return options{}, fmt.Errorf("error parsing connection_timeout, %w", err) } o.connectionTimeout = time.Duration(connectionTimeout) * time.Millisecond o.ssl = cfg.Properties.ParseBool("ssl", defaultUseSSL) o.sslcertificatefile = cfg.Properties.ParseString("cert_file", "") o.sslcertificatekey = cfg.Properties.ParseString("cert_key", "") o.serverName = cfg.Properties.ParseString("server_name", defaultServerName) return o, nil } <file_sep>package hdfs import ( "fmt" "os" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { method string filePath string oldFilePath string fileMode os.FileMode } var methodsMap = map[string]string{ "write_file": "write_file", "remove_file": "remove_file", "read_file": "read_file", "rename_file": "rename_file", "mkdir": "mkdir", "stat": "stat", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } m.filePath, err = meta.MustParseString("file_path") if err != nil { return metadata{}, fmt.Errorf("error parsing file_path, %w", err) } if m.method == "rename_file" { m.oldFilePath, err = meta.MustParseString("old_file_path") if err != nil { return metadata{}, fmt.Errorf("error parsing old_file_path, %w", err) } } m.fileMode = meta.ParseOSFileMode("file_mode", os.FileMode(0o755)) return m, nil } <file_sep>package firebase import ( "context" "encoding/json" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_db(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "db_client": "true", "db_url": dat.dbName, "auth_client": "false", "messaging_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) m := make(map[string]interface{}) m["some_key"] = "some_value" b, err := json.Marshal(m) require.NoError(t, err) m2 := make(map[string]interface{}) m2["some_key"] = "some_value_new" b2, err := json.Marshal(m2) require.NoError(t, err) k := "newValue1" bk1, err := json.Marshal(k) require.NoError(t, err) k2 := "newValue2" bk2, err := json.Marshal(k2) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "valid db-get", request: types.NewRequest(). SetMetadataKeyValue("method", "get_db"). SetMetadataKeyValue("ref_path", "test"), wantErr: false, }, { name: "valid db-set - no child ref", request: types.NewRequest(). SetMetadataKeyValue("method", "set_db"). SetMetadataKeyValue("ref_path", "test"). SetData(bk1), wantErr: false, }, { name: "valid db-set - child ref", request: types.NewRequest(). SetMetadataKeyValue("method", "set_db"). SetMetadataKeyValue("ref_path", "test"). SetMetadataKeyValue("child_ref", "test_child_ref"). SetData(bk2), wantErr: false, }, { name: "valid db-update- no child ref", request: types.NewRequest(). SetMetadataKeyValue("method", "update_db"). SetMetadataKeyValue("ref_path", "test"). SetData(b), wantErr: false, }, { name: "valid db-update - child ref ", request: types.NewRequest(). SetMetadataKeyValue("method", "update_db"). SetMetadataKeyValue("ref_path", "test"). SetMetadataKeyValue("child_ref", "test_child_ref"). SetData(b2), wantErr: false, }, { name: "valid db-update - child ref ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_db"). SetMetadataKeyValue("ref_path", "test"). SetMetadataKeyValue("child_ref", "test_child_ref"), wantErr: false, }, { name: "valid db-update - no child ref ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_db"). SetMetadataKeyValue("ref_path", "test"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) t.Logf("received response: %s for test: %s", r.Data, tt.name) }) } } <file_sep># Kubemq Athena Target Connector Kubemq Athena target connector allows services using kubemq server to access aws athena service. ## Prerequisites The following required to run the aws-athena target connector: - kubemq cluster - aws account with athena active service - kubemq-targets deployment ## Configuration athena target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-athena source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-athena" auth_token: "" channel: "query.aws.athena" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.athena name: aws-athena properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### List Catalogs list all catalogs List Catalogs: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_data_catalogs" | Example: ```json { "metadata": { "method": "list_data_catalogs" }, "data": null } ``` ### List Databases list all databases List Databases: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_databases" | | catalog | yes | aws athena catalog | "string" | Example: ```json { "metadata": { "method": "list_databases", "catalog": "my_catalog" }, "data": null } ``` ### Query create a query request return execution_id. Query: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "query" | | catalog | yes | aws athena catalog | "string" | | db | yes | aws athena db name | "string" | | output_location | yes | aws athena folder location | "string" | | query | yes | aws query to execute | "query" | Example: ```json { "metadata": { "method": "query", "catalog": "my_catalog", "db": "my_db", "output_location": "my_output_location/path", "query": "SELECT * FROM \"my_db\".\"new_table_name2\" limit 10;" }, "data": null } ``` ### Get Query Result get Query result by execution_id that return from Query result. Get Query Result: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:-------------------------------------------|:-------------------------------------------| | method | yes | type of method | "get_query_result" | | execution_id | yes | aws executionID that returned from query | "string" | Example: ```json { "metadata": { "method": "get_query_result", "execution_id": "123-456-789" }, "data": null } ``` <file_sep>package pubsub import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { topicID string tags map[string]string } func parseMetadata(meta types.Metadata, opts options) (metadata, error) { m := metadata{} m.tags = make(map[string]string) var err error m.topicID, err = meta.MustParseString("topic_id") if err != nil { return metadata{}, fmt.Errorf("error parsing topic_id, %w", err) } tags, err := meta.MustParseJsonMap("tags") if err != nil { return metadata{}, fmt.Errorf("error parsing tags, %w", err) } m.tags = tags return m, nil } <file_sep>//go:build container // +build container package main import ( "context" "flag" "fmt" "os" "os/signal" "syscall" "github.com/kubemq-io/kubemq-targets/api" "github.com/kubemq-io/kubemq-targets/binding" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" ) var version = "" var ( log *logger.Logger configFile = flag.String("config", "config.yaml", "set config file name") ) func run() error { gracefulShutdown := make(chan os.Signal, 1) signal.Notify(gracefulShutdown, syscall.SIGTERM) signal.Notify(gracefulShutdown, syscall.SIGINT) signal.Notify(gracefulShutdown, syscall.SIGQUIT) configCh := make(chan *config.Config) cfg, err := config.Load(configCh) if err != nil { return err } err = cfg.Validate() if err != nil { return err } ctx, cancel := context.WithCancel(context.Background()) defer cancel() bindingsService, err := binding.New() if err != nil { return err } err = bindingsService.Start(ctx, cfg) if err != nil { return err } apiServer, err := api.Start(ctx, cfg.ApiPort, bindingsService) if err != nil { return err } for { select { case newConfig := <-configCh: err = newConfig.Validate() if err != nil { return fmt.Errorf("error on validation new config file: %s", err.Error()) } bindingsService.Stop() err = bindingsService.Start(ctx, newConfig) if err != nil { return fmt.Errorf("error on restarting service with new config file: %s", err.Error()) } if apiServer != nil { err = apiServer.Stop() if err != nil { return fmt.Errorf("error on shutdown api server: %s", err.Error()) } } apiServer, err = api.Start(ctx, newConfig.ApiPort, bindingsService) if err != nil { return fmt.Errorf("error on start api server: %s", err.Error()) } case <-gracefulShutdown: _ = apiServer.Stop() bindingsService.Stop() return nil } } } func main() { log = logger.NewLogger("kubemq-targets") flag.Parse() config.SetConfigFile(*configFile) log.Infof("starting kubemq targets connectors version: %s", version) if err := run(); err != nil { log.Error(err) os.Exit(1) } } <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } dat, err := ioutil.ReadFile("./credentials/aws/athena/db.txt") if err != nil { log.Fatal(err) } db := string(dat) dat, err = ioutil.ReadFile("./credentials/aws/athena/catalog.txt") if err != nil { log.Fatal(err) } catalog := string(dat) dat, err = ioutil.ReadFile("./credentials/aws/athena/query.txt") if err != nil { log.Fatal(err) } query := string(dat) dat, err = ioutil.ReadFile("./credentials/aws/athena/outputLocation.txt") if err != nil { log.Fatal(err) } outputLocation := string(dat) // query Request queryRequest := types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("db", db). SetMetadataKeyValue("output_location", outputLocation). SetMetadataKeyValue("catalog", catalog). SetMetadataKeyValue("query", query) queryResponse, err := client.SetQuery(queryRequest.ToQuery()). SetChannel("query.aws.athena"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } qryResponse, err := types.ParseResponse(queryResponse.Body) if err != nil { log.Fatal(err) } executionCode := qryResponse.Metadata["execution_id"] log.Println(fmt.Sprintf("qry executed, executionCode: %s", executionCode)) // Give query time to end time.Sleep(2 * time.Second) // get query result getResultRequest := types.NewRequest(). SetMetadataKeyValue("method", "get_query_result"). SetMetadataKeyValue("execution_id", executionCode) getResult, err := client.SetQuery(getResultRequest.ToQuery()). SetChannel("query.aws.athena"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(getResult.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get resoponse %v, error: %v", getResponse.Data, getResponse.IsError)) } <file_sep>package rethinkdb import ( "context" "encoding/json" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init - valid", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, wantErr: false, }, { name: "invalid init - invalid host", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28016", "username": "root", "password": "<PASSWORD>", }, }, wantErr: true, }, { name: "invalid init - invalid user", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "fake", "password": "<PASSWORD>", }, }, wantErr: true, }, { name: "invalid init - invalid password", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "fake", "password": "<PASSWORD>", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSetErr %v", err, tt.wantErr) return } }) } } func TestClient_Insert(t *testing.T) { args := make(map[string]interface{}) args["id"] = "test_user" args["password"] = 1 insert, err := json.Marshal(args) require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid insert request", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "insert"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("table", "test"). SetData(insert), }, { name: "invalid insert request - missing db name", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "insert"). SetMetadataKeyValue("table", "test"). SetData(insert), wantErr: true, }, { name: "invalid insert request - missing table name", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "insert"). SetMetadataKeyValue("db_name", "test"). SetData(insert), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) response, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) }) } } func TestClient_Update(t *testing.T) { args := make(map[string]interface{}) args["id"] = "test_user" args["password"] = 2 update, err := json.Marshal(args) require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid update request", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "update"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "test_user"). SetMetadataKeyValue("table", "test"). SetData(update), }, { name: "invalid update request missing data", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "update"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "test_user"). SetMetadataKeyValue("table", "test"), wantErr: true, }, { name: "invalid update request missing table", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "update"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "test_user"). SetData(update), wantErr: true, }, { name: "invalid update request missing db", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "update"). SetMetadataKeyValue("key", "test_user"). SetMetadataKeyValue("table", "test"). SetData(update), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) response, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) }) } } func TestClient_Get(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid get request", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "test_user"). SetMetadataKeyValue("table", "test"), }, { name: "invalid get request - missing db_name", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "test_user"). SetMetadataKeyValue("table", "test"), wantErr: true, }, { name: "invalid get request - missing table", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "test_user"), wantErr: true, }, { name: "invalid get request - missing key does not exists", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "fake_key"). SetMetadataKeyValue("table", "test"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) response, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) }) } } func TestClient_Delete(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid delete request", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "test_user"). SetMetadataKeyValue("table", "test"), }, { name: "invalid delete request - missing db", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", "test_user"). SetMetadataKeyValue("table", "test"), wantErr: true, }, { name: "invalid delete request - missing table", cfg: config.Spec{ Name: "stores-rethinkdb", Kind: "stores.rethinkdb", Properties: map[string]string{ "host": "localhost:28015", "username": "root", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("db_name", "test"). SetMetadataKeyValue("key", "test_user"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) response, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, response) }) } } <file_sep>package keyspaces import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.keyspaces"). SetDescription("AWS Keyspaces Target"). SetName("Keyspaces"). SetProvider("AWS"). SetCategory("Store"). SetTags("cassandra", "db", "no-sql", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("hosts"). SetTitle("Hosts Addresses"). SetDescription("Set Keyspaces hosts addresses"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("port"). SetDescription("Set Keyspaces port"). SetMust(true). SetMin(0). SetMax(65535). SetDefault("9142"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Keyspaces username"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Keyspaces password"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("tls"). SetTitle("TLS"). SetDescription("Set Keyspaces tls download url"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("replication_factor"). SetDescription("Set Keyspaces replication factor"). SetMust(false). SetDefault("1"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("proto_version"). SetDescription("Set Keyspaces protoVersion"). SetMust(false). SetDefault("4"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("consistency"). SetDescription("Set Keyspaces consistency"). SetMust(true). SetOptions([]string{"One", "LocalQuorum", "local_one"}). SetDefault("LocalQuorum"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_table"). SetDescription("Set Keyspaces default table"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_keyspace"). SetDescription("Set Keyspaces default keyspace"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connect_timeout_seconds"). SetTitle("Connect Timeout (Seconds)"). SetDescription("Set Keyspaces connection timeout in seconds"). SetMust(false). SetDefault("60"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("timeout_seconds"). SetTitle("Operation Timeout (Seconds)"). SetDescription("Set Keyspaces operation timeout in seconds"). SetMust(false). SetDefault("60"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Keyspaces execution method"). SetOptions([]string{"get", "set", "delete", "query", "exec"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("consistency"). SetDescription("Set Keyspaces consistency Level"). SetOptions([]string{"strong", "eventual", ""}). SetDefault("strong"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Keyspaces key to set get or delete"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("table"). SetKind("string"). SetDescription("Keyspaces table name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("keyspace"). SetKind("string"). SetDescription("Keyspaces keyspace data container name"). SetDefault(""). SetMust(false), ) } <file_sep>package storage import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "upload": "upload", "create_bucket": "create_bucket", "download": "download", "delete": "delete", "rename": "rename", "copy": "copy", "move": "move", "list": "list", } type metadata struct { method string object string renameObject string bucket string dstBucket string path string projectID string storageClass string location string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "create_bucket" { m.bucket, err = meta.MustParseString("bucket") if err != nil { return metadata{}, fmt.Errorf("bucket is required for method:%s , error on parsing bucket, %w", m.method, err) } m.projectID, err = meta.MustParseString("project_id") if err != nil { return metadata{}, fmt.Errorf("project_id is required for method:%s, error on project_id, %w", m.method, err) } m.storageClass, err = meta.MustParseString("storage_class") if err != nil { return metadata{}, fmt.Errorf("storage_class is required for method:%s, error on storage_class, %w", m.method, err) } m.location, err = meta.MustParseString("location") if err != nil { return metadata{}, fmt.Errorf("location is required for method:%s, error on location, %w", m.method, err) } } if m.method == "upload" || m.method == "download" || m.method == "delete" || m.method == "rename" || m.method == "copy" || m.method == "move" { m.object, err = meta.MustParseString("object") if err != nil { return metadata{}, fmt.Errorf("object is required for method:%s, error on parsing upload, %w", m.method, err) } m.bucket, err = meta.MustParseString("bucket") if err != nil { return metadata{}, fmt.Errorf("bucket is required for method:%s, error on parsing bucket, %w", m.method, err) } if m.method == "upload" { m.path, err = meta.MustParseString("path") if err != nil { return metadata{}, fmt.Errorf("path is required for method:%s,error on path, %w", m.method, err) } } else if m.method == "rename" || m.method == "copy" || m.method == "move" { m.renameObject, err = meta.MustParseString("rename_object") if err != nil { return metadata{}, fmt.Errorf("rename_object is required for method:%s,error on rename_object, %w", m.method, err) } if m.method == "copy" || m.method == "move" { m.dstBucket, err = meta.MustParseString("dst_bucket") if err != nil { return metadata{}, fmt.Errorf("dst_bucket is required for method:%s,error on dst_bucket, %w", m.method, err) } } } } if m.method == "list" { m.bucket, err = meta.MustParseString("bucket") if err != nil { return metadata{}, fmt.Errorf("bucket is required for method:%s,error on parsing bucket, %w", m.method, err) } } return m, nil } <file_sep>package msk import ( "github.com/kubemq-io/kubemq-targets/config" ) const ( DefaultSaslUsername = "" DefaultSaslPassword = "" ) type options struct { brokers []string topic string saslUsername string saslPassword string } func parseOptions(cfg config.Spec) (options, error) { m := options{} var err error m.brokers, err = cfg.Properties.MustParseStringList("brokers") if err != nil { return m, err } m.topic, err = cfg.Properties.MustParseString("topic") if err != nil { return m, err } m.saslUsername = cfg.Properties.ParseString("saslUsername", DefaultSaslUsername) m.saslPassword = cfg.Properties.ParseString("saslPassword", DefaultSaslPassword) return m, nil } <file_sep>package files import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultRetryRequests = 1 DefaultRangeSize = 4194304 DefaultFileSize = 1000000 DefaultParallelism = 16 DefaultCount = 0 DefaultOffset = 0 ) var methodsMap = map[string]string{ "upload": "upload", "get": "get", "delete": "delete", "create": "create", } type metadata struct { method string serviceUrl string rangeSize int64 parallelism uint16 offset int64 count int64 size int64 maxRetryRequests int fileMetadata map[string]string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } m.serviceUrl, err = meta.MustParseString("service_url") if err != nil { return metadata{}, fmt.Errorf("error parsing service_url , %w", err) } fileMetadata, err := meta.MustParseJsonMap("file_metadata") if err != nil { return metadata{}, fmt.Errorf("error parsing file_metadata, %w", err) } else { m.fileMetadata = fileMetadata } m.rangeSize = int64(meta.ParseInt("range_size", DefaultRangeSize)) m.parallelism = uint16(meta.ParseInt("parallelism", DefaultParallelism)) m.count = int64(meta.ParseInt("count", DefaultCount)) m.offset = int64(meta.ParseInt("offset", DefaultOffset)) m.maxRetryRequests = meta.ParseInt("max_retry_request", DefaultRetryRequests) m.size = int64(meta.ParseInt("file_size", DefaultFileSize)) return m, nil } <file_sep>package hdfs import ( "encoding/json" "os" "time" ) type Stat struct { Name string `json:"name"` Size int64 `json:"size"` ModTime time.Time `json:"mod_time"` IsDir bool `json:"is_dir"` } func createStatAsByteArray(o os.FileInfo) ([]byte, error) { s := Stat{ Name: o.Name(), Size: o.Size(), ModTime: o.ModTime(), IsDir: o.IsDir(), } b, err := json.Marshal(s) if err != nil { return nil, err } return b, err } <file_sep>package sns import ( "context" "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/sns" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *sns.SNS } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := sns.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "list_topics": return c.listTopics(ctx) case "list_subscriptions": return c.listSubscriptions(ctx) case "list_subscriptions_by_topic": return c.listSubscriptionsByTopic(ctx, meta) case "create_topic": return c.createTopic(ctx, meta, req.Data) case "delete_topic": return c.deleteTopic(ctx, meta) case "send_message": return c.sendingMessageToTopic(ctx, meta, req.Data) case "subscribe": return c.subscribeToTopic(ctx, meta, req.Data) default: return nil, errors.New("invalid method type") } } func (c *Client) listTopics(ctx context.Context) (*types.Response, error) { l, err := c.client.ListTopicsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(l) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listSubscriptions(ctx context.Context) (*types.Response, error) { l, err := c.client.ListSubscriptionsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(l) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listSubscriptionsByTopic(ctx context.Context, meta metadata) (*types.Response, error) { t, err := c.client.ListSubscriptionsByTopicWithContext(ctx, &sns.ListSubscriptionsByTopicInput{ TopicArn: aws.String(meta.topic), }) if err != nil { return nil, err } b, err := json.Marshal(t) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) createTopic(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { s := &sns.CreateTopicInput{ Name: aws.String(meta.topic), } if data != nil { a := make(map[string]*string) err := json.Unmarshal(data, &a) if err != nil { return nil, err } s.Attributes = a } r, err := c.client.CreateTopicWithContext(ctx, s) if err != nil { return nil, err } b, err := json.Marshal(r) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) subscribeToTopic(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { s := &sns.SubscribeInput{ TopicArn: aws.String(meta.topic), Endpoint: aws.String(meta.endPoint), Protocol: aws.String(meta.protocol), ReturnSubscriptionArn: aws.Bool(meta.returnSubscription), } if data != nil { a := make(map[string]*string) err := json.Unmarshal(data, &a) if err != nil { return nil, err } s.Attributes = a } r, err := c.client.SubscribeWithContext(ctx, s) if err != nil { return nil, err } b, err := json.Marshal(r) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) sendingMessageToTopic(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { m, err := c.createSNSMessage(meta, data) if err != nil { return nil, err } r, err := c.client.PublishWithContext(ctx, m) if err != nil { return nil, err } b, err := json.Marshal(r) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) deleteTopic(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.DeleteTopicWithContext(ctx, &sns.DeleteTopicInput{ TopicArn: aws.String(meta.topic), }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return nil } <file_sep>package spanner import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { db string query string tableName string cred string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/querySpanner.txt") if err != nil { return nil, err } t.query = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/dbSpanner.txt") if err != nil { return nil, err } t.db = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/tableName.txt") if err != nil { return nil, err } t.tableName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") if err != nil { return nil, err } t.cred = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, "credentials": dat.cred, }, }, wantErr: false, }, { name: "invalid init - missing db", cfg: config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "credentials": dat.cred, }, }, wantErr: true, }, { name: "invalid init - missing credentials", cfg: config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } defer func() { _ = c.Stop() }() require.NoError(t, err) }) } } func TestClient_Query(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, "credentials": dat.cred, }, } tests := []struct { name string queryRequest *types.Request wantErr bool }{ { name: "valid query", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("query", dat.query), wantErr: false, }, { name: "invalid query - missing query", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"), wantErr: true, }, { name: "invalid query- missing method", queryRequest: types.NewRequest(). SetMetadataKeyValue("query", dat.query), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Read(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) columnNames := []string{"id", "name"} b, err := json.Marshal(columnNames) require.NoError(t, err) cfg := config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, "credentials": dat.cred, }, } tests := []struct { name string queryRequest *types.Request wantErr bool }{ { name: "valid read", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "read"). SetMetadataKeyValue("table_name", dat.tableName). SetData(b), wantErr: false, }, { name: "invalid read - missing data", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "read"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "invalid read - missing table_name", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "read"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Insert(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) values := make([]interface{}, 0) values = append(values, 17, "name1") firstInsUpd := InsertOrUpdate{dat.tableName, []string{"id", "name"}, values, []string{"INT64", "STRING"}} values = make([]interface{}, 0) values = append(values, 18, "name2") scnInsUpd := InsertOrUpdate{dat.tableName, []string{"id", "name"}, values, []string{"INT64", "STRING"}} var inputs []InsertOrUpdate cfg := config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, "credentials": dat.cred, }, } inputs = append(inputs, firstInsUpd, scnInsUpd) bSchema, err := json.Marshal(inputs) require.NoError(t, err) tests := []struct { name string queryRequest *types.Request wantErr bool }{ { name: "valid insert", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "insert"). SetData(bSchema), wantErr: false, }, { name: "invalid insert - missing data", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "insert"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Update(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) values := make([]interface{}, 0) values = append(values, 17, "name3") firstInsUpd := InsertOrUpdate{dat.tableName, []string{"id", "name"}, values, []string{"INT64", "STRING"}} values = make([]interface{}, 0) values = append(values, 18, "name4") scnInsUpd := InsertOrUpdate{dat.tableName, []string{"id", "name"}, values, []string{"INT64", "STRING"}} var inputs []InsertOrUpdate cfg := config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, "credentials": dat.cred, }, } inputs = append(inputs, firstInsUpd, scnInsUpd) bSchema, err := json.Marshal(inputs) require.NoError(t, err) tests := []struct { name string queryRequest *types.Request wantErr bool }{ { name: "valid update", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "update"). SetData(bSchema), wantErr: false, }, { name: "invalid update - missing data", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "update"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_UpdateDatabaseDdl(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) var statements []string statements = append(statements, "mystatment") cfg := config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, "credentials": dat.cred, }, } bSchema, err := json.Marshal(statements) require.NoError(t, err) tests := []struct { name string queryRequest *types.Request wantErr bool }{ { name: "valid UpdateDatabaseDdl", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "update_database_ddl"). SetData(bSchema), wantErr: false, }, { name: "invalid InsertOrUpdate - missing data", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "update_database_ddl"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 35*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_InsertOrUpdate(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) values := make([]interface{}, 0) values = append(values, 19, "name5") firstInsUpd := InsertOrUpdate{dat.tableName, []string{"id", "name"}, values, []string{"INT64", "STRING"}} values = make([]interface{}, 0) values = append(values, 20, "name6") scnInsUpd := InsertOrUpdate{dat.tableName, []string{"id", "name"}, values, []string{"INT64", "STRING"}} var inputs []InsertOrUpdate cfg := config.Spec{ Name: "gcp-spanner", Kind: "gcp.spanner", Properties: map[string]string{ "db": dat.db, "credentials": dat.cred, }, } inputs = append(inputs, firstInsUpd, scnInsUpd) bSchema, err := json.Marshal(inputs) require.NoError(t, err) tests := []struct { name string queryRequest *types.Request wantErr bool }{ { name: "valid InsertOrUpdate", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "insert_or_update"). SetData(bSchema), wantErr: false, }, { name: "invalid InsertOrUpdate - missing data", queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "insert_or_update"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) defer func() { err = c.Stop() require.NoError(t, err) }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } <file_sep># Kubemq kinesis target Connector Kubemq kinesis target connector allows services using kubemq server to access aws kinesis service. ## Prerequisites The following required to run the aws-kinesis target connector: - kubemq cluster - aws account with kinesis active service - kubemq-targets deployment ## Configuration sns target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-kinesis source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-kinesis" auth_token: "" channel: "query.aws.kinesis" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.kinesis name: aws-kinesis properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### List Streams list kinesis streams List Streams: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_streams" | Example: ```json { "metadata": { "method": "list_streams" }, "data": null } ``` ### List Stream Consumers list kinesis Stream Consumers. List Stream Consumers: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_stream_consumers" | | stream_arn | yes | aws stream arn of the desired stream | "arn::mystream" | Example: ```json { "metadata": { "method": "list_stream_consumers", "stream_arn": "arn::mystream" }, "data": null } ``` ### Create Stream Create a kinesis Stream. Create Stream: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_stream" | | stream_name | yes | aws stream name as string | "string" | | shard_count | no | number of shards to create (default 1) | "1" | Example: ```json { "metadata": { "method": "create_stream", "stream_name": "my_stream", "shard_count": "1" }, "data": null } ``` ### List Shards list stream Shards . List Shards: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_shards" | | stream_name | yes | aws stream name as string | "string" | Example: ```json { "metadata": { "method": "list_shards", "stream_name": "my_stream" }, "data": null } ``` ### Get Shard Iterator Get Shard Iterator used to preform get data . Get Shard Iterator: | Metadata Key | Required | Description | Possible values | |:--------------------------|:---------|:-----------------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "get_shard_iterator" | | stream_name | yes | aws stream name as string | "string" | | shard_iterator_type | yes | aws shard iterator type | see https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html | | shard_id | yes | aws shard full id (can be acquired using list shard) | see https://docs.aws.amazon.com/kinesis/latest/APIReference/API_GetShardIterator.html | Example: ```json { "metadata": { "method": "get_shard_iterator", "shard_iterator_type": "LATEST", "stream_name": "my_stream", "shard_id": "8619-AWE1" }, "data": null } ``` ### Put Record Send data to stream . Put Record: | Metadata Key | Required | Description | Possible values | |:--------------------------|:---------|:-----------------------------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "put_record" | | stream_name | yes | aws stream name as string | "string" | | partition_key | yes | determines which shard in the stream the data record is assigned to. | see https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html | | data | yes | Message to send to stream | string | Example: ```json { "metadata": { "method": "put_record", "partition_key": "0356", "stream_name": "my_stream" }, "data": "eyJteV9yZXN1bHQiOiJvayJ9" } ``` ### Put Records Send multi data to a stream . Put Records: | Metadata Key | Required | Description | Possible values | |:--------------------------|:---------|:-----------------------------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "put_records" | | stream_name | yes | aws stream name as string | "string" | | data | yes | Key value pair of partition_key(string) and message([]byte) | key value of partition_key and message as key value pair https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html| Example: ```json { "metadata": { "method": "put_records", "stream_name": "my_stream" }, "data": "<KEY> } ``` ### Put Records Send multi data to a stream . Put Records: | Metadata Key | Required | Description | Possible values | |:--------------------------|:---------|:-----------------------------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "put_records" | | stream_name | yes | aws stream name as string | "string" | | data | yes | Key value pair of partition_key(string) and message([]byte) | key value of partition_key and message as key value pair https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html| Example: ```json { "metadata": { "method": "put_records", "stream_name": "my_stream" }, "data": "<KEY> } ``` ### Get Records Get multi data from a stream . Get Records: | Metadata Key | Required | Description | Possible values | |:--------------------------|:---------|:-----------------------------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "get_records" | | stream_name | yes | aws stream name as string | "string" | | limit | no | Number of limit message to get (default "1") | "int value"| Example: ```json { "metadata": { "method": "put_records", "stream_name": "my_stream", "limit": "1" }, "data": null } ``` <file_sep>package firebase import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/stretchr/testify/require" ) type testStructure struct { projectID string dbName string cred string token string uid string uid2 string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/firebaseDBName.txt") if err != nil { return nil, err } t.dbName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/projectID.txt") if err != nil { return nil, err } t.projectID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") if err != nil { return nil, err } t.cred = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/token.txt") if err != nil { return nil, err } t.token = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/uid.txt") if err != nil { return nil, err } t.uid = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/uid2.txt") if err != nil { return nil, err } t.uid2 = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init - db client", cfg: config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "db_url": dat.dbName, "db_client": "true", }, }, wantErr: false, }, { name: "init - auth client", cfg: config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", }, }, wantErr: false, }, { name: "init - multiclient", cfg: config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "db_url": dat.dbName, "auth_client": "true", "db_client": "true", }, }, wantErr: false, }, { name: "init-firebase-project-id - missing project_id", cfg: config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "credentials": dat.cred, "auth_client": "true", "db_client": "true", }, }, wantErr: true, }, { name: "init-firebase-instance missing credentials", cfg: config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "auth_client": "true", "db_client": "true", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } <file_sep>package mqtt import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "messaging.mqtt", Kind: "messaging.mqtt", Properties: map[string]string{ "host": "localhost:1883", "username": "", "password": "", "client_id": "", }, }, wantErr: false, }, { name: "init - bad host", cfg: config.Spec{ Name: "messaging.mqtt", Kind: "messaging.mqtt", Properties: map[string]string{ "host": "localhost:6000", "username": "", "password": "", "client_id": "", }, }, wantErr: true, }, { name: "init - no host", cfg: config.Spec{ Name: "messaging.mqtt", Kind: "messaging.mqtt", Properties: map[string]string{ "username": "", "password": "", "client_id": "", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantExecErr %v", err, tt.wantErr) return } }) } } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantResponse *types.Response wantErr bool }{ { name: "valid publish request with confirmation", cfg: config.Spec{ Name: "messaging.mqtt", Kind: "messaging.mqtt", Properties: map[string]string{ "host": "localhost:1883", "username": "", "password": "", "client_id": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("topic", "some-queue"). SetMetadataKeyValue("qos", "0"). SetData([]byte("some-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantErr: false, }, { name: "invalid publish request - no topic", cfg: config.Spec{ Name: "messaging.mqtt", Kind: "messaging.mqtt", Properties: map[string]string{ "host": "localhost:1883", "username": "", "password": "", "client_id": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("qos", "0"). SetData([]byte("some-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantErr: true, }, { name: "invalid publish request - bad qos", cfg: config.Spec{ Name: "messaging.mqtt", Kind: "messaging.mqtt", Properties: map[string]string{ "host": "localhost:1883", "username": "", "password": "", "client_id": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("topic", "some-queue"). SetMetadataKeyValue("qos", "-1"). SetData([]byte("some-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotResponse, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotResponse) require.EqualValues(t, tt.wantResponse, gotResponse) }) } } <file_sep>package rabbitmq import ( "context" "crypto/tls" "crypto/x509" "fmt" "strings" "sync" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "github.com/streadway/amqp" ) type Client struct { sync.Mutex log *logger.Logger opts options channel *amqp.Channel conn *amqp.Connection isConnected bool } func New() *Client { return &Client{ opts: options{}, channel: nil, } } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } if err := c.connect(); err != nil { return err } return nil } func (c *Client) getTLSConfig() (*tls.Config, error) { tlsCfg := &tls.Config{ InsecureSkipVerify: c.opts.insecure, } if c.opts.insecure { c.log.Infof("Rabbitmq connection is configured to skip certificate verification") } if c.opts.caCert != "" { caCertPool := x509.NewCertPool() if !caCertPool.AppendCertsFromPEM([]byte(c.opts.caCert)) { return nil, fmt.Errorf("error loading Root CA Cert") } tlsCfg.RootCAs = caCertPool c.log.Infof("TLS CA Cert Loaded for RabbitMQ Connection") } return tlsCfg, nil } func (c *Client) connect() error { if strings.HasPrefix(c.opts.url, "amqps://") { tlsCfg, err := c.getTLSConfig() if err != nil { return err } c.conn, err = amqp.DialTLS(c.opts.url, tlsCfg) if err != nil { return fmt.Errorf("error dialing rabbitmq, %w", err) } } else { var err error c.conn, err = amqp.Dial(c.opts.url) if err != nil { return fmt.Errorf("error dialing rabbitmq, %w", err) } } var err error c.channel, err = c.conn.Channel() if err != nil { _ = c.conn.Close() return fmt.Errorf("error getting rabbitmq channel, %w", err) } c.isConnected = true return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, ok := c.opts.defaultMetadata() if !ok { var err error meta, err = parseMetadata(req.Metadata) if err != nil { return nil, err } } return c.Publish(ctx, meta, req.Data) } func (c *Client) Publish(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { c.Lock() defer c.Unlock() if !c.isConnected { if err := c.connect(); err != nil { return nil, err } } msg := meta.amqpMessage(data) err := c.channel.Publish(meta.exchange, meta.queue, meta.mandatory, meta.immediate, msg) if err != nil { c.isConnected = false return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.channel != nil { return c.channel.Close() } return nil } <file_sep>package nats import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultUsername = "" defaultPassword = "" defaultToken = "" defaultUseTLS = false defaultSSL = "" defaultTimeout = 100 ) type options struct { url string username string password string token string tls bool certFile string certKey string timeout int } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.url, err = cfg.Properties.MustParseString("url") if err != nil { return options{}, fmt.Errorf("error parsing url, %w", err) } o.username = cfg.Properties.ParseString("username", defaultUsername) o.password = cfg.Properties.ParseString("password", <PASSWORD>Password) o.token = cfg.Properties.ParseString("token", defaultToken) o.tls = cfg.Properties.ParseBool("tls", defaultUseTLS) o.certFile = cfg.Properties.ParseString("cert_file", defaultSSL) o.certKey = cfg.Properties.ParseString("cert_key", defaultSSL) o.timeout = cfg.Properties.ParseInt("timeout", defaultTimeout) if err != nil { return options{}, fmt.Errorf("error parsing timeout , %w", err) } return o, nil } <file_sep>package servicebus import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { connectionString string queueName string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error endPoint, err := cfg.Properties.MustParseString("end_point") if err != nil { return options{}, fmt.Errorf("error parsing end_point , %w", err) } sharedAccessKeyName, err := cfg.Properties.MustParseString("shared_access_key_name") if err != nil { return options{}, fmt.Errorf("error parsing shared_access_key_name , %w", err) } sharedAccessKey, err := cfg.Properties.MustParseString("shared_access_key") if err != nil { return options{}, fmt.Errorf("error parsing shared_access_key , %w", err) } o.connectionString = fmt.Sprintf("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s", endPoint, sharedAccessKeyName, sharedAccessKey) o.queueName, err = cfg.Properties.MustParseString("queue_name") if err != nil { return options{}, fmt.Errorf("error parsing queue_name , %w", err) } return o, nil } <file_sep>package eventhubs import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { connectionString string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error endPoint, err := cfg.Properties.MustParseString("end_point") if err != nil { return options{}, fmt.Errorf("error parsing end_point , %w", err) } sharedAccessKeyName, err := cfg.Properties.MustParseString("shared_access_key_name") if err != nil { return options{}, fmt.Errorf("error parsing shared_access_key_name , %w", err) } sharedAccessKey, err := cfg.Properties.MustParseString("shared_access_key") if err != nil { return options{}, fmt.Errorf("error parsing shared_access_key , %w", err) } entityPath, err := cfg.Properties.MustParseString("entity_path") if err != nil { return options{}, fmt.Errorf("error parsing entity_path , %w", err) } o.connectionString = fmt.Sprintf("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s", endPoint, sharedAccessKeyName, sharedAccessKey, entityPath) return o, nil } <file_sep>package storage import ( "context" "encoding/json" "errors" "fmt" "io" "io/ioutil" "os" "cloud.google.com/go/storage" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/iterator" "google.golang.org/api/option" ) type Client struct { log *logger.Logger opts options client *storage.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) client, err := storage.NewClient(ctx, option.WithCredentialsJSON(b)) if err != nil { return err } c.client = client return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "upload": return c.upload(ctx, meta) case "download": return c.download(ctx, meta) case "delete": return c.delete(ctx, meta) case "list": return c.list(ctx, meta) case "rename": return c.rename(ctx, meta) case "copy": return c.copy(ctx, meta) case "move": return c.move(ctx, meta) case "create_bucket": return c.createBucket(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) createBucket(ctx context.Context, meta metadata) (*types.Response, error) { bucket := c.client.Bucket(meta.bucket) if err := bucket.Create(ctx, meta.projectID, &storage.BucketAttrs{ StorageClass: meta.storageClass, Location: meta.location, }); err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) upload(ctx context.Context, meta metadata) (*types.Response, error) { f, err := os.Open(meta.path) if err != nil { return nil, err } defer f.Close() wc := c.client.Bucket(meta.bucket).Object(meta.object).NewWriter(ctx) if _, err = io.Copy(wc, f); err != nil { return nil, err } if err := wc.Close(); err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) download(ctx context.Context, meta metadata) (*types.Response, error) { rc, err := c.client.Bucket(meta.bucket).Object(meta.object).NewReader(ctx) if err != nil { return nil, err } data, err := ioutil.ReadAll(rc) if err != nil { return nil, fmt.Errorf("ioutil.ReadAll: %v", err) } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(data), nil } func (c *Client) delete(ctx context.Context, meta metadata) (*types.Response, error) { err := c.client.Bucket(meta.bucket).Object(meta.object).Delete(ctx) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) list(ctx context.Context, meta metadata) (*types.Response, error) { it := c.client.Bucket(meta.bucket).Objects(ctx, nil) var attrs []*storage.ObjectAttrs for { attr, err := it.Next() if err == iterator.Done { break } if err != nil { return nil, err } attrs = append(attrs, attr) } if len(attrs) == 0 { return nil, fmt.Errorf("received 0 objects from list for bucket: %s", meta.bucket) } b, err := json.Marshal(attrs) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) rename(ctx context.Context, meta metadata) (*types.Response, error) { src := c.client.Bucket(meta.bucket).Object(meta.object) dst := c.client.Bucket(meta.bucket).Object(meta.renameObject) if _, err := dst.CopierFrom(src).Run(ctx); err != nil { return nil, err } if err := src.Delete(ctx); err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) copy(ctx context.Context, meta metadata) (*types.Response, error) { src := c.client.Bucket(meta.bucket).Object(meta.object) dst := c.client.Bucket(meta.dstBucket).Object(meta.renameObject) if _, err := dst.CopierFrom(src).Run(ctx); err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) move(ctx context.Context, meta metadata) (*types.Response, error) { src := c.client.Bucket(meta.bucket).Object(meta.object) dst := c.client.Bucket(meta.dstBucket).Object(meta.renameObject) if _, err := dst.CopierFrom(src).Run(ctx); err != nil { return nil, err } if err := src.Delete(ctx); err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return c.client.Close() } <file_sep>package mysql import ( "fmt" "math" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultMaxIdleConnections = 10 defaultMaxOpenConnections = 100 defaultConnectionMaxLifetimeSeconds = 3600 ) type options struct { connection string // maxIdleConnections sets the maximum number of connections in the idle connection pool maxIdleConnections int // maxOpenConnections sets the maximum number of open connections to the database. maxOpenConnections int // connectionMaxLifetimeSeconds sets the maximum amount of time a connection may be reused. connectionMaxLifetimeSeconds int } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.connection, err = cfg.Properties.MustParseString("connection") if err != nil { return options{}, fmt.Errorf("error parsing connection string, %w", err) } o.maxIdleConnections, err = cfg.Properties.ParseIntWithRange("max_idle_connections", defaultMaxIdleConnections, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing max_idle_connections value, %w", err) } o.maxOpenConnections, err = cfg.Properties.ParseIntWithRange("max_open_connections", defaultMaxOpenConnections, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing max_open_connections value, %w", err) } o.connectionMaxLifetimeSeconds, err = cfg.Properties.ParseIntWithRange("connection_max_lifetime_seconds", defaultConnectionMaxLifetimeSeconds, 1, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing connection_max_lifetime_seconds value, %w", err) } return o, nil } <file_sep>package mongodb import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "get_by_key": "get_by_key", "set_by_key": "set_by_key", "delete_by_key": "delete_by_key", "find": "find", "find_many": "find_many", "insert": "insert", "insert_many": "insert_many", "update": "update", "update_many": "update_many", "delete": "delete", "delete_many": "delete_many", "aggregate": "aggregate", "distinct": "distinct", } type metadata struct { method string key string filter map[string]interface{} fieldName string setUpsert bool } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.key = meta.ParseString("key", "") m.fieldName = meta.ParseString("field_name", "") m.filter, err = meta.MustParseInterfaceMap("filter") if err != nil { return metadata{}, fmt.Errorf("error parsing filter, %w", err) } m.setUpsert = meta.ParseBool("set_upsert", false) return m, nil } <file_sep># Kubemq ElasticSearch Target Connector Kubemq aws-elasticsearch target connector allows services using kubemq server to access aws elasticsearch service. ## Prerequisites The following required to run the aws-elasticsearch target connector: - kubemq cluster - aws account with elasticsearch active service -elastic service with an active domain - kubemq-targets deployment ## Configuration aws-elasticsearch target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-elasticsearch source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-elasticsearch-connector" auth_token: "" channel: "query.aws.elasticsearch" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.elasticsearch name: aws-elasticsearch properties: aws_key: "id" aws_secret_key: 'json' token: "" ``` ## Usage ### Sign Message Sign Message : | Metadata Key | Required | Description | Possible values | |:------------------|:-------------------------|:------------------------------------------------------------|:-------------------------------------------| | method | yes | type of HTTP method | "GET", "POST","PUT","DELETE","OPTIONS" | | region | yes | aws region associated with domain | "region" | | json | yes (unless "GET") | json body to send with the http request | "list" | | domain | yes | elastic domain to assign the request | "list" | | index | yes | name of the elastic index | "list" | | endpoint | yes | aws domain end point | "list" | | service | no(Default "es" | type of service | "list" | | id | yes | Message ID | "list" | Example: ```json { "metadata": { "method": "GET", "region": "us-west-2", "domain": "https://my-domain-12345asdfg.us-west-2.es.amazonaws.com", "index": "myindex", "endpoint": "https://my-domain-12345asdfg.us-west-2.es.amazonaws.com/my/end_point", "service": "es", "id": "123124" }, "data": null } ``` <file_sep>package firebase import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_customToken(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", "messaging_client": "false", "db_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "custom token -valid", request: types.NewRequest(). SetMetadataKeyValue("method", "custom_token"). SetMetadataKeyValue("token_id", "some-uid"), wantErr: false, }, { name: "custom token -valid - missing token", request: types.NewRequest(). SetMetadataKeyValue("method", "custom_token"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, r.Data) }) } } func TestClient_verifyToken(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", "messaging_client": "false", "db_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "verify_token -valid", request: types.NewRequest(). SetMetadataKeyValue("method", "verify_token"). SetMetadataKeyValue("token_id", dat.token), wantErr: false, }, { name: "verify_token -invalid missing token", request: types.NewRequest(). SetMetadataKeyValue("method", "verify_token"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, r.Data) }) } } <file_sep>package binding import "encoding/json" type Request struct { Binding string `json:"binding"` Payload json.RawMessage `json:"payload"` } <file_sep>package mongodb import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.mongodb"). SetDescription("MongoDB Target"). SetName("MongoDB"). SetProvider(""). SetCategory("Store"). SetTags("db", "no-sql"). AddProperty( common.NewProperty(). SetKind("string"). SetName("host"). SetTitle("Host address"). SetDescription("Set MongoDB host address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set MongoDB username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set MongoDB password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("database"). SetDescription("Set MongoDB database"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("collection"). SetDescription("Set MongoDB collection"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("params"). SetDescription("Set MongoDB params"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("read_concurrency"). SetDescription("Set MongoDB read concurrency"). SetOptions([]string{"local", "majority", "available", "linearizable", "snapshot"}). SetMust(false). SetDefault("local"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("write_concurrency"). SetDescription("Set MongoDB write concurrency"). SetOptions([]string{"majority", "Other"}). SetMust(false). SetDefault("majority"), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("operation_timeout_seconds"). SetTitle("Operation Timeout (Seconds)"). SetDescription("Set MongoDB operation timeout seconds"). SetMust(false). SetDefault("90"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set MongoDB execution method"). SetOptions([]string{ "get_by_key", "set_by_key", "delete_by_key", "find", "find_many", "insert", "insert_many", "update", "update_many", "delete_one", "delete_many", "aggregate", "distinct", }). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Set MongoDB key"). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("filter"). SetKind("string"). SetDescription("Set filter"). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("set_upsert"). SetKind("bool"). SetDescription("Set Upsert in update mode"). SetMust(false), ) } <file_sep>package sns import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.sns"). SetDescription("AWS SNS Target"). SetName("SNS"). SetProvider("AWS"). SetCategory("Messaging"). SetTags("pub/sub", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set SNS aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set SNS aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set SNS aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set SNS token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set SNS execution method"). SetOptions([]string{"list_topics", "list_subscriptions", "list_subscriptions_by_topic", "create_topic", "subscribe", "send_message", "delete_topic"}). SetDefault("send_message"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("topic"). SetKind("string"). SetDescription("Set SNS topic"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("end_point"). SetKind("string"). SetDescription("Set SNS end point"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("bool"). SetName("return_subscription"). SetDescription("Set SNS return subscription"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("target_arn"). SetDescription("Set SNS target arn"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("message"). SetDescription("Set SNS message"). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("phone_number"). SetDescription("Set SNS phone number"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("subject"). SetDescription("Set SNS subject"). SetMust(false). SetDefault(""), ) } <file_sep>package storage import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { object string renameObject string bucket string dstBucket string filePath string projectID string storageClass string location string cred string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/storage/object.txt") if err != nil { return nil, err } t.object = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/storage/renameObject.txt") if err != nil { return nil, err } t.renameObject = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/storage/bucket.txt") if err != nil { return nil, err } t.bucket = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/storage/dstBucket.txt") if err != nil { return nil, err } t.dstBucket = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/storage/filePath.txt") if err != nil { return nil, err } t.filePath = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/storage/projectID.txt") if err != nil { return nil, err } t.projectID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/storage/storage_class.txt") if err != nil { return nil, err } t.storageClass = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/storage/location.txt") if err != nil { return nil, err } t.location = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") if err != nil { return nil, err } t.cred = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, }, wantErr: false, }, { name: "invalid init - missing credentials", cfg: config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{}, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Create_Bucket(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("storage_class", dat.storageClass). SetMetadataKeyValue("project_id", dat.projectID). SetMetadataKeyValue("location", dat.location), wantErr: false, }, { name: "invalid create bucket - already exists", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("storage_class", dat.storageClass). SetMetadataKeyValue("project_id", dat.projectID). SetMetadataKeyValue("location", dat.location), wantErr: true, }, { name: "invalid create bucket - missing bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("storage_class", dat.storageClass). SetMetadataKeyValue("project_id", dat.projectID). SetMetadataKeyValue("location", dat.location), wantErr: true, }, { name: "invalid create bucket - missing storage class", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("project_id", dat.projectID). SetMetadataKeyValue("location", dat.location), wantErr: true, }, { name: "invalid create bucket - missing project_id", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("storage_class", dat.storageClass). SetMetadataKeyValue("location", dat.location), wantErr: true, }, { name: "invalid create bucket - missing location", request: types.NewRequest(). SetMetadataKeyValue("method", "create_bucket"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("storage_class", dat.storageClass). SetMetadataKeyValue("project_id", dat.projectID), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } err = c.client.Close() require.NoError(t, err) } func TestClient_Upload_Object(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid upload object", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("path", dat.filePath). SetMetadataKeyValue("object", dat.object), wantErr: false, }, { name: "invalid upload object - missing bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("path", dat.filePath). SetMetadataKeyValue("object", dat.object), wantErr: true, }, { name: "invalid upload object - bucket dont exists", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("bucket", "not-real-bucket"). SetMetadataKeyValue("path", dat.filePath). SetMetadataKeyValue("object", dat.object), wantErr: true, }, { name: "invalid upload object - missing file path", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object), wantErr: true, }, { name: "invalid upload object - incorrect file path", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("path", "not/real/path"). SetMetadataKeyValue("object", dat.object), wantErr: true, }, { name: "invalid upload object - missing object name", request: types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("path", dat.filePath), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) require.NoError(t, err) defer func() { err = c.client.Close() require.NoError(t, err) }() require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Delete_Object(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete object", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object), wantErr: false, }, { name: "invalid delete object - object already deleted", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object), wantErr: true, }, { name: "invalid delete object - object doesn't exist ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", "madeUpObject"), wantErr: true, }, { name: "invalid delete object - missing object ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("bucket", dat.bucket), wantErr: true, }, { name: "invalid delete object - missing bucket ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("object", "madeUpObject"), wantErr: true, }, { name: "invalid delete object - bucket does not exists ", request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("bucket", "madeup-123"). SetMetadataKeyValue("object", dat.object), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) defer func() { err = c.client.Close() require.NoError(t, err) }() require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Download_Object(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid download object", request: types.NewRequest(). SetMetadataKeyValue("method", "download"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object), wantErr: false, }, { name: "invalid download - missing bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "download"). SetMetadataKeyValue("object", dat.object), wantErr: true, }, { name: "invalid download object - bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "download"). SetMetadataKeyValue("bucket", "notreal-123"). SetMetadataKeyValue("object", dat.object), wantErr: true, }, { name: "invalid download object - missing object", request: types.NewRequest(). SetMetadataKeyValue("method", "download"). SetMetadataKeyValue("bucket", dat.bucket), wantErr: true, }, { name: "invalid download object - object does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "download"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", "not-real-object"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) defer func() { err = c.client.Close() require.NoError(t, err) }() require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.NotNil(t, gotSetResponse.Data) }) } } func TestClient_List_Object(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list object", request: types.NewRequest(). SetMetadataKeyValue("method", "list"). SetMetadataKeyValue("bucket", dat.bucket), wantErr: false, }, { name: "invalid list object - missing bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "list"), wantErr: true, }, { name: "invalid list object - bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "list"). SetMetadataKeyValue("bucket", "not-real-123"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) defer func() { err = c.client.Close() require.NoError(t, err) }() require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.NotNil(t, gotSetResponse.Data) }) } } func TestClient_Rename_Object(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid rename object", request: types.NewRequest(). SetMetadataKeyValue("method", "rename"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: false, }, { name: "invalid rename object - missing bucket name", request: types.NewRequest(). SetMetadataKeyValue("method", "rename"). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid rename object - bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "rename"). SetMetadataKeyValue("bucket", "bucket-not-real-123"). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid rename object - missing object", request: types.NewRequest(). SetMetadataKeyValue("method", "rename"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid rename object - object does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "rename"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", "object-not-exits-123"). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid rename object - missing rename object", request: types.NewRequest(). SetMetadataKeyValue("method", "rename"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", "object-not-exits-123"), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) defer func() { err = c.client.Close() require.NoError(t, err) }() require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Copy_Object(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid copy object- same bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("dst_bucket", dat.bucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: false, }, { name: "valid copy object- another bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("dst_bucket", dat.dstBucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: false, }, { name: "invalid copy object - missing origin bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("dst_bucket", dat.dstBucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid copy object - origin bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("dst_bucket", dat.dstBucket). SetMetadataKeyValue("bucket", "not-real-123"). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid copy object - missing dst bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid copy object - dst bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("dst_bucket", "not-real-123"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) defer func() { err = c.client.Close() require.NoError(t, err) }() require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Move_Object(t *testing.T) { dat, err := getTestStructure() cfg2 := config.Spec{ Name: "gcp-storage", Kind: "gcp.storage", Properties: map[string]string{ "credentials": dat.cred, }, } require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid move object ", request: types.NewRequest(). SetMetadataKeyValue("method", "move"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("dst_bucket", dat.dstBucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: false, }, { name: "invalid move object - missing origin bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("dst_bucket", dat.dstBucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid move object - origin bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("dst_bucket", dat.dstBucket). SetMetadataKeyValue("bucket", "not-real-123"). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid move object - missing dst bucket", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, { name: "invalid move object - dst bucket does not exists", request: types.NewRequest(). SetMetadataKeyValue("method", "copy"). SetMetadataKeyValue("dst_bucket", "not-real-123"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("object", dat.object). SetMetadataKeyValue("rename_object", dat.renameObject), wantErr: true, }, } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg2, nil) defer func() { err = c.client.Close() require.NoError(t, err) }() require.NoError(t, err) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } <file_sep>package cloudfunctions import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.cloudfunctions"). SetDescription("GCP Cloud Functions Target"). SetName("Cloud Functions"). SetProvider("GCP"). SetCategory("Serverless"). SetTags("faas", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("project_id"). SetTitle("Project ID"). SetDescription("Set GCP project ID"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("location_match"). SetDescription("Set Cloud Functions location match"). SetMust(false). SetDefault("true"), ). AddMetadata( common.NewMetadata(). SetName("name"). SetKind("string"). SetDescription("Set Cloud Functions name"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("project"). SetKind("string"). SetDescription("Set Cloud Functions project"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("location"). SetKind("string"). SetDescription("Set Cloud Functions location"). SetDefault(""). SetMust(false), ) } <file_sep># Kubemq bigtable target Connector Kubemq gcp-bigtable target connector allows services using kubemq server to access google bigtable server. ## Prerequisites The following required to run the gcp-bigtable target connector: - kubemq cluster - gcp-bigtable set up - kubemq-targets deployment ## Configuration bigtable target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | project_id | yes | gcp bigtable project_id | "<googleurl>/myproject" | | credentials | yes | gcp credentials files | "<google json credentials" | | instance | yes | bigtable instance name | "<bigtable instance name" | Example: ```yaml bindings: - name: kubemq-query-gcp-bigtable source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-bigtable-connector" auth_token: "" channel: "query.gcp.bigtable" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.bigtable name: gcp-bigtable properties: project_id: "id" credentials: 'json' instance: "instance" ``` ## Usage ### Create Column Family Create Column Family: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_column_family" | | column_family | yes | the column_family to create | "valid unique string" | | table_name | yes | the table name | "table name to assign the column family" | Example: ```json { "metadata": { "method": "create_column_family", "column_family": "valid_unique_string", "table_name": "valid_table_string" }, "data": null } ``` ### Create Table Create a table: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------------------------| | method | yes | type of method | "create_table" | | table_name | yes | the table name | "table name to delete or create" | Example: ```json { "metadata": { "method": "create_table", "table_name": "valid_table_string" }, "data": null } ``` ### Delete Table Delete the table: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------------------------| | method | yes | type of method | "delete_table" | | table_name | yes | the table name | "table name to delete or create" | Example: ```json { "metadata": { "method": "delete_table", "table_name": "valid_table_string" }, "data": null } ``` ### Write Rows Write new rows to table by column family | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:----------------------------------------| | method | yes | type of method | "write" | | table_name | yes | the table name | "table name to delete or create" | | column_family | yes | the column_family to create | "valid unique string" | Example: ```json { "metadata": { "method": "write", "column_family": "valid_unique_string", "table_name": "valid_table_string" }, "data": "<KEY> } ``` ### Delete Rows Delete rows from table by prefix | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:----------------------------------------| | method | yes | type of method | "delete_row" | | table_name | yes | the table name | "table name to delete or create" | | row_key_prefix | yes | the row key | "valid unique string" | Example: ```json { "metadata": { "method": "delete_row", "row_key_prefix": "valid unique string", "table_name": "valid_table_string" }, "data": null } ``` ### Get All Rows Get all rows from the table: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:-----------------------------|:-------------------------------------------| | method | yes | type of method | "get_all_rows" | | table_name | yes | the table name | "table name to delete or create" | | row_key_prefix | no | the row key | "valid unique string" | | column_name | no | the column to return | "column name" | Example: ```json { "metadata": { "method": "get_all_rows", "table_name": "valid_table_string" }, "data": null } <file_sep>package firebase import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.firebase"). SetDescription("GCP Firebase Target"). SetName("Firebase"). SetProvider("GCP"). SetCategory("Store"). SetTags("db", "no-sql", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("project_id"). SetTitle("Project ID"). SetDescription("Set GCP project ID"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("auth_client"). SetDescription("Set Firebase target is a auth client"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("db_client"). SetTitle("Is DB Client"). SetDescription("Set Firebase target is a db client"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("db_url"). SetTitle("DB URL"). SetDescription("Set Firebase db url"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("messaging_client"). SetTitle("Is Messaging Client"). SetDescription("Set Firebase target is a messaging client"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set GCP Firebase execution method"). SetOptions([]string{"custom_token", "verify_token", "retrieve_user", "create_user", "delete_user", "delete_multiple_users", "list_users", "get_db", "delete_db", "set_db", "send_message", "send_multi"}). SetDefault("create_user"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("retrieve_by"). SetKind("string"). SetDescription("Set GCP Firebase retrieve by type"). SetOptions([]string{"by_uid", "by_email", "by_phone"}). SetDefault("by_uid"). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("token_id"). SetKind("string"). SetDescription("Set Firebase token id"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("uid"). SetKind("string"). SetDescription("Set Firebase user uid"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("email"). SetKind("string"). SetDescription("Set Firebase user email"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("phone"). SetKind("string"). SetDescription("Set Firebase user phone"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("ref_path"). SetKind("string"). SetDescription("Set Firebase reference path"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("child_ref"). SetKind("string"). SetDescription("Set Firebase child path"). SetDefault(""). SetMust(false), ) } <file_sep>package eventhubs import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultPartitionKey = "" ) var methodsMap = map[string]string{ "send": "send", "send_batch": "send_batch", } type metadata struct { method string partitionKey string properties map[string]interface{} } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } m.properties, err = meta.MustParseInterfaceMap("properties") if err != nil { return metadata{}, fmt.Errorf("error parsing properties, %w", err) } m.partitionKey = meta.ParseString("partition_key", DefaultPartitionKey) return m, nil } <file_sep>package postgres import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.stores.postgres"). SetDescription("GCP Postgres Direct Mode Target"). SetName("Postgres"). SetProvider("GCP"). SetCategory("Store"). SetTags("db", "sql", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("condition"). SetName("connection-type"). SetTitle("Connection Type"). SetDescription("Set Postgres Connection Type"). SetMust(true). SetOptions([]string{"Proxy", "Direct"}). SetDefault("Proxy"). NewCondition("Proxy", []*common.Property{ common.NewProperty(). SetKind("null"). SetName("use_proxy"). SetDescription("Set use proxy"). SetMust(true). SetDefault("true"), common.NewProperty(). SetKind("string"). SetName("instance_connection_name"). SetDescription("Set Postgres instance connection name"). SetMust(true). SetDefault(""), common.NewProperty(). SetKind("string"). SetName("db_user"). SetTitle("Username"). SetDescription("Set Postgres db user"). SetMust(true). SetDefault(""), common.NewProperty(). SetKind("string"). SetName("db_password"). SetTitle("Password"). SetDescription("Set Postgres db password"). SetMust(true). SetDefault(""), common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetDescription("Set Postgres credentials"). SetMust(true). SetDefault(""), }). NewCondition("Direct", []*common.Property{ common.NewProperty(). SetKind("null"). SetName("use_proxy"). SetDescription("Set use proxy"). SetMust(true). SetDefault("false"), common.NewProperty(). SetKind("string"). SetName("connection"). SetTitle("Connection String"). SetDescription("Set Postgres connection string"). SetMust(true). SetDefault("postgres://postgres:postgres@localhost:5432/postgres?sslmode=disable"), }), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_idle_connections"). SetDescription("Set Postgres max idle connections"). SetMust(false). SetDefault("10"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_open_connections"). SetDescription("Set Postgres max open connections"). SetMust(false). SetDefault("100"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connection_max_lifetime_seconds"). SetTitle("Connection Lifetime (Seconds)"). SetDescription("Set Postgres connection max lifetime seconds"). SetMust(false). SetDefault("3600"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Postgres execution method"). SetOptions([]string{"query", "exec", "transaction"}). SetDefault("query"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("isolation_level"). SetKind("string"). SetDescription("Set Postgres isolation level"). SetOptions([]string{"Default", "ReadUncommitted", "ReadCommitted", "RepeatableRead", "Serializable"}). SetDefault("Default"). SetMust(false), ) } <file_sep>package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // put Logs dat, err := ioutil.ReadFile("./credentials/aws/cloudwatch/logs/logGroupName.txt") if err != nil { panic(err) } logGroupName := string(dat) dat, err = ioutil.ReadFile("./credentials/aws/cloudwatch/logs/sequenceToken.txt") if err != nil { panic(err) } sequenceToken := string(dat) dat, err = ioutil.ReadFile("./credentials/aws/cloudwatch/logs/logStreamName.txt") if err != nil { panic(err) } logStreamName := string(dat) currentTime := time.Now().UnixNano() / 1000000 m := make(map[int64]string) m[currentTime-15] = "my first message to send" m[currentTime] = "my second message to send" b, err := json.Marshal(m) if err != nil { log.Fatal(err) } listRequest := types.NewRequest(). SetMetadataKeyValue("method", "put_log_event"). SetMetadataKeyValue("log_group_name", logGroupName). SetMetadataKeyValue("sequence_token", sequenceToken). SetMetadataKeyValue("log_stream_name", logStreamName). SetData(b) queryListResponse, err := client.SetQuery(listRequest.ToQuery()). SetChannel("query.aws.cloudwatch.logs"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } listResponse, err := types.ParseResponse(queryListResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("put logs executed, response: %s", listResponse.Data)) // get Logs getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get_log_event"). SetMetadataKeyValue("log_group_name", logGroupName). SetMetadataKeyValue("log_stream_name", logStreamName) getReq, err := client.SetQuery(getRequest.ToQuery()). SetChannel("query.aws.cloudwatch.logs"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(getReq.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get logs executed %v, error: %v", getResponse.Data, getResponse.IsError)) } <file_sep>package null import ( "context" "time" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger Delay time.Duration DoError error ResponseError error } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Do(ctx context.Context, request *types.Request) (*types.Response, error) { select { case <-time.After(c.Delay): if c.DoError != nil { return nil, c.DoError } if c.ResponseError != nil { return nil, c.ResponseError } return types.NewResponse().SetData(request.Data), nil case <-ctx.Done(): return nil, ctx.Err() } } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } return nil } func (c *Client) Stop() error { return nil } <file_sep>package config import ( "os" "reflect" "testing" ) func TestConfig_Validate(t *testing.T) { tests := []struct { name string Bindings []BindingConfig wantErr bool }{ { name: "valid config", Bindings: []BindingConfig{ { Name: "binding-1", Source: Spec{ Name: "source-1", Kind: "source-1", Properties: nil, }, Target: Spec{ Name: "target-1", Kind: "target-1", Properties: nil, }, }, }, wantErr: false, }, { name: "invalid config - no bindings", Bindings: []BindingConfig{}, wantErr: true, }, { name: "invalid config - binding no name", Bindings: []BindingConfig{ { Source: Spec{ Name: "source-1", Kind: "source-1", Properties: nil, }, Target: Spec{ Name: "target-1", Kind: "target-1", Properties: nil, }, }, }, wantErr: true, }, { name: "invalid config - invalid source", Bindings: []BindingConfig{ { Name: "binding-1", Source: Spec{ Kind: "source-1", Properties: nil, }, Target: Spec{ Name: "target-1", Kind: "target-1", Properties: nil, }, }, }, wantErr: true, }, { name: "invalid config - bad target", Bindings: []BindingConfig{ { Name: "binding-1", Source: Spec{ Name: "source-1", Kind: "source-1", Properties: nil, }, Target: Spec{ Kind: "target-1", Properties: nil, }, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c := &Config{ Bindings: tt.Bindings, } if err := c.Validate(); (err != nil) != tt.wantErr { t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) } //y, _ := yaml.Marshal(c) // //ioutil.WriteFile("config.yaml", y, 0644) }) } } func TestLoad_Env_Yaml(t *testing.T) { tests := []struct { name string cfgString string want *Config wantErr bool }{ { name: "load from env", cfgString: ` bindings: - name: binding-1 source: kind: source-1 name: source-1 properties: null target: kind: target-1 name: target-1 properties: null `, want: &Config{ Bindings: []BindingConfig{ { Name: "binding-1", Source: Spec{ Name: "source-1", Kind: "source-1", Properties: nil, }, Target: Spec{ Name: "target-1", Kind: "target-1", Properties: nil, }, }, }, }, wantErr: false, }, { name: "invalid file format", cfgString: "some-invalid-format", want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _ = os.Setenv("CONFIG", tt.cfgString) defer os.RemoveAll("./config.yaml") got, err := Load(nil) if (err != nil) != tt.wantErr { t.Errorf("Load() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("Load() got = %v, want %v", got, tt.want) } }) } } <file_sep>package aerospike import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.aerospike"). SetDescription("Aerospike Target"). SetName("Aerospike"). SetProvider(""). SetCategory("Store"). SetTags("db"). AddProperty( common.NewProperty(). SetKind("string"). SetName("host"). SetTitle("Host Address"). SetDescription("Set Aerospike host address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("port"). SetDescription("Set Aerospike port address"). SetMust(true). SetMin(0). SetMax(65355). SetDefault("3000"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Aerospike username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Aerospike password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("timeout"). SetDescription("Set aerospike timeout seconds"). SetMust(false). SetDefault("5"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set aerospike execution method"). SetOptions([]string{"get", "set", "delete", "get_batch"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("key"). SetKind("string"). SetDescription("Set aerospike key"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("user_key"). SetKind("string"). SetDescription("Set aerospike user key"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("namespace"). SetKind("string"). SetDescription("Set aerospike namespace"). SetDefault(""). SetMust(false), ) } <file_sep>package nats import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "time" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "github.com/nats-io/nats.go" ) type Client struct { log *logger.Logger opts options client *nats.Conn } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } o := setOptions(c.opts.certFile, c.opts.certKey, c.opts.username, c.opts.password, c.opts.token, c.opts.tls, c.opts.timeout) c.client, err = nats.Connect(c.opts.url, o) if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } err = c.client.Publish(meta.subject, req.Data) if err != nil { return nil, err } return types.NewResponse().SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.client != nil { c.client.Close() } return nil } func setOptions(sslcertificatefile string, sslcertificatekey string, username string, password string, token string, useTls bool, timeout int) nats.Option { return func(o *nats.Options) error { if useTls { if sslcertificatefile != "" && sslcertificatekey != "" { cert, err := tls.X509KeyPair([]byte(sslcertificatefile), []byte(sslcertificatekey)) if err != nil { return fmt.Errorf("nats: error parsing client certificate: %v", err) } cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) if err != nil { return fmt.Errorf("nats: error parsing client certificate: %v", err) } if o.TLSConfig == nil { o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} } o.TLSConfig.Certificates = []tls.Certificate{cert} o.Secure = true } else { return errors.New("when using tls make sure to pass file and key") } } if username != "" { o.User = username } if password != "" { o.Password = <PASSWORD> } if token != "" { o.Token = token } if timeout != 0 { o.Timeout = time.Duration(timeout) * time.Second } return nil } } <file_sep>package hazelcast import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultListName = "" defaultKeyName = "" ) var methodsMap = map[string]string{ "get": "get", "set": "set", "get_list": "get_list", "delete": "delete", } type metadata struct { method string mapName string key string listName string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.key = meta.ParseString("key", defaultKeyName) m.mapName, err = meta.MustParseString("map_name") if err != nil { return metadata{}, fmt.Errorf("error on parsing map_name value, %w", err) } m.listName = meta.ParseString("list_name", defaultListName) return m, nil } <file_sep>package logger import "github.com/kardianos/service" type ServiceLogger struct { logger service.Logger } func NewServiceLogger() *ServiceLogger { s := &ServiceLogger{} return s } func (s *ServiceLogger) SetLogger(logger service.Logger) { s.logger = logger } func (s *ServiceLogger) Write(p []byte) (n int, err error) { if s.logger == nil { return len(p), nil } err = s.logger.Info(string(p)) if err != nil { return 0, err } return len(p), nil } func (s *ServiceLogger) Sync() error { return nil } <file_sep>package aerospike import ( "context" "encoding/json" "testing" "time" aero "github.com/aerospike/aerospike-client-go" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "stores-aerospike", Kind: "stores.aerospike", Properties: map[string]string{ "host": "127.0.0.1", "port": "3000", }, }, wantErr: false, }, { name: "init - invalid port", cfg: config.Spec{ Name: "stores-aerospike", Kind: "stores.aerospike", Properties: map[string]string{ "host": "127.0.0.1", "port": "3001", }, }, wantErr: true, }, { name: "init - invalid host", cfg: config.Spec{ Name: "stores-aerospike", Kind: "stores.aerospike", Properties: map[string]string{ "host": "00.0.0.1", "port": "3001", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSetErr %v", err, tt.wantErr) return } }) } } func TestClient_Set_Get(t *testing.T) { k := PutRequest{ UserKey: "user_key1", KeyName: "some-key", Namespace: "test", BinMap: // define some bins with data aero.BinMap{ "bin1": 42, "bin2": "An elephant is a mouse with an operating system", "bin3": []interface{}{"Go", 2009}, }, } req, err := json.Marshal(k) require.NoError(t, err) tests := []struct { name string cfg config.Spec setRequest *types.Request getRequest *types.Request wantSetResponse *types.Response wantSetErr bool wantGetErr bool }{ { name: "valid set get request", cfg: config.Spec{ Name: "stores-aerospike", Kind: "stores.aerospike", Properties: map[string]string{ "host": "127.0.0.1", "port": "3000", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetData(req), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("namespace", "test"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("user_key", "user_key1"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("result", "ok"), wantSetErr: false, wantGetErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.setRequest) if tt.wantSetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantSetResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.getRequest) if tt.wantGetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) }) } } func TestClient_Delete(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid Delete", cfg: config.Spec{ Name: "stores-aerospike", Kind: "stores.aerospike", Properties: map[string]string{ "host": "127.0.0.1", "port": "3000", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("user_key", "user_key1"). SetMetadataKeyValue("namespace", "test"), }, { name: "invalid Delete - no key", cfg: config.Spec{ Name: "stores-aerospike", Kind: "stores.aerospike", Properties: map[string]string{ "host": "127.0.0.1", "port": "3000", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("user_key", "user_key1"). SetMetadataKeyValue("namespace", "test"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_GetBatch(t *testing.T) { var keys []*string key := "some-key" keys = append(keys, &key) k := GetBatchRequest{ KeyNames: keys, Namespace: "test", BinNames: nil, } req, err := json.Marshal(k) require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid GetBatch", cfg: config.Spec{ Name: "stores-aerospike", Kind: "stores.aerospike", Properties: map[string]string{ "host": "127.0.0.1", "port": "3000", }, }, request: types.NewRequest(). SetData(req). SetMetadataKeyValue("method", "get_batch"). SetMetadataKeyValue("user_key", "user_key1"). SetMetadataKeyValue("namespace", "test"), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } <file_sep>package openfaas import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("serverless.openfaas"). SetDescription("Openfaas Target"). SetName("OpenFaas"). SetProvider(""). SetCategory("Serverless"). SetTags("functions"). AddProperty( common.NewProperty(). SetKind("string"). SetName("gateway"). SetTitle("Gateway Address"). SetDescription("Set Openfaas gateway address"). SetMust(true). SetDefault("localhost:27017"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Openfaas username"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Openfaas password"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("topic"). SetKind("string"). SetDescription("Set OpenFaas function topic"). SetDefault(""). SetMust(true), ) } <file_sep>package athena import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.athena"). SetDescription("AWS Athena Target"). SetName("Athena"). SetProvider("AWS"). SetCategory("Analytics"). SetTags("query", "s3", "SQL"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Athena aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Athena aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Athena aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Athena aws token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Athena execution method"). SetOptions([]string{"list_databases", "list_data_catalogs", "query", "get_query_result"}). SetDefault("query"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("query"). SetKind("string"). SetDescription("Set Athena query"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("catalog"). SetKind("string"). SetDescription("Set Athena catalog"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("db"). SetKind("string"). SetDescription("Set Athena db"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("output_location"). SetKind("string"). SetDescription("Set Athena output location"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("execution_id"). SetKind("string"). SetDescription("Set Athena execution id"). SetDefault(""). SetMust(false), ) } <file_sep>package openfaas import ( "context" "fmt" "io" "io/ioutil" "github.com/go-resty/resty/v2" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *resty.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.client = resty.New() c.client.SetDoNotParseResponse(true) c.client.SetBasicAuth(c.opts.username, c.opts.password) return nil } func readBody(data io.ReadCloser) ([]byte, error) { if data == nil { return nil, nil } b, err := ioutil.ReadAll(data) if err != nil { return nil, err } return b, data.Close() } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } url := fmt.Sprintf("%s/%s", c.opts.gateway, meta.topic) resp, err := c.client.R().SetContext(ctx).SetBody(req.Data).Post(url) if err != nil { return nil, err } body, err := readBody(resp.RawBody()) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("status", fmt.Sprintf("%d", resp.RawResponse.StatusCode)). SetData(body), nil } func (c *Client) Stop() error { return nil } <file_sep>package logger import ( "context" "fmt" "os" "path/filepath" "github.com/kubemq-io/kubemq-targets/global" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) var ( ServiceLog = NewServiceLogger() core = initCore() encoderConfig = zapcore.EncoderConfig{ TimeKey: "time", LevelKey: "level", NameKey: "name", CallerKey: "caller", MessageKey: "msg", StacktraceKey: "stack", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: zapcore.CapitalLevelEncoder, EncodeTime: zapcore.ISO8601TimeEncoder, EncodeDuration: zapcore.StringDurationEncoder, EncodeCaller: zapcore.FullCallerEncoder, } ) func initCore() zapcore.Core { var w zapcore.WriteSyncer std, _, _ := zap.Open("stderr") if global.EnableLogFile { path, _ := os.Executable() err := os.MkdirAll("./logs", 0o660) if err != nil { panic(err.Error()) } logR := &LogRotator{ Ctx: context.Background(), Filename: filepath.Join(filepath.Dir(path), "/logs/kubemq-targets.log"), MaxSize: 100, // megabytes MaxBackups: 5, MaxAge: 28, // days } w = zap.CombineWriteSyncers(std, logR, ServiceLog) } else { w = zap.CombineWriteSyncers(std, ServiceLog) } enc := zapcore.NewJSONEncoder(encoderConfig) if global.LoggerType == "console" { enc = zapcore.NewConsoleEncoder(encoderConfig) } return zapcore.NewCore( enc, zapcore.AddSync(w), zapcore.DebugLevel) } func LogLevelToZapLevel(value string) zapcore.Level { switch value { case "debug": return zap.DebugLevel case "error": return zap.ErrorLevel default: return zap.InfoLevel } } type Logger struct { *zap.SugaredLogger } func (l *Logger) Printf(format string, v ...interface{}) { l.Infof(format, v) } func NewLogger(name string, level ...string) *Logger { lvlStr := "" if len(level) > 0 { lvlStr = level[0] } zapLogger := zap.New(core, zap.IncreaseLevel(LogLevelToZapLevel(lvlStr))) l := &Logger{ SugaredLogger: zapLogger.Sugar().With("source", name), } return l } func (l *Logger) Noticef(format string, v ...interface{}) { str := fmt.Sprintf(format, v...) l.Info(str) } func (l *Logger) Tracef(format string, v ...interface{}) { str := fmt.Sprintf(format, v...) l.Debug(str) } func (l *Logger) Fatalf(format string, v ...interface{}) { str := fmt.Sprintf(format, v...) l.DPanicf(str) } func (l *Logger) NewWith(p1, p2 string) *Logger { return &Logger{SugaredLogger: l.SugaredLogger.With(p1, p2)} } func (l *Logger) Write(p []byte) (n int, err error) { l.Info(string(p)) return len(p), nil } <file_sep>package ibmmq import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("messaging.ibmmq"). SetName("IBM MQ"). SetProvider(""). SetCategory("Messaging"). SetTags("queue", "pub/sub"). SetDescription("IBM-MQ Messaging Target"). AddProperty( common.NewProperty(). SetKind("string"). SetName("queue_manager_name"). SetTitle("Queue Manager Name"). SetDescription("Set IBM-MQ queue manager name"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("host_name"). SetDescription("Set IBM-MQ host name"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("channel_name"). SetDescription("Set IBM-MQ channel name the queue is under"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set IBM-MQ username"). SetDefault(""). SetMust(true), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("certificate_label"). SetDescription("Set IBM-MQ certificate_label for requests"). SetDefault(""). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("ttl"). SetTitle("TTL"). SetDescription("Sets IBM-MQ message time to live (milliseconds)"). SetDefault("1000000"). SetMax(1000000000). SetMin(0). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("queue_name"). SetDescription("Sets IBM-MQ queue name"). SetDefault(""). SetMust(true), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("transport_type"). SetDescription("Set IBM-MQ Transport type"). SetDefault("0"). SetMax(1). SetMin(0). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("tls_client_auth"). SetTitle("TLS Client Auth"). SetDescription("Set IBM-MQ tls_client_auth"). SetDefault("NONE"). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("port_number"). SetTitle("Port"). SetDescription("Set IBM-MQ server port_number"). SetDefault("1414"). SetMax(65355). SetMin(0). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set IBM-MQ password"). SetDefault(""). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("key_repository"). SetDescription("Set IBM-MQ key_repository a certificate store"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("dynamic_queue"). SetKind("string"). SetDescription("set new IBM-MQ queue route"). SetDefault(""). SetMust(false), ) } <file_sep>package dynamodb import ( "context" "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/dynamodb" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *dynamodb.DynamoDB } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := dynamodb.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "list_tables": return c.listTables(ctx) case "create_table": return c.createTable(ctx, req.Data) case "delete_table": return c.deleteTable(ctx, meta) case "insert_item": return c.insertItem(ctx, meta, req.Data) case "get_item": return c.getItem(ctx, req.Data) case "update_item": return c.updateItem(ctx, req.Data) case "delete_item": return c.deleteItem(ctx, req.Data) default: return nil, errors.New("invalid method type") } } func (c *Client) listTables(ctx context.Context) (*types.Response, error) { input := &dynamodb.ListTablesInput{} m, err := c.client.ListTablesWithContext(ctx, input) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) createTable(ctx context.Context, data []byte) (*types.Response, error) { i := &dynamodb.CreateTableInput{} err := json.Unmarshal(data, &i) if err != nil { return nil, err } result, err := c.client.CreateTableWithContext(ctx, i) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) deleteTable(ctx context.Context, meta metadata) (*types.Response, error) { result, err := c.client.DeleteTableWithContext(ctx, &dynamodb.DeleteTableInput{ TableName: aws.String(meta.tableName), }) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) insertItem(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { i := map[string]*dynamodb.AttributeValue{} err := json.Unmarshal(data, &i) if err != nil { return nil, err } input := &dynamodb.PutItemInput{ Item: i, TableName: aws.String(meta.tableName), } result, err := c.client.PutItemWithContext(ctx, input) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) getItem(ctx context.Context, data []byte) (*types.Response, error) { g := &dynamodb.GetItemInput{} err := json.Unmarshal(data, &g) if err != nil { return nil, err } result, err := c.client.GetItemWithContext(ctx, g) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) updateItem(ctx context.Context, data []byte) (*types.Response, error) { u := &dynamodb.UpdateItemInput{} err := json.Unmarshal(data, &u) if err != nil { return nil, err } result, err := c.client.UpdateItemWithContext(ctx, u) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) deleteItem(ctx context.Context, data []byte) (*types.Response, error) { d := &dynamodb.DeleteItemInput{} err := json.Unmarshal(data, &d) if err != nil { return nil, err } result, err := c.client.DeleteItemWithContext(ctx, d) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } body, err := json.Marshal("test") if err != nil { panic(err) } // send sendRequest := types.NewRequest(). SetMetadataKeyValue("method", "send"). SetMetadataKeyValue("label", `test`). SetData(body) sendUploadResponse, err := client.SetQuery(sendRequest.ToQuery()). SetChannel("azure.servicebus"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } sendResponse, err := types.ParseResponse(sendUploadResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("send request executed, error: %v , response:%s", sendResponse.Error, sendResponse.Metadata["result"])) } <file_sep>package filesystem import ( "encoding/json" "os" "path/filepath" ) type FileInfo struct { Name string `json:"name"` FullPath string `json:"full_path"` Size int64 `json:"size"` IsDir bool `json:"is_dir"` } func newFromOSFileInfo(f os.FileInfo, path string) *FileInfo { fi := &FileInfo{ Name: f.Name(), FullPath: "", Size: f.Size(), IsDir: f.IsDir(), } fi.FullPath, _ = filepath.Abs(path) return fi } type FileInfoList []*FileInfo func (l FileInfoList) Marshal() []byte { data, _ := json.Marshal(l) return data } <file_sep>package openfaas import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantStatus string wantErr bool }{ { name: "valid request", cfg: config.Spec{ Name: "openfaas", Kind: "openfaas", Properties: map[string]string{ "gateway": "http://127.0.0.1:31112", "username": "admin", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("topic", "function/nslookup"). SetData([]byte("kubemq.io")), wantStatus: "200", wantErr: false, }, { name: "invalid request - execution error", cfg: config.Spec{ Name: "openfaas", Kind: "openfaas", Properties: map[string]string{ "gateway": "http://bad:31112", "username": "admin", "password": "<PASSWORD>", }, }, request: types.NewRequest(). SetMetadataKeyValue("topic", "function/nslookup"). SetData([]byte("kubemq.io")), wantStatus: "200", wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) require.EqualValues(t, tt.wantStatus, got.Metadata.Get("status")) }) } } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "openfaas-target", Kind: "", Properties: map[string]string{ "gateway": "http://127.0.0.1:31112", "username": "admin", "password": "<PASSWORD>", }, }, wantErr: false, }, { name: "init - no gateway", cfg: config.Spec{ Name: "openfaas-target", Kind: "", Properties: map[string]string{ "username": "admin", "password": "<PASSWORD>", }, }, wantErr: true, }, { name: "init - no username", cfg: config.Spec{ Name: "openfaas-target", Kind: "", Properties: map[string]string{ "gateway": "http://127.0.0.1:31112", "password": "<PASSWORD>", }, }, wantErr: true, }, { name: "init - no password", cfg: config.Spec{ Name: "openfaas-target", Kind: "", Properties: map[string]string{ "gateway": "http://127.0.0.1:31112", "username": "admin", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantErr %v", err, tt.wantErr) return } }) } } <file_sep>package sns import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) const ( DefaultToken = "" ) type options struct { awsKey string awsSecretKey string region string token string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.awsKey, err = cfg.Properties.MustParseString("aws_key") if err != nil { return options{}, fmt.Errorf("error parsing aws_key , %w", err) } o.awsSecretKey, err = cfg.Properties.MustParseString("aws_secret_key") if err != nil { return options{}, fmt.Errorf("error parsing aws_secret_key , %w", err) } o.region, err = cfg.Properties.MustParseString("region") if err != nil { return options{}, fmt.Errorf("error parsing region , %w", err) } o.token = cfg.Properties.ParseString("token", DefaultToken) return o, nil } <file_sep>package retry import ( "errors" "fmt" "testing" "time" "github.com/stretchr/testify/assert" ) func TestDoAllFailed(t *testing.T) { var retrySum uint err := Do( func() error { return errors.New("test") }, OnRetry(func(n uint, err error) { retrySum += n }), Delay(time.Nanosecond), ) assert.Error(t, err) expectedErrorFormat := `All attempts fail: #1: test #2: test #3: test #4: test #5: test #6: test #7: test #8: test #9: test #10: test` assert.Equal(t, expectedErrorFormat, err.Error(), "retry error format") assert.Equal(t, uint(45), retrySum, "right count of retry") } func TestDoFirstOk(t *testing.T) { var retrySum uint err := Do( func() error { return nil }, OnRetry(func(n uint, err error) { retrySum += n }), ) assert.NoError(t, err) assert.Equal(t, uint(0), retrySum, "no retry") } func TestRetryIf(t *testing.T) { var retryCount uint err := Do( func() error { if retryCount >= 2 { return errors.New("special") } else { return errors.New("test") } }, OnRetry(func(n uint, err error) { retryCount++ }), RetryIf(func(err error) bool { return err.Error() != "special" }), Delay(time.Nanosecond), ) assert.Error(t, err) expectedErrorFormat := `All attempts fail: #1: test #2: test #3: special` assert.Equal(t, expectedErrorFormat, err.Error(), "retry error format") assert.Equal(t, uint(2), retryCount, "right count of retry") } func TestDefaultSleep(t *testing.T) { start := time.Now() err := Do( func() error { return errors.New("test") }, Attempts(3), ) dur := time.Since(start) assert.Error(t, err) assert.True(t, dur > 300*time.Millisecond, "3 times default retry is longer then 300ms") } func TestFixedSleep(t *testing.T) { start := time.Now() err := Do( func() error { return errors.New("test") }, Attempts(3), DelayType(FixedDelay), ) dur := time.Since(start) assert.Error(t, err) assert.True(t, dur < 500*time.Millisecond, "3 times default retry is shorter then 500ms") } func TestLastErrorOnly(t *testing.T) { var retrySum uint err := Do( func() error { return fmt.Errorf("%d", retrySum) }, OnRetry(func(n uint, err error) { retrySum += 1 }), Delay(time.Nanosecond), LastErrorOnly(true), ) assert.Error(t, err) assert.Equal(t, "9", err.Error()) } func TestUnrecoverableError(t *testing.T) { attempts := 0 expectedErr := errors.New("error") err := Do( func() error { attempts++ return Unrecoverable(expectedErr) }, Attempts(2), LastErrorOnly(true), ) assert.Equal(t, expectedErr, err) assert.Equal(t, 1, attempts, "unrecoverable error broke the loop") } func TestCombineFixedDelays(t *testing.T) { start := time.Now() err := Do( func() error { return errors.New("test") }, Attempts(3), DelayType(CombineDelay(FixedDelay, FixedDelay)), ) dur := time.Since(start) assert.Error(t, err) assert.True(t, dur > 400*time.Millisecond, "3 times combined, fixed retry is longer then 400ms") assert.True(t, dur < 500*time.Millisecond, "3 times combined, fixed retry is shorter then 500ms") } func TestRandomDelay(t *testing.T) { start := time.Now() err := Do( func() error { return errors.New("test") }, Attempts(3), DelayType(RandomDelay), MaxJitter(50*time.Millisecond), ) dur := time.Since(start) assert.Error(t, err) assert.True(t, dur > 2*time.Millisecond, "3 times random retry is longer then 2ms") assert.True(t, dur < 100*time.Millisecond, "3 times random retry is shorter then 100ms") } func TestMaxDelay(t *testing.T) { start := time.Now() err := Do( func() error { return errors.New("test") }, Attempts(5), Delay(10*time.Millisecond), MaxDelay(50*time.Millisecond), ) dur := time.Since(start) assert.Error(t, err) assert.True(t, dur > 170*time.Millisecond, "5 times with maximum delay retry is longer than 70ms") assert.True(t, dur < 200*time.Millisecond, "5 times with maximum delay retry is shorter than 200ms") } <file_sep>package bigquery import "github.com/kubemq-hub/builder/connector/common" func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.bigquery"). SetDescription("GCP Bigquery Target"). SetName("Big Query"). SetProvider("GCP"). SetCategory("Store"). SetTags("db", "sql", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("project_id"). SetTitle("Project ID"). SetDescription("Set GCP project ID"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set GCP BigQuery execution method"). SetOptions([]string{"query", "create_data_set", "delete_data_set", "create_table", "delete_table", "get_table_info", "get_data_sets", "insert"}). SetDefault("query"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("table_name"). SetKind("string"). SetDescription("Set BigQuery table name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("dataset_id"). SetKind("string"). SetDescription("Set BigQuery dataset id"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("location"). SetKind("string"). SetDescription("Set BigQuery location"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("query"). SetKind("string"). SetDescription("Set BigQuery query"). SetDefault(""). SetMust(false), ) } <file_sep>package firebase import ( "context" "encoding/json" "fmt" "strconv" "firebase.google.com/go/v4/messaging" "github.com/kubemq-io/kubemq-targets/types" ) type messages struct { single *messaging.Message multicast *messaging.MulticastMessage } func (c *Client) sendMessage(ctx context.Context, req *types.Request, opts options) (*types.Response, error) { m, err := parseMetadataMessages(req.Data, opts, SendMessage) if err != nil { return nil, err } r, err := c.messagingClient.Send(ctx, m.single) if err != nil { return nil, err } data, err := json.Marshal(r) if err != nil { return nil, err } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) sendMessageMulti(ctx context.Context, req *types.Request, opts options) (*types.Response, error) { m, err := parseMetadataMessages(req.Data, opts, SendBatch) if err != nil { return nil, err } b, err := c.messagingClient.SendMulticast(ctx, m.multicast) if err != nil { return nil, err } r := types.NewResponse(). SetMetadataKeyValue("SuccessCount", strconv.Itoa(b.SuccessCount)). SetMetadataKeyValue("FailureCount", strconv.Itoa(b.FailureCount)) for _, res := range b.Responses { msg := fmt.Sprintf("MessageID:%s, Success:%t, Error:%s", res.MessageID, res.Success, res.Error.Error()) r.SetMetadataKeyValue(fmt.Sprintf("mesage_%s", res.MessageID), msg) } return r, nil } <file_sep>package spanner import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { query string tableName string method string } var methodsMap = map[string]string{ "query": "query", "read": "read", "update_database_ddl": "update_database_ddl", "insert": "insert", "update": "update", "insert_or_update": "insert_or_update", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "query" { m.query, err = meta.MustParseString("query") if err != nil { return metadata{}, fmt.Errorf("error parsing query, %w", err) } } if m.method == "read" { m.tableName, err = meta.MustParseString("table_name") if err != nil { return metadata{}, fmt.Errorf("table_name is required for method :%s , error parsing table_name, %w", m.method, err) } } return m, nil } <file_sep>package config import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type BindingConfig struct { Name string `json:"name"` Source Spec `json:"source"` Target Spec `json:"target"` Properties types.Metadata `json:"properties"` } func (b BindingConfig) Validate() error { if b.Name == "" { return fmt.Errorf("binding must have name") } if err := b.Source.Validate(); err != nil { return fmt.Errorf("binding source error, %w", err) } if err := b.Target.Validate(); err != nil { return fmt.Errorf("binding target error, %w", err) } return nil } <file_sep>package types import ( "io/ioutil" "testing" "github.com/stretchr/testify/require" ) func loadFile(filename string) []byte { data, _ := ioutil.ReadFile(filename) return data } func getRequest(data []byte) *Request { return NewRequest(). SetMetadata(NewMetadata().Set("key", "value")). SetData(data) } func getTransportRequest(data interface{}) []byte { return NewTransportRequest(). SetMetadata(NewMetadata().Set("key", "value")). SetData(data).MarshalBinary() } func loadJson() []byte { type t struct { Param1 string Param2 int64 Param3 bool Param4 struct { Param1 string Param2 int64 Param3 bool } } test := &t{ Param1: "test", Param2: 1, Param3: true, Param4: struct { Param1 string Param2 int64 Param3 bool }{Param1: "test", Param2: 2, Param3: false}, } data, _ := json.Marshal(test) return data } func TestParseRequest(t *testing.T) { tests := []struct { name string body []byte want *Request wantErr bool }{ { name: "json", body: getTransportRequest(loadJson()), want: getRequest(loadJson()), wantErr: false, }, { name: "string-json", body: getTransportRequest(string(loadJson())), want: getRequest(loadJson()), wantErr: false, }, { name: "string", body: getTransportRequest("test-string"), want: getRequest([]byte("test-string")), wantErr: false, }, { name: "yaml-file", body: getTransportRequest(loadFile("./testdata/yaml-file.yaml")), want: getRequest(loadFile("./testdata/yaml-file.yaml")), wantErr: false, }, { name: "svg-file", body: getTransportRequest(loadFile("./testdata/svg-file.svg")), want: getRequest(loadFile("./testdata/svg-file.svg")), wantErr: false, }, { name: "png-file", body: getTransportRequest(loadFile("./testdata/png-file.png")), want: getRequest(loadFile("./testdata/png-file.png")), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := ParseRequest(tt.body) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.EqualValues(t, tt.want, got) }) } } <file_sep>package mysql import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.rds.mysql"). SetDescription("AWS RDS MySQL Target"). SetName("MySQL"). SetProvider("AWS"). SetCategory("Store"). SetTags("rds", "sql", "db", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set MySQL aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set MySQL aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set MySQL aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set MySQL aws token"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("end_point"). SetTitle("Endpoint"). SetDescription("Set MySQL end point address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("db_port"). SetTitle("Port"). SetDescription("Set MySQL end point port"). SetMust(true). SetDefault("3306"). SetMin(0). SetMax(65535), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("db_user"). SetTitle("Username"). SetDescription("Set MySQL db user"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("db_name"). SetTitle("Database"). SetDescription("Set MySQL db name"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_idle_connections"). SetDescription("Set MySQL max idle connections"). SetMust(false). SetDefault("10"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_open_connections"). SetDescription("Set MySQL max open connections"). SetMust(false). SetDefault("100"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connection_max_lifetime_seconds"). SetTitle("Connection Lifetime (Seconds)"). SetDescription("Set MySQL connection max lifetime seconds"). SetMust(false). SetDefault("3600"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set MySql execution method"). SetOptions([]string{"query", "exec", "transaction"}). SetDefault("query"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("isolation_level"). SetKind("string"). SetDescription("Set MySql isolation level"). SetOptions([]string{"Default", "ReadUncommitted", "ReadCommitted", "RepeatableRead", "Serializable"}). SetDefault("Default"). SetMust(false), ) } <file_sep># Kubemq storage target Connector Kubemq gcp-storage target connector allows services using kubemq server to access google storage server. ## Prerequisites The following required to run the gcp-storage target connector: - kubemq cluster - gcp-storage set up - kubemq-targets deployment ## Configuration storage target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:--------------------------------| | credentials | yes | gcp credentials files | "<google json credentials" | Example: ```yaml bindings: - name: kubemq-query-gcp-storage source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-storage-connector" auth_token: "" channel: "query.gcp.storage" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.storage name: gcp-storage properties: credentials: 'json' ``` ## Usage ### Create bucket create a new bucket under storage Create bucket metadata settings: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:---------------------------------------|:-------------------------| | method | yes | type of method | "create_bucket" | | bucket | yes | bucket name | "bucket name" | | storage_class | yes | gcp-storage_class | "storage_class" | | project_id | yes | gcp storage project_id | "<googleurl>/myproject" | | location | yes | gcp storage valid location | "gcp-supported locations"| Example: ```json { "metadata": { "method": "create_bucket", "bucket": "myBucketName", "storage_class": "COLDLINE", "project_id": "MyID", "location": "us" }, "data": null } ``` ### Upload file upload a file to selected bucket Upload file metadata settings: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:---------------------------------------------------| | method | yes | type of method | "upload" | | bucket | yes | bucket name | "bucket name" | | object | yes | object name to save the file under | "anyString" | | path | yes | path to the file to upload | "<absolute or relative path to file/filename.type>"| Example: ```json { "metadata": { "method": "upload", "bucket": "myBucketName", "object": "MyFile", "path": "./myFile.yaml" }, "data": null } ``` ### Delete file delete file from a bucket Delete file metadata settings: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------| | method | yes | type of method | "delete" | | bucket | yes | bucket name | "bucket name" | | object | yes | object name | "anyString" | Example: ```json { "metadata": { "method": "delete", "bucket": "myBucketName", "object": "MyFile" }, "data": null } ``` ### Download file download file from bucket by object name Download file metadata settings: | Metadata Key | Required | Description | Possible values | |:------------ |:---------|:---------------------------------------|:----------------| | method | yes | type of method | "download" | | bucket | yes | bucket name | "bucket name" | | object | yes | object name | "anyString" | Example: ```json { "metadata": { "method": "download", "bucket": "myBucketName", "object": "MyFile" }, "data": null } ``` ### Rename file rename an object under the same bucket Rename file metadata settings: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------| | method | yes | type of method | "rename" | | bucket | yes | bucket name | "bucket name" | | object | yes | old object name | "anyString" | | rename_object | yes | new object name | "anyString" | Example: ```json { "metadata": { "method": "rename", "bucket": "myBucketName", "object": "MyOldFile", "rename_object": "MyNewFile" }, "data": null } ``` ### Copy file copy file from one bucket to another Copy file metadata settings: | Metadata Key | Required | Description | Possible values | |:---------------------|:---------|:---------------------------------------|:------------------| | method | yes | type of method | "copy" | | bucket | yes | old bucket name | "bucket name" | | dst_bucket | yes | new bucket name(can be the same) | "bucket name" | | object | yes | old object name | "anyString" | | rename_object | yes | new object name(can be the same) | "anyString" | Example: ```json { "metadata": { "method": "copy", "bucket": "myOldBucketName", "dst_bucket": "myNewBucketName", "object": "MyOldFile", "rename_object": "MyNewFile" }, "data": null } ``` ### Move file move a file from one bucket to another Move file metadata settings: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:---------------------------------------|:-------------------------| | method | yes | type of method | "move" | | bucket | yes | old bucket name | "bucket name" | | dst_bucket | yes | new bucket name(can be the same) | "bucket name" | | object | yes | old object name | "anyString" | | rename_object | yes | new object name(can be the same) | "anyString" | Example: ```json { "metadata": { "method": "move", "bucket": "myOldBucketName", "dst_bucket": "myNewBucketName", "object": "MyOldFile", "rename_object": "MyNewFile" }, "data": null } ``` ### List files list all files from a bucket List files metadata settings: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:-------------------------| | method | yes | type of method | "list" | | bucket | yes | old bucket name | "bucket name" | Example: ```json { "metadata": { "method": "list", "bucket": "myBucketName" }, "data": null } ``` <file_sep>package cloudfunctions import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { name string project string location string } func parseMetadata(meta types.Metadata, opts options) (metadata, error) { m := metadata{} var err error m.name, err = meta.MustParseString("name") if err != nil { return metadata{}, fmt.Errorf("error parsing name, %w", err) } m.project = meta.ParseString("project", "") m.location = meta.ParseString("location", "") return m, nil } <file_sep>package servicebus import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("azure.servicebus"). SetDescription("Azure Service Bus Target"). SetName("ServiceBus"). SetProvider("Azure"). SetCategory("Messaging"). SetTags("queue", "pub/sub", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("end_point"). SetTitle("Endpoint"). SetDescription("Set Service Bus end point"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("shared_access_key_name"). SetTitle("Access Key Name"). SetDescription("Set Service Bus shared access key name"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("shared_access_key"). SetTitle("Access Key"). SetDescription("Set Service Bus shared access key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("queue_name"). SetDescription("Set Service Bus queue name"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Service Bus execution method"). SetOptions([]string{"send", "send_batch"}). SetDefault("send"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("label"). SetKind("string"). SetDescription("Set Service Bus label"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("content_type"). SetKind("string"). SetDescription("Set Service Bus content type"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("time_to_live"). SetDescription("Set Blob Storage time to live milliseconds"). SetMust(false). SetDefault("1000000000"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("max_batch_size"). SetDescription("Set Blob Storage max batch size in bytes"). SetMust(false). SetDefault("1024"). SetMin(0). SetMax(math.MaxInt32), ) } <file_sep>package aerospike import ( "context" "encoding/json" "errors" "fmt" aero "github.com/aerospike/aerospike-client-go" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *aero.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.client, err = aero.NewClient(c.opts.host, c.opts.port) if err != nil { return fmt.Errorf("error in creating aerospike client: %s", err) } if c.opts.username != "" { err = c.client.CreateUser(&aero.AdminPolicy{ Timeout: c.opts.timeout, }, c.opts.username, c.opts.password, nil) if err != nil { return err } } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.Get(meta) case "set": return c.Put(meta, req.Data) case "get_batch": return c.GetBatch(meta, req.Data) case "delete": return c.Delete(meta) } return nil, nil } func (c *Client) Get(meta metadata) (*types.Response, error) { key, err := aero.NewKey(meta.namespace, meta.key, meta.userKey) if err != nil { return nil, err } rec, err := c.client.Get(nil, key) if err != nil { return nil, err } if rec == nil { return nil, fmt.Errorf("no data found for key %s", key.String()) } b, err := json.Marshal(rec) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("user_key", meta.key), nil } func (c *Client) Put(meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data PutRequest") } var kb PutRequest err := json.Unmarshal(data, &kb) if err != nil { return nil, err } if kb.Namespace == "" && meta.namespace != "" { kb.Namespace = meta.namespace } key, err := aero.NewKey(kb.Namespace, kb.KeyName, kb.UserKey) if err != nil { return nil, err } err = c.client.Put(nil, key, kb.BinMap) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", kb.KeyName), nil } func (c *Client) GetBatch(meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, errors.New("missing data GetBatchRequest") } var kb GetBatchRequest err := json.Unmarshal(data, &kb) if err != nil { return nil, err } var keys []*aero.Key for _, k := range kb.KeyNames { if kb.Namespace == "" && meta.namespace != "" { kb.Namespace = meta.namespace } key, err := aero.NewKey(kb.Namespace, *k, meta.userKey) if err != nil { return nil, err } keys = append(keys, key) } rec, err := c.client.BatchGet(nil, keys, kb.BinNames...) if err != nil { return nil, err } b, err := json.Marshal(rec) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Delete(meta metadata) (*types.Response, error) { key, err := aero.NewKey(meta.namespace, meta.key, meta.userKey) if err != nil { return nil, err } del, err := c.client.Delete(nil, key) if err != nil { return nil, err } if !del { return nil, fmt.Errorf("failed to delete %s", key.String()) } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) Stop() error { c.client.Close() return nil } <file_sep>package hdfs import ( "context" "errors" "io/ioutil" hdfs "github.com/colinmarc/hdfs/v2" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *hdfs.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } co := setClientOption(c.opts) c.client, err = hdfs.NewClient(co) if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "read_file": return c.readFile(meta) case "write_file": return c.writeFile(meta, req.Data) case "remove_file": return c.removeFile(meta) case "rename_file": return c.renameFile(meta) case "mkdir": return c.makeDir(meta) case "stat": return c.stat(meta) default: return nil, errors.New("invalid method type") } } func (c *Client) writeFile(meta metadata, data []byte) (*types.Response, error) { writer, err := c.client.Create(meta.filePath) if err != nil { return nil, err } _, err = writer.Write(data) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) makeDir(meta metadata) (*types.Response, error) { err := c.client.Mkdir(meta.filePath, meta.fileMode) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) removeFile(meta metadata) (*types.Response, error) { err := c.client.Remove(meta.filePath) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) renameFile(meta metadata) (*types.Response, error) { err := c.client.Rename(meta.oldFilePath, meta.filePath) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) stat(meta metadata) (*types.Response, error) { file, err := c.client.Stat(meta.filePath) if err != nil { return nil, err } b, err := createStatAsByteArray(file) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) readFile(meta metadata) (*types.Response, error) { file, err := c.client.Open(meta.filePath) if err != nil { return nil, err } bytes, err := ioutil.ReadAll(file) if err != nil { return nil, err } return types.NewResponse(). SetData(bytes). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.client != nil { return c.client.Close() } return nil } func setClientOption(opts options) hdfs.ClientOptions { c := hdfs.ClientOptions{} if opts.address != "" { c.Addresses = append(c.Addresses, opts.address) } if opts.user != "" { c.User = opts.user } return c } <file_sep>package null import ( "context" "fmt" "reflect" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" ) func TestClient_Do(t *testing.T) { type fields struct { Delay time.Duration DoError error ResponseError error } tests := []struct { name string fields fields req *types.Request want *types.Response wantErr bool }{ { name: "do", fields: fields{ Delay: 0, DoError: nil, ResponseError: nil, }, req: types.NewRequest().SetData([]byte("data")), want: types.NewResponse().SetData([]byte("data")), wantErr: false, }, { name: "do with DoError", fields: fields{ Delay: 0, DoError: fmt.Errorf("do-error"), ResponseError: nil, }, req: types.NewRequest().SetData([]byte("data")), want: nil, wantErr: true, }, { name: "do with response error", fields: fields{ Delay: 0, DoError: nil, ResponseError: fmt.Errorf("response-error"), }, req: types.NewRequest().SetData([]byte("data")), want: nil, wantErr: true, }, { name: "do cancel ctx", fields: fields{ Delay: 5 * time.Second, DoError: nil, ResponseError: nil, }, req: types.NewRequest().SetData([]byte("data")), want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() c := &Client{ Delay: tt.fields.Delay, DoError: tt.fields.DoError, ResponseError: tt.fields.ResponseError, } _ = c.Init(ctx, config.Spec{ Name: "null", Kind: "", Properties: nil, }, nil) got, err := c.Do(ctx, tt.req) if (err != nil) != tt.wantErr { t.Errorf("Do() error = %v, wantErr %v", err, tt.wantErr) return } if !reflect.DeepEqual(got, tt.want) { t.Errorf("Do() got = %v, want %v", got, tt.want) } }) } } <file_sep>package queue import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/uuid" ) const ( defaultAddress = "localhost:50000" defaultWaitTimeout = 5 defaultSources = 1 ) type options struct { host string port int clientId string authToken string channel string responseChannel string sources int batchSize int waitTimeout int doNotParsePayload bool } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.host, o.port, err = cfg.Properties.MustParseAddress("address", defaultAddress) if err != nil { return options{}, fmt.Errorf("error parsing address value, %w", err) } o.authToken = cfg.Properties.ParseString("auth_token", "") o.clientId = cfg.Properties.ParseString("client_id", uuid.New().String()) o.channel, err = cfg.Properties.MustParseString("channel") if err != nil { return options{}, fmt.Errorf("error parsing channel value, %w", err) } o.responseChannel = cfg.Properties.ParseString("response_channel", "") o.sources, err = cfg.Properties.ParseIntWithRange("sources", defaultSources, 1, 100) if err != nil { return options{}, fmt.Errorf("error parsing sources value, %w", err) } o.batchSize, err = cfg.Properties.ParseIntWithRange("batch_size", 1, 1, 1024) if err != nil { return options{}, fmt.Errorf("error parsing batch size value, %w", err) } o.waitTimeout, err = cfg.Properties.ParseIntWithRange("wait_timeout", defaultWaitTimeout, 1, 24*60*60) if err != nil { return options{}, fmt.Errorf("error parsing wait timeout value, %w", err) } o.doNotParsePayload = cfg.Properties.ParseBool("do_not_parse_payload", false) return o, nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { dat, err := ioutil.ReadFile("./credentials/tableName.txt") if err != nil { panic(err) } tableName := string(dat) dat, err = ioutil.ReadFile("./credentials/querySpanner.txt") if err != nil { panic(err) } query := string(dat) client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // set request setRequest := types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("query", query) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.gcp.spanner"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } queryResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get query request for query: %s executed, response: %s", query, queryResponse.Data)) // read columnNames := []string{"id", "name"} b, err := json.Marshal(columnNames) if err != nil { log.Fatal(err) } readRequest := types.NewRequest(). SetMetadataKeyValue("method", "read"). SetMetadataKeyValue("table_name", tableName). SetData(b) read, err := client.SetQuery(readRequest.ToQuery()). SetChannel("query.gcp.spanner"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getReadResponse, err := types.ParseResponse(read.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("read executed, response: %s", getReadResponse.Data)) } <file_sep>package command import ( "fmt" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/uuid" ) const ( defaultAutoReconnect = true defaultSources = 1 ) type options struct { host string port int clientId string authToken string channel string group string autoReconnect bool reconnectIntervalSeconds time.Duration maxReconnects int sources int doNotParsePayload bool } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.host, o.port, err = cfg.Properties.MustParseAddress("address", "") if err != nil { return options{}, fmt.Errorf("error parsing address value, %w", err) } o.authToken = cfg.Properties.ParseString("auth_token", "") o.clientId = cfg.Properties.ParseString("client_id", uuid.New().String()) o.channel, err = cfg.Properties.MustParseString("channel") if err != nil { return o, fmt.Errorf("error parsing channel value, %w", err) } o.sources, err = cfg.Properties.ParseIntWithRange("sources", defaultSources, 1, 1024) if err != nil { return options{}, fmt.Errorf("error parsing sources value, %w", err) } o.group = cfg.Properties.ParseString("group", "") o.autoReconnect = cfg.Properties.ParseBool("auto_reconnect", defaultAutoReconnect) interval, err := cfg.Properties.ParseIntWithRange("reconnect_interval_seconds", 0, 0, 1000000) if err != nil { return o, fmt.Errorf("error parsing reconnect interval seconds value, %w", err) } o.reconnectIntervalSeconds = time.Duration(interval) * time.Second o.maxReconnects = cfg.Properties.ParseInt("max_reconnects", 0) o.doNotParsePayload = cfg.Properties.ParseBool("do_not_parse_payload", false) return o, nil } <file_sep>package firestore import ( "context" "encoding/json" "errors" "fmt" "cloud.google.com/go/firestore" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/iterator" "google.golang.org/api/option" ) type Client struct { log *logger.Logger opts options client *firestore.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) client, err := firestore.NewClient(ctx, c.opts.projectID, option.WithCredentialsJSON(b)) if err != nil { return err } c.client = client return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "documents_all": return c.documentAll(ctx, meta) case "document_key": return c.documentKey(ctx, meta) case "add": return c.add(ctx, meta, req.Data) case "delete_document_key": return c.deleteDocument(ctx, meta) } return nil, errors.New("invalid method type") } func (c *Client) add(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { m := make(map[string]interface{}) err := json.Unmarshal(data, &m) if err != nil { return nil, fmt.Errorf("failed to parse data as map") } _, _, err = c.client.Collection(meta.key).Add(ctx, m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("collection", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) documentAll(ctx context.Context, meta metadata) (*types.Response, error) { iter := c.client.Collection(meta.key).Documents(ctx) var retData []map[string]interface{} for { doc, err := iter.Next() if err == iterator.Done { break } if err != nil { return nil, err } retData = append(retData, doc.Data()) } if len(retData) <= 0 { return nil, fmt.Errorf("no data found for this key") } data, err := json.Marshal(retData) if err != nil { return nil, err } return types.NewResponse(). SetData(data). SetMetadataKeyValue("collection", meta.key), nil } func (c *Client) documentKey(ctx context.Context, meta metadata) (*types.Response, error) { obj, err := c.client.Collection(meta.key).Doc(meta.item).Get(ctx) if err != nil { return nil, err } data, err := json.Marshal(obj.Data()) if err != nil { return nil, err } return types.NewResponse(). SetData(data). SetMetadataKeyValue("item", meta.item). SetMetadataKeyValue("collection", meta.key), nil } func (c *Client) deleteDocument(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.Collection(meta.key).Doc(meta.item).Delete(ctx) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("item", meta.item). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("collection", meta.key), nil } func (c *Client) list(ctx context.Context) (*types.Response, error) { var collections []string it := c.client.Collections(ctx) for { collection, err := it.Next() if err == iterator.Done { break } if err != nil { return nil, err } collections = append(collections, collection.ID) } if len(collections) <= 0 { return nil, fmt.Errorf("no collections found for this project") } data, err := json.Marshal(collections) if err != nil { return nil, err } return types.NewResponse(). SetData(data). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.client != nil { return c.client.Close() } return nil } <file_sep>package elastic import ( "context" "fmt" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "github.com/olivere/elastic/v7" ) type Client struct { log *logger.Logger elastic *elastic.Client opts options } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } var elasticOpts []elastic.ClientOptionFunc elasticOpts = append(elasticOpts, elastic.SetURL(c.opts.urls...), elastic.SetSniff(c.opts.sniff), elastic.SetBasicAuth(c.opts.username, c.opts.password)) c.elastic, err = elastic.NewClient(elasticOpts...) if err != nil { return err } _, _, err = c.elastic.Ping(c.opts.urls[0]).Do(ctx) if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.Get(ctx, meta) case "set": return c.Set(ctx, meta, req.Data) case "delete": return c.Delete(ctx, meta) case "index.exists": return c.IndexExists(ctx, meta) case "index.create": return c.IndexCreate(ctx, meta, req.Data) case "index.delete": return c.IndexDelete(ctx, meta) default: return nil, fmt.Errorf("invalid method") } } func (c *Client) Get(ctx context.Context, meta metadata) (*types.Response, error) { getResp, err := c.elastic.Get().Index(meta.index).Id(meta.id).Do(ctx) if err != nil { return nil, err } return types.NewResponse(). SetData(getResp.Source). SetMetadataKeyValue("id", meta.id), nil } func (c *Client) Set(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { setResp, err := c.elastic.Index().Index(meta.index).Id(meta.id).BodyString(string(value)).Do(ctx) if err != nil { return nil, fmt.Errorf("failed to set document id %s: %s", meta.id, err) } return types.NewResponse(). SetMetadataKeyValue("id", setResp.Id). SetMetadataKeyValue("result", setResp.Result), nil } func (c *Client) Delete(ctx context.Context, meta metadata) (*types.Response, error) { delResp, err := c.elastic.Delete().Index(meta.index).Id(meta.id).Do(ctx) if err != nil { return nil, fmt.Errorf("failed to delete id '%s',%w", meta.id, err) } return types.NewResponse(). SetMetadataKeyValue("id", delResp.Id). SetMetadataKeyValue("result", delResp.Result), nil } func (c *Client) IndexExists(ctx context.Context, meta metadata) (*types.Response, error) { exists, err := c.elastic.IndexExists(meta.index).Do(ctx) if err != nil { return nil, fmt.Errorf("failed to execute index exist '%s',%w", meta.index, err) } return types.NewResponse(). SetMetadataKeyValue("exists", fmt.Sprintf("%t", exists)), nil } func (c *Client) IndexCreate(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { result, err := c.elastic.CreateIndex(meta.index).BodyString(string(value)).Do(ctx) if err != nil { return nil, fmt.Errorf("failed to create index'%s',%w", meta.index, err) } return types.NewResponse(). SetMetadataKeyValue("acknowledged", fmt.Sprintf("%t", result.Acknowledged)). SetMetadataKeyValue("shards_acknowledged", fmt.Sprintf("%t", result.ShardsAcknowledged)). SetMetadataKeyValue("index", result.Index), nil } func (c *Client) IndexDelete(ctx context.Context, meta metadata) (*types.Response, error) { result, err := c.elastic.DeleteIndex(meta.index).Do(ctx) if err != nil { return nil, fmt.Errorf("failed to delete index'%s',%w", meta.index, err) } return types.NewResponse(). SetMetadataKeyValue("acknowledged", fmt.Sprintf("%t", result.Acknowledged)), nil } func (c *Client) Stop() error { return nil } <file_sep>package mysql import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("stores.mysql"). SetDescription("MySQL Target"). SetName("MySQL"). SetProvider(""). SetCategory("Store"). SetTags("db", "sql"). AddProperty( common.NewProperty(). SetKind("string"). SetName("connection"). SetTitle("Connection String"). SetDescription("Set MySQL connection string"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_idle_connections"). SetDescription("Set MySQL max idle connections"). SetMust(false). SetDefault("10"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_open_connections"). SetDescription("Set MySQL max open connections"). SetMust(false). SetDefault("100"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connection_max_lifetime_seconds"). SetTitle("Connection Lifetime (Seconds)"). SetDescription("Set MySQL connection max lifetime seconds"). SetMust(false). SetDefault("3600"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set MySql execution method"). SetOptions([]string{"query", "exec", "transaction"}). SetDefault("query"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("isolation_level"). SetKind("string"). SetDescription("Set MySql isolation level"). SetOptions([]string{"Default", "ReadUncommitted", "ReadCommitted", "RepeatableRead", "Serializable"}). SetDefault("Default"). SetMust(false), ) } <file_sep>package middleware import ( "context" "github.com/kubemq-io/kubemq-targets/pkg/retry" "github.com/kubemq-io/kubemq-targets/types" ) type Middleware interface { Do(ctx context.Context, request *types.Request) (*types.Response, error) } type DoFunc func(ctx context.Context, request *types.Request) (*types.Response, error) func (df DoFunc) Do(ctx context.Context, request *types.Request) (*types.Response, error) { return df(ctx, request) } type MiddlewareFunc func(Middleware) Middleware func Log(log *LogMiddleware) MiddlewareFunc { return func(df Middleware) Middleware { return DoFunc(func(ctx context.Context, request *types.Request) (*types.Response, error) { result, err := df.Do(ctx, request) switch log.minLevel { case "debug": reqStr := "" if request != nil { reqStr = request.String() } resStr := "" if result != nil { resStr = result.String() } log.Infof("request: %s, response: %s, error:%+v", reqStr, resStr, err) case "info": reqStr := "" if request != nil { reqStr = request.Metadata.String() } resStr := "" if result != nil { resStr = result.Metadata.String() } if err != nil { log.Errorf("error processing request: %s, response: %s, error:%s", reqStr, resStr, err.Error()) } else { log.Infof("successful processing request: %s, response: %s", reqStr, resStr) } case "error": reqStr := "" if request != nil { reqStr = request.Metadata.String() } resStr := "" if result != nil { resStr = result.Metadata.String() } if err != nil { log.Errorf("error processing request: %s, response: %s, error:%s", reqStr, resStr, err.Error()) } } return result, err }) } } func RateLimiter(rl *RateLimitMiddleware) MiddlewareFunc { return func(df Middleware) Middleware { return DoFunc(func(ctx context.Context, request *types.Request) (*types.Response, error) { rl.Take() return df.Do(ctx, request) }) } } func Retry(r *RetryMiddleware) MiddlewareFunc { return func(df Middleware) Middleware { return DoFunc(func(ctx context.Context, request *types.Request) (*types.Response, error) { var resp *types.Response err := retry.Do(func() error { var doErr error resp, doErr = df.Do(ctx, request) if doErr != nil { return doErr } return nil }, r.opts...) return resp, err }) } } func Metric(m *MetricsMiddleware) MiddlewareFunc { return func(df Middleware) Middleware { return DoFunc(func(ctx context.Context, request *types.Request) (*types.Response, error) { resp, err := df.Do(ctx, request) m.clearReport() if request != nil { m.metricReport.RequestVolume = request.Size() m.metricReport.RequestCount = 1 } if resp != nil { m.metricReport.ResponseVolume = resp.Size() m.metricReport.ResponseCount = 1 } if err != nil { m.metricReport.ErrorsCount = 1 } m.exporter.Report(m.metricReport) return resp, err }) } } func Metadata(m *MetadataMiddleware) MiddlewareFunc { return func(df Middleware) Middleware { return DoFunc(func(ctx context.Context, request *types.Request) (*types.Response, error) { for key, val := range m.Metadata { request.SetMetadataKeyValue(key, val) } return df.Do(ctx, request) }) } } func Chain(md Middleware, list ...MiddlewareFunc) Middleware { chain := md for _, middleware := range list { chain = middleware(chain) } return chain } <file_sep>//go:build container // +build container package targets import ( "context" "fmt" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/targets/aws/amazonmq" "github.com/kubemq-io/kubemq-targets/targets/aws/athena" "github.com/kubemq-io/kubemq-targets/targets/aws/cloudwatch/events" "github.com/kubemq-io/kubemq-targets/targets/aws/cloudwatch/logs" "github.com/kubemq-io/kubemq-targets/targets/aws/cloudwatch/metrics" "github.com/kubemq-io/kubemq-targets/targets/aws/dynamodb" "github.com/kubemq-io/kubemq-targets/targets/aws/elasticsearch" "github.com/kubemq-io/kubemq-targets/targets/aws/keyspaces" "github.com/kubemq-io/kubemq-targets/targets/aws/kinesis" "github.com/kubemq-io/kubemq-targets/targets/aws/lambda" "github.com/kubemq-io/kubemq-targets/targets/aws/msk" "github.com/kubemq-io/kubemq-targets/targets/aws/s3" "github.com/kubemq-io/kubemq-targets/targets/aws/sns" "github.com/kubemq-io/kubemq-targets/targets/azure/eventhubs" "github.com/kubemq-io/kubemq-targets/targets/azure/servicebus" "github.com/kubemq-io/kubemq-targets/targets/azure/storage/blob" "github.com/kubemq-io/kubemq-targets/targets/azure/storage/files" "github.com/kubemq-io/kubemq-targets/targets/azure/storage/queue" "github.com/kubemq-io/kubemq-targets/targets/azure/stores/azuresql" azurmysql "github.com/kubemq-io/kubemq-targets/targets/azure/stores/mysql" azurpostgres "github.com/kubemq-io/kubemq-targets/targets/azure/stores/postgres" "github.com/kubemq-io/kubemq-targets/targets/cache/hazelcast" "github.com/kubemq-io/kubemq-targets/targets/echo" "github.com/kubemq-io/kubemq-targets/targets/gcp/firebase" "github.com/kubemq-io/kubemq-targets/targets/messaging/nats" "github.com/kubemq-io/kubemq-targets/targets/storage/filesystem" "github.com/kubemq-io/kubemq-targets/targets/storage/hdfs" "github.com/kubemq-io/kubemq-targets/targets/stores/aerospike" "github.com/kubemq-io/kubemq-targets/targets/stores/cockroachdb" "github.com/kubemq-io/kubemq-targets/targets/stores/consulkv" "github.com/kubemq-io/kubemq-targets/targets/stores/crate" "github.com/kubemq-io/kubemq-targets/targets/stores/elastic" "github.com/kubemq-io/kubemq-targets/targets/stores/percona" "github.com/kubemq-io/kubemq-targets/targets/stores/rethinkdb" "github.com/kubemq-io/kubemq-targets/targets/stores/singlestore" "github.com/kubemq-io/kubemq-targets/config" awsmariadb "github.com/kubemq-io/kubemq-targets/targets/aws/rds/mariadb" awsmssql "github.com/kubemq-io/kubemq-targets/targets/aws/rds/mssql" awsmysql "github.com/kubemq-io/kubemq-targets/targets/aws/rds/mysql" awspostgres "github.com/kubemq-io/kubemq-targets/targets/aws/rds/postgres" "github.com/kubemq-io/kubemq-targets/targets/aws/rds/redshift" redshiftsvc "github.com/kubemq-io/kubemq-targets/targets/aws/redshift" "github.com/kubemq-io/kubemq-targets/targets/aws/sqs" "github.com/kubemq-io/kubemq-targets/targets/cache/memcached" "github.com/kubemq-io/kubemq-targets/targets/cache/redis" "github.com/kubemq-io/kubemq-targets/targets/gcp/bigquery" "github.com/kubemq-io/kubemq-targets/targets/gcp/bigtable" "github.com/kubemq-io/kubemq-targets/targets/gcp/cloudfunctions" "github.com/kubemq-io/kubemq-targets/targets/gcp/firestore" gcpmemcached "github.com/kubemq-io/kubemq-targets/targets/gcp/memorystore/memcached" gcpredis "github.com/kubemq-io/kubemq-targets/targets/gcp/memorystore/redis" "github.com/kubemq-io/kubemq-targets/targets/gcp/pubsub" "github.com/kubemq-io/kubemq-targets/targets/gcp/spanner" gcpmysql "github.com/kubemq-io/kubemq-targets/targets/gcp/sql/mysql" gcppostgres "github.com/kubemq-io/kubemq-targets/targets/gcp/sql/postgres" "github.com/kubemq-io/kubemq-targets/targets/gcp/storage" "github.com/kubemq-io/kubemq-targets/targets/http" "github.com/kubemq-io/kubemq-targets/targets/messaging/activemq" "github.com/kubemq-io/kubemq-targets/targets/messaging/ibmmq" "github.com/kubemq-io/kubemq-targets/targets/messaging/kafka" "github.com/kubemq-io/kubemq-targets/targets/messaging/mqtt" "github.com/kubemq-io/kubemq-targets/targets/messaging/rabbitmq" "github.com/kubemq-io/kubemq-targets/targets/serverless/openfaas" "github.com/kubemq-io/kubemq-targets/targets/storage/minio" "github.com/kubemq-io/kubemq-targets/targets/stores/cassandra" "github.com/kubemq-io/kubemq-targets/targets/stores/couchbase" "github.com/kubemq-io/kubemq-targets/targets/stores/mongodb" "github.com/kubemq-io/kubemq-targets/targets/stores/mssql" "github.com/kubemq-io/kubemq-targets/targets/stores/mysql" "github.com/kubemq-io/kubemq-targets/targets/stores/postgres" "github.com/kubemq-io/kubemq-targets/types" ) type Target interface { Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error Do(ctx context.Context, request *types.Request) (*types.Response, error) Stop() error Connector() *common.Connector } func Init(ctx context.Context, cfg config.Spec, log *logger.Logger) (Target, error) { switch cfg.Kind { case "storage.filesystem": target := filesystem.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "echo": target := echo.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.sqs": target := sqs.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.sns": target := sns.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.s3": target := s3.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.lambda": target := lambda.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.dynamodb": target := dynamodb.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.athena": target := athena.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.kinesis": target := kinesis.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.elasticsearch": target := elasticsearch.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.cloudwatch.logs": target := logs.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.cloudwatch.events": target := events.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.cloudwatch.metrics": target := metrics.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.rds.mysql": target := awsmysql.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.rds.postgres": target := awspostgres.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.rds.mariadb": target := awsmariadb.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.rds.mssql": target := awsmssql.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.rds.redshift": target := redshift.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.redshift.service": target := redshiftsvc.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.keyspaces": target := keyspaces.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.msk": target := msk.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "aws.amazonmq": target := amazonmq.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "cache.redis": target := redis.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "cache.memcached": target := memcached.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "cache.hazelcast": target := hazelcast.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.cache.memcached": target := gcpmemcached.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.cache.redis": target := gcpredis.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.bigquery": target := bigquery.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.bigtable": target := bigtable.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.cloudfunctions": target := cloudfunctions.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.firestore": target := firestore.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.firebase": target := firebase.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.stores.postgres": target := gcppostgres.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.stores.mysql": target := gcpmysql.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.pubsub": target := pubsub.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.spanner": target := spanner.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "gcp.storage": target := storage.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "http": target := http.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "messaging.activemq": target := activemq.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "messaging.kafka": target := kafka.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "messaging.mqtt": target := mqtt.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "messaging.rabbitmq": target := rabbitmq.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil // case "messaging.ibmmq": // target := ibmmq.New() // if err := target.Init(ctx, cfg); err != nil { // return nil, err // } // return target, nil case "messaging.nats": target := nats.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.cassandra": target := cassandra.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.couchbase": target := couchbase.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.mongodb": target := mongodb.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.mssql": target := mssql.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.mysql": target := mysql.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.crate": target := crate.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.elasticsearch": target := elastic.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.postgres": target := postgres.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.cockroachdb": target := cockroachdb.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.percona": target := percona.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.aerospike": target := aerospike.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.rethinkdb": target := rethinkdb.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.singlestore": target := singlestore.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "stores.consulkv": target := consulkv.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "serverless.openfaas": target := openfaas.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "storage.minio": target := minio.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "storage.hdfs": target := hdfs.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.storage.blob": target := blob.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.storage.queue": target := queue.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.storage.files": target := files.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.eventhubs": target := eventhubs.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.servicebus": target := servicebus.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.stores.azuresql": target := azuresql.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.stores.postgres": target := azurpostgres.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil case "azure.stores.mysql": target := azurmysql.New() if err := target.Init(ctx, cfg, log); err != nil { return nil, err } return target, nil default: return nil, fmt.Errorf("invalid kind %s for target %s", cfg.Kind, cfg.Name) } } func Connectors() common.Connectors { return []*common.Connector{ echo.Connector(), // cache redis.Connector(), memcached.Connector(), // stores postgres.Connector(), crate.Connector(), mysql.Connector(), mssql.Connector(), mongodb.Connector(), elastic.Connector(), cassandra.Connector(), couchbase.Connector(), cockroachdb.Connector(), percona.Connector(), aerospike.Connector(), rethinkdb.Connector(), singlestore.Connector(), consulkv.Connector(), // http http.Connector(), // messaging mqtt.Connector(), rabbitmq.Connector(), kafka.Connector(), activemq.Connector(), ibmmq.Connector(), nats.Connector(), hazelcast.Connector(), // storage minio.Connector(), hdfs.Connector(), filesystem.Connector(), // serverless openfaas.Connector(), // aws sqs.Connector(), sns.Connector(), s3.Connector(), amazonmq.Connector(), awspostgres.Connector(), awsmysql.Connector(), awsmariadb.Connector(), awsmssql.Connector(), dynamodb.Connector(), redshift.Connector(), redshiftsvc.Connector(), athena.Connector(), msk.Connector(), lambda.Connector(), kinesis.Connector(), keyspaces.Connector(), elasticsearch.Connector(), events.Connector(), logs.Connector(), metrics.Connector(), // gcp pubsub.Connector(), gcpredis.Connector(), gcpmemcached.Connector(), gcppostgres.Connector(), gcpmysql.Connector(), spanner.Connector(), bigtable.Connector(), bigquery.Connector(), cloudfunctions.Connector(), firebase.Connector(), firestore.Connector(), storage.Connector(), // azure azurpostgres.Connector(), azurmysql.Connector(), azuresql.Connector(), queue.Connector(), files.Connector(), blob.Connector(), servicebus.Connector(), eventhubs.Connector(), } } <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) type testStructure struct { object string renameObject string bucket string filePath string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./credentials/storage/object.txt") if err != nil { return nil, err } t.object = string(dat) dat, err = ioutil.ReadFile("./credentials/storage/renameObject.txt") if err != nil { return nil, err } t.renameObject = string(dat) dat, err = ioutil.ReadFile("./credentials/storage/bucket.txt") if err != nil { return nil, err } t.bucket = string(dat) dat, err = ioutil.ReadFile("./credentials/storage/filePath.txt") if err != nil { return nil, err } t.filePath = string(dat) return t, nil } func main() { dat, err := getTestStructure() if err != nil { panic(err) } client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // add file setRequest := types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("bucket", dat.bucket). SetMetadataKeyValue("path", dat.filePath). SetMetadataKeyValue("object", dat.object) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.gcp.storage"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("upload file request for bucket : %s executed, is_error: %v", dat.bucket, setResponse.IsError)) } <file_sep>package keyspaces import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultKey = "" DefaultTable = "" DefaultKeyspace = "" ) var methodsMap = map[string]string{ "get": "get", "set": "set", "delete": "delete", "query": "query", "exec": "exec", } var consistencyMap = map[string]string{ "One": "One", "LocalOne": "LocalOne", "LocalQuorum": "LocalQuorum", "": "", } type metadata struct { method string key string consistency string table string keyspace string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.key = meta.ParseString("key", DefaultKey) m.consistency, err = meta.ParseStringMap("consistency", consistencyMap) if err != nil { return metadata{}, fmt.Errorf("error on parsing consistency, %w", err) } m.table = meta.ParseString("table", DefaultTable) m.keyspace = meta.ParseString("keyspace", DefaultKeyspace) return m, nil } func (m metadata) keyspaceTable() string { if m.keyspace != "" && m.table != "" { return fmt.Sprintf("%s.%s", m.keyspace, m.table) } return "" } <file_sep>package aerospike import ( "fmt" "math" "time" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { host string port int password string username string timeout time.Duration } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.host, err = cfg.Properties.MustParseString("host") if err != nil { return options{}, fmt.Errorf("error parsing host, %w", err) } o.port, err = cfg.Properties.MustParseInt("port") if err != nil { return options{}, fmt.Errorf("error parsing port, %w", err) } o.username = cfg.Properties.ParseString("username", "") o.password = cfg.Properties.ParseString("password", "") timeout, err := cfg.Properties.ParseIntWithRange("timeout", 2, 0, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error operation timeout seconds, %w", err) } o.timeout = time.Duration(timeout) * time.Second return o, nil } <file_sep>package kafka import ( "context" b64 "encoding/base64" "strings" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func replaceHeaderValues(req *types.Request) { r := strings.NewReplacer( "_replaceHK_", b64.StdEncoding.EncodeToString([]byte("header1")), "_replaceHV_", b64.StdEncoding.EncodeToString([]byte("headervalue1"))) req.Metadata["Headers"] = r.Replace(req.Metadata["Headers"]) } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "messaging-kafka", Kind: "messaging.kafka", Properties: map[string]string{ "brokers": "localhost:9092", "topic": "TestTopic", }, }, wantErr: false, }, { name: "invalid init - missing brokers", cfg: config.Spec{ Name: "messaging-kafka", Kind: "messaging.kafka", Properties: map[string]string{ "topic": "TestTopic", }, }, wantErr: true, }, { name: "invalid init - missing topic", cfg: config.Spec{ Name: "messaging-kafka", Kind: "messaging.kafka", Properties: map[string]string{ "brokers": "localhost:9092", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantExecErr %v", err, tt.wantErr) return } }) } } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantResponse *types.Response wantErr bool }{ { name: "valid publish request ", cfg: config.Spec{ Name: "messaging-kafka", Kind: "messaging.kafka", Properties: map[string]string{ "brokers": "localhost:9092", "topic": "TestTopic", }, }, request: types.NewRequest(). SetMetadataKeyValue("Key", "S2V5"). SetData([]byte("new-data")), wantResponse: types.NewResponse(). SetMetadataKeyValue("partition", "0"). SetMetadataKeyValue("offset", "1"), wantErr: false, }, { name: "valid publish request with headers", cfg: config.Spec{ Name: "messaging-kafka", Kind: "messaging.kafka", Properties: map[string]string{ "brokers": "localhost:9092", "topic": "TestTopic", }, }, request: types.NewRequest(). SetMetadataKeyValue("Key", "S2V5"). SetData([]byte("new-data")).SetMetadataKeyValue( "Headers", `[{"Key": "_replaceHK_","Value": "_replaceHV_"}]`), wantResponse: types.NewResponse(). SetMetadataKeyValue("partition", "0"). SetMetadataKeyValue("offset", "2"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) replaceHeaderValues(tt.request) gotResponse, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotResponse) require.EqualValues(t, tt.wantResponse, gotResponse) }) } } <file_sep>package storage import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.storage"). SetDescription("GCP Storage Target"). SetName("Storage"). SetProvider("GCP"). SetCategory("Storage"). SetTags("db", "filesystem", "object", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set GCP Storage method"). SetOptions([]string{"upload", "create_bucket", "download", "delete", "rename", "copy", "move", "list"}). SetDefault("create_bucket"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("object"). SetKind("string"). SetDescription("Set object name to save the file under"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("rename_object"). SetKind("string"). SetDescription("Set GCP name to change the file name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("bucket"). SetKind("string"). SetDescription("Set Storage bucket name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("dst_bucket"). SetKind("string"). SetDescription("Set the bucket name of the destination"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("path"). SetKind("string"). SetDescription("Set path to the file for upload"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("project_id"). SetKind("string"). SetDescription("Set GCP storage project id "). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("storage_class"). SetKind("string"). SetDescription("Set GCP storage class"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("location"). SetKind("string"). SetDescription("Set GCP storage location"). SetDefault(""). SetMust(false), ) } <file_sep>package middleware import ( "fmt" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type LogLevelType string const ( LogLevelTypeNoLog LogLevelType = "" LogLevelTypeDebug LogLevelType = "debug" LogLevelTypeInfo LogLevelType = "info" LogLevelTypeError LogLevelType = "error" ) var logLevelMap = map[string]string{ "debug": "debug", "info": "info", "error": "error", "": "", } type LogMiddleware struct { minLevel LogLevelType *logger.Logger } func NewLogMiddleware(name string, meta types.Metadata) (*LogMiddleware, error) { level, err := meta.ParseStringMap("log_level", logLevelMap) if err != nil { return nil, fmt.Errorf("invalid log level value, %w", err) } lm := &LogMiddleware{ minLevel: LogLevelTypeNoLog, Logger: logger.NewLogger(name, level), } switch level { case "debug": lm.minLevel = LogLevelTypeDebug case "info": lm.minLevel = LogLevelTypeInfo case "error": lm.minLevel = LogLevelTypeError } return lm, nil } <file_sep>package spanner import ( "context" "encoding/json" "errors" "fmt" "cloud.google.com/go/spanner" database "cloud.google.com/go/spanner/admin/database/apiv1" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/iterator" "google.golang.org/api/option" adminpb "google.golang.org/genproto/googleapis/spanner/admin/database/v1" ) type Client struct { opts options client *spanner.Client adminClient *database.DatabaseAdminClient log *logger.Logger } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } c.log = logger.NewLogger(cfg.Name) var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) adminClient, err := database.NewDatabaseAdminClient(ctx, option.WithCredentialsJSON(b)) if err != nil { return err } c.adminClient = adminClient Client, err := spanner.NewClient(ctx, c.opts.db, option.WithCredentialsJSON(b)) if err != nil { return err } c.client = Client return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "query": return c.query(ctx, meta) case "read": return c.read(ctx, meta, req.Data) case "update_database_ddl": return c.updateDatabaseDdl(ctx, req.Data) case "insert": return c.insert(ctx, req.Data) case "update": return c.update(ctx, req.Data) case "insert_or_update": return c.insertOrUpdate(ctx, req.Data) default: return nil, errors.New("invalid method type") } } func (c *Client) query(ctx context.Context, meta metadata) (*types.Response, error) { stmt := spanner.Statement{SQL: meta.query} i := c.client.Single().Query(ctx, stmt) rows, err := c.getRowsFromIterator(i) if err != nil { return nil, err } if len(rows) == 0 { return nil, fmt.Errorf("no rows found") } b, err := json.Marshal(rows) if err != nil { return nil, err } var q []spanner.Row err = json.Unmarshal(b, &q) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) insert(ctx context.Context, body []byte) (*types.Response, error) { var inserts []InsertOrUpdate err := json.Unmarshal(body, &inserts) if err != nil { return nil, err } if len(inserts) == 0 { return nil, fmt.Errorf("failed to get valid InsertOrUpdate struct") } var m []*spanner.Mutation for _, i := range inserts { err = i.validate() if err != nil { return nil, err } m = append(m, spanner.Insert(i.TableName, i.ColumnName, i.ColumnValue)) } _, err = c.client.Apply(ctx, m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) update(ctx context.Context, body []byte) (*types.Response, error) { var updates []InsertOrUpdate err := json.Unmarshal(body, &updates) if err != nil { return nil, err } if len(updates) == 0 { return nil, fmt.Errorf("failed to get valid InsertOrUpdate struct") } var m []*spanner.Mutation for _, i := range updates { err = i.validate() if err != nil { return nil, err } m = append(m, spanner.Update(i.TableName, i.ColumnName, i.ColumnValue)) } _, err = c.client.Apply(ctx, m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) insertOrUpdate(ctx context.Context, body []byte) (*types.Response, error) { var insertsOrUpdates []InsertOrUpdate err := json.Unmarshal(body, &insertsOrUpdates) if err != nil { return nil, err } if err != nil { return nil, err } if len(insertsOrUpdates) == 0 { return nil, fmt.Errorf("failed to get valid InsertOrUpdate struct") } var m []*spanner.Mutation for _, i := range insertsOrUpdates { err = i.validate() if err != nil { return nil, err } m = append(m, spanner.InsertOrUpdate(i.TableName, i.ColumnName, i.ColumnValue)) } _, err = c.client.Apply(ctx, m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) read(ctx context.Context, meta metadata, body []byte) (*types.Response, error) { var columns []string err := json.Unmarshal(body, &columns) if err != nil { return nil, fmt.Errorf("failed to parse body as []strings for columns on error %s", err.Error()) } iter := c.client.Single().Read(ctx, meta.tableName, spanner.AllKeys(), columns) rows, err := c.getRowsFromIterator(iter) if err != nil { return nil, err } if len(rows) == 0 { return nil, fmt.Errorf("no rows found") } b, err := json.Marshal(rows) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) getRowsFromIterator(iter *spanner.RowIterator) ([]*Row, error) { var rows []*Row defer iter.Stop() for { row, err := iter.Next() if err == iterator.Done { return rows, nil } if err != nil { return rows, fmt.Errorf("error iterating through results: %v", err) } r, err := extractDataByType(row) if err != nil { return nil, err } rows = append(rows, r) } } func (c *Client) updateDatabaseDdl(ctx context.Context, body []byte) (*types.Response, error) { var Statements []string err := json.Unmarshal(body, &Statements) if err != nil { return nil, fmt.Errorf("failed to parse body as []strings for args on error %s", err.Error()) } if len(Statements) == 0 { return nil, fmt.Errorf("failed to get valid Statements struct") } op, err := c.adminClient.UpdateDatabaseDdl(ctx, &adminpb.UpdateDatabaseDdlRequest{ Database: c.opts.db, Statements: Statements, }) if err != nil { return nil, err } // nolint:staticcheck b, err := json.Marshal(op) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { if c.client != nil { c.client.Close() return c.adminClient.Close() } return nil } <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // make bucket makeRequest := types.NewRequest(). SetMetadataKeyValue("method", "make_bucket"). SetMetadataKeyValue("param1", "testbucket") response, err := client.SetQuery(makeRequest.ToQuery()). SetChannel("query.minio"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } makeResponse, err := types.ParseResponse(response.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("make bucket request response: %s", makeResponse.Metadata.String())) // put object putRequest := types.NewRequest(). SetMetadataKeyValue("method", "put"). SetMetadataKeyValue("param1", "testbucket"). SetMetadataKeyValue("param2", "object"). SetData([]byte("object")) response, err = client.SetQuery(putRequest.ToQuery()). SetChannel("query.minio"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } putResponse, err := types.ParseResponse(response.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("put object request response: %s", putResponse.Metadata.String())) // get list of object getListRequest := types.NewRequest(). SetMetadataKeyValue("method", "list_objects"). SetMetadataKeyValue("param1", "testbucket") response, err = client.SetQuery(getListRequest.ToQuery()). SetChannel("query.minio"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getListResponse, err := types.ParseResponse(response.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get list object request response: %s", string(getListResponse.Data))) // get object getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("param1", "testbucket"). SetMetadataKeyValue("param2", "object") response, err = client.SetQuery(getRequest.ToQuery()). SetChannel("query.minio"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(response.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get object request response: %s", string(getResponse.Data))) // remove object removeRequest := types.NewRequest(). SetMetadataKeyValue("method", "remove"). SetMetadataKeyValue("param1", "testbucket"). SetMetadataKeyValue("param2", "object") response, err = client.SetQuery(removeRequest.ToQuery()). SetChannel("query.minio"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } removeResponse, err := types.ParseResponse(response.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("remove object request response: %s", removeResponse.Metadata.String())) // remove bucket removeBucketRequest := types.NewRequest(). SetMetadataKeyValue("method", "remove_bucket"). SetMetadataKeyValue("param1", "testbucket") response, err = client.SetQuery(removeBucketRequest.ToQuery()). SetChannel("query.minio"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } removeBucketResponse, err := types.ParseResponse(response.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("remove bucket request response: %s", removeBucketResponse.Metadata.String())) } <file_sep>package pubsub import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { projectID string credentials string topicID string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/projectID.txt") if err != nil { return nil, err } t.projectID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") if err != nil { return nil, err } t.credentials = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/topicID.txt") if err != nil { return nil, err } t.topicID = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "gcp-pubsub", Kind: "gcp.pubsub", Properties: map[string]string{ "project_id": dat.projectID, "retries": "0", "credentials": dat.credentials, }, }, wantErr: false, }, { name: "invalid init-missing-credentials", cfg: config.Spec{ Name: "gcp-pubsub", Kind: "gcp.pubsub", Properties: map[string]string{ "project_id": dat.projectID, "retries": "0", }, }, wantErr: true, }, { name: "invalid init-missing-project-id", cfg: config.Spec{ Name: "gcp-pubsub", Kind: "gcp.pubsub", Properties: map[string]string{ "retries": "0", "credentials": dat.credentials, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Do(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) validBody, _ := json.Marshal("valid body") tests := []struct { name string cfg config.Spec request *types.Request want *types.Response wantErr bool }{ { name: "valid google-pubsub sent with tags", cfg: config.Spec{ Name: "gcp-pubsub", Kind: "gcp.pubsub", Properties: map[string]string{ "project_id": dat.projectID, "retries": "0", "topic_id": dat.topicID, "credentials": dat.credentials, }, }, request: types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("topic_id", dat.topicID). SetData(validBody), want: types.NewResponse(). SetData(validBody), wantErr: false, }, { name: "valid google-pubsub sent without tags", cfg: config.Spec{ Name: "gcp-pubsub", Kind: "gcp.pubsub", Properties: map[string]string{ "project_id": dat.projectID, "retries": "0", "topic_id": dat.topicID, "credentials": dat.credentials, }, }, request: types.NewRequest(). SetMetadataKeyValue("topic_id", dat.topicID). SetData(validBody), want: types.NewResponse(). SetData(validBody), wantErr: false, }, { name: "invalid missing topic google-pubsub sent", cfg: config.Spec{ Name: "gcp-pubsub", Kind: "gcp.pubsub", Properties: map[string]string{ "project_id": dat.projectID, "retries": "0", "credentials": dat.credentials, }, }, request: types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetData(validBody), want: types.NewResponse(). SetData(validBody), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_list(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "valid google-pubsub-list", cfg: config.Spec{ Name: "gcp-pubsub", Kind: "gcp.pubsub", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.credentials, }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) got, err := c.list(ctx) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.EqualValues(t, "ok", got.Metadata["result"]) require.NotNil(t, got) }) } } <file_sep>package hazelcast import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("cache.hazelcast"). SetDescription("hazelcast source properties"). SetName("Hazelcast"). SetProvider(""). SetCategory("Cache"). SetTags("db"). AddProperty( common.NewProperty(). SetKind("string"). SetName("address"). SetDescription("Set hazelcast address connection"). SetMust(true), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set Username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set Password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connection_attempt_limit"). SetDescription("Set connections attempt limit"). SetMust(false). SetDefault("1"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connection_attempt_period"). SetDescription("Set connections attempt period in seconds"). SetMust(false). SetDefault("5"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connection_timeout"). SetDescription("Set connections attempt timeout in seconds"). SetMust(false). SetDefault("5"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("server_name"). SetDescription("Set hazelcast server name"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("ssl"). SetTitle("Use SSL"). SetDescription("Set if use ssl"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("condition"). SetName("ssl"). SetTitle("SSL"). SetOptions([]string{"true", "false"}). SetDescription("Set ssl conditions"). SetMust(true). SetDefault("false"). NewCondition("true", []*common.Property{ common.NewProperty(). SetKind("multilines"). SetName("cert_key"). SetTitle("Certification Key"). SetDescription("Set certificate key"). SetMust(false). SetDefault(""), common.NewProperty(). SetKind("multilines"). SetName("cert_file"). SetTitle("Certification File"). SetDescription("Set certificate file"). SetMust(false). SetDefault(""), }), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("key"). SetDescription("Set key"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("map_name"). SetDescription("Set map name"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("list_name"). SetDescription("Set list name"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set execution method"). SetOptions([]string{"get", "set", "delete", "get_list"}). SetDefault("get"). SetMust(true), ) } <file_sep>package redshift import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { method string resourceName string resourceARN string } var methodsMap = map[string]string{ "create_tags": "create_tags", "delete_tags": "delete_tags", "list_tags": "list_tags", "list_snapshots": "list_snapshots", "list_snapshots_by_tags_keys": "list_snapshots_by_tags_keys", "list_snapshots_by_tags_values": "list_snapshots_by_tags_values", "describe_cluster": "describe_cluster", "list_clusters": "list_clusters", "list_clusters_by_tags_keys": "list_clusters_by_tags_keys", "list_clusters_by_tags_values": "list_clusters_by_tags_values", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "create_tags" || m.method == "delete_tags" { m.resourceARN, err = meta.MustParseString("resource_arn") if err != nil { return metadata{}, fmt.Errorf("resource_arn is required when using :%s,error parsing resource_arn, %w", m.method, err) } } else if m.method == "describe_cluster" { m.resourceName, err = meta.MustParseString("resource_name") if err != nil { return metadata{}, fmt.Errorf("resource_name is required when using :%s ,error parsing resource_name, %w", m.method, err) } } return m, nil } <file_sep>package builder import ( "fmt" "strings" "github.com/go-resty/resty/v2" "gopkg.in/yaml.v2" ) type ConnectorConfig struct { Kind string `json:"kind"` ApiVersion string `json:"apiVersion"` Metadata struct { Name string `json:"name"` Namespace string `json:"namespace"` } `json:"metadata"` Spec struct { Type string `json:"type"` Config string `json:"config"` } `json:"spec"` } func GetBuildManifest(url string) (*ConnectorConfig, error) { resp, err := resty.New().NewRequest().Get(url) if err != nil { return nil, err } manifests := string(resp.Body()) for _, manifest := range strings.Split(manifests, "\n---\n") { c, err := parseConnectorConfig(manifest) if err != nil { continue } return c, nil } return nil, fmt.Errorf("no valid connector configuration found ") } func parseConnectorConfig(manifest string) (*ConnectorConfig, error) { c := &ConnectorConfig{} err := yaml.Unmarshal([]byte(manifest), c) if err != nil { return nil, err } switch c.Spec.Type { case "bridges", "targets", "sources": return c, nil default: return nil, fmt.Errorf("config is not a connector") } } <file_sep>package command import ( "context" "errors" "fmt" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/middleware" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) var errInvalidTarget = errors.New("invalid target received, cannot be nil") type Client struct { opts options clients []*kubemq.Client log *logger.Logger target middleware.Middleware } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, bindingName string, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } for i := 0; i < c.opts.sources; i++ { clientId := fmt.Sprintf("kubemq-targets_%s_%s", bindingName, c.opts.clientId) if c.opts.sources > 1 { clientId = fmt.Sprintf("kubemq-targets_%s_%s-%d", bindingName, clientId, i) } client, err := kubemq.NewClient(ctx, kubemq.WithAddress(c.opts.host, c.opts.port), kubemq.WithClientId(clientId), kubemq.WithTransportType(kubemq.TransportTypeGRPC), kubemq.WithCheckConnection(true), kubemq.WithAuthToken(c.opts.authToken), kubemq.WithMaxReconnects(c.opts.maxReconnects), kubemq.WithAutoReconnect(c.opts.autoReconnect), kubemq.WithReconnectInterval(c.opts.reconnectIntervalSeconds)) if err != nil { return err } c.clients = append(c.clients, client) } return nil } func (c *Client) Start(ctx context.Context, target middleware.Middleware) error { if target == nil { return errInvalidTarget } else { c.target = target } if c.opts.sources > 1 && c.opts.group == "" { c.opts.group = uuid.New().String() } for i := 0; i < len(c.clients); i++ { err := c.runClient(ctx, c.clients[i]) if err != nil { return fmt.Errorf("error during start of client %d: %s", i, err.Error()) } } return nil } func (c *Client) runClient(ctx context.Context, client *kubemq.Client) error { errCh := make(chan error, 1) commandsCh, err := client.SubscribeToCommands(ctx, c.opts.channel, c.opts.group, errCh) if err != nil { return fmt.Errorf("error on subscribing to command channel, %w", err) } go func(ctx context.Context, commandCh <-chan *kubemq.CommandReceive, errCh chan error) { for { select { case command := <-commandCh: go func(q *kubemq.CommandReceive) { cmdResponse := client.R(). SetRequestId(command.Id). SetResponseTo(command.ResponseTo) _, err := c.processCommand(ctx, command) if err != nil { cmdResponse.SetError(err) } err = cmdResponse.Send(ctx) if err != nil { c.log.Errorf("error sending command response %s", err.Error()) } }(command) case err := <-errCh: c.log.Errorf("error received from kuebmq server, %s", err.Error()) return case <-ctx.Done(): return } } }(ctx, commandsCh, errCh) return nil } func (c *Client) processCommand(ctx context.Context, command *kubemq.CommandReceive) (*types.Response, error) { var req *types.Request var err error if c.opts.doNotParsePayload { req = types.NewRequest().SetData(command.Body) } else { req, err = types.ParseRequest(command.Body) if err != nil { return nil, fmt.Errorf("invalid request format, %w", err) } } resp, err := c.target.Do(ctx, req) if err != nil { return nil, err } return resp, nil } func (c *Client) Stop() error { for _, client := range c.clients { _ = client.Close() } return nil } <file_sep>package events import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultDetail = "" defaultDetailType = "" defaultSource = "" defaultLimit = 10 ) type metadata struct { method string rule string detail string detailType string source string limit int64 } var methodsMap = map[string]string{ "put_targets": "put_targets", "send_event": "send_event", "list_buses": "list_buses", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } m.detail = meta.ParseString("detail", defaultDetail) m.detailType = meta.ParseString("detail_type", defaultDetailType) m.source = meta.ParseString("source", defaultSource) if m.method == "put_targets" { m.rule, err = meta.MustParseString("rule") if err != nil { return metadata{}, fmt.Errorf("rule is required for method:%s ,error parsing rule, %w", m.method, err) } } m.limit = int64(meta.ParseInt("limit", defaultLimit)) return m, nil } <file_sep>package metrics import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string namespace string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" t.namespace = "Logs" return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init ", cfg: config.Spec{ Name: "aws-cloudwatch-metrics", Kind: "aws.cloudwatch.metrics", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: false, }, { name: "init - missing secret key", cfg: config.Spec{ Name: "aws-cloudwatch-metrics", Kind: "aws.cloudwatch.metrics", Properties: map[string]string{ "aws_key": dat.awsKey, "region": dat.region, }, }, wantErr: true, }, { name: "init - missing key", cfg: config.Spec{ Name: "aws-cloudwatch-metrics", Kind: "aws.cloudwatch.metrics", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_putMetrics(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-cloudwatch-metrics", Kind: "aws.cloudwatch.metrics", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() b := []byte(`[{"Counts":null,"Dimensions":null,"MetricName":"New Metric","StatisticValues":null,"StorageResolution":null,"Timestamp":"2020-08-12T17:09:48.3895822+03:00","Unit":"Count","Value":131,"Values":null}]`) err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid put", request: types.NewRequest(). SetMetadataKeyValue("method", "put_metrics"). SetMetadataKeyValue("namespace", dat.namespace). SetData(b), wantErr: false, }, { name: "invalid put - missing namespace", request: types.NewRequest(). SetMetadataKeyValue("method", "put_metrics"). SetData(b), wantErr: true, }, { name: "invalid put - missing data", request: types.NewRequest(). SetMetadataKeyValue("method", "put_metrics"). SetMetadataKeyValue("namespace", dat.namespace), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_listMetrics(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-cloudwatch-metrics", Kind: "aws.cloudwatch.metrics", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list metrics", request: types.NewRequest(). SetMetadataKeyValue("method", "list_metrics"). SetMetadataKeyValue("namespace", dat.namespace), wantErr: false, }, { name: "valid list metrics - all namespaces", request: types.NewRequest(). SetMetadataKeyValue("method", "list_metrics"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep># Kubemq hadoop target Connector Kubemq -hadoop target connector allows services using kubemq server to access hadoop service. ## Prerequisites The following required to run the -hadoop target connector: - kubemq cluster - hadoop active server - kubemq-targets deployment ## Configuration hadoop target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | address | yes | hadoop address | "localhost:9000" | | user | no | hadoop user | "my_user" | Example: ```yaml bindings: - name: kubemq-query--hadoop source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query--hadoop-connector" auth_token: "" channel: "query..hadoop" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: storage.hadoop name: hadoop properties: _key: "id" _secret_key: 'json' region: "region" token: "" downloader: "true" uploader: "true" ``` ## Usage ### Read File Read File: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | file_path | yes | path to file | "/test/foo2.txt" | | method | yes | type of method | "read_file" | Example: ```json { "metadata": { "method": "read_file", "file_path": "/test/foo2.txt" }, "data": null } ``` ### Write File Write File: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | file_path | yes | path to file | "/test/foo2.txt" | | method | yes | type of method | "write_file" | | file_mode | no | os permission mode default(0777) | "0777" | | data | yes | file as byte array | "TXkgZXhhbXBsZSBmaWxlIHRvIHVwbG9hZA==" | Example: ```json { "metadata": { "method": "write_file", "file_path": "/test/foo2.txt" }, "data": "TXkgZXhhbXBsZSBmaWxlIHRvIHVwbG9hZA==" } ``` ### Remove File Remove File: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | file_path | yes | path to file | "/test/foo2.txt" | | method | yes | type of method | "remove_file" | Example: ```json { "metadata": { "method": "remove_file", "file_path": "/test/foo2.txt" }, "data": null } ``` ### Rename File Rename File: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | file_path | yes | new path to file | "/test/foo3.txt" | | old_file_path | yes | new path to file | "/test/foo2.txt" | | method | yes | type of method | "rename_file" | Example: ```json { "metadata": { "method": "rename_file", "file_path": "/test/foo3.txt", "old_file_path": "/test/foo2.txt" }, "data": null } ``` ### Make Dir Make Dir : | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | file_path | yes | new path to file | "/test_folder" | | file_mode | no | os permission mode default(0777) | "0777" | | method | yes | type of method | "mkdir" | Example: ```json { "metadata": { "method": "mkdir", "file_path": "/test_folder" }, "data": null } ``` ### Stat Stat : | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | file_path | yes | new path to file | "/test/foo3.txt" | | method | yes | type of method | "stat" | Example: ```json { "metadata": { "method": "stat", "file_path": "/test/foo2.txt" }, "data": null } ``` <file_sep># Kubemq sns target Connector Kubemq aws-sns target connector allows services using kubemq server to access aws sns service. ## Prerequisites The following required to run the aws-sns target connector: - kubemq cluster - aws account with sns active service - kubemq-targets deployment ## Configuration sns target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string) | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-sns source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-sns-connector" auth_token: "" channel: "query.aws.sns" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.sns name: aws-sns properties: aws_key: "id" aws_secret_key: 'json' region: "instance" token: "" ``` ## Usage ### List Topics list all topics List Topics: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_topics" | Example: ```json { "metadata": { "method": "list_topics" }, "data": null } ``` ### List Subscriptions list all subscriptions List Subscriptions: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_subscriptions" | Example: ```json { "metadata": { "method": "list_subscriptions" }, "data": null } ``` ### List Subscriptions By Topic list all Subscriptions of the selected topic List Subscriptions By Topic: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_subscriptions_by_topic" | | topic | yes | topic_name | "arn:aws-my-topic" | Example: ```json { "metadata": { "method": "list_subscriptions_by_topic", "topic": "arn:aws-my-topic" }, "data": null } ``` ### Create Topic create a new topic , topic name must by unique Create Topic: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_topic" | | topic | yes | topic_name | "arn:aws-my-topic" | | data | no | create attributes as base64 | '{"DisplayName":"my-display-name"}' Example: ```json { "metadata": { "method": "create_topic", "topic": "arn:aws-my-topic" }, "data": "eyJEaXNwbGF5TmFtZSI6Im15LWRpc3BsYXktbmFtZSJ9" } ``` ### Send Message send a message to topic. Send Message: | Metadata Key | Required | Description | Possible values | |:------------------|:------------------------------------|:-----------------------------|:-------------------------------------------| | method | yes | type of method | "send_message" | | topic | no(unless target_arn is missing) | topic_name | "arn:aws-my-topic" | | target_arn | no(unless topic is missing) | target_arn | "arn:aws-my-topic" | | message | yes | message body as string | 'some message in string format' || | message | yes | message body as string | 'some message in string format' || | subject | no | sns subject name | "string name of sns subject" || | phone_number | no | valid phone number | "valid phone number" || | data | no | message attributes as base64 | "[{"name":"store","data_type":"String","string_value":"my_store"},{"name":"event","data_type":"String","string_value":"my_event"}]" || Example: ```json { "metadata": { "method": "send_message", "topic": "arn:aws-my-topic" "message": "my message to send" }, "data": "<KEY>" } ``` ### Subscribe Subscribe to topic Subscribe: | Metadata Key | Required | Description | Possible values | |:--------------------|:------------------------------------|:---------------------------------|:--------------------------------------| | method | yes | type of method | "subscribe" | | topic | yes | topic_name | "arn:aws-my-topic" | "arn:aws-my-topic" | | data | no | Subscribe attributes as base64 | '{"store": ["mystore"],"event": [{"anything-but": "my-event"}]}' Example: ```json { "metadata": { "method": "subscribe", "topic": "arn:aws-my-topic" }, "data": "<KEY> } ``` ### Delete Topic delete the selected topic Delete Topic: | Metadata Key | Required | Description | Possible values | |:--------------------|:------------------------------------|:-------------------------------|:--------------------------------------| | method | yes | type of method | "delete_topic" | | topic | yes | topic_name | "arn:aws-my-topic" | Example: ```json { "metadata": { "method": "delete_topic", "topic": "arn:aws-my-topic" }, "data": null } ``` <file_sep>package amazonmq import ( "context" "crypto/tls" "github.com/go-stomp/stomp" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options conn *stomp.Conn } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } netConn, err := tls.Dial("tcp", c.opts.host, &tls.Config{}) if err != nil { return err } c.conn, err = stomp.Connect(netConn, stomp.ConnOpt.Login(c.opts.username, c.opts.password)) if err != nil { return err } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, ok := c.opts.defaultMetadata() if !ok { var err error meta, err = parseMetadata(req.Metadata) if err != nil { return nil, err } } err := c.conn.Send(meta.destination, "text/plain", req.Data) if err != nil { return nil, err } return types.NewResponse().SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return c.conn.Disconnect() } <file_sep>package binding import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type Status struct { Binding string `json:"binding"` Ready bool `json:"ready"` SourceType string `json:"source_type"` SourceConnection string `json:"source_connection"` SourceConfig map[string]string `json:"source_config"` TargetType string `json:"target_type"` TargetConfig map[string]string `json:"target_config"` } func getSourceConnection(properties map[string]string) string { return fmt.Sprintf("%s/%s", properties["address"], properties["channel"]) } func newStatus(cfg config.BindingConfig) *Status { return &Status{ Binding: cfg.Name, Ready: false, SourceType: cfg.Source.Kind, SourceConnection: getSourceConnection(cfg.Source.Properties), SourceConfig: cfg.Source.Properties, TargetType: cfg.Target.Kind, TargetConfig: cfg.Target.Properties, } } <file_sep>package minio import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { endpoint string useSSL bool accessKeyId string secretAccessKey string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.endpoint, err = cfg.Properties.MustParseString("endpoint") if err != nil { return options{}, fmt.Errorf("error parsing endpoint, %w", err) } o.useSSL = cfg.Properties.ParseBool("use_ssl", true) o.accessKeyId, err = cfg.Properties.MustParseEnv("access_key_id", "ACCESS_KEY_ID", "") if err != nil { return options{}, fmt.Errorf("error parsing access key id, %w", err) } o.secretAccessKey, err = cfg.Properties.MustParseEnv("secret_access_key", "SECRET_ACCESS_KEY", "") if err != nil { return options{}, fmt.Errorf("error parsing secret access key, %w", err) } return o, nil } <file_sep>package consulkv import ( "fmt" "time" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultUseTLS = false defaultWaitTime = 36000 defaultCertFile = "" defaultCertKey = "" defaultScheme = "" defaultDataCenter = "" defaultToken = "" defaultTokenFile = "" ) type options struct { address string scheme string datacenter string token string tokenFile string tls bool tlscertificatefile string tlscertificatekey string insecureSkipVerify bool waitTime time.Duration } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.address, err = cfg.Properties.MustParseString("address") if err != nil { return options{}, fmt.Errorf("error parsing address, %w", err) } waitTime, err := cfg.Properties.ParseIntWithRange("wait_time", defaultWaitTime, 0, 2147483647) if err != nil { return options{}, fmt.Errorf("error parsing wait_time, %w", err) } o.waitTime = time.Duration(waitTime) * time.Millisecond o.scheme = cfg.Properties.ParseString("scheme", defaultScheme) o.datacenter = cfg.Properties.ParseString("data_center", defaultDataCenter) o.token = cfg.Properties.ParseString("token", defaultToken) o.tokenFile = cfg.Properties.ParseString("token_file", defaultTokenFile) o.insecureSkipVerify = cfg.Properties.ParseBool("insecure_skip_verify", false) o.tls = cfg.Properties.ParseBool("tls", defaultUseTLS) o.tlscertificatefile = cfg.Properties.ParseString("cert_file", defaultCertFile) o.tlscertificatekey = cfg.Properties.ParseString("cert_key", defaultCertKey) return o, nil } <file_sep>package queue import ( "context" "errors" "fmt" "time" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-go/queues_stream" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/middleware" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) var errInvalidTarget = errors.New("invalid controller received, cannot be null") type Client struct { opts options log *logger.Logger target middleware.Middleware isStopped bool bindingName string } func (c *Client) getQueuesClient(ctx context.Context, id int) (*queues_stream.QueuesStreamClient, error) { return queues_stream.NewQueuesStreamClient(ctx, queues_stream.WithAddress(c.opts.host, c.opts.port), queues_stream.WithClientId(fmt.Sprintf("kubemq-targets_%s_%s-%d", c.bindingName, c.opts.clientId, id)), queues_stream.WithCheckConnection(true), queues_stream.WithAutoReconnect(true), queues_stream.WithAuthToken(c.opts.authToken), queues_stream.WithConnectionNotificationFunc( func(msg string) { c.log.Infof(fmt.Sprintf("connection: %d, %s", id, msg)) }), ) } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) onError(err error) { c.log.Error(err.Error()) } func (c *Client) Init(ctx context.Context, cfg config.Spec, bindingName string, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.bindingName = bindingName return nil } func (c *Client) Start(ctx context.Context, target middleware.Middleware) error { if target == nil { return errInvalidTarget } else { c.target = target } for i := 0; i < c.opts.sources; i++ { client, err := c.getQueuesClient(ctx, i+1) if err != nil { return err } go c.run(ctx, client) } return nil } func (c *Client) run(ctx context.Context, client *queues_stream.QueuesStreamClient) { defer func() { _ = client.Close() }() for { if c.isStopped { return } err := c.processQueueMessage(ctx, client) if err != nil { c.log.Error(err.Error()) time.Sleep(time.Second) } select { case <-ctx.Done(): return default: } } } func (c *Client) processQueueMessage(ctx context.Context, client *queues_stream.QueuesStreamClient) error { pr := queues_stream.NewPollRequest(). SetChannel(c.opts.channel). SetMaxItems(c.opts.batchSize). SetWaitTimeout(c.opts.waitTimeout * 1000). SetAutoAck(true). SetOnErrorFunc(c.onError) pollResp, err := client.Poll(ctx, pr) if err != nil { return err } if !pollResp.HasMessages() { return nil } for _, message := range pollResp.Messages { var req *types.Request var err error if c.opts.doNotParsePayload { req = types.NewRequest().SetData(message.Body) } else { req, err = types.ParseRequest(message.Body) if err != nil { return fmt.Errorf("invalid request format, %w", err) } } resp, err := c.target.Do(ctx, req) if err != nil { if c.opts.responseChannel != "" { errResp := types.NewResponse().SetError(err) _, errSend := client.Send(ctx, errResp.ToQueueStreamMessage().SetChannel(c.opts.responseChannel)) if errSend != nil { c.log.Errorf("error sending response to a queue, %s", errSend.Error()) } } } if resp != nil { if c.opts.responseChannel != "" { _, errSend := client.Send(ctx, resp.ToQueueStreamMessage().SetChannel(c.opts.responseChannel)) if errSend != nil { c.log.Errorf("error sending response to a queue, %s", errSend.Error()) } } } } return nil } func (c *Client) Stop() error { c.isStopped = true return nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { dat, err := ioutil.ReadFile("./credentials/aws/sqs/queue.txt") if err != nil { log.Fatal(err) } queue := string(dat) validBody, err := json.Marshal("valid body2") if err != nil { log.Fatal(err) } client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // sendRequest sendRequest := types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("delay", "0"). SetMetadataKeyValue("queue", queue). SetData(validBody) querySendResponse, err := client.SetQuery(sendRequest.ToQuery()). SetChannel("query.aws.sqs"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } sendResponse, err := types.ParseResponse(querySendResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("send executed, response: %s", sendResponse.Data)) } <file_sep>package openfaas import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { gateway string username string password string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.gateway, err = cfg.Properties.MustParseString("gateway") if err != nil { return options{}, fmt.Errorf("error parsing gateway value, %w", err) } o.username, err = cfg.Properties.MustParseString("username") if err != nil { return options{}, fmt.Errorf("error parsing username value, %w", err) } o.password, err = cfg.Properties.MustParseString("password") if err != nil { return options{}, fmt.Errorf("error parsing password value, %w", err) } return o, nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } dat, err := ioutil.ReadFile("./credentials/azure/storage/queue/queueName.txt") if err != nil { panic(err) } queueName := string(dat) dat, err = ioutil.ReadFile("./credentials/azure/storage/queue/serviceURL.txt") if err != nil { panic(err) } serviceURL := string(dat) myMessage := "my message to send to queue" b, err := json.Marshal(myMessage) if err != nil { panic(err) } // upload uploadRequest := types.NewRequest(). SetMetadataKeyValue("method", "push"). SetMetadataKeyValue("queue_name", queueName). SetMetadataKeyValue("service_url", serviceURL). SetData(b) queryUploadResponse, err := client.SetQuery(uploadRequest.ToQuery()). SetChannel("azure.storage.queue"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } uploadResponse, err := types.ParseResponse(queryUploadResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("push request executed, error: %v", uploadResponse.Error)) // get count getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get_messages_count"). SetMetadataKeyValue("queue_name", queueName). SetMetadataKeyValue("service_url", serviceURL) getQueryResponse, err := client.SetQuery(getRequest.ToQuery()). SetChannel("azure.storage.queue"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(getQueryResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get request done, response : %s and count : %s", getResponse.Data, getResponse.Metadata["count"])) } <file_sep>package eventhubs import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("azure.eventhubs"). SetDescription("Azure EventHubs Target"). SetName("EventBus"). SetProvider("Azure"). SetCategory("Messaging"). SetTags("pub/sub", "iot", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("end_point"). SetTitle("Endpoint"). SetDescription("Set EventHubs end point"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("shared_access_key_name"). SetTitle("Access Key Name"). SetDescription("Set EventHubs shared access key name"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("shared_access_key"). SetTitle("Access Key"). SetDescription("Set EventHubs shared access key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("entity_path"). SetDescription("Set EventHubs entity path"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set EventHubs execution method"). SetOptions([]string{"send", "send_batch"}). SetDefault("send"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("properties"). SetKind("string"). SetDescription("Set EventHubs properties"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("partition_key"). SetKind("string"). SetDescription("Set EventHubs partition key"). SetDefault(""). SetMust(false), ) } <file_sep>package queue import ( "testing" "github.com/kubemq-io/kubemq-targets/config" "github.com/stretchr/testify/require" ) func TestOptions_parseOptions(t *testing.T) { tests := []struct { name string cfg config.Spec want options wantErr bool }{ { name: "valid options", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "some-clients-id", "auth_token": "some-auth token", "channel": "some-channel", "response_channel": "some-response-channel", "batch_size": "2", "wait_timeout": "60", }, }, want: options{ host: "localhost", port: 50000, clientId: "some-clients-id", authToken: "some-auth token", channel: "some-channel", responseChannel: "some-response-channel", sources: 1, waitTimeout: 60, batchSize: 2, }, wantErr: false, }, { name: "invalid options - address", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "bad_address", "channel": "", }, }, want: options{}, wantErr: true, }, { name: "invalid options - bad channel", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "channel": "", }, }, want: options{}, wantErr: true, }, { name: "invalid options - bad max visibility", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "channel": "channel", "sources": "1", "batch_size": "-1", }, }, want: options{}, wantErr: true, }, { name: "invalid options - bad wait timeout", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "channel": "channel", "sources": "1", "batch_size": "1", "wait_timeout": "-1", }, }, want: options{}, wantErr: true, }, { name: "invalid options - bad sources", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "channel": "channel", "sources": "-1", "batch_size": "1", "wait_timeout": "1", }, }, want: options{}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := parseOptions(tt.cfg) if tt.wantErr { require.Error(t, err) } else { require.NoError(t, err) } require.EqualValues(t, got, tt.want) }) } } <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } request := types.NewRequest(). SetMetadataKeyValue("topic", "function/nslookup"). SetData([]byte("kubemq.io")) queryResponse, err := client.SetQuery(request.ToQuery()). SetChannel("query.openfaas"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } response, err := types.ParseResponse(queryResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("request lookup for kubemq:\n%s", string(response.Data))) } <file_sep># Kubemq firestore target Connector Kubemq gcp-firestore target connector allows services using kubemq server to access google firestore server. ## Prerequisites The following required to run the gcp-firestore target connector: - kubemq cluster - gcp-firestore set up in native mode - kubemq-targets deployment ## Configuration firestore target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:---------------------------| | project_id | yes | gcp firestore project_id | "<googleurl>/myproject" | | credentials | yes | gcp credentials files | "<google json credentials" | Example: ```yaml bindings: - name: kubemq-query-gcp-firestore source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-firestore-connector" auth_token: "" channel: "query.gcp.firestore" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.firestore name: gcp-firestore properties: project_id: "id" credentials: 'json' instance: "instance" ``` ## Usage ### Add Key add a key under collection Add Key metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:---------------------| | method | yes | type of method | "add" | | collection | yes | the name of the collection to sent to | "collection name" | Example: ```json { "metadata": { "method": "add", "collection": "my_collection" }, "data": "QWRkIFZhbHVl" } ``` ### get Values by document key get values by key under collection Get Key metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------------------------|:---------------------------| | method | yes | type of method | "document_key" | | collection | yes | the name of the collection to sent to | "collection name" | | document_key | yes | the name of the key to get his value | "valid existing key" | Example: ```json { "metadata": { "method": "documents_all", "collection": "my_collection", "item": "<valid existing key>" }, "data": null } ``` ### get all Values get all values under collection Get all metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:-----------------------| | method | yes | type of method | "documents_all" | | collection | yes | the name of the collection to sent to | "collection name" | Example: ```json { "metadata": { "method": "documents_all", "collection": "my_collection" }, "data": null } ``` ### delete key delete key in collection Delete key metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:------------------------| | method | yes | type of method | "delete_document_key" | | collection | yes | the name of the collection to sent to | "collection name" | | document_key | yes | the name of the key to delete his value | "valid existing key" | Example: ```json { "metadata": { "method": "delete_document_key", "collection": "my_collection", "item": "valid existing key" }, "data": null } ``` <file_sep>package firebase import ( "encoding/json" "fmt" "firebase.google.com/go/v4/messaging" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { projectID string credentials string authClient bool dbClient bool dbURL string messagingClient bool defaultMessaging *messages } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.projectID, err = cfg.Properties.MustParseString("project_id") if err != nil { return options{}, fmt.Errorf("error parsing project_id, %w", err) } o.credentials, err = cfg.Properties.MustParseString("credentials") if err != nil { return options{}, err } o.authClient, err = cfg.Properties.MustParseBool("auth_client") if err != nil { return options{}, fmt.Errorf("error parsing auth_client, %w", err) } o.dbClient, err = cfg.Properties.MustParseBool("db_client") if err != nil { return options{}, fmt.Errorf("error parsing db_client, %w", err) } o.dbURL = cfg.Properties.ParseString("db_url", "") o.messagingClient, err = cfg.Properties.MustParseBool("messaging_client") if err != nil { return options{}, fmt.Errorf("error parsing messaging_client, %w", err) } if o.messagingClient { o.defaultMessaging = &messages{} n := cfg.Properties.ParseString("defaultmsg", "") if n != "" { m := &messaging.Message{} err := json.Unmarshal([]byte(n), m) if err != nil { return o, err } o.defaultMessaging.single = m } n = cfg.Properties.ParseString("defaultmultimsg", "") if n != "" { multi := &messaging.MulticastMessage{} err := json.Unmarshal([]byte(n), multi) if err != nil { return o, err } o.defaultMessaging.multicast = multi } } return o, nil } <file_sep>package mqtt import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/uuid" ) type options struct { host string username string password string clientId string defaultTopic string defaultQos int } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.host, err = cfg.Properties.MustParseString("host") if err != nil { return options{}, fmt.Errorf("error parsing host, %w", err) } o.username = cfg.Properties.ParseString("username", "") o.password = cfg.Properties.ParseString("password", "") o.clientId = cfg.Properties.ParseString("client_id", uuid.New().String()) o.defaultTopic = cfg.Properties.ParseString("default_topic", "") o.defaultQos, err = cfg.Properties.ParseIntWithRange("default_qos", 0, 0, 2) if err != nil { return options{}, fmt.Errorf("error parsing default_qos, %w", err) } return o, nil } func (o options) defaultMetadata() (metadata, bool) { if o.defaultTopic != "" { return metadata{ topic: o.defaultTopic, qos: o.defaultQos, }, true } return metadata{}, false } <file_sep>package firebase import ( "context" "encoding/json" "fmt" "github.com/kubemq-io/kubemq-targets/types" ) func (c *Client) customToken(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { token := "" if data != nil { claims := make(map[string]interface{}) err := json.Unmarshal(data, &claims) if err != nil { return nil, err } if len(claims) == 0 { return nil, fmt.Errorf("body was set but data was missing claims") } token, err = c.clientAuth.CustomTokenWithClaims(ctx, meta.tokenID, claims) if err != nil { return nil, err } } else { var err error token, err = c.clientAuth.CustomToken(ctx, meta.tokenID) if err != nil { return nil, err } } b, err := json.Marshal(token) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) verifyToken(ctx context.Context, meta metadata) (*types.Response, error) { token, err := c.clientAuth.VerifyIDToken(ctx, meta.tokenID) if err != nil { return nil, err } b, err := json.Marshal(token) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } <file_sep>package bigquery import ( "context" "errors" "fmt" "cloud.google.com/go/bigquery" jsoniter "github.com/json-iterator/go" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/iterator" "google.golang.org/api/option" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary type Client struct { opts options client *bigquery.Client log *logger.Logger } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } c.log = logger.NewLogger(cfg.Name) var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) Client, err := bigquery.NewClient(ctx, c.opts.projectID, option.WithCredentialsJSON(b)) if err != nil { return err } c.client = Client return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "query": return c.query(ctx, meta) case "create_table": return c.createTable(ctx, meta, req.Data) case "delete_table": return c.deleteTable(ctx, meta) case "create_data_set": return c.createDataSet(ctx, meta) case "delete_data_set": return c.deleteDataSet(ctx, meta) case "get_table_info": return c.getTableInfo(ctx, meta) case "get_data_sets": return c.getDataSets(ctx) case "insert": return c.insert(ctx, meta, req.Data) default: return nil, errors.New("invalid method type") } } func (c *Client) getTableInfo(ctx context.Context, meta metadata) (*types.Response, error) { m, err := c.client.Dataset(meta.datasetID).Table(meta.tableName).Metadata(ctx) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) getDataSets(ctx context.Context) (*types.Response, error) { i := c.client.Datasets(ctx) s, err := c.getDataSetsFromIterator(i) if err != nil { return nil, err } b, err := json.Marshal(s) if err != nil { return nil, err } if len(s) == 0 { return nil, fmt.Errorf("no data sets found") } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) query(ctx context.Context, meta metadata) (*types.Response, error) { query := c.client.Query(meta.query) i, err := query.Read(ctx) if err != nil { return nil, err } rows, err := c.getRowsFromIterator(i) if err != nil { return nil, err } if len(rows) == 0 { return nil, fmt.Errorf("no rows found") } b, err := json.Marshal(rows) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) createDataSet(ctx context.Context, meta metadata) (*types.Response, error) { met := &bigquery.DatasetMetadata{ Location: meta.location, // See https://cloud.google.com/bigquery/docs/locations } err := c.client.Dataset(meta.datasetID).Create(ctx, met) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteDataSet(ctx context.Context, meta metadata) (*types.Response, error) { err := c.client.Dataset(meta.datasetID).Delete(ctx) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) insert(ctx context.Context, meta metadata, body []byte) (*types.Response, error) { ir, err := newInsertRecord(body) if err != nil { return nil, err } ins := c.client.Dataset(meta.datasetID).Table(meta.tableName).Inserter() err = ins.Put(ctx, ir.records) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("insert_rows", fmt.Sprintf("%d", len(ir.records))), nil } func (c *Client) createTable(ctx context.Context, meta metadata, body []byte) (*types.Response, error) { metaData := &bigquery.TableMetadata{} err := json.Unmarshal(body, &metaData) if err != nil { return nil, err } tableRef := c.client.Dataset(meta.datasetID).Table(meta.tableName) err = tableRef.Create(ctx, metaData) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) deleteTable(ctx context.Context, meta metadata) (*types.Response, error) { tableRef := c.client.Dataset(meta.datasetID).Table(meta.tableName) err := tableRef.Delete(ctx) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) getRowsFromIterator(iter *bigquery.RowIterator) ([]map[string]bigquery.Value, error) { var rows []map[string]bigquery.Value for { row := make(map[string]bigquery.Value) err := iter.Next(&row) if err == iterator.Done { return rows, nil } if err != nil { return rows, fmt.Errorf("error iterating through results: %v", err) } rows = append(rows, row) } } func (c *Client) getDataSetsFromIterator(iter *bigquery.DatasetIterator) ([]*bigquery.Dataset, error) { var datasets []*bigquery.Dataset for { dataset, err := iter.Next() if err == iterator.Done { return datasets, nil } if err != nil { return datasets, fmt.Errorf("error iterating through results: %v", err) } datasets = append(datasets, dataset) } } func (c *Client) Stop() error { return c.client.Close() } <file_sep>//go:build container // +build container package global const ( DefaultApiPort = 8080 EnableLogFile = false LoggerType = "json" ) <file_sep>package sqs import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string sqsQueue string deadLetter string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/sqs/queue.txt") if err != nil { return nil, err } t.sqsQueue = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/sqs/deadLetter.txt") if err != nil { return nil, err } t.deadLetter = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "token": dat.token, "region": dat.region, "max_retries": "0", "max_receive": "10", "dead_letter": dat.deadLetter, }, }, wantErr: false, }, { name: "invalid init - no region", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "token": dat.token, "region": "", "max_retries": "0", }, }, wantErr: true, }, { name: "invalid init - no aws_key", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": "", "aws_secret_key": dat.awsSecretKey, "token": dat.token, "queue": dat.sqsQueue, "region": dat.region, "max_retries": "0", }, }, wantErr: true, }, { name: "invalid init - no aws_secret_key", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": "", "token": dat.token, "region": dat.region, "max_retries": "0", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSetErr %v", err, tt.wantErr) return } }) } } func TestClient_Do(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) validBody, err := json.Marshal("valid body") require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request want *types.Response wantErr bool }{ { name: "valid sqs sent without tags", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "max_retries": "0", "retries": "0", }, }, request: types.NewRequest(). SetMetadataKeyValue("delay", "0"). SetMetadataKeyValue("queue", dat.sqsQueue). SetData(validBody), want: types.NewResponse(). SetData(validBody), wantErr: false, }, { name: "valid sqs sent - with tags", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "max_retries": "0", "retries": "0", }, }, request: types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("delay", "0"). SetMetadataKeyValue("queue", dat.sqsQueue). SetData(validBody), want: types.NewResponse(). SetData(validBody), wantErr: false, }, { name: "valid sqs sent", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "max_retries": "0", "retries": "0", }, }, request: types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("delay", "0"). SetMetadataKeyValue("queue", dat.sqsQueue). SetData(validBody), want: types.NewResponse(). SetData(validBody), wantErr: false, }, { name: "invalid send - incorrect signature", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": "Incorrect", "aws_secret_key": dat.awsSecretKey, "region": dat.region, "max_retries": "0", "retries": "0", }, }, request: types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("delay", "0"). SetMetadataKeyValue("queue", dat.sqsQueue). SetData(validBody), want: nil, wantErr: true, }, { name: "invalid send - incorrect queue", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "max_retries": "0", "retries": "1", }, }, request: types.NewRequest(). SetMetadataKeyValue("tags", `{"tag-1":"test","tag-2":"test2"}`). SetMetadataKeyValue("delay", "0"). SetData(validBody), want: nil, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_SetQueueAttributes(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec queueURL string want *types.Response wantErr bool }{ { name: "valid set queue attribute", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "max_receive": "10", "dead_letter": dat.deadLetter, "max_retries": "0", "retries": "0", }, }, queueURL: dat.sqsQueue, wantErr: false, }, { name: "invalid - set queue attribute", cfg: config.Spec{ Name: "aws-sqs", Kind: "aws.sqs", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, "dead_letter": dat.deadLetter, "max_retries": "0", "retries": "0", }, }, queueURL: dat.sqsQueue, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) err = c.SetQueueAttributes(ctx, dat.sqsQueue) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } <file_sep>package uuid import ( "crypto/rand" "encoding/hex" "fmt" "regexp" "strings" ) func init() { v4Regex, _ = regexp.Compile(V4UUIDRegex) } // V4UUIDRegex is a simple string regex that will match valid v4 UUIDs const V4UUIDRegex = "\\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}\\b" var v4Regex *regexp.Regexp // UUID Represents a UUID type UUID [16]byte // ToString converts the UUID into its string representation func (u *UUID) String() string { result := hex.EncodeToString(u[:]) result = result[:8] + "-" + result[8:12] + "-" + result[12:16] + "-" + result[16:20] + "-" + result[20:] return result } // GetVersion returns the version of the UUID based on the 13th character (1st char of 7th byte) of the UUID func (u *UUID) GetVersion() string { bytes := []byte{u[6]} result := hex.EncodeToString(bytes)[:1] return result } // GetUUIDFromString takes a string representing a UUID and converts it to a UUID type // Returns an error if the string does not match a UUID func GetUUIDFromString(strUUID string) (*UUID, error) { if ismatch := v4Regex.MatchString(strUUID); !ismatch { return nil, fmt.Errorf("%s is not a valid v4 UUID", strUUID) } strUUID = strings.Replace(strUUID, "-", "", 4) resultUUIDSlice, _ := hex.DecodeString(strUUID) resultUUID, _ := GetUUIDFromByteSlice(resultUUIDSlice) return resultUUID, nil } // GetUUIDFromByteSlice takes a slice of bytes and converts it to a UUID // If the slice is not 16 bytes long it will return an error // @TODO add version checking func GetUUIDFromByteSlice(slice []byte) (*UUID, error) { if length := len(slice); length != 16 { return nil, fmt.Errorf("%s is %d bytes. Expects 16", slice, length) } uuid := UUID{} for i, v := range slice { uuid[i] = v } return &uuid, nil } // NewNilUUID returns a nil UUID (All bits set to zero) func NewNilUUID() *UUID { return &UUID{} } // NewV4UUID returns a randomized version 4 UUID func New() (result *UUID) { bytes := make([]byte, 16) _, _ = rand.Read(bytes) result = &UUID{} for i, v := range bytes { result[i] = v } result.setVersion(4) result.setVariant() return } func (u *UUID) Equals(comp *UUID) bool { for i, v := range u { if comp[i] != v { return false } } return true } // SetVersion sets the version of the uuid (first nibble of the 7th byte) func (u *UUID) setVersion(v byte) { u[6] = (v << 4) | (u[6] & 0xf) } // setVariant sets the variant of the uuid (first nibble of the 9th byte) func (u *UUID) setVariant() { // Clear the first two bits of the byte u[8] = u[8] & 0x3f // Set the first two bits of the byte to 10 u[8] = u[8] | 0x80 } <file_sep>package bigquery import ( "crypto/sha256" "encoding/hex" "fmt" "cloud.google.com/go/bigquery" ) type insertRecords struct { records []record } func newInsertRecord(payload []byte) (*insertRecords, error) { if len(payload) == 0 { return nil, fmt.Errorf("no insert payload found") } ir := &insertRecords{ records: nil, } var recs []record err := json.Unmarshal(payload, &recs) if err != nil { return nil, err } for _, rec := range recs { if rec != nil { ir.records = append(ir.records, rec) } } return ir, err } func hash(data []byte) string { if data == nil { return "" } h := sha256.New() _, _ = h.Write(data) return hex.EncodeToString(h.Sum(nil)) } type record map[string]bigquery.Value func (rec record) Save() (map[string]bigquery.Value, string, error) { data, err := json.Marshal(&rec) if err != nil { return nil, "", err } st := hash(data) return rec, st, nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { dat, err := ioutil.ReadFile("./credentials/aws/redshift-svc/resourceARN.txt") if err != nil { log.Fatal(err) } resourceARN := string(dat) client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // Create tag tags := make(map[string]string) tags["test-key"] = "test-value" b, err := json.Marshal(tags) if err != nil { log.Fatal(err) } createRequest := types.NewRequest(). SetMetadataKeyValue("method", "create_tags"). SetMetadataKeyValue("resource_arn", resourceARN). SetData(b) getCreate, err := client.SetQuery(createRequest.ToQuery()). SetChannel("query.aws.redshift.service"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } createResponse, err := types.ParseResponse(getCreate.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("create tag executed, error: %v", createResponse.IsError)) // listRequest listRequest := types.NewRequest(). SetMetadataKeyValue("method", "list_tags") queryListResponse, err := client.SetQuery(listRequest.ToQuery()). SetChannel("query.aws.redshift.service"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } listResponse, err := types.ParseResponse(queryListResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("list tags executed, response: %s", listResponse.Data)) } <file_sep>package rabbitmq import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("messaging.rabbitmq"). SetDescription("RabbitMQ Messaging Target"). SetName("RabbitMQ"). SetProvider(""). SetCategory("Messaging"). SetTags("queue", "pub/sub"). AddProperty( common.NewProperty(). SetKind("string"). SetName("url"). SetDescription("Set RabbitMQ url connection string"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("skip_insecure"). SetDescription("Set skip TLS Certificate verification"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("ca_cert"). SetDescription("Set TLS CA Certificate"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_exchange"). SetDescription("Set Default Exchange for routing"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_topic"). SetDescription("Set Default Topic for routing"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("default_persistence"). SetDescription("Set Default Persistence for routed message"). SetMust(false). SetDefault("true"), ). AddMetadata( common.NewMetadata(). SetName("queue"). SetKind("string"). SetDescription("Set RabbitMQ queue Name"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("exchange"). SetKind("string"). SetDescription("Set RabbitMQ exchange name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("bool"). SetName("mandatory"). SetDescription("Set RabbitMQ mandatory"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetKind("bool"). SetName("immediate"). SetDescription("Set RabbitMQ immediate"). SetMust(false). SetDefault("false"), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("delivery_mode"). SetDescription("Set RabbitMQ delivery mode"). SetMust(true). SetMin(0). SetMax(2). SetDefault("1"), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("priority"). SetDescription("Set RabbitMQ priority"). SetMust(true). SetMin(0). SetMax(9). SetDefault("0"), ). AddMetadata( common.NewMetadata(). SetName("correlation_id"). SetKind("string"). SetDescription("Set RabbitMQ correlation id "). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("reply_to"). SetKind("string"). SetDescription("Set RabbitMQ set reply to target "). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("expiry_seconds"). SetDescription("Set RabbitMQ expiry in seconds"). SetMust(true). SetMin(0). SetMax(math.MaxInt32), ) } <file_sep>package mqtt import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("messaging.mqtt"). SetDescription("MQTT Messaging Target"). SetName("MQTT"). SetProvider(""). SetCategory("Messaging"). SetTags("iot", "pub/sub"). AddProperty( common.NewProperty(). SetKind("string"). SetName("host"). SetTitle("Host Address"). SetDescription("Set MQTT broker host"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("username"). SetDescription("Set MQTT broker username"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("password"). SetDescription("Set MQTT broker password"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("client_id"). SetTitle("Client ID"). SetDescription("Set MQTT broker client id"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("default_topic"). SetDescription("Set MQTT default topic"). SetDefault(""). SetMust(false), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("default_qos"). SetDescription("Set MQTT default qos level"). SetMust(false). SetMin(0). SetMax(2). SetDefault("0"), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("topic"). SetDescription("Set MQTT topic"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("qos"). SetDescription("Set MQTT qos level"). SetMust(true). SetMin(0). SetMax(2). SetDefault("0"), ) } <file_sep>package main import ( "context" "encoding/json" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // list buses listRequest := types.NewRequest(). SetMetadataKeyValue("method", "list_buses"). SetMetadataKeyValue("limit", "1") queryListResponse, err := client.SetQuery(listRequest.ToQuery()). SetChannel("query.aws.cloudwatch.events"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } listResponse, err := types.ParseResponse(queryListResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("list executed, response: %s", listResponse.Data)) dat, err := ioutil.ReadFile("./credentials/aws/cloudwatch/events/rule.txt") if err != nil { panic(err) } rule := string(dat) dat, err = ioutil.ReadFile("./credentials/aws/cloudwatch/events/resourceARN.txt") if err != nil { panic(err) } resourceARN := string(dat) m := make(map[string]string) m["my_arn_id"] = resourceARN b, err := json.Marshal(m) if err != nil { log.Fatal(err) } // put targets putRequest := types.NewRequest(). SetMetadataKeyValue("method", "put_targets"). SetMetadataKeyValue("rule", rule). SetData(b) putReq, err := client.SetQuery(putRequest.ToQuery()). SetChannel("query.aws.cloudwatch.events"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } putResponse, err := types.ParseResponse(putReq.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("put request executed error: %v", putResponse.IsError)) } <file_sep>package main import ( "context" "encoding/json" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func getUserStruct() map[string]interface{} { m := make(map[string]interface{}) m["disabled"] = false m["display_name"] = "test" m["email"] = "<EMAIL>" m["email_verified"] = true m["password"] = "<PASSWORD>" m["phone_number"] = "+12343678123" m["photo_url"] = "https://kubemq.io/wp-content/uploads/2018/11/24350KubeMQ_clean.png" return m } func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } u := getUserStruct() b, err := json.Marshal(&u) if err != nil { log.Fatal(err) } // create user createRequest := types.NewRequest(). SetMetadataKeyValue("method", "create_user"). SetData(b) queryCreateResponse, err := client.SetQuery(createRequest.ToQuery()). SetChannel("query.gcp.firebase"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } createResponse, err := types.ParseResponse(queryCreateResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("create request done, is_error: %v", createResponse.IsError)) // retrieve by email value setRequest := types.NewRequest(). SetMetadataKeyValue("method", "retrieve_user"). SetMetadataKeyValue("email", fmt.Sprintf("%s", u["email"])). SetMetadataKeyValue("retrieve_by", "by_email") queryRetrieveResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.gcp.firebase"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } retrieveResponse, err := types.ParseResponse(queryRetrieveResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("retrieve user for ref path :test is_error: %v , user :%s", retrieveResponse.IsError, retrieveResponse.Data)) } <file_sep>package kinesis import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.kinesis"). SetDescription("AWS Kinesis Target"). SetName("Kinesis"). SetProvider("AWS"). SetCategory("Messaging"). SetTags("streaming", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Kinesis aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Kinesis aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Kinesis aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Kinesis aws token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Kinesis execution method"). SetOptions([]string{"list_streams", "list_stream_consumers", "create_stream", "delete_stream", "put_record", "put_records", "get_records", "get_shard_iterator", "list_shards"}). SetDefault("put_record"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("stream_name"). SetKind("string"). SetDescription("Set Kinesis stream name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("partition_key"). SetKind("string"). SetDescription("Set Kinesis partition key"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("shard_id"). SetKind("string"). SetDescription("Set Kinesis shard id"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("stream_arn"). SetKind("string"). SetDescription("Set Kinesis stream arn"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("shard_iterator_type"). SetKind("string"). SetDescription("Set Kinesis shard iterator type"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("shard_iterator_id"). SetKind("string"). SetDescription("Set Kinesis shard iterator id"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("limit"). SetDescription("Set Kinesis limit"). SetMust(false). SetDefault("1"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("shard_count"). SetDescription("Set Kinesis shard count"). SetMust(false). SetDefault("1"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("consumer_name"). SetDescription("Set consumer name"). SetDefault(""). SetMust(false), ) } <file_sep># Kubemq spanner target Connector Kubemq gcp-spanner target connector allows services using kubemq server to access google spanner server. ## Prerequisites The following are required to run the gcp-spanner target connector: - kubemq cluster - gcp-spanner set up - kubemq-targets deployment ## Configuration spanner target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:--------------------------------| | db | yes | gcp spanner db name | "<googleurl>/mydb" should conform to pattern "^projects/(?P<project>[^/]+)/instances/(?P<instance>[^/]+)/databases/(?P<database>[^/]+)$" | | credentials | yes | gcp credentials files | "<google json credentials" | Example: ```yaml bindings: - name: kubemq-query-gcp-spanner source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-spanner-connector" auth_token: "" channel: "query.gcp.spanner" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.spanner name: target-gcp-spanner properties: db: "id" credentials: 'json' ``` ## Usage ### Query Request create query request. Query metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------------------|:----------------------| | method | yes | type of method | "query" | | query | yes | the query body | "select * from table" | Example: ```json { "metadata": { "method": "query", "query": "select * from table" }, "data": null } ``` ### Read Table Request by columns read table by table_name Read Table metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------------|:----------------------------------------| | method | yes | type of method | "read" | | table_name | yes | table name to read from | "<your data set ID>" | Example: ```json { "metadata": { "method": "read", "table_name": "<myTable>" }, "data": "<KEY>Il0=" } ``` ### Insert Or Update Table insert or update a table Insert Or Update metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------------------|:----------------------------------------| | method | yes | type of method | "insert","update","insert_or_update" | Example: ```json { "metadata": { "method": "insert_or_update" }, "data": "<KEY> } ``` <file_sep>//go:build !container // +build !container package main import ( "context" "flag" "fmt" "io/ioutil" "os" "os/signal" "syscall" "github.com/ghodss/yaml" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/api" "github.com/kubemq-io/kubemq-targets/binding" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/browser" "github.com/kubemq-io/kubemq-targets/pkg/builder" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/sources" "github.com/kubemq-io/kubemq-targets/targets" ) var version = "" var ( log *logger.Logger generateManifest = flag.Bool("manifest", false, "generate targets connectors manifest") build = flag.Bool("build", false, "build targets configuration") buildUrl = flag.String("get", "", "get config file from url") configFile = flag.String("config", "config.yaml", "set config file name") svcFlag = flag.String("service", "", "control the kubemq-targets service") svcUsername = flag.String("username", "", "kubemq-targets service username") svcPassword = flag.String("password", "", "kubemq-targets service password") ) func saveManifest() error { sourceConnectors := sources.Connectors() if err := sourceConnectors.Validate(); err != nil { return err } targetConnectors := targets.Connectors() if err := targetConnectors.Validate(); err != nil { return err } return common.NewManifest(). SetSchema("targets"). SetVersion(version). SetSourceConnectors(sourceConnectors). SetTargetConnectors(targetConnectors). Save() } func downloadUrl() error { c, err := builder.GetBuildManifest(*buildUrl) if err != nil { return err } cfg := &config.Config{} err = yaml.Unmarshal([]byte(c.Spec.Config), &cfg) if err != nil { return err } data, err := yaml.Marshal(cfg) if err != nil { return err } err = ioutil.WriteFile("config.yaml", data, 0o644) if err != nil { return err } return nil } func runInteractive(serviceExit chan bool) error { gracefulShutdown := make(chan os.Signal, 1) signal.Notify(gracefulShutdown, syscall.SIGTERM) signal.Notify(gracefulShutdown, syscall.SIGINT) signal.Notify(gracefulShutdown, syscall.SIGQUIT) configCh := make(chan *config.Config) cfg, err := config.Load(configCh) if err != nil { return err } err = cfg.Validate() if err != nil { return err } ctx, cancel := context.WithCancel(context.Background()) defer cancel() bindingsService, err := binding.New() if err != nil { return err } err = bindingsService.Start(ctx, cfg) if err != nil { return err } apiServer, err := api.Start(ctx, cfg.ApiPort, bindingsService) if err != nil { return err } for { select { case newConfig := <-configCh: err = newConfig.Validate() if err != nil { return fmt.Errorf("error on validation new config file: %s", err.Error()) } bindingsService.Stop() err = bindingsService.Start(ctx, newConfig) if err != nil { return fmt.Errorf("error on restarting service with new config file: %s", err.Error()) } if apiServer != nil { err = apiServer.Stop() if err != nil { return fmt.Errorf("error on shutdown api server: %s", err.Error()) } } apiServer, err = api.Start(ctx, newConfig.ApiPort, bindingsService) if err != nil { return fmt.Errorf("error on start api server: %s", err.Error()) } case <-gracefulShutdown: _ = apiServer.Stop() bindingsService.Stop() return nil case <-serviceExit: _ = apiServer.Stop() bindingsService.Stop() return nil } } } func preRun() { if *generateManifest { err := saveManifest() if err != nil { log.Error(err) os.Exit(1) } log.Infof("generated manifest.json completed") os.Exit(0) } if *build { err := browser.OpenURL("https://build.kubemq.io/#/targets") if err != nil { log.Error(err) os.Exit(1) } else { os.Exit(0) } } if *buildUrl != "" { err := downloadUrl() if err != nil { log.Error(err) os.Exit(1) } } } func main() { log = logger.NewLogger("kubemq-targets") flag.Parse() config.SetConfigFile(*configFile) app := newAppService() if err := app.init(*svcFlag, *svcUsername, *svcPassword); err != nil { log.Error(err) os.Exit(1) } else { os.Exit(0) } } <file_sep># Kubemq CloudWatch Metrics Target Connector Kubemq cloudwatch-metrics target connector allows services using kubemq server to access aws cloudwatch-metrics service. ## Prerequisites The following required to run the aws-cloudwatch-metrics target connector: - kubemq cluster - aws account with cloudwatch-metrics active service - kubemq-targets deployment ## Configuration cloudwatch-metrics target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-cloudwatch-metrics source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-cloudwatch-metrics" auth_token: "" channel: "query.aws.cloudwatch.metrics" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.cloudwatch.metrics name: aws-cloudwatch-metrics properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### Put Metrics Put Metrics: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "put_metrics" | | namespace | yes | aws namespace name | "string" | | data | yes | array of aws MetricDatum | `W3siQ291bnRzIjpudWxsLCJEaW1lbnNpb2<KEY>` | Example: ```json { "metadata": { "method": "put_metrics", "namespace": "Logs" }, "data": "<KEY>" } ``` ### List Metrics List Metrics: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_metrics" | | namespace | no | aws namespace name | "string" | Example: ```json { "metadata": { "method": "list_metrics" }, "data": null } ``` <file_sep>package firebase import ( "context" "encoding/json" "fmt" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func getUserStruct() map[string]interface{} { m := make(map[string]interface{}) m["disabled"] = false m["display_name"] = "te3st" m["email"] = "<EMAIL>" m["email_verified"] = true m["password"] = "<PASSWORD>" m["phone_number"] = "+12343678912" m["photo_url"] = "https://kubemq.io/wp-content/uploads/2018/11/24350KubeMQ_clean.png" return m } func TestClient_createUser(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) u := getUserStruct() b, err := json.Marshal(&u) require.NoError(t, err) cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", "messaging_client": "false", "db_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "create user-valid", request: types.NewRequest(). SetMetadataKeyValue("method", "create_user"). SetData(b), wantErr: false, }, { name: "create user-invalid - user already exists", request: types.NewRequest(). SetMetadataKeyValue("method", "create_user"). SetData(b), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, r.Data) }) } } func TestClient_retrieveUser(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) u := getUserStruct() cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", "messaging_client": "false", "db_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "retrieve user- by email", request: types.NewRequest(). SetMetadataKeyValue("method", "retrieve_user"). SetMetadataKeyValue("email", fmt.Sprintf("%s", u["email"])). SetMetadataKeyValue("retrieve_by", "by_email"), wantErr: false, }, { name: "retrieve user- by_uid", request: types.NewRequest(). SetMetadataKeyValue("method", "retrieve_user"). SetMetadataKeyValue("uid", dat.uid). SetMetadataKeyValue("retrieve_by", "by_uid"), wantErr: false, }, { name: "retrieve user - by_phone", request: types.NewRequest(). SetMetadataKeyValue("method", "retrieve_user"). SetMetadataKeyValue("phone", fmt.Sprintf("%s", u["phone_number"])). SetMetadataKeyValue("retrieve_by", "by_phone"), wantErr: false, }, { name: "retrieve user- by email", request: types.NewRequest(). SetMetadataKeyValue("method", "retrieve_user"). SetMetadataKeyValue("email", fmt.Sprintf("%s", u["email"])). SetMetadataKeyValue("retrieve_by", "by_email"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, r.Data) t.Logf("received response: %s for test: %s", r.Data, tt.name) }) } } func TestClient_listUsers(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", "messaging_client": "false", "db_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "list users", request: types.NewRequest(). SetMetadataKeyValue("method", "list_users"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, r.Data) t.Logf("received response: %s for test: %s", r.Data, tt.name) }) } } func TestClient_updateUser(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) u := make(map[string]interface{}) u["email"] = "<EMAIL>" b, err := json.Marshal(&u) require.NoError(t, err) cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", "messaging_client": "false", "db_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "update user-valid", request: types.NewRequest(). SetMetadataKeyValue("method", "update_user"). SetMetadataKeyValue("uid", dat.uid). SetData(b), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, r.Data) }) } } func TestClient_deleteUser(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) u := []string{dat.uid, dat.uid2} b, err := json.Marshal(&u) require.NoError(t, err) cfg := config.Spec{ Name: "gcp-firebase", Kind: "gcp.firebase", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "auth_client": "true", "messaging_client": "false", "db_client": "false", }, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) tests := []struct { name string wantErr bool request *types.Request }{ { name: "delete user-valid", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_user"). SetMetadataKeyValue("uid", dat.uid), wantErr: false, }, { name: "delete delete_multiple_users-valid", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_multiple_users"). SetData(b), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, r.Metadata) }) } } <file_sep># Kubemq Echo Target Connector Kubemq Echo target connector allows to echo back any request for testing purposes. ## Prerequisites The following are required to run the echo target connector: - kubemq cluster - kubemq-targets deployment ## Configuration echo target does not need any configuration Example: ```yaml bindings: - name: kubemq-query-https source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-http-connector" auth_token: "" channel: "query.http" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: echo name: echo properties: {} default_headers: '{"Content-Type":"application/json"}' ``` ## Usage Any request will be send back as a response with the host name data embed within the metadata Example: ```json { "metadata": { "method": "get", "url": "https://httpbin.org/get" }, "data": null } ``` Will response back with: ```json { "metadata": { "host": "some-host", "method": "get", "url": "https://httpbin.org/get" }, "data": null } ``` <file_sep>package events import ( "context" "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudwatchevents" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *cloudwatchevents.CloudWatchEvents } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := cloudwatchevents.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "put_targets": return c.putTarget(ctx, meta, req.Data) case "send_event": return c.sendEvent(ctx, meta, req.Data) case "list_buses": return c.listEventBuses(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) putTarget(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { var m map[string]string err := json.Unmarshal(data, &m) if err != nil { return nil, errors.New("failed to parse Targets ,please verify data is map[string]string ,string:Arn and string:Id") } var targets []*cloudwatchevents.Target for k, v := range m { i := cloudwatchevents.Target{ Arn: aws.String(v), Id: aws.String(k), } targets = append(targets, &i) } _, err = c.client.PutTargetsWithContext(ctx, &cloudwatchevents.PutTargetsInput{ Rule: aws.String(meta.rule), Targets: targets, }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) sendEvent(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { var s []*string if data != nil { err := json.Unmarshal(data, &s) if err != nil { return nil, errors.New("failed to parse Resources ,please verify data is a valid []*string of RESOURCE_ARN ") } } res, err := c.client.PutEventsWithContext(ctx, &cloudwatchevents.PutEventsInput{ Entries: []*cloudwatchevents.PutEventsRequestEntry{ { Detail: aws.String(meta.detail), DetailType: aws.String(meta.detailType), Resources: s, Source: aws.String(meta.source), }, }, }) if err != nil { return nil, err } b, err := json.Marshal(res) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) listEventBuses(ctx context.Context, meta metadata) (*types.Response, error) { res, err := c.client.ListEventBusesWithContext(ctx, &cloudwatchevents.ListEventBusesInput{ Limit: aws.Int64(meta.limit), }) if err != nil { return nil, err } b, err := json.Marshal(res) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>package config import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type Spec struct { Name string `json:"-"` Kind string `json:"kind"` Properties types.Metadata `json:"properties"` } func (s Spec) Validate() error { if s.Kind == "" { return fmt.Errorf("kind cannot be empty") } return nil } <file_sep>package metrics import ( "github.com/prometheus/client_golang/prometheus" ) type promCounterMetric struct { metric *prometheus.CounterVec } func newPromCounterMetric(subsystem, name, help string, labels ...string) *promCounterMetric { opts := prometheus.CounterOpts{ Namespace: "kubemq_targets", Subsystem: subsystem, Name: name, Help: help, ConstLabels: nil, } c := &promCounterMetric{} c.metric = prometheus.NewCounterVec(opts, labels) return c } func (c *promCounterMetric) add(value float64, labels prometheus.Labels) { if value > 0 { c.metric.With(labels).Add(value) } } <file_sep>package queue import ( "context" "encoding/json" "errors" "fmt" "net/url" "github.com/Azure/azure-storage-queue-go/azqueue" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options retryOption azqueue.RetryOptions credential *azqueue.SharedKeyCredential } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } // Create a default request pipeline using your storage account name and account key. c.credential, err = azqueue.NewSharedKeyCredential(c.opts.storageAccount, c.opts.storageAccessKey) if err != nil { return fmt.Errorf("failed to create shared key credential on error %s , please check storage access key and acccount are correct", err.Error()) } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "create": return c.create(ctx, meta) case "delete": return c.delete(ctx, meta) case "get_messages_count": return c.getMessageCount(ctx, meta) case "peek": return c.peek(ctx, meta) case "push": return c.push(ctx, meta, req.Data) case "pop": return c.pop(ctx, meta) } return nil, errors.New("invalid method type") } func (c *Client) create(ctx context.Context, meta metadata) (*types.Response, error) { url, err := url.Parse(fmt.Sprintf("%s/%s", meta.serviceUrl, meta.queueName)) if err != nil { return nil, err } queueUrl := azqueue.NewQueueURL(*url, azqueue.NewPipeline(c.credential, azqueue.PipelineOptions{ Retry: c.retryOption, })) _, err = queueUrl.GetProperties(ctx) if err != nil { // https://godoc.org/github.com/Azure/azure-storage-queue-go/azqueue#StorageErrorCodeType errorType := err.(azqueue.StorageError).ServiceCode() if errorType == azqueue.ServiceCodeQueueNotFound { if len(meta.queueMetadata) > 0 { _, err = queueUrl.Create(ctx, meta.queueMetadata) if err != nil { return nil, err } } else { _, err = queueUrl.Create(ctx, azqueue.Metadata{}) if err != nil { return nil, err } } _, err := queueUrl.GetProperties(ctx) if err != nil { return nil, err } } else { return nil, err } } else { return nil, errors.New("queue already exists") } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) delete(ctx context.Context, meta metadata) (*types.Response, error) { url, err := url.Parse(fmt.Sprintf("%s/%s", meta.serviceUrl, meta.queueName)) if err != nil { return nil, err } queueUrl := azqueue.NewQueueURL(*url, azqueue.NewPipeline(c.credential, azqueue.PipelineOptions{ Retry: c.retryOption, })) _, err = queueUrl.GetProperties(ctx) if err != nil { return nil, err } _, err = queueUrl.Delete(ctx) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) getMessageCount(ctx context.Context, meta metadata) (*types.Response, error) { url, err := url.Parse(fmt.Sprintf("%s/%s", meta.serviceUrl, meta.queueName)) if err != nil { return nil, err } queueUrl := azqueue.NewQueueURL(*url, azqueue.NewPipeline(c.credential, azqueue.PipelineOptions{ Retry: c.retryOption, })) props, err := queueUrl.GetProperties(ctx) if err != nil { return nil, err } messageCount := fmt.Sprintf("%v", props.ApproximateMessagesCount()) return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("count", messageCount), nil } func (c *Client) peek(ctx context.Context, meta metadata) (*types.Response, error) { url, err := url.Parse(fmt.Sprintf("%s/%s", meta.serviceUrl, meta.queueName)) if err != nil { return nil, err } queueUrl := azqueue.NewQueueURL(*url, azqueue.NewPipeline(c.credential, azqueue.PipelineOptions{ Retry: c.retryOption, })) messageUrl := queueUrl.NewMessagesURL() resp, err := messageUrl.Peek(ctx, meta.maxMessages) if err != nil { return nil, err } messages := make([]*azqueue.PeekedMessage, 0) for i := int32(0); i < resp.NumMessages(); i++ { msg := resp.Message(i) messages = append(messages, msg) } b, err := json.Marshal(messages) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) push(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { url, err := url.Parse(fmt.Sprintf("%s/%s", meta.serviceUrl, meta.queueName)) if err != nil { return nil, err } queueUrl := azqueue.NewQueueURL(*url, azqueue.NewPipeline(c.credential, azqueue.PipelineOptions{ Retry: c.retryOption, })) var message string err = json.Unmarshal(data, &message) if err != nil { return nil, err } messageUrl := queueUrl.NewMessagesURL() _, err = messageUrl.Enqueue(ctx, message, meta.visibilityTimeout, meta.timeToLive) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) pop(ctx context.Context, meta metadata) (*types.Response, error) { url, err := url.Parse(fmt.Sprintf("%s/%s", meta.serviceUrl, meta.queueName)) if err != nil { return nil, err } queueUrl := azqueue.NewQueueURL(*url, azqueue.NewPipeline(c.credential, azqueue.PipelineOptions{ Retry: c.retryOption, })) messageUrl := queueUrl.NewMessagesURL() resp, err := messageUrl.Dequeue(ctx, meta.maxMessages, meta.visibilityTimeout) if err != nil { return nil, err } messages := make([]*azqueue.DequeuedMessage, 0) for i := int32(0); i < resp.NumMessages(); i++ { msg := resp.Message(i) messages = append(messages, msg) msgIdUrl := messageUrl.NewMessageIDURL(msg.ID) // PopReceipt represents a Message's opaque pop receipt. _, err = msgIdUrl.Delete(ctx, msg.PopReceipt) if err != nil { return nil, err } } b, err := json.Marshal(messages) if err != nil { return nil, err } return types.NewResponse(). SetData(b). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { return nil } <file_sep>package main import ( "context" "encoding/json" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } m := make(map[string]interface{}) m["some_key"] = "some_value" b, err := json.Marshal(m) if err != nil { log.Fatal(err) } // get value getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get_db"). SetMetadataKeyValue("ref_path", "test") queryGetResponse, err := client.SetQuery(getRequest.ToQuery()). SetChannel("query.gcp.firebase"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(queryGetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get request for ref path : est, is_error: %v", getResponse.IsError)) // set value setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set_db"). SetMetadataKeyValue("ref_path", "test"). SetData(b) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.gcp.firebase"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("set request for ref path :test is_error: %v", setResponse.IsError)) } <file_sep>package types import ( b64 "encoding/base64" "fmt" "reflect" jsoniter "github.com/json-iterator/go" "github.com/kubemq-io/kubemq-go" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary type Request struct { Metadata Metadata `json:"metadata,omitempty"` Data []byte `json:"data,omitempty"` } func NewRequest() *Request { return &Request{ Metadata: NewMetadata(), Data: nil, } } func (r *Request) SetMetadata(value Metadata) *Request { r.Metadata = value return r } func (r *Request) SetMetadataKeyValue(key, value string) *Request { r.Metadata.Set(key, value) return r } func (r *Request) SetData(value []byte) *Request { r.Data = value return r } func (r *Request) Size() float64 { return float64(len(r.Data)) } func ParseRequest(body []byte) (*Request, error) { if body == nil { return nil, fmt.Errorf("empty request") } req := &TransportRequest{} err := json.Unmarshal(body, req) if err != nil { return NewRequest().SetData(body), nil } switch v := req.Data.(type) { case nil: return &Request{ Metadata: req.Metadata, Data: nil, }, nil case []byte: return &Request{ Metadata: req.Metadata, Data: v, }, nil case string: sDec, err := b64.StdEncoding.DecodeString(v) if err != nil { sDec = []byte(v) } return &Request{ Metadata: req.Metadata, Data: sDec, }, nil case map[string]interface{}: data, err := json.Marshal(v) if err != nil { return nil, fmt.Errorf("error during casting json data, %s", err.Error()) } return &Request{ Metadata: req.Metadata, Data: data, }, nil default: return nil, fmt.Errorf("invalid data format, %s", reflect.TypeOf(v)) } } func (r *Request) MarshalBinary() []byte { data, _ := json.Marshal(r) return data } func (r *Request) ToEvent() *kubemq.Event { return kubemq.NewEvent(). SetBody(r.MarshalBinary()) } func (r *Request) ToEventStore() *kubemq.EventStore { return kubemq.NewEventStore(). SetBody(r.MarshalBinary()) } func (r *Request) ToCommand() *kubemq.Command { return kubemq.NewCommand(). SetBody(r.MarshalBinary()) } func (r *Request) ToQuery() *kubemq.Query { return kubemq.NewQuery(). SetBody(r.MarshalBinary()) } func (r *Request) ToQueueMessage() *kubemq.QueueMessage { return kubemq.NewQueueMessage(). SetBody(r.MarshalBinary()) } func (r *Request) String() string { str, err := json.MarshalToString(r) if err != nil { return "" } return str } type TransportRequest struct { Metadata Metadata `json:"metadata,omitempty"` Data interface{} `json:"data,omitempty"` } func NewTransportRequest() *TransportRequest { return &TransportRequest{ Metadata: NewMetadata(), Data: nil, } } func (r *TransportRequest) SetMetadata(value Metadata) *TransportRequest { r.Metadata = value return r } func (r *TransportRequest) SetMetadataKeyValue(key, value string) *TransportRequest { r.Metadata.Set(key, value) return r } func (r *TransportRequest) SetData(value interface{}) *TransportRequest { r.Data = value return r } func (r *TransportRequest) ToEvent() *kubemq.Event { return kubemq.NewEvent(). SetBody(r.MarshalBinary()) } func (r *TransportRequest) MarshalBinary() []byte { data, _ := json.Marshal(r) return data } <file_sep>/* forked from: https://github.com/avast/retry-go */ package retry import ( "fmt" "strings" "time" ) // Function signature of retryable function type RetryableFunc func() error var ( DefaultAttempts = uint(10) DefaultDelay = 100 * time.Millisecond DefaultMaxJitter = 100 * time.Millisecond DefaultOnRetry = func(n uint, err error) {} DefaultRetryIf = IsRecoverable DefaultDelayType = CombineDelay(BackOffDelay, RandomDelay) DefaultLastErrorOnly = false ) func Do(retryableFunc RetryableFunc, opts ...Option) error { var n uint // default config := &Config{ attempts: DefaultAttempts, delay: DefaultDelay, maxJitter: DefaultMaxJitter, onRetry: DefaultOnRetry, retryIf: DefaultRetryIf, delayType: DefaultDelayType, lastErrorOnly: DefaultLastErrorOnly, } // apply opts for _, opt := range opts { opt(config) } var errorLog Error if !config.lastErrorOnly { errorLog = make(Error, config.attempts) } else { errorLog = make(Error, 1) } lastErrIndex := n for n < config.attempts { err := retryableFunc() if err != nil { errorLog[lastErrIndex] = unpackUnrecoverable(err) if !config.retryIf(err) { break } config.onRetry(n, err) // if this is last attempt - don't wait if n == config.attempts-1 { break } delayTime := config.delayType(n, config) if config.maxDelay > 0 && delayTime > config.maxDelay { delayTime = config.maxDelay } time.Sleep(delayTime) } else { return nil } n++ if !config.lastErrorOnly { lastErrIndex = n } } if config.lastErrorOnly { return errorLog[lastErrIndex] } return errorLog } // Error type represents list of errors in retry type Error []error // Error method return string representation of Error // It is an implementation of error interface func (e Error) Error() string { logWithNumber := make([]string, lenWithoutNil(e)) for i, l := range e { if l != nil { logWithNumber[i] = fmt.Sprintf("#%d: %s", i+1, l.Error()) } } return fmt.Sprintf("All attempts fail:\n%s", strings.Join(logWithNumber, "\n")) } func lenWithoutNil(e Error) (count int) { for _, v := range e { if v != nil { count++ } } return } // WrappedErrors returns the list of errors that this Error is wrapping. // It is an implementation of the `errwrap.Wrapper` interface // in package [errwrap](https://github.com/hashicorp/errwrap) so that // `retry.Error` can be used with that library. func (e Error) WrappedErrors() []error { return e } type unrecoverableError struct { error } // Unrecoverable wraps an error in `unrecoverableError` struct func Unrecoverable(err error) error { return unrecoverableError{err} } // IsRecoverable checks if error is an instance of `unrecoverableError` func IsRecoverable(err error) bool { _, isUnrecoverable := err.(unrecoverableError) return !isUnrecoverable } func unpackUnrecoverable(err error) error { if unrecoverable, isUnrecoverable := err.(unrecoverableError); isUnrecoverable { return unrecoverable.error } return err } <file_sep># Kubemq Hazelcast Target Connector Kubemq hazelcast target connector allows services using kubemq server to access hazelcast server functions such `set`, `get` and `delete`. ## Prerequisites The following are required to run the hazelcast target connector: - kubemq cluster - hazelcast - kubemq-targets deployment ## Configuration hazelcast target connector configuration properties: | Properties Key | Required| Description | Example | |:--------------------------|:--------|:-----------------------------|:-----------------| | address | yes | hazelcast connection string | "localhost:5701" | | username | no | hazelcast username | "admin" | | password | no | hazelcast password | "<PASSWORD>" | | connectionAttemptLimit | no | hazelcast connection attempts(default 1) | 1 | | connectionAttemptPeriod | no | hazelcast attempt period seconds(default 5) | 5 | | connectionTimeout | no | hazelcast connection timeout seconds(default 5) | 5 | | ssl | no | hazelcast use ssl | false | | sslcertificatefile | no | hazelcast certificate file | "" | | sslcertificatekey | no | hazelcast certificate key | "" | | serverName | no | hazelcast server name | "myserver" | Example: ```yaml bindings: - name: kubemq-hazelcast source: kind: kubemq.query properties: address: localhost:50000 channel: query.hazelcast target: kind: cache.hazelcast properties: address: localhost:5701 server_name: test properties: {} ``` ## Usage ### Get Request Get request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------|:----------------| | key | yes | hazelcast key string | any string | | method | yes | get | "get" | | map_name | yes | hazelcast map name | "my_map" | Example: ```json { "metadata": { "key": "your-hazelcast-key", "map_name": "my_map", "method": "get" }, "data": null } ``` ### Set Request Set request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | key | yes | hazelcast key | any string | | method | yes | set | "set" | | map_name | yes | hazelcast map name | "my_map" | Set request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:----------------------------------|:--------------------| | data | yes | data to set for the hazelcast key | base64 bytes array | Example: ```json { "metadata": { "key": "your-hazelcast-key", "map_name": "my_map", "method": "set" }, "data": "c29tZS1kYXRh" } ``` ### Delete Request Delete request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:---------------------|:----------------| | key | yes | hazelcast key string | any string | | method | yes | delete | "delete" | | map_name | yes | hazelcast map name | "my_map" | Example: ```json { "metadata": { "key": "your-hazelcast-key", "map_name": "my_map", "method": "delete" }, "data": null } ``` <file_sep>package hdfs import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { address string user string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.address, err = cfg.Properties.MustParseString("address") if err != nil { return options{}, fmt.Errorf("error parsing address , %w", err) } o.user, err = cfg.Properties.MustParseString("user") if err != nil { return options{}, fmt.Errorf("error parsing user , %w", err) } return o, nil } <file_sep>package couchbase import ( "fmt" "math" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultNumToReplicate = 1 defaultNumToPersist = 1 ) type options struct { url string username string password string bucket string numToReplicate int numToPersist int collection string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.url, err = cfg.Properties.MustParseString("url") if err != nil { return options{}, fmt.Errorf("error parsing url, %w", err) } o.username = cfg.Properties.ParseString("username", "") o.password = cfg.Properties.ParseString("password", "") o.bucket, err = cfg.Properties.MustParseString("bucket") if err != nil { return options{}, fmt.Errorf("error parsing cluster name, %w", err) } o.numToReplicate, err = cfg.Properties.ParseIntWithRange("num_to_replicate", defaultNumToReplicate, 0, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing num to replicate, %w", err) } o.numToPersist, err = cfg.Properties.ParseIntWithRange("num_to_persist", defaultNumToPersist, 0, math.MaxInt32) if err != nil { return options{}, fmt.Errorf("error parsing num to persist, %w", err) } o.collection = cfg.Properties.ParseString("collection", "") return o, nil } <file_sep># Kubemq GCP-Redis Target Connector Kubemq redis target connector allows services using kubemq server to access redis server functions such `set`, `get` and `delete`. ## Prerequisites The following are required to run the redis target connector: - kubemq cluster - redis v5.0.0 (or later) - access to gcp redis server - kubemq-targets deployment ## Configuration Redis target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-----------------------------|:-----------------| | url | yes | redis connection string | "redis://localhost:6379" | Example: ```yaml bindings: - name: kubemq-query-redis source: kind: kubemq.kubemq.query name: kubemq-query properties: host: "localhost" port: "50000" client_id: "kubemq-query-redis-connector" auth_token: "" channel: "query.redis" group: "" concurrency: "1" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.cache.redis name: target-redis properties: url: "redis://localhost:6379" ``` ## Usage ### Get Request Get request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | key | yes | redis key string | any string | | method | yes | get | "get" | Example: ```json { "metadata": { "key": "your-redis-key", "method": "get" }, "data": null } ``` ### Set Request Set request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | key | yes | redis key string | any string | | method | yes | set | "set" | | etag | no | set etag version | "0" | | concurrency | no | set concurrency | "" | | | | | "first-write" | | | | | "last-write" | | | | | | | consistency | no | set consistency | "" | | | | | "strong" | | | | | "eventual" | Set request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:------------------------------|:--------------------| | data | yes | data to set for the redis key | base64 bytes array | Example: ```json { "metadata": { "key": "your-redis-key", "method": "set", "etag": "0", "concurrency": "", "consistency": "" }, "data": "c29tZS1kYXRh" } ``` ### Delete Request Delete request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------|:----------------| | key | yes | redis key string | any string | | method | yes | delete | "delete" | Example: ```json { "metadata": { "key": "your-redis-key", "method": "delete" }, "data": null } ``` <file_sep># Kubemq Filesystem Target Connector Kubemq Filesystem target connector allows services using kubemq server to perform filesystem operation such as save,load, delete and list. ## Prerequisites The following are required to run the minio target connector: - kubemq cluster - kubemq-targets deployment ## Configuration Filesystem target connector configuration properties: | Properties Key | Required | Description | Example | |:------------------|:---------|:-----------------------------------------|:-----------------| | base_path | yes | base root for all functions | "./" | Example: ```yaml bindings: - name: kubemq-query-filesystem source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-fs-connector" auth_token: "" channel: "query.fs" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: storage.filesystem name: target-filesystem properties: base_path: "./" ``` ## Usage ### Save File Request Save file request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "save" | | path | no | set path for filename | "path" | | filename | yes | set filename | "filename.txt" | Example: ```json { "metadata": { "method": "save", "path": "path", "filename": "filename.txt" }, "data": "c29tZS1kYXRh" } ``` ### Load File Request Load file request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "load" | | path | no | set path for filename | "path" | | filename | yes | set filename | "filename.txt" | Example: ```json { "metadata": { "method": "load", "path": "path", "filename": "filename.txt" }, "data": null } ``` ### Delete File Request Delete file request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "delete" | | path | no | set path for filename | "path" | | filename | yes | set filename | "filename.txt" | Example: ```json { "metadata": { "method": "delete", "path": "path", "filename": "filename.txt" }, "data": null } ``` ### List Request List files in directory request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:--------------------|:----------------| | method | yes | method name | "list" | | path | no | set path for filename | "path" | Example: ```json { "metadata": { "method": "list", "path": "path" }, "data": null } ``` <file_sep>package bigquery import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) type metadata struct { query string tableName string method string location string datasetID string } var methodsMap = map[string]string{ "query": "query", "create_data_set": "create_data_set", "delete_data_set": "delete_data_set", "create_table": "create_table", "delete_table": "delete_table", "get_table_info": "get_table_info", "get_data_sets": "get_data_sets", "insert": "insert", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "query" { m.query, err = meta.MustParseString("query") if err != nil { return metadata{}, fmt.Errorf("query is required for method: %s ,error parsing query, %w", m.method, err) } } if m.method == "create_table" || m.method == "get_table_info" || m.method == "insert" || m.method == "delete_table" { m.tableName, err = meta.MustParseString("table_name") if err != nil { return metadata{}, fmt.Errorf("table_name is required for method: %s ,error parsing table_name, %w", m.method, err) } m.datasetID, err = meta.MustParseString("dataset_id") if err != nil { return metadata{}, fmt.Errorf("dataset_id is required for method: %s ,error parsing dataset_id, %w", m.method, err) } } else if m.method == "create_data_set" || m.method == "delete_data_set" { m.datasetID, err = meta.MustParseString("dataset_id") if err != nil { return metadata{}, fmt.Errorf("dataset_id is required for method: %s ,error parsing dataset_id, %w", m.method, err) } if m.method == "create_data_set" { m.location, err = meta.MustParseString("location") if err != nil { return metadata{}, fmt.Errorf("location is required for method: %s ,error parsing dataset_id, %w", m.method, err) } } } return m, nil } <file_sep>package cloudfunctions import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { parentProject string locationMatch bool credentials string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.parentProject, err = cfg.Properties.MustParseString("project_id") if err != nil { return options{}, fmt.Errorf("error parsing project, %w", err) } o.credentials, err = cfg.Properties.MustParseString("credentials") if err != nil { return options{}, fmt.Errorf("error parsing credentials, %w", err) } o.locationMatch = cfg.Properties.ParseBool("location_match", true) return o, nil } <file_sep>package cassandra import ( "context" "fmt" "github.com/gocql/gocql" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) // Client is a Client state store type Client struct { log *logger.Logger session *gocql.Session cluster *gocql.ClusterConfig table string opts options } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.cluster = gocql.NewCluster(c.opts.hosts...) if c.opts.username != "" && c.opts.password != "" { c.cluster.Authenticator = gocql.PasswordAuthenticator{Username: c.opts.username, Password: c.opts.password} } c.cluster.Port = c.opts.port c.cluster.ProtoVersion = c.opts.protoVersion c.cluster.Consistency = c.opts.consistency c.cluster.Timeout = c.opts.timeoutSeconds c.cluster.ConnectTimeout = c.opts.connectTimeoutSeconds session, err := c.cluster.CreateSession() if err != nil { return fmt.Errorf("error creating session: %s", err) } c.session = session if c.opts.defaultKeyspace != "" && c.opts.defaultTable != "" { err = c.tryCreateKeyspace(c.opts.defaultKeyspace, c.opts.replicationFactor) if err != nil { return fmt.Errorf("error creating defaultKeyspace %s: %s", c.opts.defaultTable, err) } err = c.tryCreateTable(c.opts.defaultTable, c.opts.defaultKeyspace) if err != nil { return fmt.Errorf("error creating defaultKeyspace %s: %s", c.opts.defaultTable, err) } c.table = fmt.Sprintf("%s.%s", c.opts.defaultKeyspace, c.opts.defaultTable) } return nil } func (c *Client) tryCreateKeyspace(keyspace string, replicationFactor int) error { return c.session.Query(fmt.Sprintf("CREATE KEYSPACE IF NOT EXISTS %s WITH REPLICATION = {'class' : 'SimpleStrategy', 'replication_factor' : %s};", keyspace, fmt.Sprintf("%v", replicationFactor))).Exec() } func (c *Client) tryCreateTable(table, keyspace string) error { return c.session.Query(fmt.Sprintf("CREATE TABLE IF NOT EXISTS %s.%s (key text, value blob, PRIMARY KEY (key));", keyspace, table)).Exec() } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.Get(ctx, meta) case "set": return c.Set(ctx, meta, req.Data) case "delete": return c.Delete(ctx, meta) case "query": return c.Query(ctx, meta, req.Data) case "exec": return c.Exec(ctx, meta, req.Data) } return nil, nil } func (c *Client) createSession(consistency gocql.Consistency) (*gocql.Session, error) { session, err := c.cluster.CreateSession() if err != nil { return nil, fmt.Errorf("error creating session: %s", err) } session.SetConsistency(consistency) return session, nil } func (c *Client) Get(ctx context.Context, meta metadata) (*types.Response, error) { session := c.session switch meta.consistency { case "strong": sess, err := c.createSession(gocql.All) if err != nil { return nil, err } defer sess.Close() session = sess case "eventual": sess, err := c.createSession(gocql.One) if err != nil { return nil, err } defer sess.Close() session = sess } table := meta.keyspaceTable() if table == "" { table = c.table } /* #nosec */ stmt := fmt.Sprintf("SELECT value FROM %s WHERE key = ?", table) results, err := session.Query(stmt, meta.key).WithContext(ctx).Iter().SliceMap() if err != nil { return nil, err } if len(results) == 0 { return nil, fmt.Errorf("no results for key %s", meta.key) } return types.NewResponse(). SetData(results[0]["value"].([]byte)). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) Exec(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { session := c.session switch meta.consistency { case "strong": sess, err := c.createSession(gocql.Quorum) if err != nil { return nil, err } defer sess.Close() session = sess case "eventual": sess, err := c.createSession(gocql.Any) if err != nil { return nil, err } defer sess.Close() session = sess } query := string(value) if query == "" { return nil, fmt.Errorf("no query string found") } err := session.Query(query).WithContext(ctx).Exec() if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Query(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { session := c.session switch meta.consistency { case "strong": sess, err := c.createSession(gocql.Quorum) if err != nil { return nil, err } defer sess.Close() session = sess case "eventual": sess, err := c.createSession(gocql.Any) if err != nil { return nil, err } defer sess.Close() session = sess } query := string(value) if query == "" { return nil, fmt.Errorf("no query string found") } results, err := session.Query(query).WithContext(ctx).Iter().SliceMap() if err != nil { return nil, err } if len(results) == 0 { return nil, fmt.Errorf("no results for this query") } return types.NewResponse(). SetData(results[0]["value"].([]byte)). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Set(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { session := c.session switch meta.consistency { case "strong": sess, err := c.createSession(gocql.Quorum) if err != nil { return nil, err } defer sess.Close() session = sess case "eventual": sess, err := c.createSession(gocql.Any) if err != nil { return nil, err } defer sess.Close() session = sess } table := meta.keyspaceTable() if table == "" { table = c.table } /* #nosec */ stmt := fmt.Sprintf("INSERT INTO %s (key, value) VALUES (?, ?)", table) err := session.Query(stmt, meta.key, value).WithContext(ctx).Exec() if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Delete(ctx context.Context, meta metadata) (*types.Response, error) { table := meta.keyspaceTable() if table == "" { table = c.table } /* #nosec */ stmt := fmt.Sprintf("DELETE FROM %s WHERE key = ?", table) err := c.session.Query(stmt, meta.key).WithContext(ctx).Exec() if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { c.session.Close() return nil } <file_sep>package elastic import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "get": "get", "set": "set", "delete": "delete", "index.exists": "index.exists", "index.create": "index.create", "index.delete": "index.delete", } type metadata struct { method string index string id string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.index, err = meta.MustParseString("index") if err != nil { return metadata{}, fmt.Errorf("error parsing index value, %w", err) } switch m.method { case "set", "get", "delete": m.id, err = meta.MustParseString("id") if err != nil { return metadata{}, fmt.Errorf("error on parsing id value, %w", err) } } return m, nil } <file_sep>//go:build !container // +build !container package global const ( DefaultApiPort = 8081 EnableLogFile = true LoggerType = "console" ) <file_sep>package config import ( "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "fmt" "io/ioutil" "log" "os" "path/filepath" "strings" "github.com/fsnotify/fsnotify" "github.com/ghodss/yaml" "github.com/kubemq-io/kubemq-targets/global" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/spf13/viper" ) const defaultApiPort = global.DefaultApiPort var ( configFile string logr = logger.NewLogger("config") lastConf *Config ) type Config struct { Bindings []BindingConfig `json:"bindings"` ApiPort int `json:"apiPort"` LogLevel string `json:"logLevel"` } func SetConfigFile(filename string) { configFile = filename } func (c *Config) hash() string { b, err := json.Marshal(c) if err != nil { return "" } h := sha256.New() _, _ = h.Write(b) hash := hex.EncodeToString(h.Sum(nil)) return hash } func (c *Config) copy() *Config { b, _ := json.Marshal(c) n := &Config{} _ = json.Unmarshal(b, n) return n } func (c *Config) Validate() error { if c.ApiPort == 0 { c.ApiPort = defaultApiPort } exitedBindings := map[string]string{} for _, binding := range c.Bindings { if err := binding.Validate(); err != nil { return err } if _, ok := exitedBindings[binding.Name]; ok { return fmt.Errorf("duplicated binding names found: %s", binding.Name) } else { exitedBindings[binding.Name] = binding.Name } } return nil } func getConfigFormat(in []byte) (string, error) { c := &Config{} yamlErr := yaml.Unmarshal(in, c) if yamlErr == nil { return "yaml", nil } jsonErr := json.Unmarshal(in, c) if jsonErr == nil { return "json", nil } return "", fmt.Errorf("yaml parsing error: %s, json parsing error: %s", yamlErr.Error(), jsonErr.Error()) } func decodeBase64(in string) string { // base64 string cannot contain space so this is indication of base64 string if !strings.Contains(in, " ") { sDec, err := base64.StdEncoding.DecodeString(in) if err != nil { log.Println(fmt.Sprintf("error decoding config file base64 string: %s ", err.Error())) return in } return string(sDec) } return in } func getConfigDataFromLocalFile(filename string) (string, error) { data, err := ioutil.ReadFile(filename) if err != nil { return "", err } fileExt, err := getConfigFormat(data) if fileExt == "" { return "", err } if strings.HasSuffix(filename, "."+fileExt) { return filename, nil } return filename + "." + fileExt, nil } func getConfigDataFromEnv() (string, error) { envConfigData, ok := os.LookupEnv("CONFIG") envConfigData = decodeBase64(envConfigData) if ok { fileExt, err := getConfigFormat([]byte(envConfigData)) if fileExt == "" { return "", err } /* #nosec */ err = ioutil.WriteFile("./config."+fileExt, []byte(envConfigData), 0o644) if err != nil { return "", fmt.Errorf("cannot save environment config file") } return "./config." + fileExt, nil } return "", fmt.Errorf("no config data from environment variable") } func getConfigFile() (string, error) { if configFile != "" { loadedConfigFile, err := getConfigDataFromLocalFile(configFile) if err != nil { return "", err } return loadedConfigFile, nil } else { loadedConfigFile, err := getConfigDataFromEnv() if err != nil { return "", err } return loadedConfigFile, nil } } func load() (*Config, error) { path, err := os.Executable() if err != nil { return nil, err } loadedConfigFile, err := getConfigFile() if err != nil { return nil, err } else { viper.SetConfigFile(filepath.Join(filepath.Dir(path), loadedConfigFile)) } err = viper.ReadInConfig() if err != nil { return nil, err } cfg := &Config{} err = viper.Unmarshal(cfg) if err != nil { return nil, err } logr.Infof("%d bindings loaded", len(cfg.Bindings)) return cfg, err } func Load(cfgCh chan *Config) (*Config, error) { path, err := os.Executable() if err != nil { return nil, err } viper.AddConfigPath(filepath.Dir(path)) cfg, err := load() if err != nil { return nil, err } viper.WatchConfig() viper.OnConfigChange(func(e fsnotify.Event) { cfg, err := load() if err != nil { logr.Errorf("error loading new configuration file: %s", err.Error()) return } if cfg.hash() != lastConf.hash() { logr.Info("config file changed, reloading...") lastConf = cfg.copy() cfgCh <- cfg } }) return cfg, err } <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) var ( transactionString = `DROP TABLE IF EXISTS post; CREATE TABLE post ( ID bigint, TITLE varchar(40), CONTENT varchar(255), BIGNUMBER bigint, BOOLVALUE boolean, CONSTRAINT pk_post PRIMARY KEY(ID) ); INSERT INTO post(ID,TITLE,CONTENT,BIGNUMBER,BOOLVALUE) VALUES (0,NULL,'Content One',1231241241231231123,true), (1,'Title Two','Content Two',123125241231231123,false);` queryString = `SELECT id,title,content,bignumber,boolvalue FROM post;` ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } transactionRequest := types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetData([]byte(transactionString)) queryTransactionResponse, err := client.SetQuery(transactionRequest.ToQuery()). SetChannel("query.percona"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } transactionResponse, err := types.ParseResponse(queryTransactionResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("transaction request result: %s ", transactionResponse.Metadata.String())) queryRequest := types.NewRequest(). SetMetadataKeyValue("method", "query"). SetData([]byte(queryString)) queryResponse, err := client.SetQuery(queryRequest.ToQuery()). SetChannel("query.percona"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } response, err := types.ParseResponse(queryResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("query request results: %s ", string(response.Data))) } <file_sep>package files import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("azure.storage.files"). SetDescription("Azure Files Storage Target"). SetName("Files"). SetProvider("Azure"). SetCategory("Storage"). SetTags("filesystem", "db", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("storage_access_key"). SetDescription("Set Files Storage storage access key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("storage_account"). SetDescription("Set Files Storage storage account"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("policy"). SetDescription("Set Files Storage retry policy"). SetOptions([]string{"exponential", "fixed"}). SetMust(true). SetDefault("exponential"), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_tries"). SetDescription("Set Files Storage max tries"). SetMust(false). SetDefault("1"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("try_timeout"). SetTitle("Try Timout (milliseconds)"). SetDescription("Set Files Storage try timeout in milliseconds"). SetMust(false). SetDefault("1000"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("retry_delay"). SetDescription("Set Files Storage retry delay in milliseconds"). SetMust(false). SetDefault("60000"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_retry_delay"). SetDescription("Set Files Storage max retry delay in milliseconds"). SetMust(false). SetDefault("180000"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set GCP files Storage execution method"). SetOptions([]string{"upload", "get", "delete", "create"}). SetDefault("get"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("service_url"). SetKind("string"). SetDescription("Set files Storage service url"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("file_metadata"). SetKind("string"). SetDescription("Set files Storage file metadata"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("range_size"). SetDescription("Set files Storage range size"). SetMust(false). SetDefault("4194304"). SetMin(0), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("parallelism"). SetDescription("Set files Storage parallelism"). SetMust(false). SetDefault("16"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("count"). SetDescription("Set files Storage count"). SetMust(false). SetDefault("0"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("offset"). SetDescription("Set files Storage offset"). SetMust(false). SetDefault("0"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("max_retry_request"). SetDescription("Set files Storage max retry request"). SetMust(false). SetDefault("1"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("file_size"). SetDescription("Set files Storage file size"). SetMust(false). SetDefault("1000000"). SetMin(0). SetMax(math.MaxInt32), ) } <file_sep>package msk import ( "context" "crypto/tls" "fmt" "strconv" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/pkg/logger" kafka "github.com/Shopify/sarama" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger producer kafka.SyncProducer opts options } func New() *Client { return &Client{} } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } kc := kafka.NewConfig() kc.Version = kafka.V2_0_0_0 kc.Producer.RequiredAcks = kafka.WaitForAll kc.Producer.Retry.Max = 5 kc.Producer.Return.Successes = true if c.opts.saslUsername != "" { kc.Net.SASL.Enable = true kc.Net.SASL.User = c.opts.saslUsername kc.Net.SASL.Password = <PASSWORD> kc.Net.TLS.Enable = true kc.Net.TLS.Config = &tls.Config{ ClientAuth: 0, } } c.producer, err = kafka.NewSyncProducer(c.opts.brokers, kc) if err != nil { return fmt.Errorf("error connecting to kafka at %s: %w", c.opts.brokers, err) } return nil } func (c *Client) Do(ctx context.Context, request *types.Request) (*types.Response, error) { m, err := parseMetadata(request.Metadata, c.opts) if err != nil { return nil, err } partition, offset, err := c.producer.SendMessage(&kafka.ProducerMessage{ Headers: m.Headers, Key: kafka.ByteEncoder(m.Key), Value: kafka.ByteEncoder(request.Data), Topic: c.opts.topic, }) if err != nil { return nil, err } r := types.NewResponse(). SetMetadataKeyValue("partition", strconv.FormatInt(int64(partition), 10)). SetMetadataKeyValue("offset", strconv.FormatInt(offset, 10)) return r, nil } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Stop() error { return c.producer.Close() } <file_sep>package consulkv import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8500", }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSetErr %v", err, tt.wantErr) return } }) } } func TestClient_Put(t *testing.T) { kvp := `{"Key":"some-key","CreateIndex":0,"ModifyIndex":0,"LockIndex":0,"Flags":0,"Value":"bXkgdmFsdWU=","Session":""}` tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid put key", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8500", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "put"). SetData([]byte(kvp)), wantErr: false, }, { name: "invalid put key - missing data", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8500", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "put"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) _, err = c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } func TestClient_Get(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid get key", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8500", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "some-key"), wantErr: false, }, { name: "invalid get key invalid address ", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8511", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "some-key"), wantErr: true, }, { name: "invalid get key key not exists ", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8511", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "fake-key"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) k, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, k.Data) }) } } func TestClient_Delete(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid delete key", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8500", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("key", "some-key"), wantErr: false, }, { name: "invalid delete key - missing key ", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8511", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "delete"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) k, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, k.Data) }) } } func TestClient_List(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid list", cfg: config.Spec{ Name: "stores-consulkv", Kind: "stores.consulkv", Properties: map[string]string{ "address": "localhost:8500", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "list"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) k, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, k.Data) }) } } <file_sep># KubeMQ Targets KubeMQ Targets connects KubeMQ Message Broker with external systems and cloud services. KubeMQ Targets allows us to build a message-based microservices architecture on Kubernetes with minimal efforts and without developing connectivity interfaces between KubeMQ Message Broker and external systems such as databases, cache, messaging, and REST-base APIs. **Key Features**: - **Runs anywhere** - Kubernetes, Cloud, on-prem, anywhere - **Stand-alone** - small docker container / binary - **Single Interface** - One interface all the services - **Any Service** - Support all major services types (databases, cache, messaging, serverless, HTTP, etc.) - **Plug-in Architecture** Easy to extend, easy to connect - **Middleware Supports** - Logs, Metrics, Retries, and Rate Limiters - **Easy Configuration** - simple yaml file builds your topology ## Concepts KubeMQ Targets building blocks are: - Binding - Source - Target - Request/Response ### Binding Binding is a 1:1 connection between Source and Target. Every Binding runs independently. ![binding](.github/assets/binding.jpeg) ### Target Target is an external service that exposes an API allowing to interact and serve his functionalists with other services. Targets can be Cache systems such as Redis and Memcached, SQL Databases such as Postgres and MySql, and even an HTTP generic Rest interface. KubeMQ Targets integrate each one of the supported targets and service requests based on the request data. A list of supported targets is below. #### Standalone Services | Category | Target | Kind | Configuration | Example | |:-----------|:--------------------------------------------------------------------|:----------------------|:-------------------------------------|:----------------------------------------| | Cache | | | | | | | [Redis](https://redis.io/) | cache.redis | [Usage](targets/cache/redis) | [Example](examples/cache/redis) | | | [Memcached](https://memcached.org/) | cache.memcached | [Usage](targets/cache/memcached) | [Example](examples/cache/memcached) | | | [Hazelcast](https://hazelcast.com/) | cache.hazelcast | [Usage](targets/cache/hazelcast) | [Example](examples/cache/hazelcast) | | Stores/db | | | | | | | [Postgres](https://www.postgresql.org/) | stores.postgres | [Usage](targets/stores/postgres) | [Example](examples/stores/postgres) | | | [Mysql](https://www.mysql.com/) | stores.mysql | [Usage](targets/stores/mysql) | [Example](examples/stores/mysql) | | | [MSSql](https://www.microsoft.com/en-us/sql-server/sql-server-2019) | stores.mssql | [Usage](targets/stores/mssql) | [Example](examples/stores/mssql) | | | [MongoDB](https://www.mongodb.com/) | stores.mongodb | [Usage](targets/stores/mongodb) | [Example](examples/stores/mongodb) | | | [Elastic Search](https://www.elastic.co/) | stores.elastic-search | [Usage](targets/stores/elastic) | [Example](examples/stores/elastic) | | | [Cassandra](https://cassandra.apache.org/) | stores.cassandra | [Usage](targets/stores/cassandra) | [Example](examples/stores/cassandra) | | | [Couchbase](https://www.couchbase.com/) | stores.couchbase | [Usage](targets/stores/couchbase) | [Example](examples/stores/couchbase) | | | [Percona](https://www.percona.com/) | stores.percona | [Usage](targets/stores/percona) | [Example](examples/stores/percona) | | | [Cockroachdb](https://www.cockroachlabs.com/) | stores.cockroachdb | [Usage](targets/stores/cockroachdb) | [Example](examples/stores/cockroachdb) | | | [Aerospike](https://www.aerospike.com/) | stores.aerospike | [Usage](targets/stores/aerospike) | [Example](examples/stores/aerospike) | | | [RethinkDB](https://rethinkdb.com/) | stores.rethinkdb | [Usage](targets/stores/rethinkdb) | [Example](examples/stores/rethinkdb) | | | [SingleStore](https://www.singlestore.com/) | stores.singlestore | [Usage](targets/stores/singlestore) | [Example](examples/stores/singlestore) | | | [Crate.io](https://crate.io/) |stores.crate |[Usage](targets/stores/create) | Similar to postgres | | Messaging | | | | | | | [Kafka](https://kafka.apache.org/) | messaging.kafka | [Usage](targets/messaging/kafka) | [Example](examples/messaging/kafka) | | | [Nats](https://nats.io/) | messaging.nats | [Usage](targets/messaging/nats) | [Example](examples/messaging/nats) | | | [RabbitMQ](https://www.rabbitmq.com/) | messaging.rabbitmq | [Usage](targets/messaging/rabbitmq) | [Example](examples/messaging/rabbitmq) | | | [MQTT](http://mqtt.org/) | messaging.mqtt | [Usage](targets/messaging/mqtt) | [Example](examples/messaging/mqtt) | | | [ActiveMQ](http://activemq.apache.org/) | messaging.activemq | [Usage](targets/messaging/activemq) | [Example](examples/messaging/activemq) | | | [IBM-MQ](https://developer.ibm.com/components/ibm-mq) | messaging.ibmmq | [Usage](targets/messaging/ibmmq) | [Example](examples/messaging/ibmmq) | | Storage | | | | | | | [Minio/S3](https://min.io/) | storage.minio | [Usage](targets/storage/minio) | [Example](examples/storage/minio) | | | [hadoop/hdfs](https://hadoop.apache.org/) | storage.hdfs | [Usage](targets/storage/hdfs) | [Example](examples/storage/hdfs) | | | Filesystem | storage.filesystem | [Usage](targets/storage/filesystem) | | | Serverless | | | | | | | [OpenFaas](https://www.openfaas.com/) | serverless.openfaas | [Usage](targets/serverless/openfaas) | [Example](examples/serverless/openfaas) | | Http | | | | | | | Http | http | [Usage](targets/http) | [Example](examples/http) | | Testing | | | | | | | Echo | echo | [Usage](targets/echo) | | #### Google Cloud Platform (GCP) | Category | Target | Kind | Configuration | Example | |:-----------|:--------------------------------------------------------------------|:---------------------------|:-------------------------------------------|:----------------------------------------------| | Cache | | | | | | | [Redis](https://cloud.google.com/memorystore) |gcp.cache.redis | [Usage](targets/gcp/memorystore/redis) | [Example](examples/gcp/memorystore/redis) | | | [Memcached](https://cloud.google.com/memorystore) |gcp.cache.memcached | [Usage](targets/gcp/memorystore/memcached) | [Example](examples/gcp/memorystore/memcached) | | Stores/db | | | | | | | [Postgres](https://cloud.google.com/sql) |gcp.stores.postgres | [Usage](targets/gcp/sql/postgres) | [Example](examples/gcp/sql/postgres) | | | [Mysql](https://cloud.google.com/sql) |gcp.stores.mysql | [Usage](targets/gcp/sql/mysql) | [Example](examples/gcp/sql/mysql) | | | [BigQuery](https://cloud.google.com/bigquery) |gcp.bigquery | [Usage](targets/gcp/bigquery) | [Example](examples/gcp/bigquery) | | | [BigTable](https://cloud.google.com/bigtable) |gcp.bigtable | [Usage](targets/gcp/bigtable) | [Example](examples/gcp/bigtable) | | | [Firestore](https://cloud.google.com/firestore) |gcp.firestore | [Usage](targets/gcp/firestore) | [Example](examples/gcp/firestore) | | | [Spanner](https://cloud.google.com/spanner) |gcp.spanner | [Usage](targets/gcp/spanner) | [Example](examples/gcp/spanner) | | | [Firebase](https://firebase.google.com/products/realtime-database/) |gcp.firebase | [Usage](targets/gcp/firebase) | [Example](examples/gcp/firebase) | | Messaging | | | | | | | [Pub/Sub](https://cloud.google.com/pubsub) |gcp.pubsub | [Usage](targets/gcp/pubsub) | [Example](examples/gcp/pubsub) | | Storage | | | | | | | [Storage](https://cloud.google.com/storage) |gcp.storage | [Usage](targets/gcp/storage) | [Example](examples/gcp/storage) | | Serverless | | | | | | | [Functions](https://cloud.google.com/functions) |gcp.cloudfunctions | [Usage](targets/gcp/cloudfunctions) | [Example](examples/gcp/cloudfunctions) | | | | | | | #### Amazon Web Service (AWS) | Category | Target | Kind | Configuration | Example | |:-----------|:---------------------------------------------------------------|:--------------------------------|:----------------------------------------|:-------------------------------------------| | Stores/db | | | | | | | [Athena](https://docs.aws.amazon.com/athena) |aws.athena | [Usage](targets/aws/athena) | [Example](examples/aws/athena) | | | [DynamoDB](https://aws.amazon.com/dynamodb/) |aws.dynamodb | [Usage](targets/aws/dynamodb) | [Example](examples/aws/dynamodb) | | | [Elasticsearch](https://aws.amazon.com/elasticsearch-service/) |aws.elasticsearch | [Usage](targets/aws/elasticsearch) | [Example](examples/aws/elasticsearch) | | | [KeySpaces](https://docs.aws.amazon.com/keyspaces) |aws.keyspaces | [Usage](targets/aws/keyspaces) | [Example](examples/aws/keyspaces) | | | [MariaDB](https://aws.amazon.com/rds/mariadb/) |aws.rds.mariadb | [Usage](targets/aws/rds/mariadb) | [Example](examples/aws/rds/mariadb) | | | [MSSql](https://aws.amazon.com/rds/sqlserver/) |aws.rds.mssql | [Usage](targets/aws/rds/mssql) | [Example](examples/aws/rds/mssql) | | | [MySQL](https://aws.amazon.com/rds/mysql/) |aws.rds.mysql | [Usage](targets/aws/rds/mysql) | [Example](examples/aws/rds/mysql) | | | [Postgres](https://aws.amazon.com/rds/postgresql/) |aws.rds.postgres | [Usage](targets/aws/rds/postgres) | [Example](examples/aws/rds/postgres) | | | [RedShift](https://aws.amazon.com/redshift/) |aws.rds.redshift | [Usage](targets/aws/rds/redshift) | [Example](examples/aws/rds/redshift) | | | [RedShiftSVC](https://aws.amazon.com/redshift/) |aws.rds.redshift.service | [Usage](targets/aws/redshift) | [Example](examples/aws/redshift) | | Messaging | | | | | | | [AmazonMQ](https://aws.amazon.com/amazon-mq/) |aws.amazonmq | [Usage](targets/aws/amazonmq) | [Example](examples/aws/amazonmq) | | | [msk](https://aws.amazon.com/msk/) |aws.msk | [Usage](targets/aws/msk) | [Example](examples/aws/msk) | | | [Kinesis](https://aws.amazon.com/kinesis/) |aws.kinesis | [Usage](targets/aws/kinesis) | [Example](examples/aws/kinesis) | | | [SQS](https://aws.amazon.com/sqs/) |aws.sqs | [Usage](targets/aws/sqs) | [Example](examples/aws/sqs) | | | [SNS](https://aws.amazon.com/sns/) |aws.sns | [Usage](targets/aws/sns) | [Example](examples/aws/sns) | | Storage | | | | | | | [s3](https://aws.amazon.com/s3/) |aws.s3 | [Usage](targets/aws/s3) | [Example](examples/aws/s3) | | Serverless | | | | | | | [lambda](https://aws.amazon.com/lambda/) |aws.lambda | [Usage](targets/aws/lambda) | [Example](examples/aws/lambda) | | Other | | | | | | | [Cloud Watch Logs](https://aws.amazon.com/cloudwatch/) |aws.cloudwatch.logs | [Usage](targets/aws/cloudwatch/logs) | [Example](examples/aws/cloudwatch/logs) | | | [Cloud Watch Events](https://aws.amazon.com/cloudwatch/) |aws.cloudwatch.events | [Usage](targets/aws/cloudwatch/events) | [Example](examples/aws/cloudwatch/events) | | | [Cloud Watch Metrics ](https://aws.amazon.com/cloudwatch/) |aws.cloudwatch.metrics | [Usage](targets/aws/cloudwatch/metrics) | [Example](examples/aws/cloudwatch/metrics) | #### Microsoft Azure | Category | Target | Kind | Configuration | Example | |:-----------|:----------------------------------------------------------------------|:-----------------------------|:---------------------------------------|:-----------------------------------------| | Stores/db | | | | | | | [Azuresql](https://docs.microsoft.com/en-us/azure/mysql/) |azure.stores.azuresql | [Usage](targets/azure/stores/azuresql) | [Example](examples/azure/store/azuresql) | | | [Mysql](https://aws.amazon.com/dynamodb/) |azure.stores.mysql | [Usage](targets/azure/stores/mysql) | [Example](examples/azure/store/mysql) | | | [Postgres](https://azure.microsoft.com/en-us/services/postgresql/) |azure.stores.postgres | [Usage](targets/azure/stores/postgres) | [Example](examples/azure/store/postgres) | | Storage | | | | | | | [Blob](https://azure.microsoft.com/en-us/services/storage/blobs/) |azure.storage.blob | [Usage](targets/azure/storage/blob) | [Example](examples/azure/storage/blob) | | | [Files](https://azure.microsoft.com/en-us/services/storage/files/) |azure.storage.files | [Usage](targets/azure/storage/files) | [Example](examples/azure/storage/files) | | | [Queue](https://docs.microsoft.com/en-us/azure/storage/queues/) |azure.storage.queue | [Usage](targets/azure/storage/queue) | [Example](examples/azure/storage/queue) | | EventHubs | | | | | | | [EventHubs](https://azure.microsoft.com/en-us/services/event-hubs/) |azure.eventhubs | [Usage](targets/azure/eventhubs) | [Example](examples/azure/eventhubs) | | ServiceBus | | | | | | | [ServiceBus](https://azure.microsoft.com/en-us/services/service-bus/) |azure.servicebus | [Usage](targets/azure/servicebus) | [Example](examples/azure/servicebus) | ### Source The source is a KubeMQ connection (in subscription mode), which listens to requests from services and route them to the appropriate target for action, and return back a response if needed. KubeMQ Targets supports all of KubeMQ's messaging patterns: Queue, Events, Events-Store, Command, and Query. | Type | Kind | Configuration | |:----------------------------------------------------------------------------------|:--------------------|:----------------------------------------| | [Queue](https://docs.kubemq.io/learn/message-patterns/queue) | kubemq.queue | [Usage](sources/queue/README.md) | | [Queue-Stream](https://docs.kubemq.io/learn/message-patterns/queue) | kubemq.queue-stream | [Usage](sources/queue_stream/README.md) | | [Events](https://docs.kubemq.io/learn/message-patterns/pubsub#events) | kubemq.events | [Usage](sources/events/README.md) | | [Events Store](https://docs.kubemq.io/learn/message-patterns/pubsub#events-store) | kubemq.events-store | [Usage](sources/events-store/README.md) | | [Command](https://docs.kubemq.io/learn/message-patterns/rpc#commands) | kubemq.command | [Usage](sources/command/README.md) | | [Query](https://docs.kubemq.io/learn/message-patterns/rpc#queries) | kubemq.query | [Usage](sources/query/README.md) | ### Request / Response ![concept](.github/assets/concept.jpeg) #### Request A request is an object that sends to a designated target with metadata and data fields, which contains the needed information to perform the requested data. ##### Request Object Structure | Field | Type | Description | |:---------|:----------------------|:-----------------------------------------| | metadata | string, string object | contains metadata information for action | | data | bytes array | contains raw data for action | ##### Example Request to get a data from Redis cache for the key "log" ```json { "metadata": { "method": "get", "key": "log" }, "data": null } ``` #### Response The response is an object that sends back as a result of executing an action in the target ##### Response Object Structure | Field | Type | Description | |:---------|:---------------------|:------------------------------------------------| | metadata | string, string object | contains metadata information result for action | | data | bytes array | contains raw data result | | is_error | bool | indicate if the action ended with an error | | error | string | contains error information if any | ##### Example Response received on request to get the data stored in Redis for key "log" ```json { "metadata": { "result": "ok", "key": "log" }, "data": "SU5TRVJUIElOVE8gcG9zdChJRCxUSVRMRSxDT05URU5UKSBWQUxVRVMKCSAgICAgICAgICAgICAgICAgICAgICA" } ``` ## Installation ### Kubernetes 1. Install KubeMQ Cluster ```bash kubectl apply -f https://get.kubemq.io/deploy ``` 2. Run Redis Cluster deployment yaml ```bash kubectl apply -f https://raw.githubusercontent.com/kubemq-hub/kubemq-targets/master/redis-example.yaml ``` 2. Run KubeMQ Targets deployment yaml ```bash kubectl apply -f https://raw.githubusercontent.com/kubemq-hub/kubemq-targets/master/deploy-example.yaml ``` ### Binary (Cross-platform) Download the appropriate version for your platform from KubeMQ Targets Releases. Once downloaded, the binary can be run from anywhere. Ideally, you should install it somewhere in your PATH for easy use. /usr/local/bin is the most probable location. Running KubeMQ Targets ```bash ./kubemq-targets --config config.yaml ``` ### Windows Service 1. Download the Windows version from KubeMQ Targets Releases. Once downloaded, the binary can be installed from anywhere. 2. Create config.yaml configuration file and save it to the same location of the Windows binary. #### Service Installation Run: ```bash kubemq-targets.exe --service install ``` #### Service Installation With Username and Password Run: ```bash kubemq-targets.exe --service install --username {your-username} --password {<PASSWORD>} ``` #### Service UnInstall Run: ```bash kubemq-sources.exe --service uninstall ``` #### Service Start Run: ```bash kubemq-targets.exe --service start ``` #### Service Stop Run: ```bash kubemq-targets.exe --service stop ``` #### Service Restart Run: ```bash kubemq-targets.exe --service restart ``` **NOTE**: When running under Windows service, all logs will be emitted to Windows Events Logs. ## Configuration ### Build Wizard KubeMQ Targets configuration can be build with Build and Deploy tool [https://build.kubemq.io/#/sources](https://build.kubemq.io/#/targets) ### Structure Config file structure: ```yaml apiPort: 8080 # kubemq targets api and health end-point port bindings: - name: clusters-sources # unique binding name properties: # Bindings properties such middleware configurations log_level: error retry_attempts: 3 retry_delay_milliseconds: 1000 retry_max_jitter_milliseconds: 100 retry_delay_type: "back-off" rate_per_second: 100 source: kind: kubemq.query # source kind name: name-of-sources # source name properties: # a set of key/value settings per each source kind ..... target: kind:cache.redis # target kind name: name-of-target # targets name properties: # a set of key/value settings per each target kind - ..... ``` ### Build Wizard KubeMQ Targets configuration can be build with --build flag ``` ./kubemq-targets --build ``` ### Properties In bindings configuration, KubeMQ targets support properties setting for each pair of source and target bindings. These properties contain middleware information settings as follows: #### Logs Middleware KubeMQ targets support level based logging to console according to as follows: | Property | Description | Possible Values | |:----------|:------------------|:-----------------------| | log_level | log level setting | "debug","info","error" | | | | "" - indicate no logging on this bindings | An example for only error level log to console: ```yaml bindings: - name: sample-binding properties: log_level: error source: ...... ``` #### Retry Middleware KubeMQ targets support Retries' target execution before reporting of error back to the source on failed execution. Retry middleware settings values: | Property | Description | Possible Values | |:------------------------------|:------------------------------------------------------|:--------------------------------------------| | retry_attempts | how many retries before giving up on target execution | default - 1, or any int number | | retry_delay_milliseconds | how long to wait between retries in milliseconds | default - 100ms or any int number | | retry_max_jitter_milliseconds | max delay jitter between retries | default - 100ms or any int number | | retry_delay_type | type of retry delay | "back-off" - delay increase on each attempt | | | | "fixed" - fixed time delay | | | | "random" - random time delay | An example for 3 retries with back-off strategy: ```yaml bindings: - name: sample-binding properties: retry_attempts: 3 retry_delay_milliseconds: 1000 retry_max_jitter_milliseconds: 100 retry_delay_type: "back-off" source: ...... ``` #### Rate Limiter Middleware KubeMQ targets support a Rate Limiting of target executions. Rate Limiter middleware settings values: | Property | Description | Possible Values | |:----------------|:-----------------------------------------------|:-------------------------------| | rate_per_second | how many executions per second will be allowed | 0 - no limitation | | | | 1 - n integer times per second | An example for 100 executions per second: ```yaml bindings: - name: sample-binding properties: rate_per_second: 100 source: ...... ``` ### Source Source section contains source configuration for Binding as follows: | Property | Description | Possible Values | |:------------|:--------------------------------------------------|:--------------------------------------------------------------| | name | sources name (will show up in logs) | string without white spaces | | kind | source kind type | kubemq.queue | | | | kubemq.query | | | | kubemq.query-stream | | | | kubemq.command | | | | kubemq.events | | | | kubemq.events-store | | properties | an array of key/value setting for source connection| see above | ### Target Target section contains the target configuration for Binding as follows: | Property | Description | Possible Values | |:------------|:--------------------------------------------------|:--------------------------------------------------------------| | name | targets name (will show up in logs) | string without white spaces | | kind | source kind type |type-of-target | | properties | an array of key/value set for target connection | see above | <file_sep># Kubemq s3 target Connector Kubemq aws-s3 target connector allows services using kubemq server to access aws s3 service. ## Prerequisites The following required to run the aws-s3 target connector: - kubemq cluster - aws account with s3 active service - kubemq-targets deployment ## Configuration s3 target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-s3 source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-s3-connector" auth_token: "" channel: "query.aws.s3" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.s3 name: aws-s3 properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### List Buckets list all buckets. List Buckets: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_buckets" | Example: ```json { "metadata": { "method": "list_buckets" }, "data": null } ``` ### List Bucket Items list all items in the selected bucket List Bucket Items: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list_bucket_items" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | Example: ```json { "metadata": { "method": "list_bucket_items", "bucket_name": "my_bucket_name" }, "data": null } ``` ### Create Bucket create a new bucket, name must be unique Create Bucket : | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "create_bucket" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | | wait_for_completion | no | wait for operation to end | "true","false" default of false | Example: ```json { "metadata": { "method": "create_bucket", "bucket_name": "my_bucket_name" }, "data": null } ``` ### Upload Item upload item to bucket. Upload Bucket Items: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:----------------------------------------|:-------------------------------------| | method | yes | type of method | "upload_item" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | | wait_for_completion | no | wait for operation to end | "true","false" (default of false ) | | item_name | yes | the name of the item | "valid-string" | | data | yes | the object data in byte array | "valid-string" | Example: ```json { "metadata": { "method": "upload_item", "bucket_name": "my_bucket_name", "item_name": "my_item_name" }, "data": "bXkgaXRlbSBoZXJl" } ``` ### Get Item Get item by item name from bucket Get Bucket Items: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:----------------------------------------|:-------------------------------------| | method | yes | type of method | "get_item" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | | item_name | yes | the name of the item | "valid-string" | Example: ```json { "metadata": { "method": "get_item", "bucket_name": "my_bucket_name", "item_name": "my_item_name" }, "data": null } ``` ### Delete Item delete item by item name from bucket Delete Item: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:----------------------------------------|:-------------------------------------| | method | yes | type of method | "delete_item_from_bucket" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | | wait_for_completion | no | wait for operation to end | "true","false" (default of false ) | | item_name | yes | the name of the item | "valid-string" | Example: ```json { "metadata": { "method": "delete_item_from_bucket", "bucket_name": "my_bucket_name", "item_name": "my_item_name" }, "data": null } ``` ### Delete All Items delete all items from a bucket Delete All Items: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:----------------------------------------|:-------------------------------------| | method | yes | type of method | "delete_all_items_from_bucket" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | | wait_for_completion | no | wait for operation to end | "true","false" (default of false ) | Example: ```json { "metadata": { "method": "delete_item_from_bucket", "bucket_name": "my_bucket_name" }, "data": null } ``` ### Copy Item copy an item from one bucket to another Copy Items: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:----------------------------------------|:-------------------------------------| | method | yes | type of method | "copy_item" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | | copy_source | yes | s3 bucket name source name | "my_bucket_source_name" | | item_name | yes | the name of the item | "valid-string" | | wait_for_completion | no | wait for operation to end | "true","false" (default of false ) | Example: ```json { "metadata": { "method": "copy_item", "bucket_name": "my_bucket_name", "copy_source": "my_bucket_source_name", "item_name": "my_item_name" }, "data": null } ``` ### Delete Bucket delete a bucket by name. Delete Bucket: | Metadata Key | Required | Description | Possible values | |:--------------------|:---------|:----------------------------------------|:-------------------------------------| | method | yes | type of method | "delete_bucket" | | bucket_name | yes | s3 bucket name | "my_bucket_name" | | wait_for_completion | no | wait for operation to end | "true","false" (default of false ) | Example: ```json { "metadata": { "method": "delete_bucket", "bucket_name": "my_bucket_name" }, "data": null } ``` <file_sep>package bigtable import ( "testing" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestParseMetaData(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool Request *types.Request }{ { name: "valid method write", cfg: config.Spec{ Name: "google-big-table-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "write"). SetMetadataKeyValue("table_name", dat.tableName). SetMetadataKeyValue("column_family", dat.columnFamily), wantErr: false, }, { name: "invalid method write - missing column_family", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "write"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "valid method write_batch", cfg: config.Spec{ Name: "google-big-table-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "write_batch"). SetMetadataKeyValue("table_name", dat.tableName). SetMetadataKeyValue("column_family", dat.columnFamily), wantErr: false, }, { name: "invalid method write_batch - missing column_family", cfg: config.Spec{ Name: "google-big-table-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "write_batch"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "valid method delete_rows", cfg: config.Spec{ Name: "google-big-table-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "delete_row"). SetMetadataKeyValue("table_name", dat.tableName). SetMetadataKeyValue("row_key_prefix", dat.rowKeyPrefix), wantErr: false, }, { name: "invalid method delete_row - missing row_key_prefix", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "delete_row"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "valid method create_table", cfg: config.Spec{ Name: "google-big-table-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetMetadataKeyValue("table_name", dat.tempTable), wantErr: false, }, { name: "valid method delete_table", cfg: config.Spec{ Name: "google-big-table-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("table_name", dat.tempTable), wantErr: false, }, { name: "valid method get_tables", cfg: config.Spec{ Name: "google-big-table-target", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "get_tables"), wantErr: false, }, { name: "invalid method type", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "", Properties: map[string]string{ "project_id": dat.projectID, "instance": dat.instance, }, }, Request: types.NewRequest(). SetMetadataKeyValue("method", "non_existing_type"). SetMetadataKeyValue("table_name", dat.tempTable), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { m, err := parseMetadata(tt.Request.Metadata) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, m) }) } } <file_sep># Kubemq Kafka Source Connector Kubemq kafka target connector allows services using kubemq server to store messages on kafka specific topics. ## Prerequisites The following are required to run the redis target connector: - kubemq cluster - kafka server - kubemq-targets deployment ## Configuration Kafka source connector configuration properties: | Properties Key | Required | Description | Example | |:-------------------|:---------|:------------------------------------------|:--------------------------------------------------------------| | brokers | yes | kafka brokers connection, comma separated | "localhost:9092" | | topic | yes | kafka stored topic | "TestTopic" | | sasl_username | no | SASL based authentication with broker | "user" | | sasl_password | no | SASL based authentication with broker | "<PASSWORD>" | | sasl_mechanism | no | SASL Mechanism | SCRAM-SHA-256, SCRAM-SHA-512, plain, 0Auth bearer, or GSS-API | | security_protocol | no | Set connection security protocol | plaintext, SASL-plaintext, SASL-SSL, SSL | | ca_cert | no | SSL CA certificate | pem certificate value | | client_certificate | no | SSL Client certificate (mMTL) | pem certificate value | | client_key | no | SSL Client Key (mTLS) | pem key value | | insecure | no | SSL Insecure (Self signed) | true / false | Example: ```yaml bindings: - name: kubemq-query-kafka source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-kafka-connector" auth_token: "" channel: "query.kafka" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: messaging.kafka name: kafka-stream properties: brokers: "localhost:9092" topic: "TestTopic" sasl_username: "test" sasl_password: "<PASSWORD>" ``` ## Usage ### Get Request Get request metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------------------------| | key | yes | kafka message key base64 | "a2V5" | | headers | no | kafka message headers Key Value base64 | `[{"Key": "ZG9n","Value": "bWV0YTE="}]` | Example: ```json { "metadata": { "key": "a2V5", "headers": [{"Key": "ZG9n","Value": "bWV0YTE="}] }, "data": null } ``` <file_sep>package firebase import ( "context" "encoding/json" "fmt" "testing" "time" "firebase.google.com/go/v4/messaging" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestMessageMetadata(t *testing.T) { m := &messaging.Message{ Topic: "test", Token: "1231231", } mb, err := json.Marshal(m) if err != nil { return } multi := &messaging.MulticastMessage{ Tokens: []string{"123", "456"}, Notification: &messaging.Notification{ Title: "title", }, Data: map[string]string{"key": "val"}, } multib, err := json.Marshal(multi) if err != nil { return } fmt.Print(string(multib)) tests := []struct { name string isMulti bool request *types.Request wantmsg messages wantErr bool }{ { name: "parse message", isMulti: false, request: types.NewRequest(). SetMetadataKeyValue("method", "send_message"). SetData(mb), wantmsg: messages{single: m}, wantErr: true, }, { name: "parse multicast msg", isMulti: true, request: types.NewRequest(). SetMetadataKeyValue("method", "SendBatch"). SetData(multib), wantmsg: messages{multicast: &messaging.MulticastMessage{ Tokens: []string{"123", "456"}, Notification: &messaging.Notification{ Title: "title", }, Data: map[string]string{"key": "val"}, }}, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.isMulti { m, err := parseMetadataMessages(tt.request.Data, options{ defaultMessaging: &messages{}, }, SendBatch) require.NoError(t, err) require.EqualValues(t, tt.wantmsg.multicast, m.multicast) } else { m, err := parseMetadataMessages(tt.request.Data, options{ defaultMessaging: &messages{}, }, SendMessage) require.NoError(t, err) require.EqualValues(t, tt.wantmsg.single, m.single) } }) } } func TestOptionsParse(t *testing.T) { m := messages{ single: &messaging.Message{ Topic: "newmsg", }, } mb, err := json.Marshal(m.single) if err != nil { return } ms := string(mb) tests := []struct { name string cfg config.Spec wantmsg *messages wantErr bool }{ { name: "parse options", cfg: config.Spec{ Name: "test", Kind: "test", Properties: map[string]string{ "project_id": "123", "credentials": "noc", "messaging_client": "true", "auth_client": "false", "db_client": "false", "defaultmsg": ms, }, }, wantmsg: &m, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { o, err := parseOptions(tt.cfg) require.NoError(t, err) require.EqualValues(t, tt.wantmsg, o.defaultMessaging) }) } } func TestDefaultMessage(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantmsg *messages wantErr bool }{ { name: "missing data on SendMessage", cfg: config.Spec{ Name: "test", Kind: "test", Properties: map[string]string{ "project_id": "123", "credentials": "noc", "messaging_client": "true", "auth_client": "false", "db_client": "false", "defaultmsg": `{"topic":"defult"}`, }, }, wantmsg: &messages{ single: &messaging.Message{ Topic: "defult", Data: map[string]string{"key1": "val1"}, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "send_message"), wantErr: true, }, { name: "combine default and SendMessage", cfg: config.Spec{ Name: "test", Kind: "test", Properties: map[string]string{ "project_id": "123", "credentials": "noc", "messaging_client": "true", "auth_client": "false", "db_client": "false", "defaultmsg": `{"topic":"defult"}`, }, }, wantmsg: &messages{ single: &messaging.Message{ Topic: "defult", Data: map[string]string{"key1": "val1"}, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "send_message").SetData([]byte(`{"Topic":"defult","data":{"key1":"val1"}}`)), wantErr: false, }, { name: "combine and replace defult SendMessage", cfg: config.Spec{ Name: "test", Kind: "test", Properties: map[string]string{ "project_id": "123", "credentials": "noc", "messaging_client": "true", "auth_client": "false", "db_client": "false", "defaultmsg": `{"Topic":"defult","token":"<PASSWORD>"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "send_message"). SetData([]byte(`{"Topic":"newTopic"}`)), wantmsg: &messages{ single: &messaging.Message{ Topic: "newTopic", Token: "<PASSWORD>", }, }, wantErr: false, }, { name: "replace defult SendMessage", cfg: config.Spec{ Name: "test", Kind: "test", Properties: map[string]string{ "project_id": "123", "credentials": "noc", "messaging_client": "true", "auth_client": "false", "db_client": "false", "defaultmsg": `{"Topic":"defult"}`, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "send_message"). SetData([]byte(`{"Topic":"newTopic"}`)), wantmsg: &messages{ single: &messaging.Message{ Topic: "newTopic", }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { o, err := parseOptions(tt.cfg) require.NoError(t, err) m, err := parseMetadataMessages(tt.request.Data, o, SendMessage) if tt.wantErr { require.Error(t, err) } else { require.NoError(t, err) require.EqualValues(t, tt.wantmsg, m) } // defult message not changed oc, _ := parseOptions(tt.cfg) require.EqualValues(t, oc.defaultMessaging, o.defaultMessaging) }) } } func TestClientDo(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "test do", cfg: config.Spec{ Kind: "test", Name: "test", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "messaging_client": "true", "auth_client": "false", "db_client": "false", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "send_message"). SetData([]byte(`{"Topic":"test"}`)), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c := New() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute) defer cancel() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) _, err = c.Do(ctx, tt.request) if err != nil { t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) } require.NoError(t, err) }) } } <file_sep>package metrics import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultNameSpace = "" ) type metadata struct { method string namespace string } var methodsMap = map[string]string{ "put_metrics": "put_metrics", "list_metrics": "list_metrics", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "put_metrics" { m.namespace, err = meta.MustParseString("namespace") if err != nil { return metadata{}, fmt.Errorf("namespace is required for method %s ,error parsing namespace, %w", m.method, err) } } else if m.method == "list_metrics" { m.namespace = meta.ParseString("namespace", defaultNameSpace) } return m, nil } <file_sep>package events_store import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("kubemq.events-store"). SetDescription("Kubemq Events-Store Source"). SetName("KubeMQ Events Store"). SetProvider(""). SetCategory("Pub/Sub"). AddProperty( common.NewProperty(). SetKind("string"). SetName("address"). SetTitle("KubeMQ gRPC Service Address"). SetDescription("Set Kubemq grpc endpoint address"). SetMust(true). SetDefault("kubemq-cluster-grpc.kubemq:50000"). SetLoadedOptions("kubemq-address"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("channel"). SetDescription("Set Events-Store channel"). SetMust(true). SetDefaultFromKey("channel.events-store"), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("do_not_parse_payload"). SetTitle("Don't Parse Payload"). SetDescription("Allow payload pass-through"). SetMust(false). SetDefault("false"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("group"). SetDescription("Set Events-Store channel group"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("sources"). SetTitle("Concurrent Connections"). SetDescription("Set how many concurrent events sources to run"). SetMust(false). SetDefault("1"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("response_channel"). SetTitle("Response Channel"). SetDescription("Set Events-Store response channel"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("client_id"). SetTitle("Client ID"). SetDescription("Set Events-Store connection client Id"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("auth_token"). SetTitle("Authentication Token"). SetDescription("Set Events-Store connection authentication token"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("auto_reconnect"). SetTitle("Reconnect Automatically"). SetDescription("Set auto reconnection "). SetMust(false). SetDefault("true"), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("reconnect_interval_seconds"). SetTitle("Reconnection Interval (Seconds)"). SetDescription("Set auto reconnection interval in seconds "). SetMust(false). SetDefault("0"), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_reconnects"). SetTitle("Max Reconnections"). SetDescription("Set auto reconnection max reconnects"). SetMust(false). SetDefault("0"), ) } <file_sep>package sqs import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) const ( DefaultRetries = 0 DefaultDelay = 10 DefaultMaxReceive = 0 DefaultToken = "" DefaultDeadLetter = "" ) type options struct { sqsKey string sqsSecretKey string retries int region string maxReceiveCount int deadLetterQueue string token string defaultDelay int defaultQueue string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.sqsKey, err = cfg.Properties.MustParseString("aws_key") if err != nil { return options{}, fmt.Errorf("error sqsKey , %w", err) } o.sqsSecretKey, err = cfg.Properties.MustParseString("aws_secret_key") if err != nil { return options{}, fmt.Errorf("error sqsSecretKey , %w", err) } o.retries = cfg.Properties.ParseInt("retries", DefaultRetries) o.region, err = cfg.Properties.MustParseString("region") if err != nil { return options{}, fmt.Errorf("error parsing region , %w", err) } o.defaultDelay = cfg.Properties.ParseInt("default_delay", DefaultDelay) o.maxReceiveCount = cfg.Properties.ParseInt("max_receive", DefaultMaxReceive) o.deadLetterQueue = cfg.Properties.ParseString("dead_letter", DefaultDeadLetter) o.token = cfg.Properties.ParseString("token", DefaultToken) o.defaultQueue = cfg.Properties.ParseString("default_queue", "") return o, nil } func (o options) defaultMetadata() (metadata, bool) { if o.defaultQueue != "" { return metadata{ delay: o.defaultDelay, tags: nil, queueURL: o.defaultQueue, }, true } return metadata{}, false } <file_sep>package lambda import ( "context" "encoding/json" "errors" "fmt" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/lambda" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *lambda.Lambda } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := lambda.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "list": return c.list(ctx) case "create": return c.create(ctx, meta, req.Data) case "run": return c.run(ctx, meta, req.Data) case "delete": return c.delete(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) list(ctx context.Context) (*types.Response, error) { m, err := c.client.ListFunctionsWithContext(ctx, nil) if err != nil { return nil, err } b, err := json.Marshal(m) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) create(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if data == nil { return nil, fmt.Errorf("data is empty , please add lambda body as []byte") } input := &lambda.CreateFunctionInput{ Code: &lambda.FunctionCode{ ZipFile: data, }, Description: aws.String(meta.description), FunctionName: aws.String(meta.functionName), Handler: aws.String(meta.handlerName), MemorySize: aws.Int64(meta.memorySize), Role: aws.String(meta.role), Runtime: aws.String(meta.runtime), Timeout: aws.Int64(meta.timeout), } result, err := c.client.CreateFunctionWithContext(ctx, input) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) run(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { if isValid := isJson(data); !isValid { return nil, fmt.Errorf("function payload must be a valid json") } invoke := &lambda.InvokeInput{} invoke.SetFunctionName(meta.functionName).SetPayload(data) if meta.isDryRun { invoke.SetInvocationType("DryRun") } result, err := c.client.InvokeWithContext(ctx, invoke) if err != nil { return nil, err } b, err := json.Marshal(result) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) delete(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.client.DeleteFunctionWithContext(ctx, &lambda.DeleteFunctionInput{FunctionName: aws.String(meta.functionName)}) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func isJson(data []byte) bool { if len(data) == 0 { return true } obj := map[string]interface{}{} err := json.Unmarshal(data, &obj) return err == nil } func (c *Client) Stop() error { return nil } <file_sep># Kubemq MQTT Target Connector Kubemq mqtt target connector allows services using kubemq server to access mqtt messaging services. ## Prerequisites The following are required to run the mqtt target connector: - kubemq cluster - mqtt server - kubemq-targets deployment ## Configuration MQTT target connector configuration properties: | Properties Key | Required | Description | Example | |:--------------------------------|:---------|:--------------------------------------------|:-----------------------------------------------------------------------| | host | yes | mqtt connection host | "localhost:1883" | | username | no | set mqtt username | "username" | | password | no | set mqtt password | "<PASSWORD>" | | client_id | no | mqtt connection string address | "client_id" | | default_topic | no | set MQTT default topic | "topic" | | default_qos | no | set MQTT default qos | 0 | Example: ```yaml bindings: - name: kubemq-query-mqtt source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-mqtt-connector" auth_token: "" channel: "query.mqtt" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: messaging.mqtt name: target-mqtt properties: host: "localhost:1883" username: "username" password: "<PASSWORD>" client_id: "client_id" default_topic: "topic" default_qos: 0 ``` ## Usage ### Request Request metadata setting: | Metadata Key | Required | Description | Possible values | |:---------------|:---------|:--------------------|:----------------| | topic | yes | set topic name | "topic" | | qos | yes | set qos level | "0","1","2" | Query request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:-------------|:-------------------| | data | yes | data to publish | base64 bytes array | Example: ```json { "metadata": { "topic": "topic", "qos": "0" }, "data": "U0VMRUNUIGlkLHRpdGxlLGNvbnRlbnQgRlJPTSBwb3N0Ow==" } ``` <file_sep>package blob import ( "fmt" "github.com/Azure/azure-storage-blob-go/azblob" "github.com/kubemq-io/kubemq-targets/types" ) const ( DeleteSnapshotsOptionInclude = "include" DeleteSnapshotsOptionNone = "" DeleteSnapshotsOptionOnly = "only" DefaultRetryRequests = 1 DefaultBlockSize = 4194304 DefaultParallelism = 16 DefaultCount = 0 DefaultOffset = 0 ) var methodsMap = map[string]string{ "upload": "upload", "get": "get", "delete": "delete", } var deleteSnapShotTypes = map[string]string{ "include": "include", "only": "only", "": "", } type metadata struct { method string fileName string serviceUrl string blockSize int64 parallelism uint16 offset int64 count int64 deleteSnapshotsOptionType azblob.DeleteSnapshotsOptionType maxRetryRequests int blobMetadata map[string]string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method == "delete" { deleteSnapshotsOptionType, err := meta.ParseStringMap("delete_snapshots_option_type", deleteSnapShotTypes) if err != nil { return metadata{}, meta.GetValidSupportedTypes(deleteSnapShotTypes, "delete_snapshots_option_type") } switch deleteSnapshotsOptionType { case DeleteSnapshotsOptionInclude: m.deleteSnapshotsOptionType = azblob.DeleteSnapshotsOptionInclude case DeleteSnapshotsOptionOnly: m.deleteSnapshotsOptionType = azblob.DeleteSnapshotsOptionOnly case DeleteSnapshotsOptionNone: m.deleteSnapshotsOptionType = azblob.DeleteSnapshotsOptionNone } } m.fileName, err = meta.MustParseString("file_name") if err != nil { return metadata{}, fmt.Errorf("error parsing file_name , %w", err) } m.serviceUrl, err = meta.MustParseString("service_url") if err != nil { return metadata{}, fmt.Errorf("error parsing service_url , %w", err) } blobMetadata, err := meta.MustParseJsonMap("blob_metadata") if err != nil { return metadata{}, fmt.Errorf("error parsing blob_metadata, %w", err) } else { m.blobMetadata = blobMetadata } m.blockSize = int64(meta.ParseInt("block_size", DefaultBlockSize)) m.parallelism = uint16(meta.ParseInt("parallelism", DefaultParallelism)) m.count = int64(meta.ParseInt("count", DefaultCount)) m.offset = int64(meta.ParseInt("offset", DefaultOffset)) m.maxRetryRequests = meta.ParseInt("max_retry_request", DefaultRetryRequests) return m, nil } <file_sep>package mqtt import ( "context" "fmt" "time" mqtt "github.com/eclipse/paho.mqtt.golang" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultConnectTimeout = 5 * time.Second ) type Client struct { log *logger.Logger opts options client mqtt.Client } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } opts := mqtt.NewClientOptions() opts.AddBroker(fmt.Sprintf("tcp://%s", c.opts.host)) opts.SetUsername(c.opts.username) opts.SetPassword(c.opts.password) opts.SetClientID(c.opts.clientId) opts.SetConnectTimeout(defaultConnectTimeout) c.client = mqtt.NewClient(opts) if token := c.client.Connect(); token.Wait() && token.Error() != nil { return fmt.Errorf("error connecting to mqtt broker, %w", token.Error()) } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, ok := c.opts.defaultMetadata() if !ok { var err error meta, err = parseMetadata(req.Metadata) if err != nil { return nil, err } } token := c.client.Publish(meta.topic, byte(meta.qos), false, req.Data) token.Wait() if token.Error() != nil { return nil, token.Error() } return types.NewResponse().SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.client != nil { c.client.Disconnect(0) } return nil } <file_sep>package sns import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultEndPoint = "" DefaultPhoneNumber = "" DefaultSubject = "" ) type metadata struct { method string topic string endPoint string protocol string returnSubscription bool message string phoneNumber string subject string targetArn string } var methodsMap = map[string]string{ "list_topics": "list_topics", "list_subscriptions": "list_subscriptions", "list_subscriptions_by_topic": "list_subscriptions_by_topic", "create_topic": "create_topic", "subscribe": "subscribe", "send_message": "send_message", "delete_topic": "delete_topic", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } if m.method != "list_topics" && m.method != "list_subscriptions" && m.method != "send_message" { m.topic, err = meta.MustParseString("topic") if err != nil { return metadata{}, fmt.Errorf("error parsing topic, %w", err) } if m.method == "subscribe" { m.endPoint = meta.ParseString("end_point", DefaultEndPoint) if err != nil { return metadata{}, fmt.Errorf("error parsing end_point, %w", err) } m.protocol, err = meta.MustParseString("protocol") if err != nil { return metadata{}, fmt.Errorf("error parsing protocol, %w", err) } m.returnSubscription, err = meta.MustParseBool("return_subscription") if err != nil { return metadata{}, fmt.Errorf("error parsing return_subscription, %w", err) } } } else if m.method == "send_message" { m.targetArn, err = meta.MustParseString("target_arn") if err != nil { m.topic, err = meta.MustParseString("topic") if err != nil { return metadata{}, fmt.Errorf("error parsing topic or target_arn , one of them must be set , %w", err) } } else { m.topic, err = meta.MustNotParseString("topic", "target_arn") if err == nil { return metadata{}, err } } m.message, err = meta.MustParseString("message") if err != nil { return metadata{}, fmt.Errorf("error parsing message, %w", err) } m.phoneNumber = meta.ParseString("phone_number", DefaultPhoneNumber) m.subject = meta.ParseString("subject", DefaultSubject) } return m, nil } <file_sep>package dynamodb import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.dynamodb"). SetDescription("AWS Dynamodb Target"). SetName("DynamoDB"). SetProvider("AWS"). SetCategory("Store"). SetTags("db", "no-sql", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Dynamodb aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Dynamodb aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Dynamodb aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Dynamodb aws token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Dynamodb execution method"). SetOptions([]string{"list_tables", "create_table", "delete_table", "insert_item", "get_item", "delete_item", "update_item"}). SetDefault("insert_item"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("table_name"). SetKind("string"). SetDescription("Set Dynamodb table name"). SetDefault(""). SetMust(false), ) } <file_sep>package activemq import ( "context" "fmt" "github.com/go-stomp/stomp" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options conn *stomp.Conn } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } var options []func(*stomp.Conn) error = []func(*stomp.Conn) error{ stomp.ConnOpt.Login(c.opts.username, c.opts.password), stomp.ConnOpt.Host("/"), } c.conn, err = stomp.Dial("tcp", c.opts.host, options...) if err != nil { return fmt.Errorf("error connecting to activemq broker, %w", err) } return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, ok := c.opts.defaultMetadata() if !ok { var err error meta, err = parseMetadata(req.Metadata) if err != nil { return nil, err } } err := c.conn.Send(meta.destination, "text/plain", req.Data) if err != nil { return nil, err } return types.NewResponse().SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.conn != nil { return c.conn.Disconnect() } return nil } <file_sep>package binding import ( "context" "fmt" "net/http" "sync" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/pkg/metrics" "github.com/kubemq-io/kubemq-targets/types" ) const ( addRetryInterval = 1 * time.Second ) type Service struct { bindings sync.Map log *logger.Logger exporter *metrics.Exporter currentCtx context.Context currentCancelFunc context.CancelFunc bindingStatus sync.Map cfg *config.Config } func New() (*Service, error) { s := &Service{ bindings: sync.Map{}, log: logger.NewLogger("binding-service"), bindingStatus: sync.Map{}, } var err error s.exporter, err = metrics.NewExporter() if err != nil { return nil, fmt.Errorf("failed to to initialized metrics exporter, %w", err) } return s, nil } func (s *Service) Start(ctx context.Context, cfg *config.Config) error { s.currentCtx, s.currentCancelFunc = context.WithCancel(ctx) s.cfg = cfg if len(cfg.Bindings) == 0 { return nil } for _, bindingCfg := range cfg.Bindings { go func(ctx context.Context, cfg config.BindingConfig) { err := s.Add(ctx, cfg) if err == nil { return } else { s.log.Errorf("failed to initialized binding, %s", err.Error()) } count := 0 for { select { case <-time.After(addRetryInterval): count++ err := s.Add(ctx, cfg) if err != nil { s.log.Errorf("failed to initialized binding: %s, attempt: %d, error: %s", cfg.Name, count, err.Error()) } else { return } case <-ctx.Done(): return } } }(s.currentCtx, bindingCfg) } return nil } func (s *Service) Stop() { s.currentCancelFunc() s.bindings.Range(func(key, value interface{}) bool { binder := value.(*Binder) err := s.Remove(binder.name) if err != nil { s.log.Error(err) } return true }) } func (s *Service) Add(ctx context.Context, cfg config.BindingConfig) error { binder := NewBinder() status := newStatus(cfg) s.bindingStatus.Store(cfg.Name, status) err := binder.Init(ctx, cfg, s.exporter) if err != nil { return err } err = binder.Start(ctx) if err != nil { return err } s.bindings.Store(cfg.Name, binder) status.Ready = true s.bindingStatus.Store(cfg.Name, status) return nil } func (s *Service) Remove(name string) error { val, ok := s.bindings.Load(name) if !ok { return fmt.Errorf("binding %s not found", name) } binder := val.(*Binder) err := binder.Stop() if err != nil { return err } s.bindings.Delete(name) s.bindingStatus.Delete(name) return nil } func (s *Service) PrometheusHandler() http.Handler { return s.exporter.PrometheusHandler() } func (s *Service) Stats() []*metrics.Report { return s.exporter.Store.List() } func (s *Service) GetStatus() []*Status { var list []*Status for _, binding := range s.cfg.Bindings { val, ok := s.bindingStatus.Load(binding.Name) if ok { list = append(list, val.(*Status)) } } return list } func (s *Service) SendRequest(ctx context.Context, req *Request) *Response { val, ok := s.bindings.Load(req.Binding) if !ok { return toResponse(types.NewResponse().SetError(fmt.Errorf("no such binding, %s", req.Binding))) } r, err := types.ParseRequest(req.Payload) if err != nil { return toResponse(types.NewResponse().SetError(fmt.Errorf("error during parsing request: %s", err.Error()))) } binder := val.(*Binder) resp, err := binder.md.Do(ctx, r) if err != nil { return toResponse(types.NewResponse().SetError(fmt.Errorf("error during executing request: %s", err.Error()))) } return toResponse(resp) } <file_sep>package middleware import ( "fmt" "math" "time" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/pkg/retry" "github.com/kubemq-io/kubemq-targets/types" ) var delayTypeMap = map[string]string{ "back-off": "back-off", "fixed": "fixed", "random": "random", "": "", } type RetryMiddleware struct { opts []retry.Option } func parseRetryOptions(meta types.Metadata) ([]retry.Option, error) { var opts []retry.Option attempts, err := meta.ParseIntWithRange("retry_attempts", 1, 1, math.MaxInt32) if err != nil { return nil, fmt.Errorf("invalid retry attempts value") } opts = append(opts, retry.Attempts(uint(attempts))) delayMilliseconds, err := meta.ParseIntWithRange("retry_delay_milliseconds", 100, 0, math.MaxInt32) if err != nil { return nil, fmt.Errorf("invalid retry delay millisecond svalue") } opts = append(opts, retry.MaxDelay(time.Duration(delayMilliseconds)*time.Millisecond)) maxJitterMilliseconds, err := meta.ParseIntWithRange("retry_max_jitter_milliseconds", 100, 1, math.MaxInt32) if err != nil { return nil, fmt.Errorf("invalid retry delay jitter millisecond value") } opts = append(opts, retry.MaxJitter(time.Duration(maxJitterMilliseconds)*time.Millisecond)) delayType, err := meta.ParseStringMap("retry_delay_type", delayTypeMap) if err != nil { return nil, fmt.Errorf("invalid retry delay type value") } switch delayType { case "back-off", "": opts = append(opts, retry.DelayType(retry.BackOffDelay)) case "fixed": opts = append(opts, retry.DelayType(retry.FixedDelay)) case "random": opts = append(opts, retry.DelayType(retry.RandomDelay)) } return opts, nil } func NewRetryMiddleware(meta types.Metadata, log *logger.Logger) (*RetryMiddleware, error) { opts, err := parseRetryOptions(meta) if err != nil { return nil, fmt.Errorf("error parsing retry options, %w", err) } if log != nil { opts = append(opts, retry.OnRetry(func(n uint, err error) { log.Errorf("retry %d failed, error: %s", n, err.Error()) })) } return &RetryMiddleware{ opts: opts, }, nil } <file_sep># Kubemq AmazonMQ Target Connector Kubemq AmazonMQ target connector allows services using kubemq server to access AmazonMQ messaging services. ## Prerequisites The following are required to run the AmazonMQ target connector: - kubemq cluster - AmazonMQ server - with access - kubemq-targets deployment - Please note the connector uses connection with stomp+ssl, when finishing handling messages need to call Close(). ## Configuration AmazonMQ target connector configuration properties: | Properties Key | Required | Description | Example | |:--------------------------------|:---------|:---------------------------------------------|:-----------------------------------------------------------------------| | host | yes | AmazonMQ connection host (stomp+ssl endpoint)| "localhost:1883" | | username | no | set AmazonMQ username | "username" | | password | no | set AmazonMQ password | "<PASSWORD>" | | default_destination | no | set AmazonMQ default destination | "q1" | Example: ```yaml bindings: - name: kubemq-query-amazonmq source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-amazonmq-connector" auth_token: "" channel: "query.amazonmq" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.amazonmq name: aws-amazonmq properties: host: "localhost:61613" username: "admin" password: "<PASSWORD>" default_destination: "" ``` ## Usage ### Request Request metadata setting: | Metadata Key | Required | Description | Possible values | |:---------------|:---------|:--------------------|:----------------| | destination | yes | set destination name| "destination" | Query request data setting: | Data Key | Required | Description | Possible values | |:---------|:---------|:-------------|:-------------------| | data | yes | data to publish | base64 bytes array | Example: ```json { "metadata": { "destination": "destination" }, "data": "<KEY> } ``` <file_sep>package main import ( "context" "encoding/json" "fmt" "log" "strconv" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) const mapping = `{ "settings": { "number_of_shards": 1, "number_of_replicas": 0 }, "mappings": { "properties": { "id": { "type": "keyword" }, "data": { "type": "text" } } } }` type logRecord struct { Id string `json:"id"` Data string `json:"data"` } func (l *logRecord) marshal() []byte { b, _ := json.Marshal(l) return b } func newLog(id, data string) *logRecord { return &logRecord{ Id: id, Data: data, } } func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } existRequest := types.NewRequest(). SetMetadataKeyValue("method", "index.exists"). SetMetadataKeyValue("index", "log") queryExistResponse, err := client.SetQuery(existRequest.ToQuery()). SetChannel("query.elastic"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } existResponse, err := types.ParseResponse(queryExistResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("check if log index exist executed, response: %s", existResponse.Metadata.String())) exist, err := strconv.ParseBool(existResponse.Metadata["exists"]) if err != nil { log.Fatal(err) } if exist { deleteIndexRequest := types.NewRequest(). SetMetadataKeyValue("method", "index.delete"). SetMetadataKeyValue("index", "log") queryDeleteIndexResponse, err := client.SetQuery(deleteIndexRequest.ToQuery()). SetChannel("query.elastic"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } deleteIndexResponse, err := types.ParseResponse(queryDeleteIndexResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("delete log index executed, response: %s", deleteIndexResponse.Metadata.String())) } createIndexRequest := types.NewRequest(). SetMetadataKeyValue("method", "index.create"). SetMetadataKeyValue("index", "log"). SetData([]byte(mapping)) queryCreateIndexResponse, err := client.SetQuery(createIndexRequest.ToQuery()). SetChannel("query.elastic"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } createIndexResponse, err := types.ParseResponse(queryCreateIndexResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("create log index executed, response: %s", createIndexResponse.Metadata.String())) randomKey := uuid.New().String() // set request setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("id", randomKey). SetMetadataKeyValue("index", "log"). SetData(newLog("some-id", "some-data").marshal()) querySetResponse, err := client.SetQuery(setRequest.ToQuery()). SetChannel("query.elastic"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } setResponse, err := types.ParseResponse(querySetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("set request for key: %s executed, response: %s", randomKey, setResponse.Metadata.String())) // get request getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("index", "log"). SetMetadataKeyValue("id", randomKey) queryGetResponse, err := client.SetQuery(getRequest.ToQuery()). SetChannel("query.elastic"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(queryGetResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get request for key: %s executed, response: %s, data: %s", randomKey, getResponse.Metadata.String(), string(getResponse.Data))) // delete request delRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("index", "log"). SetMetadataKeyValue("id", randomKey) queryDelResponse, err := client.SetQuery(delRequest.ToQuery()). SetChannel("query.elastic"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } delResponse, err := types.ParseResponse(queryDelResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("delete request for key: %s executed, response: %s", randomKey, delResponse.Metadata.String())) } <file_sep>package keyspaces import ( "context" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { username string password string endPoint string tlsPath string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/keyspaces/username.txt") if err != nil { return nil, err } t.username = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/keyspaces/password.txt") if err != nil { return nil, err } t.password = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/keyspaces/endPoint.txt") if err != nil { return nil, err } t.endPoint = string(dat) t.tlsPath = "https://www.amazontrust.com/repository/AmazonRootCA1.pem" return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, wantErr: false, }, { name: "invalid init - bad hosts", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": "", "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, wantErr: true, }, { name: "invalid init - bad port", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "-1", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, wantErr: true, }, { name: "invalid init - pad proto version", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "-1", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, wantErr: true, }, { name: "invalid init - bad replication factor", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "-1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, wantErr: true, }, { name: "invalid init - bad consistency", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "bad-value", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantExecErr %v", err, tt.wantErr) return } }) } } func TestClient_Set_Get(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec setRequest *types.Request getRequest *types.Request wantSetResponse *types.Response wantGetResponse *types.Response wantSetErr bool wantGetErr bool }{ { name: "valid set get request", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("consistency", "LocalQuorum"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("result", "ok"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-id"). SetData([]byte("some-data")), wantSetErr: false, wantGetErr: false, }, { name: "update set get request", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data-2")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("consistency", "LocalQuorum"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("result", "ok"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-id"). SetData([]byte("some-data-2")), wantSetErr: false, wantGetErr: false, }, { name: "invalid set", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetMetadataKeyValue("table", "bad-table"). SetMetadataKeyValue("keyspace", "bad-keyspace"). SetData([]byte("some-data")), getRequest: nil, wantSetResponse: nil, wantGetResponse: nil, wantSetErr: true, wantGetErr: false, }, { name: "valid set - bad get table", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("table", "bad-table"). SetMetadataKeyValue("keyspace", "bad-keyspace"). SetMetadataKeyValue("consistency", "LocalQuorum"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("result", "ok"), wantGetResponse: nil, wantSetErr: false, wantGetErr: true, }, { name: "valid set - empty result", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data")), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", "not-exist-key"). SetMetadataKeyValue("consistency", "LocalQuorum"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("key", "some-id"). SetMetadataKeyValue("result", "ok"), wantGetResponse: nil, wantSetErr: false, wantGetErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.setRequest) if tt.wantSetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantSetResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.getRequest) if tt.wantGetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantGetResponse, gotGetResponse) }) } } func TestClient_Query_Exec(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec execRequest *types.Request queryRequest *types.Request wantExecResponse *types.Response wantQueryResponse *types.Response wantExecErr bool wantQueryErr bool }{ { name: "valid exec query request", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte(`INSERT INTO test.test (key, value) VALUES (textAsBlob('some-key'), textAsBlob('some-data'));`)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte(`SELECT value FROM test.test WHERE key = textAsBlob('some-key')`)), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData([]byte("some-data")), wantExecErr: false, wantQueryErr: false, }, { name: "invalid exec request - empty", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData(nil), queryRequest: nil, wantExecResponse: nil, wantQueryResponse: nil, wantExecErr: true, wantQueryErr: false, }, { name: "invalid exec request", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some bad exec query")), queryRequest: nil, wantExecResponse: nil, wantQueryResponse: nil, wantExecErr: true, wantQueryErr: false, }, { name: "invalid query request - empty", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte(`INSERT INTO test.test (key, value) VALUES (textAsBlob('some-key'),textAsBlob('some-data'))`)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData(nil), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: nil, wantExecErr: false, wantQueryErr: true, }, { name: "invalid query request - empty", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte(`INSERT INTO test.test (key, value) VALUES (textAsBlob('some-key'),textAsBlob('some-data'))`)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some bad query")), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: nil, wantExecErr: false, wantQueryErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.execRequest) if tt.wantExecErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantExecResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantQueryErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantQueryResponse, gotGetResponse) }) } } func TestClient_Delete(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err = c.Init(ctx, config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": dat.password, "proto_version": "4", "replication_factor": "1", "consistency": "LocalQuorum", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, nil) key := uuid.New().String() require.NoError(t, err) setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", key). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data")) _, err = c.Do(ctx, setRequest) require.NoError(t, err) getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("key", key). SetMetadataKeyValue("consistency", "LocalQuorum") gotGetResponse, err := c.Do(ctx, getRequest) require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, []byte("some-data"), gotGetResponse.Data) delRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetMetadataKeyValue("key", key) _, err = c.Do(ctx, delRequest) require.NoError(t, err) gotGetResponse, err = c.Do(ctx, getRequest) require.Error(t, err) require.Nil(t, gotGetResponse) delRequest = types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("consistency", ""). SetMetadataKeyValue("table", "bad-table"). SetMetadataKeyValue("keyspace", "bad-keyspace"). SetMetadataKeyValue("key", key) _, err = c.Do(ctx, delRequest) require.Error(t, err) } func TestClient_Do(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid request", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", uuid.New().String()). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data")), wantErr: false, }, { name: "invalid request - bad method", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "bad-method"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data")), wantErr: true, }, { name: "invalid request - no key", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("consistency", "LocalQuorum"). SetData([]byte("some-data")), wantErr: true, }, { name: "invalid request - bad consistency key", cfg: config.Spec{ Name: "aws-elasticsearch", Kind: "aws.keyspaces", Properties: map[string]string{ "hosts": dat.endPoint, "port": "9142", "username": dat.username, "password": <PASSWORD>, "proto_version": "4", "replication_factor": "1", "consistency": "LocalOne", "default_table": "test", "default_keyspace": "test", "tls": dat.tlsPath, }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("key", "some-key"). SetMetadataKeyValue("consistency", "not-valid"). SetData([]byte("some-data")), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) _, err = c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } <file_sep>package firestore import ( "context" "encoding/json" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) func TestClient_Init(t *testing.T) { dat, err := ioutil.ReadFile("./../../../credentials/projectID.txt") require.NoError(t, err) projectID := string(dat) require.NoError(t, err) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") require.NoError(t, err) credentials := string(dat) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "gcp-firestore", Kind: "gcp.firestore", Properties: map[string]string{ "project_id": projectID, "credentials": credentials, }, }, wantErr: false, }, { name: "invalid init-missing-credentials", cfg: config.Spec{ Name: "gcp-firestore", Kind: "gcp.firestore", Properties: map[string]string{ "project_id": projectID, }, }, wantErr: true, }, { name: "invalid init-missing-project-id", cfg: config.Spec{ Name: "gcp-firestore", Kind: "", Properties: map[string]string{}, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 1000*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_Set_Get(t *testing.T) { dat, err := ioutil.ReadFile("./../../../credentials/projectID.txt") require.NoError(t, err) projectID := string(dat) require.NoError(t, err) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") require.NoError(t, err) credentials := string(dat) user := map[string]interface{}{ "first": "kubemq", "last": "kubemq-last", "id": 123, } bUser, err := json.Marshal(user) require.NoError(t, err) dat, err = ioutil.ReadFile("./../../../credentials/objKey.txt") require.NoError(t, err) objKey := string(dat) tests := []struct { name string cfg config.Spec setRequest *types.Request getRequest *types.Request getAllRequest *types.Request wantSetResponse *types.Response wantGetResponse *types.Response }{ { name: "valid set get request", cfg: config.Spec{ Name: "gcp-firestore", Kind: "gcp.firestore", Properties: map[string]string{ "project_id": projectID, "credentials": credentials, }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "add"). SetMetadataKeyValue("collection", "myCollection"). SetData(bUser), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "document_key"). SetMetadataKeyValue("item", objKey). SetMetadataKeyValue("collection", "myCollection"), getAllRequest: types.NewRequest(). SetMetadataKeyValue("method", "documents_all"). SetMetadataKeyValue("collection", "myCollection"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("collection", "myCollection"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("collection", "myCollection"). SetMetadataKeyValue("item", objKey). SetData(bUser), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.setRequest) require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantSetResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.getRequest) require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantGetResponse, gotGetResponse) gotGetAllResponse, err := c.Do(ctx, tt.getAllRequest) require.NoError(t, err) require.NotNil(t, gotGetResponse) require.Equal(t, gotGetAllResponse.Error, "") }) } } func TestClient_Delete(t *testing.T) { dat, err := ioutil.ReadFile("./../../../credentials/projectID.txt") require.NoError(t, err) projectID := string(dat) require.NoError(t, err) dat, err = ioutil.ReadFile("./../../../credentials/deleteKey.txt") require.NoError(t, err) deleteKey := string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") require.NoError(t, err) credentials := string(dat) tests := []struct { name string cfg config.Spec deleteRequest *types.Request wantDeleteRequest *types.Response wantErr bool }{ { name: "valid delete request", cfg: config.Spec{ Name: "gcp-firestore", Kind: "gcp.firestore", Properties: map[string]string{ "project_id": projectID, "credentials": credentials, }, }, deleteRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_document_key"). SetMetadataKeyValue("item", deleteKey). SetMetadataKeyValue("collection", "myCollection"), wantDeleteRequest: types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("item", deleteKey). SetMetadataKeyValue("collection", "myCollection"), wantErr: false, }, { name: "invalid delete request - missing item", cfg: config.Spec{ Name: "gcp-firestore", Kind: "gcp.firestore", Properties: map[string]string{ "project_id": projectID, "credentials": credentials, }, }, deleteRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_document_key"). SetMetadataKeyValue("collection", "myCollection"), wantDeleteRequest: types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetMetadataKeyValue("error", "false"). SetMetadataKeyValue("item", "fake-key"). SetMetadataKeyValue("collection", "myCollection"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) deleteResponse, err := c.Do(ctx, tt.deleteRequest) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, deleteResponse) require.EqualValues(t, tt.wantDeleteRequest, deleteResponse) }) } } func TestClient_list(t *testing.T) { dat, err := ioutil.ReadFile("./../../../credentials/projectID.txt") require.NoError(t, err) projectID := string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") require.NoError(t, err) credentials := string(dat) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "valid google-firestore-list", cfg: config.Spec{ Name: "google.firestore", Kind: "google.firestore", Properties: map[string]string{ "project_id": projectID, "credentials": credentials, }, }, wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) got, err := c.list(ctx) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.EqualValues(t, "ok", got.Metadata["result"]) require.NotNil(t, got) }) } } <file_sep>package metrics import ( "context" "encoding/json" "errors" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/cloudwatch" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) type Client struct { log *logger.Logger opts options client *cloudwatch.CloudWatch } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } sess, err := session.NewSession(&aws.Config{ Region: aws.String(c.opts.region), Credentials: credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token), }) if err != nil { return err } svc := cloudwatch.New(sess) c.client = svc return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "put_metrics": return c.putMetrics(ctx, meta, req.Data) case "list_metrics": return c.listMetrics(ctx, meta) default: return nil, errors.New("invalid method type") } } func (c *Client) putMetrics(ctx context.Context, meta metadata, data []byte) (*types.Response, error) { var metrics []*cloudwatch.MetricDatum err := json.Unmarshal(data, &metrics) if err != nil { return nil, err } _, err = c.client.PutMetricDataWithContext(ctx, &cloudwatch.PutMetricDataInput{ Namespace: aws.String(meta.namespace), MetricData: metrics, }) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) listMetrics(ctx context.Context, meta metadata) (*types.Response, error) { var resp *cloudwatch.ListMetricsOutput var err error if meta.namespace != "" { resp, err = c.client.ListMetricsWithContext(ctx, &cloudwatch.ListMetricsInput{ Namespace: aws.String(meta.namespace), }) } else { resp, err = c.client.ListMetricsWithContext(ctx, &cloudwatch.ListMetricsInput{}) } if err != nil { return nil, err } b, err := json.Marshal(resp) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>package middleware import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/metrics" ) type MetricsMiddleware struct { exporter *metrics.Exporter metricReport *metrics.Report } func NewMetricsMiddleware(cfg config.BindingConfig, exporter *metrics.Exporter) (*MetricsMiddleware, error) { if exporter == nil { return nil, fmt.Errorf("no valid exporter found") } m := &MetricsMiddleware{ exporter: exporter, metricReport: &metrics.Report{ Key: fmt.Sprintf("%s-%s-%s", cfg.Name, cfg.Source.Kind, cfg.Target.Kind), Binding: cfg.Name, SourceKind: cfg.Source.Kind, TargetKind: cfg.Target.Kind, RequestCount: 0, RequestVolume: 0, ResponseCount: 0, ResponseVolume: 0, ErrorsCount: 0, }, } return m, nil } func (m *MetricsMiddleware) clearReport() { m.metricReport.ErrorsCount = 0 m.metricReport.ResponseVolume = 0 m.metricReport.ResponseCount = 0 m.metricReport.RequestVolume = 0 m.metricReport.RequestCount = 0 } <file_sep>package minio import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("storage.minio"). SetDescription("Minio Storage Target"). SetName("Minio"). SetProvider(""). SetCategory("Storage"). SetTags("s3"). AddProperty( common.NewProperty(). SetKind("string"). SetName("endpoint"). SetTitle("Endpoint"). SetDescription("Set Minio endpoint address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("bool"). SetName("use_ssl"). SetTitle("USE SSL"). SetDescription("Set Minio SSL connection"). SetMust(false). SetDefault("true"), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("access_key_id"). SetTitle("Access Key ID"). SetDescription("Set Minio access key id"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("secret_access_key"). SetTitle("Access Key Secret"). SetDescription("Set Minio secret access key"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Minio method"). SetOptions([]string{"make_bucket", "list_buckets", "bucket_exists", "remove_bucket", "list_objects", "put", "get", "remove"}). SetDefault("make_bucket"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("param1"). SetKind("string"). SetDescription("Set Minio bucket name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("param2"). SetKind("string"). SetDescription("Set Minio object name"). SetDefault(""). SetMust(false), ) } <file_sep>package metrics import "github.com/kubemq-hub/builder/connector/common" func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.cloudwatch.metrics"). SetDescription("AWS Cloudwatch Metrics Target"). SetName("Cloudwatch Metrics"). SetProvider("AWS"). SetCategory("Observability"). SetTags("metrics", "cloud"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Cloudwatch-Metrics aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Cloudwatch-Metrics aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Cloudwatch-Metrics aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Cloudwatch-Metrics aws token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Cloudwatch-Metrics execution method"). SetOptions([]string{"put_metrics", "list_metrics"}). SetDefault("put_metrics"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("namespace"). SetKind("string"). SetDescription("Set Cloudwatch-Metrics namespace"). SetDefault(""). SetMust(false), ) } <file_sep>package main import ( "context" "encoding/json" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { validBody, err := json.Marshal("valid body2") if err != nil { log.Fatal(err) } client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } // sendRequest sendRequest := types.NewRequest(). SetData(validBody) querySendResponse, err := client.SetQuery(sendRequest.ToQuery()). SetChannel("query.messaging.ibmmq"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } sendResponse, err := types.ParseResponse(querySendResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("send executed, response: %s", sendResponse.Data)) } <file_sep>package filesystem import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("storage.filesystem"). SetDescription("Local Filesystem Target"). SetName("File System"). SetProvider(""). SetCategory("Storage"). SetTags("filesystem"). AddProperty( common.NewProperty(). SetKind("string"). SetName("base_path"). SetTitle("Destination Path"). SetDescription("Set local file system base path"). SetMust(true). SetDefault("./"), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set file system method"). SetOptions([]string{"save", "load", "delete", "list"}). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("path"). SetKind("string"). SetDescription("Set path"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("filename"). SetKind("string"). SetDescription("Set filename"). SetDefault(""). SetMust(true), ) } <file_sep>package sns import ( "context" "encoding/json" "fmt" "io/ioutil" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { awsKey string awsSecretKey string region string token string topic string message string endPoint string protocol string returnSubscription string } func createSendMessageAttributes(store string, event string) ([]byte, error) { var at []Attributes aStore := Attributes{ Name: "store", StringValue: store, DataType: "String", } at = append(at, aStore) aEvent := Attributes{ Name: "event", StringValue: event, DataType: "String", } at = append(at, aEvent) b, err := json.Marshal(at) if err != nil { return nil, err } return b, nil } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/aws/awsKey.txt") if err != nil { return nil, err } t.awsKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/awsSecretKey.txt") if err != nil { return nil, err } t.awsSecretKey = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/region.txt") if err != nil { return nil, err } t.region = string(dat) t.token = "" dat, err = ioutil.ReadFile("./../../../credentials/aws/sns/topic.txt") if err != nil { return nil, err } t.topic = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/sns/message.txt") if err != nil { return nil, err } t.message = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/aws/sns/email.txt") if err != nil { return nil, err } t.endPoint = string(dat) t.protocol = "email" t.returnSubscription = "true" return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init ", cfg: config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: false, }, { name: "init - missing secret key", cfg: config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "region": dat.region, }, }, wantErr: true, }, { name: "init - missing key", cfg: config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) }) } } func TestClient_List_Topics(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_topics"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Subscriptions(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list", request: types.NewRequest(). SetMetadataKeyValue("method", "list_subscriptions"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_List_Subscriptions_By_Topic(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid list by topic", request: types.NewRequest(). SetMetadataKeyValue("method", "list_subscriptions_by_topic"). SetMetadataKeyValue("topic", dat.topic), wantErr: false, }, { name: "invalid list by topic - missing topic", request: types.NewRequest(). SetMetadataKeyValue("method", "list_subscriptions_by_topic"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Create_Topic(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) attributes := make(map[string]*string) DisplayName := "my-display-name" attributes["DisplayName"] = &DisplayName b, err := json.Marshal(attributes) require.NoError(t, err) cfg := config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid create topic -with attributes", request: types.NewRequest(). SetMetadataKeyValue("method", "create_topic"). SetMetadataKeyValue("topic", dat.topic). SetData(b), wantErr: false, }, { name: "valid create topic -without attributes", request: types.NewRequest(). SetMetadataKeyValue("method", "create_topic"). SetMetadataKeyValue("topic", fmt.Sprintf("%s-another", dat.topic)), wantErr: false, }, { name: "invalid create topic - missing topic", request: types.NewRequest(). SetMetadataKeyValue("method", "create_topic"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_SendMessage(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } attributes, err := createSendMessageAttributes("mystore", "test") require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid send Message- target_arn", request: types.NewRequest(). SetMetadataKeyValue("method", "send_message"). SetMetadataKeyValue("target_arn", dat.topic). SetMetadataKeyValue("message", dat.message). SetData(attributes), wantErr: false, }, { name: "valid send message - topic", request: types.NewRequest(). SetMetadataKeyValue("method", "send_message"). SetMetadataKeyValue("topic", dat.topic). SetMetadataKeyValue("message", dat.message). SetData(attributes), wantErr: false, }, { name: "invalid send message - missing target_arn", request: types.NewRequest(). SetMetadataKeyValue("message", dat.message). SetMetadataKeyValue("method", "send_message"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Subscribe(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } attributes := make(map[string]*string) RawMessageDelivery := `{ "store": ["mystore"], "event": [{"anything-but": "my-event"}]}` attributes["FilterPolicy"] = &RawMessageDelivery b, err := json.Marshal(attributes) require.NoError(t, err) tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid subscribe topic", request: types.NewRequest(). SetMetadataKeyValue("method", "subscribe"). SetMetadataKeyValue("topic", dat.topic). SetMetadataKeyValue("protocol", dat.protocol). SetMetadataKeyValue("return_subscription", dat.returnSubscription). SetMetadataKeyValue("end_point", dat.endPoint). SetData(b), wantErr: false, }, { name: "invalid subscribe topic - missing topic", request: types.NewRequest(). SetMetadataKeyValue("method", "subscribe"). SetMetadataKeyValue("protocol", dat.protocol). SetMetadataKeyValue("return_subscription", dat.returnSubscription). SetMetadataKeyValue("end_point", dat.endPoint), wantErr: true, }, { name: "invalid subscribe topic - missing protocol", request: types.NewRequest(). SetMetadataKeyValue("method", "subscribe"). SetMetadataKeyValue("topic", dat.topic). SetMetadataKeyValue("return_subscription", dat.returnSubscription). SetMetadataKeyValue("end_point", dat.endPoint), wantErr: true, }, { name: "invalid subscribe topic - missing return_subscription", request: types.NewRequest(). SetMetadataKeyValue("method", "subscribe"). SetMetadataKeyValue("topic", dat.topic). SetMetadataKeyValue("protocol", dat.protocol). SetMetadataKeyValue("end_point", dat.endPoint), wantErr: true, }, { name: "invalid subscribe topic - missing end_point", request: types.NewRequest(). SetMetadataKeyValue("method", "subscribe"). SetMetadataKeyValue("topic", dat.topic). SetMetadataKeyValue("protocol", dat.protocol). SetMetadataKeyValue("return_subscription", dat.returnSubscription), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } func TestClient_Delete_Topic(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) cfg := config.Spec{ Name: "aws-sns", Kind: "aws.sns", Properties: map[string]string{ "aws_key": dat.awsKey, "aws_secret_key": dat.awsSecretKey, "region": dat.region, }, } tests := []struct { name string request *types.Request wantErr bool }{ { name: "valid delete topic", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_topic"). SetMetadataKeyValue("topic", dat.topic), wantErr: false, }, { name: "invalid delete topic - missing topic", request: types.NewRequest(). SetMetadataKeyValue("method", "delete_topic"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err = c.Init(ctx, cfg, nil) require.NoError(t, err) got, err := c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } require.NoError(t, err) require.NotNil(t, got) }) } } <file_sep>package singlestore import ( "context" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type post struct { Id int64 `json:"id"` Title string `json:"title,omitempty"` Content string `json:"content,omitempty"` BigNumber int64 `json:"bignumber,omitempty"` BoolValue bool `json:"boolvalue"` } type posts []*post func (p *posts) marshal() []byte { b, _ := json.Marshal(p) return b } func unmarshal(data []byte) *posts { if data == nil { return nil } p := &posts{} _ = json.Unmarshal(data, p) return p } var allPosts = posts{ &post{ Id: 0, Content: "Content One", BigNumber: 1231241241231231123, BoolValue: true, }, &post{ Id: 1, Title: "Title Two", Content: "Content Two", BigNumber: 123125241231231123, BoolValue: false, }, } const ( createPostTable = `DROP TABLE IF EXISTS post; CREATE TABLE post ( ID bigint, TITLE varchar(40), CONTENT varchar(255), BIGNUMBER bigint, BOOLVALUE boolean, CONSTRAINT pk_post PRIMARY KEY(ID) ); INSERT INTO post(ID,TITLE,CONTENT,BIGNUMBER,BOOLVALUE) VALUES (0,NULL,'Content One',1231241241231231123,true), (1,'Title Two','Content Two',123125241231231123,false);` selectPostTable = `SELECT id,title,content,bignumber,boolvalue FROM post;` ) func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, wantErr: false, }, { name: "init - bad connection string", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "bad connection string", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, wantErr: true, }, { name: "init - bad port connection string", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:5678)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, wantErr: true, }, { name: "init - no connection string", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, wantErr: true, }, { name: "init - bad max idle connections", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "-1", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, wantErr: true, }, { name: "init - bad max open connections", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "-1", "connection_max_lifetime_seconds": "", }, }, wantErr: true, }, { name: "init - bad connection max lifetime seconds", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "-1", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantExecErr %v", err, tt.wantErr) return } }) } } func TestClient_Query_Exec_Transaction(t *testing.T) { tests := []struct { name string cfg config.Spec execRequest *types.Request queryRequest *types.Request wantExecResponse *types.Response wantQueryResponse *types.Response wantExecErr bool wantQueryErr bool }{ { name: "valid exec query request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetData([]byte(createPostTable)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetData([]byte(selectPostTable)), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(allPosts.marshal()), wantExecErr: false, wantQueryErr: false, }, { name: "empty exec request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"), queryRequest: nil, wantExecResponse: nil, wantQueryResponse: nil, wantExecErr: true, wantQueryErr: false, }, { name: "invalid exec request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetData([]byte("bad statement")), queryRequest: nil, wantExecResponse: nil, wantQueryResponse: nil, wantExecErr: true, wantQueryErr: false, }, { name: "valid exec empty query request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetData([]byte(createPostTable)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetData([]byte("")), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: nil, wantExecErr: false, wantQueryErr: true, }, { name: "valid exec bad query request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetData([]byte(createPostTable)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetData([]byte("some bad query")), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: nil, wantExecErr: false, wantQueryErr: true, }, { name: "valid exec valid query - no results", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetData([]byte(createPostTable)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetData([]byte("SELECT id,title,content FROM post where id=100")), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantExecErr: false, wantQueryErr: false, }, { name: "valid exec query request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "exec"). SetData([]byte(createPostTable)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetData([]byte(selectPostTable)), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(allPosts.marshal()), wantExecErr: false, wantQueryErr: false, }, { name: "empty transaction request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "transaction"), queryRequest: nil, wantExecResponse: nil, wantQueryResponse: nil, wantExecErr: true, wantQueryErr: false, }, { name: "invalid transaction request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetData([]byte("bad statement")), queryRequest: nil, wantExecResponse: nil, wantQueryResponse: nil, wantExecErr: true, wantQueryErr: false, }, { name: "valid transaction empty query request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, execRequest: types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetData([]byte(createPostTable)), queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"), wantExecResponse: types.NewResponse(). SetMetadataKeyValue("result", "ok"), wantQueryResponse: nil, wantExecErr: false, wantQueryErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.execRequest) if tt.wantExecErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantExecResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantQueryErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) if tt.wantQueryResponse != nil { wantPosts := unmarshal(tt.wantQueryResponse.Data) var gotPosts *posts if gotGetResponse != nil { gotPosts = unmarshal(gotGetResponse.Data) } require.EqualValues(t, wantPosts, gotPosts) } else { require.EqualValues(t, tt.wantQueryResponse, gotGetResponse) } }) } } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "valid request", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetMetadataKeyValue("isolation_level", "read_uncommitted"). SetData([]byte(createPostTable)), wantErr: false, }, { name: "valid request - 2", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetMetadataKeyValue("isolation_level", "read_committed"). SetData([]byte(createPostTable)), wantErr: false, }, { name: "valid request - 3", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetMetadataKeyValue("isolation_level", "repeatable_read"). SetData([]byte(createPostTable)), wantErr: false, }, { name: "valid request - 3", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetMetadataKeyValue("isolation_level", "serializable"). SetData([]byte(createPostTable)), wantErr: false, }, { name: "invalid request - bad method", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "bad-method"), wantErr: true, }, { name: "invalid request - bad isolation level", cfg: config.Spec{ Name: "stores-singlestore", Kind: "stores.singlestore", Properties: map[string]string{ "connection": "root:password@(localhost:3306)/test?charset=utf8&parseTime=True&loc=Local", "max_idle_connections": "", "max_open_connections": "", "connection_max_lifetime_seconds": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "transaction"). SetMetadataKeyValue("isolation_level", "bad_level"). SetData([]byte(createPostTable)), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) _, err = c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } <file_sep>package elasticsearch import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.elasticsearch"). SetDescription("AWS Elastic Search Target"). SetName("Elasticsearch"). SetProvider("AWS"). SetCategory("Store"). SetTags("db", "log", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Elastic Search aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Elastic Search aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Elastic Search aws token"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Elastic Search execution method"). SetOptions([]string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}). SetDefault("GET"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("region"). SetKind("string"). SetDescription("Set Elastic Search region"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("domain"). SetKind("string"). SetDescription("Set Elastic Search domain"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("index"). SetDescription("Set Elastic Search index"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("endpoint"). SetDescription("Set Elastic Search endpoint"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("id"). SetDescription("Set Elastic Search id"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("multilines"). SetName("json"). SetDescription("Set Elastic Search json"). SetMust(false). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetKind("string"). SetName("service"). SetDescription("Set Elastic Search service"). SetMust(false). SetDefault("es"), ) } <file_sep>package mysql import ( "context" "database/sql" "fmt" "strconv" "strings" "time" _ "github.com/go-sql-driver/mysql" jsoniter "github.com/json-iterator/go" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary // Client is a Client state store type Client struct { log *logger.Logger db *sql.DB opts options } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } c.db, err = sql.Open("mysql", c.opts.connection) if err != nil { return err } err = c.db.PingContext(ctx) if err != nil { _ = c.db.Close() return fmt.Errorf("error connecting to mysql at %s: %w", c.opts.connection, err) } c.db.SetMaxOpenConns(c.opts.maxOpenConnections) c.db.SetMaxIdleConns(c.opts.maxIdleConnections) c.db.SetConnMaxLifetime(time.Duration(c.opts.connectionMaxLifetimeSeconds) * time.Second) return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "query": return c.Query(ctx, meta, req.Data) case "exec": return c.Exec(ctx, meta, req.Data) case "transaction": return c.Transaction(ctx, meta, req.Data) } return nil, nil } func (c *Client) Exec(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { stmts := getStatements(value) if stmts == nil { return nil, fmt.Errorf("no exec statement found") } for i, stmt := range stmts { if stmt != "" { _, err := c.db.ExecContext(ctx, stmt) if err != nil { return nil, fmt.Errorf("error on statement %d, %w", i, err) } } } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func getStatements(data []byte) []string { if data == nil { return nil } return strings.Split(string(data), ";") } func (c *Client) Transaction(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { stmts := getStatements(value) if stmts == nil { return nil, fmt.Errorf("no transaction statements found") } tx, err := c.db.BeginTx(ctx, &sql.TxOptions{ Isolation: meta.isolationLevel, ReadOnly: false, }) if err != nil { return nil, err } defer func() { if r := recover(); r != nil { _ = tx.Rollback() } }() for i, stmt := range stmts { if stmt != "" { _, err := tx.ExecContext(ctx, stmt) if err != nil { rollBackErr := tx.Rollback() if rollBackErr != nil { return nil, rollBackErr } return nil, fmt.Errorf("error on statement %d, %w", i, err) } } } err = tx.Commit() if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Query(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { stmt := string(value) if stmt == "" { return nil, fmt.Errorf("no query statement found") } rows, err := c.db.QueryContext(ctx, stmt) if err != nil { return nil, err } defer rows.Close() return types.NewResponse(). SetData(c.rowsToMap(rows)). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) rowsToMap(rows *sql.Rows) []byte { cols, _ := rows.Columns() colsTypes, err := rows.ColumnTypes() if err != nil { return nil } var results []map[string]interface{} for rows.Next() { results = append(results, parseWithRawBytes(rows, cols, colsTypes)) } if results == nil { return nil } b, _ := json.Marshal(results) return b } func parseWithRawBytes(rows *sql.Rows, cols []string, colsTypes []*sql.ColumnType) map[string]interface{} { vals := make([]sql.RawBytes, len(cols)) scanArgs := make([]interface{}, len(vals)) for i := range vals { scanArgs[i] = &vals[i] } if err := rows.Scan(scanArgs...); err != nil { panic(err) } m := make(map[string]interface{}) for i, col := range vals { if col == nil { continue } switch colsTypes[i].DatabaseTypeName() { case "TINYINT", "BOOLEAN": m[cols[i]], _ = strconv.ParseBool(string(col)) case "SMALLINT", "MEDIUMINT": m[cols[i]], _ = strconv.Atoi(string(col)) case "BIGINT": m[cols[i]], _ = strconv.ParseInt(string(col), 10, 64) case "FLOAT": val, _ := strconv.ParseFloat(string(col), 32) m[cols[i]] = float32(val) case "DOUBLE", "DECIMAL": m[cols[i]], _ = strconv.ParseFloat(string(col), 64) default: m[cols[i]] = string(col) } } return m } func (c *Client) Stop() error { if c.db != nil { return c.db.Close() } return nil } <file_sep>package files import ( "fmt" "time" "github.com/Azure/azure-storage-file-go/azfile" "github.com/kubemq-io/kubemq-targets/config" ) const ( defaultPolicy = "retry_policy_exponential" defaultMaxTries = 1 defaultTryTimeout = 10000 defaultRetryDelay = 600 defaultMaxRetryDelay = 1800 ) var policyMap = map[string]string{ "exponential": "retry_policy_exponential", "fixed": "retry_policy_fixed", } type options struct { storageAccessKey string storageAccount string policy azfile.RetryPolicy maxTries int32 tryTimeout time.Duration retryDelay time.Duration maxRetryDelay time.Duration } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.storageAccessKey, err = cfg.Properties.MustParseString("storage_access_key") if err != nil { return options{}, fmt.Errorf("error parsing storage_access_key , %w", err) } o.storageAccount, err = cfg.Properties.MustParseString("storage_account") if err != nil { return options{}, fmt.Errorf("error parsing storage_account , %w", err) } var policy string policy, err = cfg.Properties.ParseStringMap("policy", policyMap) if err != nil { policy = defaultPolicy } if policy == "retry_policy_fixed" { o.policy = azfile.RetryPolicyFixed } else if policy == "retry_policy_exponential" { o.policy = azfile.RetryPolicyExponential } else { o.policy = azfile.RetryPolicyExponential } o.maxTries = int32(cfg.Properties.ParseInt("max_tries", defaultMaxTries)) o.tryTimeout = cfg.Properties.ParseTimeDuration("try_timeout", defaultTryTimeout) o.retryDelay = cfg.Properties.ParseTimeDuration("retry_delay", defaultRetryDelay) o.maxRetryDelay = cfg.Properties.ParseTimeDuration("max_retry_delay", defaultMaxRetryDelay) return o, nil } <file_sep>package main import ( "context" "fmt" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } publishRequest := types.NewRequest(). SetMetadataKeyValue("topic", "some-queue"). SetMetadataKeyValue("qos", "0"). SetData([]byte("some-data")) queryPublishResponse, err := client.SetQuery(publishRequest.ToQuery()). SetChannel("query.mqtt"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } publishResponse, err := types.ParseResponse(queryPublishResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("publish message, response: %s", publishResponse.Metadata.String())) } <file_sep>package postgres import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("aws.rds.postgres"). SetDescription("AWS RDS Postgres Target"). SetName("Postgres"). SetProvider("AWS"). SetCategory("Store"). SetTags("rds", "sql", "db", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_key"). SetDescription("Set Postgres aws key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("aws_secret_key"). SetDescription("Set Postgres aws secret key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("region"). SetDescription("Set Postgres aws region"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("token"). SetDescription("Set Postgres aws token"). SetMust(false). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("end_point"). SetTitle("Endpoint"). SetDescription("Set Postgres end point address"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("db_port"). SetTitle("Port"). SetDescription("Set Postgres end point port"). SetMust(true). SetDefault("5432"). SetMin(0). SetMax(65535), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("db_user"). SetTitle("Username"). SetDescription("Set Postgres db user(should match user created for IAM Access)"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("db_name"). SetTitle("Database"). SetDescription("Set Postgres db name"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_idle_connections"). SetDescription("Set Postgres max idle connections"). SetMust(false). SetDefault("10"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_open_connections"). SetDescription("Set Postgres max open connections"). SetMust(false). SetDefault("100"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("connection_max_lifetime_seconds"). SetTitle("Connection Lifetime (Seconds)"). SetDescription("Set Postgres connection max lifetime seconds"). SetMust(false). SetDefault("3600"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Postgres execution method"). SetOptions([]string{"query", "exec", "transaction"}). SetDefault("query"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("isolation_level"). SetKind("string"). SetDescription("Set Postgres isolation level"). SetOptions([]string{"Default", "ReadUncommitted", "ReadCommitted", "RepeatableRead", "Serializable"}). SetDefault("Default"). SetMust(false), ) } <file_sep># Kubemq bigquery target Connector Kubemq gcp-bigquery target connector allows services using kubemq server to access google bigquery server. ## Prerequisites The following are required to run the gcp-bigquery target connector: - kubemq cluster - gcp-bigquery set up - kubemq-targets deployment ## Configuration bigquery target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:---------------------------| | project_id | yes | gcp bigquery project_id | "<googleurl>/myproject" | | credentials | yes | gcp credentials files | "<google json credentials" | Example: ```yaml bindings: - name: kubemq-query-gcp-bigquery source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-gcp-bigquery-connector" auth_token: "" channel: "query.gcp.bigquery" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: gcp.bigquery name: gcp-bigquery properties: project_id: "id" credentials: 'json' ``` ## Usage ### Query Request query request. Query metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:-----------------------------|:----------------------| | method | yes | type of method | "query" | | query | yes | the query body | "select * from table" | Example: ```json { "metadata": { "method": "query", "query": "select * from table" }, "data": null } ``` ### Create Table Request create a new table under data set This method required a body of rows of string [bigquery.TableMetadata] Example how to create the struct: ```go mySchema := bigquery.Schema{ {Name: "name", Type: bigquery.StringFieldType}, {Name: "age", Type: bigquery.IntegerFieldType}, } metaData := &bigquery.TableMetadata{ Schema: mySchema, ExpirationTime: time.Now().AddDate(2, 1, 0), // Table will deleted in 2 years and 1 month. } bSchema, err := json.Marshal(metaData) ``` Create table metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------| | method | yes | type of method | "create_table" | | dataset_id | yes | dataset to assign the table to | "your data set ID" | | table_name | yes | table name | "unique name" | Example: ```json { "metadata": { "method": "create_table", "dataset_id": "<mySet>", "table_name": "<myTable>" }, "data": "<KEY> } ``` ### Delete Table Request delete a new table under data set Delete table metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------| | method | yes | type of method | "create_table" | | dataset_id | yes | dataset to assign the table to | "your data set ID" | | table_name | yes | table name | "unique name" | Example: ```json { "metadata": { "method": "delete_table", "dataset_id": "<mySet>", "table_name": "<myTable>" }, "data":null } ``` ### Create Data Set Request Create a Data Set Create Data Set metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------| | method | yes | type of method | "create_data_set" | | dataset_id | yes | dataset to assign the table to | "your data set ID" | | location | yes | dataset location to set | "US" See https://cloud.google.com/bigquery/docs/locations | Example: ```json { "metadata": { "method": "create_data_set", "dataset_id": "<mySet>", "location": "US" }, "data":null } ``` ### Delete Data Set Request delete a Data Set Delete Data Set metadata setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------| | method | yes | type of method | "delete_data_set" | | dataset_id | yes | dataset to assign the table to | "your data set ID" | Example: ```json { "metadata": { "method": "delete_data_set", "dataset_id": "<mySet>" }, "data":null } ``` ### Get DataSets Request get data sets. Get DataSets setting: | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:------------------| | method | yes | type of method | "get_data_sets" | Example: ```json { "metadata": { "method": "get_data_sets" }, "data": null } ``` ### Get Table Info get basic information on a table by name Get table Info | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------| | method | yes | type of method | "get_table_info" | | dataset_id | yes | dataset to assign the table to | "your data set ID" | | table_name | yes | table name | "unique table name" | Example: ```json { "metadata": { "method": "get_table_info", "dataset_id": "<mySet>", "table_name": "<myTable>" }, "data": null } ``` ### Insert To Table insert rows to table Insert To Table this method required a body of rows as json array ```json [ {"id":"id-1","service":{"id":"service_id_1","value":0.1},"time":"1980-10-10T00:00:00Z"}, {"id":"id-2","service":{"id":"service_id_2","value":0.1},"time":"1980-10-10T00:00:00Z"} ] ``` | Metadata Key | Required | Description | Possible values | |:-------------|:---------|:----------------------------------------|:----------------------| | method | yes | type of method | "insert" | | dataset_id | yes | dataset to assign the table to | "your data set ID" | | table_name | yes | table name | "unique table name" | Example: ```json { "metadata": { "method": "insert", "dataset_id": "<mySet>", "table_name": "<myTable>" }, "data": "W3sgIm<KEY>==" } ``` <file_sep>package bigquery import ( "context" "io/ioutil" "testing" "time" "cloud.google.com/go/bigquery" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" ) type testStructure struct { projectID string tableName string query string dataSetID string emptyTable string emptyTableQry string cred string } func getTestStructure() (*testStructure, error) { t := &testStructure{} dat, err := ioutil.ReadFile("./../../../credentials/projectID.txt") if err != nil { return nil, err } t.projectID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/query.txt") if err != nil { return nil, err } t.query = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/tableName.txt") if err != nil { return nil, err } t.tableName = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/emptyTable.txt") if err != nil { return nil, err } t.emptyTable = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/emptyTableQry.txt") if err != nil { return nil, err } t.emptyTableQry = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/dataSetID.txt") if err != nil { return nil, err } t.dataSetID = string(dat) dat, err = ioutil.ReadFile("./../../../credentials/google_cred.json") if err != nil { return nil, err } t.cred = string(dat) return t, nil } func TestClient_Init(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, wantErr: false, }, { name: "invalid init - missing credentials", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, }, }, wantErr: true, }, { name: "invalid init - missing project_id", cfg: config.Spec{ Name: "gcp-bigtable", Kind: "gcp.bigquery", Properties: map[string]string{ "credentials": dat.cred, }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) if tt.wantErr { require.Error(t, err) t.Logf("init() error = %v, wantSetErr %v", err, tt.wantErr) return } defer func() { _ = c.Stop() }() require.NoError(t, err) }) } } func TestClient_Query(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid query", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("query", dat.query), wantErr: false, }, { name: "invalid query - missing query", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"), wantErr: true, }, { name: "valid query - empty table", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "query"). SetMetadataKeyValue("query", dat.emptyTableQry), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } // See https://cloud.google.com/bigquery/docs/locations func TestClient_Create_Data_Set(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid get create_data_set", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "create_data_set"). SetMetadataKeyValue("location", "US"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: false, }, { name: "invalid create_data_set - already exists", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "location": "US", }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "create_data_set"). SetMetadataKeyValue("location", "US"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: true, }, { name: "invalid get get_table_info - missing location", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_table_info"). SetMetadataKeyValue("location", "US"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: true, }, { name: "invalid get get_table_info - invalid location", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_table_info"). SetMetadataKeyValue("location", "fake"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, gotSetResponse.Metadata["result"], "ok") }) } } func TestClient_Delete_Data_Set(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid delete_data_set", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_data_set"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: false, }, { name: "invalid delete_data_set - not exists", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, "location": "US", }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_data_set"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: true, }, { name: "invalid get delete_data_set - missing dataset_id", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_data_set"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, gotSetResponse.Metadata["result"], "ok") }) } } func TestClient_Create_Table(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) mySchema := bigquery.Schema{ {Name: "name", Type: bigquery.StringFieldType}, {Name: "age", Type: bigquery.IntegerFieldType}, } metaData := &bigquery.TableMetadata{ Schema: mySchema, ExpirationTime: time.Now().AddDate(2, 1, 0), // Table will deleted in 2 years and 1 month. } bSchema, err := json.Marshal(metaData) require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid create table", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetMetadataKeyValue("table_name", dat.tableName). SetData(bSchema), wantErr: false, }, { name: "invalid create_table - missing tableName", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetData(bSchema), wantErr: true, }, { name: "invalid create_table - table already exists", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetMetadataKeyValue("table_name", dat.tableName). SetData(bSchema), wantErr: true, }, { name: "invalid create_table - missing dataset_id", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "create_table"). SetMetadataKeyValue("table_name", dat.tableName). SetData(bSchema), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Delete_Table(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid delete_table table", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetMetadataKeyValue("table_name", dat.tableName), wantErr: false, }, { name: "invalid delete_table - missing tableName", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: true, }, { name: "invalid delete_table - table already deleted", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "invalid delete_table - missing dataset_id", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "delete_table"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Get_Data_Sets(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid get_data_sets", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_data_sets"), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, gotSetResponse.Metadata["result"], "ok") }) } } func TestClient_Get_Table_Info(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid get get_table_info", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_table_info"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetMetadataKeyValue("table_name", dat.tableName), wantErr: false, }, { name: "invalid get get_table_info - missing dataset_id", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_table_info"). SetMetadataKeyValue("table_name", dat.tableName), wantErr: true, }, { name: "invalid get get_table_info - missing table_name", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_table_info"). SetMetadataKeyValue("dataset_id", dat.dataSetID), wantErr: true, }, { name: "valid get get_table_info - not existing table", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "get_table_info"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetMetadataKeyValue("table_name", "NotExistingTable"), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.EqualValues(t, gotSetResponse.Metadata["result"], "ok") require.NoError(t, err) require.NotNil(t, gotSetResponse) }) } } func TestClient_Insert_To_Table(t *testing.T) { dat, err := getTestStructure() require.NoError(t, err) var rows []map[string]bigquery.Value firstRow := make(map[string]bigquery.Value) firstRow["name"] = "myName4" firstRow["age"] = 25 rows = append(rows, firstRow) secondRow := make(map[string]bigquery.Value) secondRow["name"] = "myName5" secondRow["age"] = 28 rows = append(rows, secondRow) bRows, err := json.Marshal(&rows) require.NoError(t, err) tests := []struct { name string cfg config.Spec queryRequest *types.Request wantErr bool }{ { name: "valid insert to table", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "insert"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetMetadataKeyValue("table_name", dat.tableName). SetData(bRows), wantErr: false, }, { name: "invalid insert to table - missing table_name", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "insert"). SetMetadataKeyValue("dataset_id", dat.dataSetID). SetData(bRows), wantErr: true, }, { name: "invalid insert to table - missing dataset_id", cfg: config.Spec{ Name: "gcp-bigquery", Kind: "gcp.bigquery", Properties: map[string]string{ "project_id": dat.projectID, "credentials": dat.cred, }, }, queryRequest: types.NewRequest(). SetMetadataKeyValue("method", "insert"). SetMetadataKeyValue("table_name", dat.tableName). SetData(bRows), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) defer func() { err = c.Stop() require.NoError(t, err) }() require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.queryRequest) if tt.wantErr { t.Logf("init() error = %v, wantErr %v", err, tt.wantErr) require.Error(t, err) return } require.NoError(t, err) require.EqualValues(t, gotSetResponse.Metadata["result"], "ok") require.NotNil(t, gotSetResponse) }) } } <file_sep>package main import ( "context" "fmt" "io/ioutil" "log" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" ) func main() { client, err := kubemq.NewClient(context.Background(), kubemq.WithAddress("kubemq-cluster", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { log.Fatal(err) } contents, err := ioutil.ReadFile("./credentials/azure/storage/blob/contents.txt") if err != nil { panic(err) } dat, err := ioutil.ReadFile("./credentials/azure/storage/blob/fileName.txt") if err != nil { panic(err) } fileName := string(dat) dat, err = ioutil.ReadFile("./credentials/azure/storage/blob/serviceURL.txt") if err != nil { panic(err) } serviceURL := string(dat) // upload uploadRequest := types.NewRequest(). SetMetadataKeyValue("method", "upload"). SetMetadataKeyValue("file_name", fileName). SetMetadataKeyValue("service_url", serviceURL). SetData(contents) queryUploadResponse, err := client.SetQuery(uploadRequest.ToQuery()). SetChannel("azure.storage.blob"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } uploadResponse, err := types.ParseResponse(queryUploadResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("upload request executed, error: %v", uploadResponse.Error)) // get request getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("file_name", fileName). SetMetadataKeyValue("service_url", serviceURL) getQueryResponse, err := client.SetQuery(getRequest.ToQuery()). SetChannel("azure.storage.blob"). SetTimeout(10 * time.Second).Send(context.Background()) if err != nil { log.Fatal(err) } getResponse, err := types.ParseResponse(getQueryResponse.Body) if err != nil { log.Fatal(err) } log.Println(fmt.Sprintf("get request done, response : %s", getResponse.Data)) } <file_sep>package aerospike import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) var methodsMap = map[string]string{ "get": "get", "set": "set", "delete": "delete", "get_batch": "get_batch", } type metadata struct { method string key string userKey string namespace string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.key = meta.ParseString("key", "") m.userKey = meta.ParseString("user_key", "") m.namespace = meta.ParseString("namespace", "") return m, nil } <file_sep>package redis import ( "context" "fmt" "strconv" "strings" redisClient "github.com/go-redis/redis/v7" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" ) const ( setQuery = "local var1 = redis.pcall(\"HGET\", KEYS[1], \"version\"); if type(var1) == \"table\" then redis.call(\"DEL\", KEYS[1]); end; if not var1 or type(var1)==\"table\" or var1 == \"\" or var1 == ARGV[1] or ARGV[1] == \"0\" then redis.call(\"HSET\", KEYS[1], \"data\", ARGV[2]) return redis.call(\"HINCRBY\", KEYS[1], \"version\", 1) else return error(\"failed to set key \" .. KEYS[1]) end" delQuery = "local var1 = redis.pcall(\"HGET\", KEYS[1], \"version\"); if not var1 or type(var1)==\"table\" or var1 == ARGV[1] or var1 == \"\" or ARGV[1] == \"0\" then return redis.call(\"DEL\", KEYS[1]) else return error(\"failed to delete \" .. KEYS[1]) end" connectedSlavesReplicas = "connected_slaves:" infoReplicationDelimiter = "\r\n" ) // Client is a Client state store type Client struct { log *logger.Logger redis *redisClient.Client opts options replicas int } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } redisInfo, err := redisClient.ParseURL(c.opts.url) if err != nil { return fmt.Errorf("error parsing redis url %s: %w", c.opts.url, err) } c.redis = redisClient.NewClient(redisInfo) _, err = c.redis.WithContext(ctx).Ping().Result() if err != nil { _ = c.redis.Close() return fmt.Errorf("error connecting to redis at %s: %w", redisInfo.Addr, err) } c.replicas, err = c.getConnectedSlaves(ctx) return err } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } switch meta.method { case "get": return c.Get(ctx, meta) case "set": return c.Set(ctx, meta, req.Data) case "delete": return c.Delete(ctx, meta) } return nil, nil } func (c *Client) getConnectedSlaves(ctx context.Context) (int, error) { res, err := c.redis.DoContext(ctx, "INFO", "replication").Result() if err != nil { return 0, err } s, _ := strconv.Unquote(fmt.Sprintf("%q", res)) if len(s) == 0 { return 0, nil } return c.parseConnectedSlaves(s), nil } func (c *Client) parseConnectedSlaves(res string) int { infos := strings.Split(res, infoReplicationDelimiter) for _, info := range infos { if strings.Contains(info, connectedSlavesReplicas) { parsedReplicas, _ := strconv.ParseUint(info[len(connectedSlavesReplicas):], 10, 32) return int(parsedReplicas) } } return 0 } func (c *Client) Get(ctx context.Context, meta metadata) (*types.Response, error) { res, err := c.redis.DoContext(ctx, "HGETALL", meta.key).Result() // Prefer values with ETags if err != nil { return c.directGet(ctx, meta.key) // Falls back to original get } if res == nil { return nil, fmt.Errorf("no data found for this key") } vals := res.([]interface{}) if len(vals) == 0 { return nil, fmt.Errorf("no data found for this key") } data, _, err := c.getKeyVersion(vals) if err != nil { return nil, fmt.Errorf("error found for get this key, %w", err) } return types.NewResponse(). SetData([]byte(data)). SetMetadataKeyValue("key", meta.key), nil } func (c *Client) getKeyVersion(vals []interface{}) (data string, version string, err error) { seenData := false seenVersion := false for i := 0; i < len(vals); i += 2 { field, _ := strconv.Unquote(fmt.Sprintf("%q", vals[i])) switch field { case "data": data, _ = strconv.Unquote(fmt.Sprintf("%q", vals[i+1])) seenData = true case "version": version, _ = strconv.Unquote(fmt.Sprintf("%q", vals[i+1])) seenVersion = true } } if !seenData || !seenVersion { return "", "", fmt.Errorf("required hash field 'data' or 'version' was not found") } return data, version, nil } func (c *Client) directGet(ctx context.Context, key string) (*types.Response, error) { res, err := c.redis.DoContext(ctx, "GET", key).Result() if err != nil { return nil, err } s, _ := strconv.Unquote(fmt.Sprintf("%q", res)) return types.NewResponse(). SetMetadataKeyValue("key", key). SetData([]byte(s)), nil } func (c *Client) Set(ctx context.Context, meta metadata, value []byte) (*types.Response, error) { if meta.concurrency == "last-write" { meta.etag = 0 } _, err := c.redis.DoContext(ctx, "EVAL", setQuery, 1, meta.key, meta.etag, value).Result() if err != nil { return nil, fmt.Errorf("failed to set key %s: %s", meta.key, err) } if meta.consistency == "strong" && c.replicas > 0 { _, err = c.redis.DoContext(ctx, "WAIT", c.replicas, 1000).Result() if err != nil { return nil, fmt.Errorf("timed out while waiting for %v replicas to acknowledge write", c.replicas) } } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Delete(ctx context.Context, meta metadata) (*types.Response, error) { _, err := c.redis.DoContext(ctx, "EVAL", delQuery, 1, meta.key, meta.etag).Result() if err != nil { return nil, fmt.Errorf("failed to delete key '%s',%w", meta.key, err) } return types.NewResponse(). SetMetadataKeyValue("key", meta.key). SetMetadataKeyValue("result", "ok"), nil } func (c *Client) Stop() error { if c.redis != nil { return c.redis.Close() } return nil } <file_sep>package cloudfunctions import ( "context" "fmt" "strings" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/logger" gf "github.com/kubemq-io/kubemq-targets/targets/gcp/cloudfunctions/functions/apiv1" "github.com/kubemq-io/kubemq-targets/types" "google.golang.org/api/iterator" "google.golang.org/api/option" functionspb "google.golang.org/genproto/googleapis/cloud/functions/v1" ) type Client struct { log *logger.Logger opts options client *gf.CloudFunctionsClient parrantProject string list []string // nameFunctions map[string]string } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } c.log = logger.NewLogger(cfg.Name) var err error c.opts, err = parseOptions(cfg) if err != nil { return err } b := []byte(c.opts.credentials) client, err := gf.NewCloudFunctionsClient(ctx, option.WithCredentialsJSON(b)) if err != nil { return err } c.client = client c.parrantProject = c.opts.parentProject if c.opts.locationMatch { it := client.ListFunctions(ctx, &functionspb.ListFunctionsRequest{ Parent: fmt.Sprintf("projects/%s/locations/-", c.opts.parentProject), }) for { resp, err := it.Next() if err == iterator.Done { break } if err != nil { return err } if resp != nil { c.list = append(c.list, resp.GetName()) } } } return nil } func (c *Client) Do(ctx context.Context, request *types.Request) (*types.Response, error) { m, err := parseMetadata(request.Metadata, c.opts) if err != nil { return nil, err } if m.project == "" { m.project = c.parrantProject } name := fmt.Sprintf("projects/%s/locations/%s/functions/%s", m.project, m.location, m.name) if m.location == "" { for _, n := range c.list { if strings.Contains(n, m.name) && strings.Contains(n, m.project) { m.location = "added from match" name = n break } } } if m.location == "" { return nil, fmt.Errorf("no location found for function") } cfo := &functionspb.CallFunctionRequest{ Name: name, Data: string(request.Data), } res, err := c.client.CallFunction(ctx, cfo) if err != nil { return nil, err } if res.Error != "" { return nil, fmt.Errorf(res.Error) } return types.NewResponse(). SetMetadataKeyValue("result", res.Result). SetMetadataKeyValue("execution_id", res.ExecutionId). SetData([]byte(res.Result)), nil } func (c *Client) Stop() error { if c.client != nil { return c.client.Close() } return nil } <file_sep># Kubemq lambda target Connector Kubemq aws-lambda target connector allows services using kubemq server to access aws lambda service. ## Prerequisites The following required to run the aws-lambda target connector: - kubemq cluster - aws account with lambda active service - kubemq-targets deployment ## Configuration lambda target connector configuration properties: | Properties Key | Required | Description | Example | |:---------------|:---------|:-------------------------------------------|:----------------------------| | aws_key | yes | aws key | aws key supplied by aws | | aws_secret_key | yes | aws secret key | aws secret key supplied by aws | | region | yes | region | aws region | | token | no | aws token ("default" empty string | aws token | Example: ```yaml bindings: - name: kubemq-query-aws-lambda source: kind: kubemq.query name: kubemq-query properties: address: "kubemq-cluster:50000" client_id: "kubemq-query-aws-lambda-connector" auth_token: "" channel: "query.aws.lambda" group: "" auto_reconnect: "true" reconnect_interval_seconds: "1" max_reconnects: "0" target: kind: aws.lambda name: aws-lambda properties: aws_key: "id" aws_secret_key: 'json' region: "region" token: "" ``` ## Usage ### List Lambda List all lambdas List Lambda: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:----------------------------------------|:-------------------------------------------| | method | yes | type of method | "list" | Example: ```json { "metadata": { "method": "list" }, "data": null } ``` ### Create Lambda create a new lambda. Create Lambda: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "create" | | zip_file_name | yes | name of the zip file | "file.zip" | | handler_name | yes | lambda handler name | "handler-path" | | role | yes | aws role name | "arn:aws:iam::0000000:myRole" | | runtime | yes | lambda runtime version | see https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html| | function_name | yes | lambda function name | string | | data | yes | the function code , in byte array | byte array | | memory_size | no | memory_size needed default of 256 | int | | timeout | no | timeout set for task default of 15 (Seconds) | int | | description | no | function description default of "" | string | Example: ```json { "metadata": { "method": "create", "zip_file_name": "myfile.zip", "handler_name": "myhandler", "role": "arn:aws:iam::0000000:myRole", "runtime": "nodejs12.x", "function_name": "testfunction", "memory_size": "256", "timeout": "3", "description": "my awesome testing method" }, "data": "<KEY> } ``` ### Run Lambda run a specific lambda Run Lambda: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "run" | | function_name | yes | lambda function name | string | | data | yes | the run request code , in byte array, must be base64 encoded json | byte array | | dry-run | no | run function in dry run mode | "true", "false" | "false"| Example: ```json { "metadata": { "method": "run", "function_name": "testfunction", "dry-run": "false" }, "data": "eyJ0ZXN0IjogInRlc3QifQ==" } ``` ### Delete Lambda Delete Lambda: | Metadata Key | Required | Description | Possible values | |:------------------|:---------|:------------------------------------------------|:-------------------------------------------| | method | yes | type of method | "delete" | | function_name | yes | lambda function name | string | Example: ```json { "metadata": { "method": "delete", "function_name": "testfunction" }, "data": null } ``` <file_sep>package elastic import ( "fmt" "github.com/kubemq-io/kubemq-targets/config" ) type options struct { urls []string sniff bool username string password string } func parseOptions(cfg config.Spec) (options, error) { o := options{} var err error o.urls, err = cfg.Properties.MustParseStringList("urls") if err != nil { return options{}, fmt.Errorf("error parsing urls, %w", err) } o.sniff = cfg.Properties.ParseBool("sniff", true) o.username = cfg.Properties.ParseString("username", "") o.password = cfg.Properties.ParseString("password", "") return o, nil } <file_sep>package events import ( "testing" "github.com/kubemq-io/kubemq-targets/config" "github.com/stretchr/testify/require" ) func TestOptions_parseOptions(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "valid options", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "<PASSWORD>-auth token", "channel": "some-channel", "group": "", "concurrency": "1", "response_channel": "", "auto_reconnect": "true", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "2", }, }, wantErr: false, }, { name: "invalid options - bad address", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "badaddress", }, }, wantErr: true, }, { name: "invalid options - no channel", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "some-auth token", "channel": "", "group": "", "response_channel": "", "auto_reconnect": "true", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "2", }, }, wantErr: true, }, { name: "valid options - bad auto reconnect", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "some-auth token", "channel": "some-channel", "group": "", "response_channel": "", "auto_reconnect": "some-bad-error", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "2", }, }, wantErr: false, }, { name: "valid options - bad reconnect interval", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "some-auth token", "channel": "some-channel", "group": "", "response_channel": "", "auto_reconnect": "true", "reconnect_interval_seconds": "-1", "max_reconnects": "0", "sources": "2", }, }, wantErr: true, }, { name: "valid options - bad sources", cfg: config.Spec{ Name: "kubemq-rpc", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "", "auth_token": "some-auth token", "channel": "some-channel", "group": "", "response_channel": "", "auto_reconnect": "true", "reconnect_interval_seconds": "1", "max_reconnects": "0", "sources": "-1", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { _, err := parseOptions(tt.cfg) if tt.wantErr { require.Error(t, err) return } else { require.NoError(t, err) } }) } } <file_sep>helm repo add bitnami https://charts.bitnami.com/bitnami helm install rabbitmq bitnami/rabbitmq --set auth.username=rabbitmq --set auth.password=<PASSWORD> --set service.type=LoadBalancer helm delete rabbitmq kubectl port-forward --namespace default svc/rabbitmq 5672:5672 kubectl port-forward --namespace default svc/rabbitmq 15672:15672 kubectl create secret generic rabbitmq-certificates --from-file=./ca.crt --from-file=./tls.crt --from-file=./tls.key helm install rabbitmq bitnami/rabbitmq --set auth.username=rabbitmq --set auth.password=<PASSWORD> --set auth.tls.enabled=true --set auth.tls.existingSecret=rabbitmq-certificates helm install rabbitmq bitnami/rabbitmq --set auth.username=rabbitmq --set auth.password=<PASSWORD> --set auth.tls.enabled=true --set auth.tls.autoGenerated=true --set auth.tls.failIfNoPeerCert=true <file_sep>package elastic import ( "context" "encoding/json" "os" "testing" "time" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/types" "github.com/olivere/elastic/v7" "github.com/stretchr/testify/require" ) const mapping = `{ "settings": { "number_of_shards": 1, "number_of_replicas": 0 }, "mappings": { "properties": { "id": { "type": "keyword" }, "data": { "type": "text" } } } }` const ( elasticUrl = "http://localhost:9200" testIndex = "log" ) type log struct { Id string `json:"id"` Data string `json:"data"` } func (l *log) marshal() []byte { b, _ := json.Marshal(l) return b } func newLog(id, data string) *log { return &log{ Id: id, Data: data, } } func TestMain(m *testing.M) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() client, err := elastic.NewClient(elastic.SetURL(elasticUrl), elastic.SetSniff(false)) if err != nil { panic(err) } _, _, err = client.Ping(elasticUrl).Do(ctx) if err != nil { panic(err) } exists, err := client.IndexExists(testIndex).Do(ctx) if err != nil { panic(err) } if exists { _, err := client.DeleteIndex(testIndex).Do(ctx) if err != nil { panic(err) } } _, err = client.CreateIndex(testIndex).BodyString(mapping).Do(ctx) if err != nil { panic(err) } exitVal := m.Run() os.Exit(exitVal) } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, wantErr: false, }, { name: "init - bad urls", cfg: config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "scheme://localhost:9200", "sniff": "false", "username": "", "password": "", "retries_backoff_seconds": "0", }, }, wantErr: true, }, { name: "init - bad options - no urls", cfg: config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "", "sniff": "false", "username": "", "password": "", "retries_backoff_seconds": "0", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantSetErr %v", err, tt.wantErr) return } }) } } func TestClient_Set_Get(t *testing.T) { tests := []struct { name string cfg config.Spec setRequest *types.Request getRequest *types.Request wantSetResponse *types.Response wantGetResponse *types.Response wantSetErr bool wantGetErr bool }{ { name: "valid set get request", cfg: config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("id", "some-id"). SetMetadataKeyValue("index", "log"). SetData(newLog("some-id", "some-data").marshal()), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("index", "log"). SetMetadataKeyValue("id", "some-id"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("id", "some-id"). SetMetadataKeyValue("result", "created"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("id", "some-id"). SetData(newLog("some-id", "some-data").marshal()), wantSetErr: false, wantGetErr: false, }, { name: "update set get request", cfg: config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("id", "some-id"). SetMetadataKeyValue("index", "log"). SetData(newLog("some-id", "some-data-2").marshal()), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("index", "log"). SetMetadataKeyValue("id", "some-id"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("id", "some-id"). SetMetadataKeyValue("result", "updated"), wantGetResponse: types.NewResponse(). SetMetadataKeyValue("id", "some-id"). SetData(newLog("some-id", "some-data-2").marshal()), wantSetErr: false, wantGetErr: false, }, { name: "bad set - invalid index", cfg: config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("id", "some-id"). SetMetadataKeyValue("index", "bad-index"). SetData(nil), getRequest: nil, wantSetResponse: nil, wantGetResponse: nil, wantSetErr: true, wantGetErr: false, }, { name: "valid set - not found index", cfg: config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, setRequest: types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("id", "some-id-2"). SetMetadataKeyValue("index", "log"). SetData(newLog("some-id-2", "some-data").marshal()), getRequest: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("index", "log"). SetMetadataKeyValue("id", "bad-id"), wantSetResponse: types.NewResponse(). SetMetadataKeyValue("id", "some-id-2"). SetMetadataKeyValue("result", "created"), wantGetResponse: nil, wantSetErr: false, wantGetErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) gotSetResponse, err := c.Do(ctx, tt.setRequest) if tt.wantSetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotSetResponse) require.EqualValues(t, tt.wantSetResponse, gotSetResponse) gotGetResponse, err := c.Do(ctx, tt.getRequest) if tt.wantGetErr { require.Error(t, err) return } require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, tt.wantGetResponse, gotGetResponse) }) } } func TestClient_Delete(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, config.Spec{ Name: "elastic-target", Kind: "", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, nil) key := uuid.New().String() require.NoError(t, err) setRequest := types.NewRequest(). SetMetadataKeyValue("method", "set"). SetMetadataKeyValue("index", testIndex). SetMetadataKeyValue("id", key). SetData(newLog(key, "some-data").marshal()) _, err = c.Do(ctx, setRequest) require.NoError(t, err) getRequest := types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("index", testIndex). SetMetadataKeyValue("id", key) gotGetResponse, err := c.Do(ctx, getRequest) require.NoError(t, err) require.NotNil(t, gotGetResponse) require.EqualValues(t, newLog(key, "some-data").marshal(), gotGetResponse.Data) delRequest := types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("index", testIndex). SetMetadataKeyValue("id", key) _, err = c.Do(ctx, delRequest) require.NoError(t, err) gotGetResponse, err = c.Do(ctx, getRequest) require.Error(t, err) require.Nil(t, gotGetResponse) delRequest = types.NewRequest(). SetMetadataKeyValue("method", "delete"). SetMetadataKeyValue("index", "bad-index"). SetMetadataKeyValue("id", key) _, err = c.Do(ctx, delRequest) require.Error(t, err) } func TestClient_Do(t *testing.T) { tests := []struct { name string cfg config.Spec request *types.Request wantErr bool }{ { name: "bad request - bad method", cfg: config.Spec{ Name: "elastic", Kind: "elastic", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "bad method"). SetMetadataKeyValue("id", "some-id"), wantErr: true, }, { name: "bad request - no index", cfg: config.Spec{ Name: "elastic", Kind: "elastic", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("id", "some-id"), wantErr: true, }, { name: "bad request - no id", cfg: config.Spec{ Name: "elastic", Kind: "elastic", Properties: map[string]string{ "urls": "http://localhost:9200", "sniff": "false", "username": "", "password": "", }, }, request: types.NewRequest(). SetMetadataKeyValue("method", "get"). SetMetadataKeyValue("index", testIndex), wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() c := New() err := c.Init(ctx, tt.cfg, nil) require.NoError(t, err) _, err = c.Do(ctx, tt.request) if tt.wantErr { require.Error(t, err) return } require.NoError(t, err) }) } } <file_sep>package elasticsearch import ( "context" "io/ioutil" "net/http" "strings" "time" "github.com/kubemq-hub/builder/connector/common" "github.com/kubemq-io/kubemq-targets/pkg/logger" "github.com/kubemq-io/kubemq-targets/types" "github.com/aws/aws-sdk-go/aws/credentials" signer "github.com/aws/aws-sdk-go/aws/signer/v4" "github.com/kubemq-io/kubemq-targets/config" ) type Client struct { log *logger.Logger opts options signer *signer.Signer } func New() *Client { return &Client{} } func (c *Client) Connector() *common.Connector { return Connector() } func (c *Client) Init(ctx context.Context, cfg config.Spec, log *logger.Logger) error { c.log = log if c.log == nil { c.log = logger.NewLogger(cfg.Kind) } var err error c.opts, err = parseOptions(cfg) if err != nil { return err } signer := signer.NewSigner(credentials.NewStaticCredentials(c.opts.awsKey, c.opts.awsSecretKey, c.opts.token)) c.signer = signer return nil } func (c *Client) Do(ctx context.Context, req *types.Request) (*types.Response, error) { meta, err := parseMetadata(req.Metadata) if err != nil { return nil, err } httpClient := &http.Client{} reader := strings.NewReader(meta.json) request, err := http.NewRequestWithContext(ctx, meta.method, meta.endpoint, reader) if err != nil { return nil, err } request.Header.Add("Content-Type", "application/json") _, err = c.signer.Sign(request, reader, meta.service, meta.region, time.Now()) if err != nil { return nil, err } resp, err := httpClient.Do(request) if err != nil { return nil, err } defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } return types.NewResponse(). SetMetadataKeyValue("result", "ok"). SetData(b), nil } func (c *Client) Stop() error { return nil } <file_sep>package queue import ( "fmt" "time" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultMaxMessages = 32 DefaultVisibilityTimeout = 100000000 DefaultTimeToLive = 100000000 ) var methodsMap = map[string]string{ "create": "create", "get_messages_count": "get_messages_count", "peek": "peek", "push": "push", "pop": "pop", "delete": "delete", } type metadata struct { method string queueName string serviceUrl string maxMessages int32 visibilityTimeout time.Duration timeToLive time.Duration queueMetadata map[string]string } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } m.queueName, err = meta.MustParseString("queue_name") if err != nil { return metadata{}, fmt.Errorf("error parsing queue_name , %w", err) } m.serviceUrl, err = meta.MustParseString("service_url") if err != nil { return metadata{}, fmt.Errorf("error parsing service_url , %w", err) } queueMetadata, err := meta.MustParseJsonMap("queue_metadata") if err != nil { return metadata{}, fmt.Errorf("error parsing queue_metadata, %w", err) } else { m.queueMetadata = queueMetadata } m.maxMessages = int32(meta.ParseInt("max_messages", DefaultMaxMessages)) if err != nil { return metadata{}, fmt.Errorf("error parsing max_messages, %w", err) } m.visibilityTimeout = meta.ParseTimeDuration("visibility_timeout", DefaultVisibilityTimeout) m.timeToLive = meta.ParseTimeDuration("time_to_live", DefaultTimeToLive) m.timeToLive = m.timeToLive * time.Second return m, nil } <file_sep>package consulkv import ( "fmt" "time" "github.com/kubemq-io/kubemq-targets/types" ) const ( defaultKey = "" defaultNear = "" defaultFilter = "" defaultPrefix = "" defaultAllowStale = false defaultRequireConsistent = false defaultUserCache = false defaultMaxAge = 36000 defaultStaleIfError = 36000 ) var methodsMap = map[string]string{ "get": "get", "put": "put", "list": "list", "delete": "delete", } type metadata struct { method string key string near string filter string prefix string allowStale bool requireConsistent bool useCache bool maxAge time.Duration staleIfError time.Duration } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, fmt.Errorf("error parsing method, %w", err) } m.key = meta.ParseString("key", defaultKey) m.near = meta.ParseString("near", defaultNear) m.filter = meta.ParseString("filter", defaultFilter) m.prefix = meta.ParseString("prefix", defaultPrefix) m.allowStale = meta.ParseBool("allow_stale", defaultAllowStale) m.requireConsistent = meta.ParseBool("require_consistent", defaultRequireConsistent) m.useCache = meta.ParseBool("user_cache", defaultUserCache) maxAge, err := meta.ParseIntWithRange("max_age", defaultMaxAge, 0, 2147483647) if err != nil { return metadata{}, fmt.Errorf("error parsing max_age, %w", err) } m.maxAge = time.Duration(maxAge) * time.Millisecond staleIfError, err := meta.ParseIntWithRange("stale_if_error", defaultStaleIfError, 0, 2147483647) if err != nil { return metadata{}, fmt.Errorf("error parsing stale_if_error, %w", err) } m.staleIfError = time.Duration(staleIfError) * time.Millisecond return m, nil } <file_sep>package bigtable import ( "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.bigtable"). SetDescription("GCP Bigtable Target"). SetName("Big Table"). SetProvider("GCP"). SetCategory("Store"). SetTags("db", "sql", "distributed", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("project_id"). SetTitle("Project ID"). SetDescription("Set GCP project ID"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("instance"). SetDescription("Set Bigtable instance"). SetMust(true). SetDefault(""), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set GCP Bigtable execution method"). SetOptions([]string{"write", "write_batch", "get_row", "get_all_rows", "delete_row", "get_tables", "create_table", "delete_table", "create_column_family", "get_all_rows_by_column"}). SetDefault("write"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("table_name"). SetKind("string"). SetDescription("Set Bigtable table name"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("column_family"). SetKind("string"). SetDescription("Set Bigtable column family"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("row_key_prefix"). SetKind("string"). SetDescription("Set Bigtable row key prefix"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("column_name"). SetKind("string"). SetDescription("Set Bigtable column name"). SetDefault(""). SetMust(false), ) } <file_sep>package queue import ( "context" "fmt" "testing" "time" "github.com/kubemq-io/kubemq-go" "github.com/kubemq-io/kubemq-targets/config" "github.com/kubemq-io/kubemq-targets/middleware" "github.com/kubemq-io/kubemq-targets/pkg/uuid" "github.com/kubemq-io/kubemq-targets/targets/null" "github.com/kubemq-io/kubemq-targets/types" "github.com/stretchr/testify/require" "github.com/kubemq-io/kubemq-targets/targets" ) func setupClient(ctx context.Context, target middleware.Middleware, channel string) (*Client, error) { c := New() err := c.Init(ctx, config.Spec{ Name: "kubemq-queue", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "some-clients-id", "auth_token": "", "channel": channel, "response_channel": "queue.stream.response", "batch_size": "1", "wait_timeout": "60", "sources": "1", }, }, "", nil) if err != nil { return nil, err } err = c.Start(ctx, target) if err != nil { return nil, err } time.Sleep(time.Second) return c, nil } func sendQueueMessage(t *testing.T, ctx context.Context, req *types.Request, sendChannel, respChannel string) (*types.Response, error) { client, err := kubemq.NewClient(ctx, kubemq.WithAddress("localhost", 50000), kubemq.WithClientId(uuid.New().String()), kubemq.WithTransportType(kubemq.TransportTypeGRPC)) if err != nil { return nil, err } go func() { time.Sleep(time.Second) result, err := client.SetQueueMessage( req.ToQueueMessage()). SetChannel(sendChannel). SetPolicyMaxReceiveCount(2). Send(ctx) require.NoError(t, err) require.NotNil(t, result) require.False(t, result.IsError) }() if respChannel != "" { respMsgs, err := client.ReceiveQueueMessages(ctx, client.NewReceiveQueueMessagesRequest(). SetChannel(respChannel). SetClientId(uuid.New().String()). SetMaxNumberOfMessages(1). SetWaitTimeSeconds(5)) if err != nil { return nil, err } if len(respMsgs.Messages) == 0 { return nil, fmt.Errorf("no messages") } return types.ParseResponse(respMsgs.Messages[0].Body) } return nil, nil } func TestClient_processQueue(t *testing.T) { tests := []struct { name string target targets.Target respChannel string req *types.Request wantResp *types.Response sendCh string wantErr bool }{ { name: "request", target: &null.Client{ Delay: time.Second, DoError: nil, ResponseError: nil, }, respChannel: "queue.stream.response", req: types.NewRequest().SetData([]byte("some-data")), wantResp: types.NewResponse().SetData([]byte("some-data")), sendCh: uuid.New().String(), wantErr: false, }, { name: "request with target do error", target: &null.Client{ Delay: 0, DoError: fmt.Errorf("do-error"), ResponseError: nil, }, respChannel: "queue.stream.response", req: types.NewRequest().SetData([]byte("some-data")), wantResp: types.NewResponse().SetError(fmt.Errorf("do-error")), sendCh: uuid.New().String(), wantErr: false, }, { name: "request with target remote error", target: &null.Client{ Delay: 0, DoError: nil, ResponseError: fmt.Errorf("do-error"), }, respChannel: "queue.stream.response", req: types.NewRequest().SetData([]byte("some-data")), wantResp: types.NewResponse().SetError(fmt.Errorf("do-error")), sendCh: uuid.New().String(), wantErr: false, }, { name: "bad request", target: &null.Client{ Delay: 0, DoError: nil, ResponseError: nil, }, req: nil, wantResp: nil, sendCh: uuid.New().String(), wantErr: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c, err := setupClient(ctx, tt.target, tt.sendCh) require.NoError(t, err) defer func() { _ = c.Stop() }() gotResp, err := sendQueueMessage(t, ctx, tt.req, tt.sendCh, tt.respChannel) if tt.wantErr { require.Error(t, err) return } require.EqualValues(t, tt.wantResp, gotResp) }) } } func TestClient_Init(t *testing.T) { tests := []struct { name string cfg config.Spec wantErr bool }{ { name: "init", cfg: config.Spec{ Name: "kubemq-queue", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "some-clients-id", "auth_token": "some-auth token", "channel": "some-channel", "response_channel": "some-response-channel", "batch_size": "1", "wait_timeout": "60", "sources": "2", }, }, wantErr: false, }, { name: "init - error", cfg: config.Spec{ Name: "kubemq-queue", Kind: "", Properties: map[string]string{ "host": "localhost", "port": "-1", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() if err := c.Init(ctx, tt.cfg, "", nil); (err != nil) != tt.wantErr { t.Errorf("Init() error = %v, wantErr %v", err, tt.wantErr) } }) } } func TestClient_Start(t *testing.T) { tests := []struct { name string target targets.Target cfg config.Spec wantErr bool }{ { name: "start", target: &null.Client{ Delay: 0, DoError: nil, ResponseError: nil, }, cfg: config.Spec{ Name: "kubemq-queue", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "some-clients-id", "auth_token": "<PASSWORD> token", "channel": "some-channel", "response_channel": "some-response-channel", "batch_size": "1", "wait_timeout": "60", "sources": "2", }, }, wantErr: false, }, { name: "start - bad target", target: nil, cfg: config.Spec{ Name: "kubemq-queue", Kind: "", Properties: map[string]string{ "address": "localhost:50000", "client_id": "some-clients-id", "auth_token": "<PASSWORD>", "channel": "some-channel", "response_channel": "some-response-channel", "batch_size": "1", "wait_timeout": "60", "sources": "2", }, }, wantErr: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() c := New() _ = c.Init(ctx, tt.cfg, "", nil) if err := c.Start(ctx, tt.target); (err != nil) != tt.wantErr { t.Errorf("Start() error = %v, wantErr %v", err, tt.wantErr) } }) } } <file_sep>package rabbitmq import ( "fmt" "math" "strconv" "time" "github.com/kubemq-io/kubemq-targets/types" "github.com/streadway/amqp" ) type metadata struct { queue string exchange string mandatory bool immediate bool deliveryMode int priority int correlationId string replyTo string expiration time.Duration } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.queue, err = meta.MustParseString("queue") if err != nil { return metadata{}, fmt.Errorf("error parsing queue name, %w", err) } m.exchange = meta.ParseString("exchange", "") m.mandatory = meta.ParseBool("mandatory", false) m.immediate = meta.ParseBool("immediate", false) m.deliveryMode, err = meta.ParseIntWithRange("delivery_mode", 1, 0, 2) if err != nil { return metadata{}, fmt.Errorf("error parsing delivery mode, %w", err) } m.priority, err = meta.ParseIntWithRange("priority", 0, 0, 9) if err != nil { return metadata{}, fmt.Errorf("error parsing priority, %w", err) } m.correlationId = meta.ParseString("correlation_id", "") m.replyTo = meta.ParseString("reply_to", "") expirySeconds, err := meta.ParseIntWithRange("expiry_seconds", math.MaxInt32, 0, math.MaxInt32) if err != nil { return metadata{}, fmt.Errorf("error parsing expiry_seconds, %w", err) } m.expiration = time.Duration(expirySeconds) * time.Second return m, nil } func (m metadata) amqpMessage(data []byte) amqp.Publishing { return amqp.Publishing{ Headers: amqp.Table{}, ContentType: "text/plain", ContentEncoding: "", DeliveryMode: uint8(m.deliveryMode), Priority: uint8(m.priority), CorrelationId: m.correlationId, ReplyTo: m.replyTo, Expiration: strconv.FormatInt(m.expiration.Milliseconds(), 10), Body: data, } } <file_sep>package pubsub import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("gcp.pubsub"). SetDescription("GCP PubSub Target"). SetName("PubSub"). SetProvider("GCP"). SetCategory("Messaging"). SetTags("streaming", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("project_id"). SetTitle("Project ID"). SetDescription("Set GCP project ID"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("multilines"). SetName("credentials"). SetTitle("Json Credentials"). SetDescription("Set GCP credentials"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("retries"). SetDescription("Set PubSub sending message retries"). SetMust(false). SetDefault("0"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("topic_id"). SetKind("string"). SetDescription("Set PubSub request topic id"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetName("tags"). SetKind("string"). SetDescription("Set PubSub request tags"). SetDefault(""). SetMust(false), ) } <file_sep>package queue import ( "math" "github.com/kubemq-hub/builder/connector/common" ) func Connector() *common.Connector { return common.NewConnector(). SetKind("azure.storage.queue"). SetDescription("Azure Queue Storage Target"). SetName("Queue"). SetProvider("Azure"). SetCategory("Storage"). SetTags("queue", "messaging", "db", "cloud", "managed"). AddProperty( common.NewProperty(). SetKind("string"). SetName("storage_access_key"). SetDescription("Set Queue Storage storage access key"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("storage_account"). SetDescription("Set Queue Storage storage account"). SetMust(true). SetDefault(""), ). AddProperty( common.NewProperty(). SetKind("string"). SetName("policy"). SetDescription("Set Queue Storage retry policy"). SetOptions([]string{"retry_policy_exponential", "retry_policy_fixed"}). SetMust(true). SetDefault("retry_policy_exponential"), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_tries"). SetDescription("Set Queue Storage max tries"). SetMust(false). SetDefault("1"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("try_timeout"). SetTitle("Try Timout (milliseconds)"). SetDescription("Set Queue Storage try timeout in milliseconds"). SetMust(false). SetDefault("1000"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("retry_delay"). SetDescription("Set Queue Storage retry delay in milliseconds"). SetMust(false). SetDefault("60000"). SetMin(1). SetMax(math.MaxInt32), ). AddProperty( common.NewProperty(). SetKind("int"). SetName("max_retry_delay"). SetDescription("Set Queue Storage max retry delay in milliseconds"). SetMust(false). SetDefault("180000"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetName("method"). SetKind("string"). SetDescription("Set Queue Storage execution method"). SetOptions([]string{"create", "get_messages_count", "peek", "push", "pop", "delete"}). SetDefault("create"). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("queue_name"). SetKind("string"). SetDescription("Set Queue Storage queue name"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("service_url"). SetKind("string"). SetDescription("Set Queue Storage service url"). SetDefault(""). SetMust(true), ). AddMetadata( common.NewMetadata(). SetName("queue_metadata"). SetKind("string"). SetDescription("Set Queue Storage queue metadata"). SetDefault(""). SetMust(false), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("max_messages"). SetDescription("Set Queue Storage max messages"). SetMust(false). SetDefault("32"). SetMin(1). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("visibility_timeout"). SetDescription("Set Queue Storage visibility timeout"). SetMust(false). SetDefault("100000000"). SetMin(0). SetMax(math.MaxInt32), ). AddMetadata( common.NewMetadata(). SetKind("int"). SetName("time_to_live"). SetDescription("Set Queue Storage time to live"). SetMust(false). SetDefault("100000000"). SetMin(1). SetMax(math.MaxInt32), ) } <file_sep>package kinesis import ( "fmt" "github.com/kubemq-io/kubemq-targets/types" ) const ( DefaultLimit = 1 DefaultShardCount = 1 ) type metadata struct { method string streamName string partitionKey string shardID string streamARN string shardIteratorType string shardIteratorID string consumerName string limit int64 shardCount int64 } var methodsMap = map[string]string{ "list_streams": "list_streams", "list_stream_consumers": "list_stream_consumers", "create_stream": "create_stream", "delete_stream": "delete_stream", "put_record": "put_record", "put_records": "put_records", "get_records": "get_records", "get_shard_iterator": "get_shard_iterator", "list_shards": "list_shards", "create_stream_consumer": "create_stream_consumer", } func parseMetadata(meta types.Metadata) (metadata, error) { m := metadata{} var err error m.method, err = meta.ParseStringMap("method", methodsMap) if err != nil { return metadata{}, meta.GetValidMethodTypes(methodsMap) } m.shardCount = int64(meta.ParseInt("shard_count", DefaultShardCount)) m.limit = int64(meta.ParseInt("limit", DefaultLimit)) if m.method != "list_streams" && m.method != "list_stream_consumers" && m.method != "get_record" && m.method != "create_stream_consumer" { m.streamName, err = meta.MustParseString("stream_name") if err != nil { return metadata{}, fmt.Errorf("error parsing stream_name, %w", err) } } switch m.method { case "put_record": m.partitionKey, err = meta.MustParseString("partition_key") if err != nil { return metadata{}, fmt.Errorf("partition_key is required when using %s,error parsing partition_key, %w", m.method, err) } case "get_shard_iterator": m.shardID, err = meta.MustParseString("shard_id") if err != nil { return metadata{}, fmt.Errorf("shard_id is required when using %s error parsing shard_id, %w", m.method, err) } m.shardIteratorType, err = meta.MustParseString("shard_iterator_type") if err != nil { return metadata{}, fmt.Errorf("shard_iterator_type is required when using %s,error parsing shard_iterator_type, %w", m.method, err) } case "get_records": m.shardIteratorID, err = meta.MustParseString("shard_iterator_id") if err != nil { return metadata{}, fmt.Errorf("shard_iterator_id is required when using %s,error parsing shard_iterator_id, %w", m.method, err) } case "list_stream_consumers": m.streamARN, err = meta.MustParseString("stream_arn") if err != nil { return metadata{}, fmt.Errorf("stream_arn error is required when using %s,parsing stream_arn, %w", m.method, err) } case "create_stream_consumer": m.streamARN, err = meta.MustParseString("stream_arn") if err != nil { return metadata{}, fmt.Errorf("stream_arn error is required when using %s,parsing stream_arn, %w", m.method, err) } m.consumerName, err = meta.MustParseString("consumer_name") if err != nil { return metadata{}, fmt.Errorf("consumer_name error is required when using %s,parsing consumer_name, %w", m.method, err) } } return m, nil }
574ae56fddfd250a8f758d34800f9306eaf8bdc2
[ "Markdown", "Go", "Go Module", "Dockerfile", "Shell" ]
356
Markdown
kubemq-hub/kubemq-targets
ba3cfeddcfb195258f4f1ea10f00cc2b2f46a478
02b42f244cd47f91688e7f5641c1264434b9fe36
refs/heads/master
<repo_name>belgrades/maestria<file_sep>/README.md # maestria Tesis de Maestria <file_sep>/mysql.py import mysql.connector import cplex import cplex.exceptions config = { 'user': 'belgrades', 'password': '<PASSWORD>', 'host': '127.0.0.1', 'database': 'mlb', 'raise_on_warnings': True } cnx = mysql.connector.connect(**config) cursor = cnx.cursor() query = ("SELECT * FROM teams LIMIT 10") cursor.execute(query) for i in cursor: print(i) cnx.close()
45ccc2e4152526074f60e1f4d51c6c977ed03630
[ "Markdown", "Python" ]
2
Markdown
belgrades/maestria
0c67dfd36c9b75ddc45643f97ca77413df078665
3d5726e9fe8f2e4f89c19056ce06cdeb8821dda7
refs/heads/main
<repo_name>armennmuradyan/django_projects<file_sep>/first_project/to_do/models.py from django.db import models from helpers.choices import STATUS_CHOICES class Task(models.Model): title = models.CharField(max_length=256) description = models.TextField() status = models.IntegerField(choices=STATUS_CHOICES) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title<file_sep>/first_project/to_do/urls.py from django.urls import path from to_do import views urlpatterns = [ path('', views.home), path('newurl/', views.new_url), path("filtered_data/",views.filtered_data) ]<file_sep>/first_project/helpers/choices.py STATUS_CHOICES = ( (0, "New"), (1, "Doing"), (2, "Done"), )<file_sep>/new_project/new_app/views.py from django.shortcuts import render, HttpResponse from new_app.models import Task def home(request): tasks = Task.objects.all() # return HttpResponse("django app {}".format(tasks[0])) return render(request, "new_app/home.html")<file_sep>/new_project/new_app/admin.py from django.contrib import admin from new_app.models import Task class TaskAdmin(admin.ModelAdmin): list_display = ("id", "name", "status") fields = ("name", "status", 'created_at') readonly_fields = ('created_at',) admin.site.register(Task, TaskAdmin)<file_sep>/first_project/to_do/views.py from django.shortcuts import HttpResponse from to_do.models import Task def home(request): tasks = Task.objects.all() return HttpResponse("Hello from Django app{}{}".format(*tasks)) def new_url(request): tasks = Task(title="Task 4 ", description="test", status=0) tasks.save() return HttpResponse("Okay") def filtered_data(request): task = Task.objects.get(id=1, title="New one") # print(task.query) return HttpResponse(task)<file_sep>/new_project/new_app/urls.py from django.urls import path from new_app import views urlpatterns = [ path('home', views.home) ]<file_sep>/second_project/to_do/views.py from django.http import HttpResponse from django.shortcuts import render from datetime import datetime def home(request): return HttpResponse("Hello from Django app") def greeting(request): return HttpResponse("Hi everyone") def introduction(request): return HttpResponse("second project") def date_time(request): return HttpResponse(datetime.now()) def task(request): dict_ = {} for i in range(16): dict_[i] = i**2 print(dict_) return HttpResponse(dict_)<file_sep>/first_project/to_do/admin.py from django.contrib import admin from to_do.models import Task admin.site.register(Task)<file_sep>/second_project/to_do/urls.py from django.urls import path from to_do import views urlpatterns = [ path('', views.home), path('greeting/', views.greeting), path('intro/', views.introduction), path('dt/', views.date_time), path('task/', views.task), ]
c675cfd25cf3ced5664e987a1fab1fdbd7289f2a
[ "Python" ]
10
Python
armennmuradyan/django_projects
efacebf49ad3a22eb138563a3436b786419807f4
02fac0c07ec737391961b6b229727e2267936eb0
refs/heads/master
<repo_name>froala/wysiwyg-rails<file_sep>/lib/wysiwyg-rails/engine.rb module WYSIWYG module Rails class Engine < ::Rails::Engine initializer 'froala.assets.precompile', group: :all do |app| app.config.assets.precompile += %W( froala_editor.min.js plugins/*.js languages/*.js froala_editor.min.css froala_style.min.css plugins/*.css themes/*.css ) end end end end<file_sep>/build-push-to-nexus.sh #!/bin/bash if [ ${TRAVIS_PULL_REQUEST} != "false" ]; then echo "Not publishing a pull request !!!" && exit 0; fi export BRANCH_NAME=`echo "${TRAVIS_BRANCH}" | tr '[:upper:]' '[:lower:]'` case "${BRANCH_NAME}" in dev*) echo "Branch ${TRAVIS_BRANCH} is eligible for CI/CD" ;; ao-dev*)echo "Branch ${TRAVIS_BRANCH} is eligible for CI/CD" ;; qa*) echo "Branch ${TRAVIS_BRANCH} is eligible for CI/CD" ;; qe*) echo "Branch ${TRAVIS_BRANCH} is eligible for CI/CD" ;; rc*) echo "Branch ${TRAVIS_BRANCH} is eligible for CI/CD" ;; release-master*) echo "Branch ${TRAVIS_BRANCH} is eligible for CI/CD" ;; ft*) echo "Branch ${TRAVIS_BRANCH} is eligible for CI" ;; bf*) echo "Branch ${TRAVIS_BRANCH} is eligible for CI" ;; *) echo "Not a valid branch name for CI/CD" && exit -1;; esac echo $TRAVIS_BRANCH echo ${DEPLOYMENT_SERVER} export SHORT_COMMIT=`git rev-parse --short=7 ${TRAVIS_COMMIT}` echo "short commit $SHORT_COMMIT" sudo apt-get update && sudo apt-get install -y jq gem DEPENDENCIES=`cat wysiwyg-rails.gemspec | grep "gem.add_dependency"` sed -i -e "/.*end/d" wysiwyg-rails.gemspec echo ${DEPENDENCIES} >> wysiwyg-rails.gemspec echo "gem.metadata['allowed_push_host'] = 'https://nexus.tools.froala-infra.com/repository/Froala-rubygems-repo'" >> wysiwyg-rails.gemspec echo "end" >> wysiwyg-rails.gemspec echo "checking gemspecs file: " cat wysiwyg-rails.gemspec PACKAGE_NAME=`jq '.name' version.json | tr -d '"'` PACKAGE_VERSION=`jq '.version' version.json | tr -d '"'` wget --timeout=10 --no-check-certificate --user ${NEXUS_USER} --password ${NEXUS_USER_PWD} https://nexus.tools.froala-infra.com/repository/Froala-npm/${PACKAGE_NAME}/-/${PACKAGE_NAME}-${PACKAGE_VERSION}.tgz if [ $? -ne 0 ]; then echo "Error pulling core library from nexus" exit -1 fi tar -xvf ${PACKAGE_NAME}-${PACKAGE_VERSION}.tgz echo "Copying core library css & js to app/assets/stylesheets/ & app/assets/javascripts/ ......" /bin/cp -fr package/css/* app/assets/stylesheets/ /bin/cp -fr package/js/* app/assets/javascripts/ echo "Done ..." rm -rf package/ ${PACKAGE_NAME}-${PACKAGE_VERSION}.tgz gem install nexus gem build wysiwyg-rails.gemspec GEM_NAME=`ls -A wysiwyg-rails*.gem ` echo "Rails SDK gem filename $GEM_NAME" GEM_NAME2="" GEM_NAME2=`echo ${GEM_NAME} | awk -F'-' '{print $1}'` GEM_NAME2="${GEM_NAME2}-`echo ${GEM_NAME} | awk -F'-' '{print $2}'`" GEM_NAME2="${GEM_NAME2}-${TRAVIS_BRANCH}" GEM_NAME2="${GEM_NAME2}-`echo ${GEM_NAME} | awk -F'-' '{print $3}'`" echo "gem name : ${GEM_NAME2}" mv ${GEM_NAME} ${GEM_NAME2} NXS_PASS=`echo ${NEXUS_USER_PWD}` curl -k --user "${NEXUS_USER}:${NXS_PASS}" --upload-file ./${GEM_NAME2} https://nexus.tools.froala-infra.com/repository/Froala-raw-repo/rails/${GEM_NAME2} exit $? <file_sep>/lib/wysiwyg-rails.rb require "wysiwyg-rails/version" require "wysiwyg-rails/engine" if defined?(::Rails)<file_sep>/wysiwyg-rails.gemspec # -*- encoding: utf-8 -*- require File.expand_path('../lib/wysiwyg-rails/version', __FILE__) Gem::Specification.new do |gem| gem.authors = ["Froala Labs"] gem.email = ["<EMAIL>"] gem.description = "A beautiful WYSIWYG HTML text editor. High performance and modern design make it easy to use for developers and loved by users." gem.summary = "an asset gemification of the Froala WYSIWYG Editor library" gem.homepage = "https://github.com/froala/wysiwyg-rails" gem.licenses = ["MIT"] gem.files = Dir["{app,lib}/**/*"] + ["LICENSE" ,"Rakefile", "README.md"] gem.name = "wysiwyg-rails" gem.require_paths = ["lib"] gem.version = WYSIWYG::Rails::VERSION gem.add_dependency "railties", ">= 3.2.7", "< 7.1" end <file_sep>/README.md # Rails Froala WYSIWYG HTML Editor [![Travis](https://img.shields.io/travis/froala/wysiwyg-rails.svg)](http://travis-ci.org/froala/wysiwyg-rails) [![Gem](https://img.shields.io/gem/v/wysiwyg-rails.svg)](https://rubygems.org/gems/wysiwyg-rails/versions/2.1.0) [![Gem](https://img.shields.io/gem/dt/wysiwyg-rails.svg)](https://rubygems.org/gems/wysiwyg-rails/versions/2.1.0) [![license](https://img.shields.io/github/license/froala/wysiwyg-rails.svg)](https://rubygems.org/gems/wysiwyg-rails/versions/2.1.0) >wysiwyg-rails provides the [Froala WYSIWYG HTML Editor](https://froala.com/wysiwyg-editor) javascript and stylesheets as a Rails engine for use with the asset pipeline. ## Installation Add this to your Gemfile: ```ruby gem "wysiwyg-rails" ``` and run `bundle install`. ## Usage In your index.html.erb add ``` <script type="text/javascript" src = "../../assets/froala_editor.pkgd.min.js"></script> ``` To use third-party plugins add ``` <script type="text/javascript" src = "../../assets/third_party/font_awesome.min.js"></script> <script type="text/javascript" src = "../../assets/third_party/embedly.min.js"></script> <script type="text/javascript" src = "../../assets/third_party/image_tui.min.js"></script> <script type="text/javascript" src = "../../assets/third_party/spell_checker.min.js"</script> ``` Initialize editor by adding below in body of index.html.erb ``` new FroalaEditor('#edit', { }) ``` ## Options You can pass options to editor by including these in index.html.erb ``` new FroalaEditor('#editor', { options : value }); ``` ## Include in assets In your `application.css.scss`, include the css file: ```css /* @import "froala_editor.min"; @import "froala_style.min"; */ ``` If you want to use the dark theme, then you have to include `themes/dark.min.css` file too. In your `application.js.coffee`, include the JS file: ```coffeescript #= require froala_editor.min.js new FroalaEditor('selector',{ }); ``` If you need to use any of the [Available Plugins](https://froala.com/wysiwyg-editor/docs/plugins), then you should include those too in your `application.js.coffee` and `application.css.scss`. ```coffeescript # Include other plugins. #= require plugins/align.min.js #= require plugins/char_counter.min.js #= require plugins/code_beautifier.min.js #= require plugins/code_view.min.js #= require plugins/colors.min.js #= require plugins/emoticons.min.js #= require plugins/entities.min.js #= require plugins/file.min.js #= require plugins/font_family.min.js #= require plugins/font_size.min.js #= require plugins/fullscreen.min.js #= require plugins/help.min.js #= require plugins/image.min.js #= require plugins/image_manager.min.js #= require plugins/inline_class.min.js #= require plugins/inline_style.min.js #= require plugins/line_breaker.min.js #= require plugins/line_height.min.js #= require plugins/link.min.js #= require plugins/lists.min.js #= require plugins/paragraph_format.min.js #= require plugins/paragraph_style.min.js #= require plugins/print.min.js #= require plugins/quick_insert.min.js #= require plugins/quote.min.js #= require plugins/save.min.js #= require plugins/table.min.js #= require plugins/special_characters.min.js #= require plugins/url.min.js #= require plugins/video.min.js #= require third_party/embedly.min.js #= require third_party/font_awesome.min.js #= require third_party/image_tui.min.js #= require third_party/spell_checker.min.js ``` ```css @import 'plugins/char_counter.min.css'; @import 'plugins/code_view.min.css'; @import 'plugins/colors.min.css'; @import 'plugins/emoticons.min.css'; @import 'plugins/file.min.css'; @import 'plugins/fullscreen.min.css'; @import 'plugins/help.min.css'; @import 'plugins/image_manager.min.css'; @import 'plugins/image.min.css'; @import 'plugins/line_breaker.min.css'; @import 'plugins/quick_insert.min.css'; @import 'plugins/special_characters.min.css'; @import 'plugins/table.min.css'; @import 'plugins/video.min.css'; @import 'third_party/embedly.min.css'; @import 'third_party/image_tui.min.css'; @import 'third_party/spell_checker.min.css'; ``` Similar, if you want to use language translation you have to include the translation file. ```coffeescript # Include Language if needed #= require languages/ro.js ``` Then restart your web server if it was previously running. ## Initialize Editor Details about initializing the editor can be found in the [Froala WYSIWYG Editor official documentation](https://www.froala.com/wysiwyg-editor/docs). ## License The `wysiwyg-rails` project is under MIT license. However, in order to use Froala WYSIWYG HTML Editor plugin you should purchase a license for it. Froala Editor has [3 different licenses](https://froala.com/wysiwyg-editor/pricing). For details please see [License Agreement](https://froala.com/wysiwyg-editor/terms).
d8ce0bb20540f238103ac34bffed16d24d893130
[ "Markdown", "Ruby", "Shell" ]
5
Ruby
froala/wysiwyg-rails
8a63209be6bf519fc3860bec8e18699de6460a98
bdc711dc2e0769b2af586be8072b7a4b780cc22c
refs/heads/main
<file_sep>import Vue from "vue"; import CustomVuex from "../think-vuex" Vue.use(CustomVuex); //导出⼯⼚函数 export function createStore() { return new CustomVuex.Store({ state: { counter: 0 }, mutations: { add(state, payload){ state.counter += payload } }, actions: { add({commit}) { setTimeout(() => { commit('add') }, 2000) } }, getters: { doubleCounter(state) { return state.counter * 2 } } }) }<file_sep>// import Vue from 'vue' // import App from './App.vue' // import ElementUI from 'element-ui' // import 'element-ui/lib/theme-chalk/index.css' // // import { Button, Row, Col } from 'element-ui' // Vue.use(ElementUI) // /* Vue.use(Button) // Vue.use(Row) // Vue.use(Col) */ // Vue.config.productionTip = false // const v = new Vue({ // render: h => h(App), // }).$mount('#app') // console.log(v.$options.render) import Vue from "vue"; import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' // import { Button, Row, Col } from 'element-ui' import App from "./App.vue"; import { createRouter } from "./router"; import { createStore } from "./store" // 导出Vue实例⼯⼚函数,为每次请求创建独⽴实例 // 上下⽂⽤于给vue实例传递参数 export function createApp(context) { const router = createRouter(); const store = createStore() Vue.use(ElementUI) const app = new Vue({ router, context, store, render: h => h(App) }); return { app, router, store }; }<file_sep>const express = require('express') const app = express() // 服务器渲染模块 const {createRenderer} = require('vue-server-renderer') // 获取渲染器 const renderer = createRenderer() const Vue = require('vue') app.get('/', (req, res) => { res.send('hello') }) app.listen(3000, '服务器在3000端口启动了')<file_sep>function test (){ this.a = 'a' /* return { a: 'a88888s' } */ } test.prototype.b = 'b' const t = new test() console.log(t) <file_sep>function* flattenComponents(nestedComponents:any, pathPrefix:any):any { for (const { routes: routes, path, ...component } of nestedComponents) { const newPath = `${path}`; yield { ...component, path: newPath }; if (routes) { yield* flattenComponents(routes, newPath); } } } <file_sep># vue-pac ## Project setup ``` yarn install ``` ### Compiles and hot-reloads for development ``` yarn serve ``` ### Compiles and minifies for production ``` yarn build ``` ### Lints and fixes files ``` yarn lint ``` ### Customize configuration See [Configuration Reference](https://cli.vuejs.org/config/). ### 记录vscode配置调试 修改目录及文件:.vscode/launch.json { "version": "0.2.0", "configurations": [ { "type": "node", "request": "attach", "name": "Node: Nodemon", "processId": "${command:PickProcess}", "restart": true, "protocol": "inspector" } ] } <file_sep>import Vue from "vue"; import Router from "vue-router"; Vue.use(Router); //导出⼯⼚函数 export function createRouter() { return new Router({ mode: 'history', routes: [ // 客户端没有编译器,这⾥要写成渲染函数 { path: "/", component: { render: h => h('div', 'index page') } }, { path: "/detail", component: { render: h => h('div', 'detail page') } } ] }); }<file_sep>/* 1、为什么new vue()创建vue实例时,选项中需要加入router router作为插件,install方法被调用时,router的实例还没有被创建,所以在 install方法中利用Vue.mixin({})全局混入beforeCreate生命周期钩子,此时有机会 通过this.$options拿到router实例 */ let Vue; class VueRouter{ constructor(ops) { this.$ops = ops const initial = window.location.hash.slice(1) || '/' // ************将current变成响应式的************ Vue.util.defineReactive(this, 'current', initial) window.addEventListener('hashchange', () => { this.current = window.location.hash.slice(1) }) } } VueRouter.install = function(_Vue){ Vue = _Vue Vue.mixin({ beforeCreate() { if (this.$options.router) { Vue.prototype.$router = this.$options.router } } }) // 2、注册实现两个组件router-link、router-view Vue.component('router-link', { props: {}, render() { } }) Vue.component('router-view', { render(){ // 获取路由配置 const routes = this.$router.$ops.routes // 获取当前路由(这个current要把它变成响应式的,current变化,这个render就重新执行) const cur = this.$router.current // 获取当前路由所对应的组件 let component = null const route = routes.find((route) => { return route.path === cur }) if (route) { component = route.component } return h(component) } }) }
aa3b014b3466d56c307abec6638e4ce681be34ae
[ "JavaScript", "Markdown" ]
8
JavaScript
optimistic-wyl/vue-pac
ef36dc57682de674e06cad2bcf08a264439e1f84
e0141344ed9cfec64fee83b7ff7b281e470cf6d4
refs/heads/master
<repo_name>KavinRamesh/Algorithms<file_sep>/README.md # Algorithms This is my first git repository # Sorts This section describes sorting algorithms ## MergeSort ## BubbleSort ## SelectionSort ## InsertionSort ## CocktailSort <file_sep>/src/Algorithms.java import java.util.Random; /** * Created by Kavin on 12/21/18. */ public class Algorithms { public static void selectionSort(int[] input) { int n = input.length; for (int i = 0; i < n-1; i++) { /* Find the smallest number */ int smallest = i; for (int j = i+1; j < n; j++) { if (input[j] < input[smallest]) { smallest = j; } } //switch with first number int temp = input[smallest]; input[smallest] = input[i]; input[i] = temp; } } public static void merge(int[] a, int[] first, int[] second) { int firstIndex = 0; int secondIndex = 0; int primeIndex = 0; //as merging, sort from smallest to biggest while (firstIndex < first.length && secondIndex < second.length) { if (first[firstIndex] <= second[secondIndex]) { a[primeIndex] = first[firstIndex]; primeIndex++; firstIndex++; } else { a[primeIndex] = second[secondIndex]; primeIndex++; secondIndex++; } } //if one of the arrays finishes before the other, then finish up the process for the other one while (firstIndex < first.length) { a[primeIndex] = first[firstIndex]; primeIndex++; firstIndex++; } while (secondIndex < second.length) { a[primeIndex] = second[secondIndex]; primeIndex++; secondIndex++; } } public static void mergeSort(int[] a) { if(a.length < 2) { return; } int mid = a.length/2; int[] first = new int[mid]; int[] second = new int[a.length - mid]; //put correct numbers into respective arrays for(int i = 0; i < mid; i++) { first[i] = a[i]; } for(int i = mid ; i < a.length; i++) { second[i - mid] = a[i]; } //keep on splitting mergeSort(first); mergeSort(second); merge(a, first, second); } public static void insertionSort(int[] a) { for(int i = 1; i < a.length; i++) { //store current value to be later set in correct place int current = a[i]; int update = i - 1; //set all values in previous positions one position above (only if current value is less than them) while(update >= 0 && a[update] > current) { a[update+1] = a[update]; update -= 1; } //set the current value where it needs to be a[update + 1] = current; } } public static void swap(int[] arr, int indexOfFirst, int indexOfSecond) { int temp = arr[indexOfFirst]; arr[indexOfFirst] = arr[indexOfSecond]; arr[indexOfSecond] = temp; } public static void cocktailSort(int[] a) { boolean swapped = true; int start = 0; int end = a.length; while (swapped == true) { // reset swapped = false; // put biggest number where it need to be for (int i = start; i < end - 1; i++) { if (a[i] > a[i + 1]) { swap(a, i, i + 1); swapped = true; } } // reset swapped = false; end = end - 1; //put the smallest number where it needs to be for (int i = end - 1; i >= start; i--) { if (a[i] > a[i + 1]) { swap(a, i, i+1); swapped = true; } } start = start + 1; } } public static int binarySearch(int[] a, int numTF) { /*int iteration=2; for (int i=0; i<a.length; i++) { int midPoint=a.length/iteration; if }*/ int index = -1; int guess = a.length/2; int count = 0; for(int i = 0; i < a.length; i++) { System.out.println(count); if(numTF == a[guess]) { index = guess; return index; } else if(numTF > a[guess]) { guess += a.length/((i+1)*4); } else if(numTF < a[guess]) { guess -= a.length/((i+1)*4); } count++; } return index; } public static int[] randomArrayGen(int length) { Random random = new Random(12); int[] result = new int[length]; for(int i = 0; i < result.length; i++) { result[i] = random.nextInt(length); } return result; } public static void main(String[] args) { //selection sort System.out.println("Selection Sort:"); int[] test = {5, 6, 3, 78, 9}; System.out.println("Original: " + PrintArray.printArray(test)); selectionSort(test); System.out.println("Sorted: " + PrintArray.printArray(test) + "\n"); //merge sort System.out.println("Merge Sort:"); int[] test2 = {4, 3, 31, 1, 25, 6}; System.out.println("Original: " + PrintArray.printArray(test2)); mergeSort(test2); System.out.println("Sorted: " + PrintArray.printArray(test2) + "\n"); //insertion sort System.out.println("Insertion Sort:"); int[] test3 = {2, 4, 5, 8, 9 , 4, 2, 2, 34, 6}; System.out.println("Original: " + PrintArray.printArray(test3)); insertionSort(test3); System.out.println("Sorted: " + PrintArray.printArray(test3) + "\n"); //cocktail sort System.out.println("Cocktail Sort:"); int[] test4 = {2, 5, 8, 0, 4, 2, 1, 3, 6, 9, 5}; System.out.println("Original: " + PrintArray.printArray(test4)); cocktailSort(test4); System.out.println("Sorted: " + PrintArray.printArray(test4) + "\n"); //binary search System.out.println("Binary Search:"); int[] test5 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; System.out.println("Original: " + PrintArray.printArray(test5)); System.out.println("Number: " + 8); System.out.println("Index Of Number: " + binarySearch(test5, 8) + "\n"); //binary search with random array System.out.println("Binary search with random array"); //int size = (int)(Math.random() * 1000); int[] test6 = randomArrayGen(10000); System.out.println("Size of Array: " + 10000); System.out.println("Original: " + PrintArray.printArray(test6)); mergeSort(test6); System.out.println("Sorted: " + PrintArray.printArray(test6)); int r = 3031;//(int)(Math.random() * 10000); System.out.println("Number: " + r); System.out.println("Index Of Number: " + binarySearch(test6, r) + "\n"); } }
402d8b14c2163888545547d129e562f56045b38b
[ "Markdown", "Java" ]
2
Markdown
KavinRamesh/Algorithms
0dc3073e965fb2910f733f155640e88bd0240dec
c6427626f78fd477f08c03e60ca6ba99bcaf3fab
refs/heads/master
<file_sep>import React, { PropTypes } from 'react'; const MainLayout = (props) => ( <div id="main-layout"> <div id="content">{props.children}</div> </div> ); MainLayout.propTypes = { children: PropTypes.element.isRequired }; export default MainLayout; <file_sep>import React, { Component } from 'react'; import { List } from 'material-ui/List'; import Subheader from 'material-ui/Subheader'; import Divider from 'material-ui/Divider'; import MerchantListItem from './MerchantListItem'; export default class MerchantList extends Component { render() { return ( <List> <Subheader>Merchant List</Subheader> <MerchantListItem name="<NAME>" /> <Divider /> <MerchantListItem name="<NAME>" /> <Divider /> <MerchantListItem name="<NAME>" /> <Divider /> <MerchantListItem name="<NAME>" /> <Divider /> </List> ) } } <file_sep>import React, { Component, PropTypes } from 'react'; import AppBar from 'material-ui/AppBar'; class Header extends Component { render() { return ( <AppBar title={this.props.title} iconElementRight={this.props.iconRight} /> ) } }; Header.propTypes = { title: PropTypes.string.isRequired, iconRight: PropTypes.element.isRequired }; export default Header; <file_sep>import React from 'react'; import MerchantContainer from '../components/MerchantContainer'; import MerchantList from '../components/MerchantList'; import MerchantForm from '../components/MerchantForm'; const MerchantPage = () => ( <div> <MerchantContainer content={<MerchantList />} /> </div> ); export default MerchantPage; <file_sep>import React, { Component, PropTypes } from 'react'; import Subheader from 'material-ui/Subheader'; import TextField from 'material-ui/TextField'; export default class MerchantForm extends Component { render() { return ( <div id="merchant-form"> <Subheader>New Merchant</Subheader> <TextField floatingLabelText="Name" fullWidth={true} /><br /> <TextField floatingLabelText="Address" fullWidth={true} /><br /> <TextField floatingLabelText="Email" fullWidth={true} /> </div> ) } } <file_sep>import React, { PropTypes } from 'react'; import Header from '../components/Header'; const DashboardLayout = (props) => ( <div id="dashboard-layout"> <Header title="BetterHealth PH"/> <div id="content">{props.children}</div> </div> ); DashboardLayout.propTypes = { children: PropTypes.element.isRequired }; export default DashboardLayout;
58c514aed1310223fe5f39ece151e065c243d890
[ "JavaScript" ]
6
JavaScript
aabanaag/bh
4baf656d2f71160a9441998eb33dba16bd314e58
f1af08ed9ed44756a0fadbeca27cf6a69716b12c
refs/heads/master
<repo_name>Alirehmankhan1/ScTerminal<file_sep>/ChainOfResponsibility/src/Dollar20Despencer.java public class Dollar20Despencer implements DespenceChain { public DespenceChain chain; public Dollar20Despencer(DespenceChain nextChain){ this.chain=nextChain; } public void setNext(DespenceChain nextChain) { this.chain=nextChain; if(currency.getAmount >=20) { int num.getAmount(1/20); int remainder.getAmount(1%20); System.out.println("Despencing new Currency") if(currency !=0) { this.chain Despence new currency; else { this.chain new Despencer ; } } @Override public void setNextChain(DespenceChain nextChain) { // TODO Auto-generated method stub } @Override public void Despence(int currency) { // TODO Auto-generated method stub }<file_sep>/ChainOfResponsibility/src/Dollar10Despencer.java import java.util.Currency; public class Dollar10Despencer implements DespenceChain { this.chain= nextchain; public void Despence(currency){ return currency; } if(Currency.getAmount >=10) { int num.getAmount(1/10); int remainder.getAmount(1%10); System.out.println("Despensing new Currency"); if(Currency !=0) { this.chain Despense new Currency; else { this.chain new Despencer; } } @Override public void setNextChain(DespenceChain nextChain) { // TODO Auto-generated method stub } @Override public void Despence(int currency) { // TODO Auto-generated method stub }
1df0f95b216e08df6957b18c1b5608881322a3a2
[ "Java" ]
2
Java
Alirehmankhan1/ScTerminal
cca795af4fb33ec4437b76539ab48f858f73b471
ccb541d16947e39c53440550dd172aaf3571bf4e
refs/heads/master
<file_sep>include ':app' rootProject.name='My Caculate' <file_sep>package com.example.mycaculate; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends Activity implements View.OnClickListener { Button bt_0, bt_1, bt_2, bt_3, bt_4, bt_5, bt_6, bt_7, bt_8, bt_9, bt_pt; Button bt_mul, bt_div, bt_add, bt_sub, bt_tras, bt_squ; Button bt_clr, bt_del, bt_eq; EditText et_input; boolean clr_flag; //判断et中是否清空 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //实例化对象 setContentView(R.layout.activity_main); bt_0 = (Button) findViewById(R.id.bt_0); bt_1 = (Button) findViewById(R.id.bt_1); bt_2 = (Button) findViewById(R.id.bt_2); bt_3 = (Button) findViewById(R.id.bt_3); bt_4 = (Button) findViewById(R.id.bt_4); bt_5 = (Button) findViewById(R.id.bt_5); bt_6 = (Button) findViewById(R.id.bt_6); bt_7 = (Button) findViewById(R.id.bt_7); bt_8 = (Button) findViewById(R.id.bt_8); bt_9 = (Button) findViewById(R.id.bt_9); bt_pt = (Button) findViewById(R.id.bt_pt); bt_add = (Button) findViewById(R.id.bt_add); bt_sub = (Button) findViewById(R.id.bt_sub); bt_mul = (Button) findViewById(R.id.bt_mul); bt_div = (Button) findViewById(R.id.bt_div); bt_tras = (Button) findViewById(R.id.bt_tras); bt_squ = (Button) findViewById(R.id.bt_squ); bt_clr = (Button) findViewById(R.id.bt_clr); bt_del = (Button) findViewById(R.id.bt_del); bt_eq = (Button) findViewById(R.id.bt_eq); et_input = (EditText) findViewById(R.id.et_input); //设置按钮的点击事件 bt_0.setOnClickListener(this); bt_1.setOnClickListener(this); bt_2.setOnClickListener(this); bt_3.setOnClickListener(this); bt_4.setOnClickListener(this); bt_5.setOnClickListener(this); bt_6.setOnClickListener(this); bt_7.setOnClickListener(this); bt_8.setOnClickListener(this); bt_9.setOnClickListener(this); bt_pt.setOnClickListener(this); bt_add.setOnClickListener(this); bt_sub.setOnClickListener(this); bt_mul.setOnClickListener(this); bt_div.setOnClickListener(this); bt_tras.setOnClickListener(this); bt_squ.setOnClickListener(this); bt_clr.setOnClickListener(this); bt_del.setOnClickListener(this); bt_eq.setOnClickListener(this); } @Override public void onClick(View v) { String str = et_input.getText().toString(); switch (v.getId()) { case R.id.bt_0: case R.id.bt_1: case R.id.bt_2: case R.id.bt_3: case R.id.bt_4: case R.id.bt_5: case R.id.bt_6: case R.id.bt_7: case R.id.bt_8: case R.id.bt_9: case R.id.bt_pt: if (clr_flag) { clr_flag = false; str = ""; et_input.setText(""); } et_input.setText(str + ((Button) v).getText()); break; //初始化数据 case R.id.bt_add: case R.id.bt_sub: case R.id.bt_mul: case R.id.bt_div: if (clr_flag) { clr_flag = false; str = ""; et_input.setText(""); }//初始化数据 if (str.contains("+") || str.contains("-") || str.contains("×") || str.contains("÷")) { str = str.substring(0, str.indexOf(" ")); } et_input.setText(str + " " + ((Button) v).getText() + " "); break;//输入运算符的格式为“ ”+“运算符”+“ ” case R.id.bt_clr: if (clr_flag) clr_flag = false; str = ""; et_input.setText(""); break;//清空按钮 case R.id.bt_del: //判断是否为空,然后在进行删除 if (clr_flag) { clr_flag = false; str = ""; et_input.setText(""); } else if (str != null && !str.equals("")) { et_input.setText(str.substring(0, str.length() - 1));//利用字符串长度-1的方法删除 } break; case R.id.bt_eq: //单独运算最后结果 getResult(); break; case R.id.bt_tras: if (clr_flag) { clr_flag = false; str = ""; et_input.setText(""); } Tras(); break; case R.id.bt_squ: if (clr_flag) { clr_flag = false; str = ""; et_input.setText(""); } Square(); break; } } private void getResult() { String exp = et_input.getText().toString(); if (exp == null || exp.equals("")) return; //因为没有运算符所以不用运算 if (!exp.contains(" ")) { return; } if (clr_flag) { clr_flag = false; return; } clr_flag = true; //截取运算符前面的字符串 String s1 = exp.substring(0, exp.indexOf(" ")); //截取的运算符 String op = exp.substring(exp.indexOf(" ") + 1, exp.indexOf(" ") + 2); //截取运算符后面的字符串 String s2 = exp.substring(exp.indexOf(" ") + 3); double cnt = 0; if (!s1.equals("") && !s2.equals("")) { double d1 = Double.parseDouble(s1); double d2 = Double.parseDouble(s2); if (op.equals("+")) { cnt = d1 + d2; } if (op.equals("-")) { cnt = d1 - d2; } if (op.equals("×")) { cnt = d1 * d2; } if (op.equals("÷")) { if (d2 == 0) cnt = 0;//除数不能为0 else cnt = d1 / d2; } if (!s1.contains(".") && !s2.contains(".") && !op.equals("÷")) {//有小数的情况 int res = (int) cnt; et_input.setText(res + ""); } else { et_input.setText(cnt + ""); } } //s1不为空但s2为空 else if (!s1.equals("") && s2.equals("")) { double d1 = Double.parseDouble(s1); if (op.equals("+")) { cnt = d1; } if (op.equals("-")) { cnt = d1; } if (op.equals("×")) { cnt = 0; } if (op.equals("÷")) { cnt = 0; } if (!s1.contains(".")) {//有小数的情况 int res = (int) cnt; et_input.setText(res + ""); } else { et_input.setText(cnt + ""); } } //s1是空但s2不是空 else if (s1.equals("") && !s2.equals("")) { double d2 = Double.parseDouble(s2); if (op.equals("+")) { cnt = d2; } if (op.equals("-")) { cnt = 0 - d2; } if (op.equals("×")) { cnt = 0; } if (op.equals("÷")) { cnt = 0; } if (!s2.contains(".")) { int res = (int) cnt; et_input.setText(res + ""); } else { et_input.setText(cnt + ""); } } else { et_input.setText(""); } } public void Tras() {//正负数转化函数 String exp = et_input.getText().toString(); double answer = 0; if (exp.equals("")) { et_input.setText(""); } else if (exp.equals(".")) {//单独的小数点不支持正负变换 et_input.setText(exp); } else if (!exp.contains(" ")) {//整个字符串中不含“ ”,即只有一个操作数时 answer = 0 - Double.parseDouble(exp); et_input.setText(answer + ""); } else { String s = exp.substring(exp.indexOf(" ") + 3); if (s == null || s.equals("")) { et_input.setText(exp); } else { answer = 0 - Double.parseDouble(s); et_input.setText(exp.substring(0, exp.indexOf(" ") + 3) + answer + ""); }//有两个操作数时对第二个操作数进行正负变换 } } public void Square() {//平方函数 String str = et_input.getText().toString(); double answer; if (str.equals("")) { et_input.setText(""); } else if (!str.contains(" ")) {//只有一个操作数时 double x = Double.parseDouble(str); if (x > 2147483647) { Toast tip = Toast.makeText(getBaseContext(), "输入数据超出范围", Toast.LENGTH_SHORT); tip.show(); et_input.setText(str);//Toast方法给出提示 } else { if (str.contains(".")) {//小数的平方 double a = Double.parseDouble(str); answer = a * a; et_input.setText(answer + ""); } else { int y = Integer.parseInt(str);//正整数的平方 answer = y * y; if (answer > 2147483647) { Toast tip = Toast.makeText(getBaseContext(), "输入数据超出范围", Toast.LENGTH_SHORT); tip.show(); et_input.setText(str); } else { et_input.setText(answer + ""); } } } } else { String s = str.substring(str.indexOf(" ") + 3); String o = str.substring(str.indexOf(" "),str.indexOf(" ") + 2); if (s == null || s.equals("")) { et_input.setText(str); } else { double x = Double.parseDouble(s); if (x > 2147483647) { Toast tip = Toast.makeText(getBaseContext(), "输入数据超出范围", Toast.LENGTH_SHORT); tip.show(); et_input.setText(str); } else { if (s.contains(".")) { double a = Double.parseDouble(s); answer = a * a; et_input.setText(answer + ""); } else { int y = Integer.parseInt(s); answer = y * y; if (answer > 2147483647) { Toast tip = Toast.makeText(getBaseContext(), "输入数据超出范围", Toast.LENGTH_SHORT); tip.show(); et_input.setText(str); } else {if(o.contains("-")){ et_input.setText(answer+ "");}//复数的平方为正数 else et_input.setText(str.substring(0, str.indexOf(" ") + 3) + answer+ ""); } } } } } } }
ef202ab14520aca4d4a0d11134aabe0069491b8d
[ "Java", "Gradle" ]
2
Gradle
Wwjl2020/Android-Caculate
cd169a91f305d6c3f9c78c8bd022a9f791238fe6
f17e49e9e67b046acceca82f9db70956e5f97a69
refs/heads/main
<repo_name>salvadormarmol/shiny-developer-test<file_sep>/app.R usePackage <- function(p) { if (!is.element(p, installed.packages()[,1])) install.packages(p, dep = TRUE, repos = "https://cran.itam.mx/") require(p, character.only = TRUE) } # usePackage('tidyverse') # usePackage('shiny') # usePackage('shiny.semantic') # usePackage('semantic.dashboard') # usePackage('leaflet') # usePackage('gmt') # usePackage('sp') library('tidyverse') library('shiny') library('shiny.semantic') library('semantic.dashboard') library('leaflet') library('gmt') library('sp') ships <- read_csv('ships.csv', col_types = cols( .default = col_double(), DESTINATION = col_character(), FLAG = col_character(), SHIPNAME = col_character(), DATETIME = col_datetime(format = ""), PORT = col_character(), date = col_date(format = ""), ship_type = col_character(), port = col_character() )) ship_types <- unique(ships$ship_type) ship_names_by_type <- ships %>% group_by(ship_type, SHIPNAME) %>% summarise(count=n(), .groups="drop") ship_names <- ship_names_by_type %>% filter(ship_type == "Cargo") %>% pull(SHIPNAME) shipNamesDropDown <- function(id, label = "ship_names") { ns <- NS(id) tabItems( selected = 1, tabItem( tabName = "main", fluidRow( column( div( p(strong("Ship Type")), dropdown_input(ns("ship_type_dropdown"), ship_types, type = "search selection", value = "Cargo"), br(), br(), p(strong("Ship Name")), dropdown_input(ns("ship_name_dropdown"), ship_names, type = "search selection", value = ". PRINCE OF WAVES"), br(), br(), # title = "Ship type", width = 4, color = "blue"), width = 4), box(flow_layout( p(strong("Largest sail:"),.noWS="after"), textOutput(ns("largest_sail"))), br(), p(strong("Starting point"), style="color:Navy;",.noWS="after"), p(strong("Ending point"), style="color:Red;",.noWS="after"), br() , title = "Note", width = 6, color = "blue"), width = 6 ), box(leafletOutput(ns("map")), title = "Ship's largest sail", width = 10, color = "blue") ) ), tabItem( tabName = "extra", box(plotOutput(ns("boxplot")) ,title = "Ship's sensor records", width = 16, color = "blue" ) ) ) } shipNamesServer <- function(id) { moduleServer( id, function(input, output, session) { ship_type <- reactiveVal("Cargo") ship_name <- reactiveVal(". PRINCE OF WAVES") largest_sail_value <- reactiveVal(0.0) observeEvent(input$ship_type_dropdown, { ship_type(input$ship_type_dropdown) names <- ship_names_by_type %>% filter(ship_type == ship_type()) %>% pull(SHIPNAME) update_dropdown_input(session, "ship_name_dropdown", choices = names) #, value = input$simple_dropdown }) observeEvent(input$ship_name_dropdown, { ship_name(input$ship_name_dropdown) }) output$largest_sail <- renderText({ paste0(largest_sail_value(), " mts") }) output$boxplot <- renderPlot({ tmp <- ships %>% filter(SHIPNAME==ship_name() & is_parked==0) %>% arrange(desc(DATETIME)) %>% mutate(LAT_PREV = lag(LAT), LON_PREV = lag(LON), dist = suppressWarnings(ifelse(LAT-LAT_PREV+LON-LON_PREV==0,0, geodist(LAT, LON, LAT_PREV, LON_PREV, units="nm"))*1000)) %>% arrange(desc(dist)) if (dim(tmp)[1]>1) { boxplot(tmp$dist, horizontal=TRUE, pch=16, outcol="red", xlab="Distance traveled between readings (non parked)") } }) output$map <- renderLeaflet({ temp <- ships %>% filter(SHIPNAME==ship_name()) %>% arrange(desc(DATETIME)) %>% mutate(LAT_PREV = lag(LAT), LON_PREV = lag(LON), dist = suppressWarnings(ifelse(LAT-LAT_PREV+LON-LON_PREV==0,0, geodist(LAT, LON, LAT_PREV, LON_PREV, units="nm"))*1000)) %>% arrange(desc(dist)) largest_sail_value(round(temp[1,]$dist,2)) if (temp[1,]$dist<1000) { zoom = 13 } else if (temp[1,]$dist<2500) { zoom = 12 } else if (temp[1,]$dist<5000) { zoom = 11 } else if (temp[1,]$dist<10000) { zoom = 10 } else if (temp[1,]$dist<20000) { zoom = 9 } else if (temp[1,]$dist<30000) { zoom = 8 } else if (temp[1,]$dist<50000) { zoom = 5 } else { zoom = 3 } pal <- colorFactor(c("navy", "red"), domain = c("start", "end")) leaflet() %>% addTiles() %>% # Add default OpenStreetMap map tiles setView(lng=temp[1,]$LON , lat=temp[1,]$LAT, zoom = zoom) %>% addCircleMarkers( lng=temp[1,]$LON , lat=temp[1,]$LAT, radius = 4, color = pal("start"), stroke = FALSE, fillOpacity = 0.5 ) %>% addCircleMarkers( lng=temp[1,]$LON_PREV, lat=temp[1,]$LAT_PREV, radius = 4, color = pal("end"), stroke = FALSE, fillOpacity = 0.5 ) # largest_sail_value(temp[1,]$dist) }) ship_name } ) } ui <- dashboardPage( dashboardHeader(color = "blue", title = "Shiny Developer Test", inverted = TRUE), dashboardSidebar( size = "thin", color = "teal", sidebarMenu( menuItem(tabName = "main", "Main"), menuItem(tabName = "extra", "Extra") ) ), dashboardBody( shipNamesDropDown("ship_name") ) ) server <- function(input, output, session) { shipNamesServer("ship_name") } shinyApp(ui, server)<file_sep>/README.md # shiny-developer-test # Goals - User can select a vessel type (Ship_type) from the dropdown field - User can select a vessel from a dropdown field (available vessels should correspond to the selected type). Dropdown fields was created as a Shiny module - For the vessel selected, I found the observation when it sailed the longest distance between two consecutive observations. If there was a situation when a vessel moved exactly the same amount of meters, I selected the most recent. - I display that on the map - and show two points, the beginning and the end of the movement. The map was created using the leaflet library. Changing type and vessel name re-rends the map and the note. - I provided a short note saying how much the ship sailed - distance should be provided in meters. - I use the best practices I know, to ensure project quality. The application is reasonably efficient and tested. - I added an additional visualizations to see a box plot of the sailed distances
4511e38dd293e6217cf5b94851a353b178279b49
[ "Markdown", "R" ]
2
R
salvadormarmol/shiny-developer-test
30ddfbd62b35ae33f6d88a356d530adc2cc9fc4b
a62069c6846d56de40fbe062c1be7be63d075d83
refs/heads/source
<repo_name>mcfranc/mcfranc.github.io<file_sep>/src/containers/project_list.jsx import React, { Component } from 'react'; import { connect } from 'react-redux'; import Project from '../containers/project'; class ProjectList extends Component { renderList() { return this.props.projects.map((project) => { return ( <Project key={project.name} project={project} /> ); }); } render() { return ( <div> Projects: &nbsp; {this.renderList()} </div> ); } } function mapStateToProps(state) { return { projects: state.projects }; } export default connect(mapStateToProps)(ProjectList); <file_sep>/src/containers/active_project.js import React from 'react'; import { connect } from 'react-redux'; const ActiveProject = (props) => { if (!props.activeProject) { return ( <div className="active-project"> </div> ); } return ( <div className="active-project"> <a href={props.activeProject.url}> <p>{props.activeProject.name}</p> </a> <p>{props.activeProject.desc}</p> <p className="technology">{props.activeProject.technology}</p> </div> ); }; function mapStateToProps(state) { return { activeProject: state.activeProject }; } export default connect(mapStateToProps)(ActiveProject); <file_sep>/README.md # mcfranc.github.io GitHub User Page created using React, Redux, and Bideo.js. Bootstrapped with create-react-app.
eacba8989e576ba6047b34538df0659d871325ae
[ "JavaScript", "Markdown" ]
3
JavaScript
mcfranc/mcfranc.github.io
ff81b0e09c72ddae0f145152eebba7728139bb36
2aea96bcb2c8921d456495973380a3ca84f958b4
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParkingBonMVVM.Model { public class ParkingBon { public ParkingBon() { Datum = DateTime.Now; Aankomst = DateTime.Now; Vertrek = Aankomst; Bedrag = 0; } public DateTime Datum { get; set; } public DateTime Aankomst { get; set; } public DateTime Vertrek { get; set; } public int Bedrag { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WPFOef.Model { enum Kleur { Red, Orange, Green }; class Verkeerslicht { public Kleur kleur { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Telefoon { /// <summary> /// Interaction logic for TelefoonWindow.xaml /// </summary> public partial class TelefoonWindow : Window { public TelefoonWindow() { InitializeComponent(); } public List<Persoon> personen = new List<Persoon>(); private void Window_Loaded(object sender, RoutedEventArgs e) { personen.Add(new Persoon("kleine zus", "03 213 45 12", "Familie", new BitmapImage(new Uri(@"images\kleinezus.jpg", UriKind.Relative)))); personen.Add(new Persoon("grote zus", " 03 213 45 12", "Familie", new BitmapImage(new Uri(@"images\grotezus.jpg", UriKind.Relative)))); personen.Add(new Persoon("vader", "02 12 45 78", "Familie", new BitmapImage(new Uri(@"images\vader.jpg", UriKind.Relative)))); personen.Add(new Persoon("tante non", "056 78 45 12", "Familie", new BitmapImage(new Uri(@"images\tantenon.jpg", UriKind.Relative)))); personen.Add(new Persoon("collega 1", "014 45 16 98", "Werk", new BitmapImage(new Uri(@"images\collega1.jpg", UriKind.Relative)))); personen.Add(new Persoon("collega 2", "03 86 54 79", "Werk", new BitmapImage(new Uri(@"images\collega2.jpg", UriKind.Relative)))); personen.Add(new Persoon("collega 3", "045 12 45 23", "Werk", new BitmapImage(new Uri(@"images\collega3.jpg", UriKind.Relative)))); personen.Add(new Persoon("bob", "012 45 37 58", "Vrienden", new BitmapImage(new Uri(@"images\bob.jpg", UriKind.Relative)))); personen.Add(new Persoon("ed", "065 43 29 75", "Vrienden", new BitmapImage(new Uri(@"images\ed.jpg", UriKind.Relative)))); personen.Add(new Persoon("anne", "065 43 29 76", "Vrienden", new BitmapImage(new Uri(@"images\anne.jpg", UriKind.Relative)))); foreach (Persoon dePersoon in personen) { ListBoxPersonen.Items.Add(dePersoon); } ComboBoxGroepen.Items.Add("Iedereen"); ComboBoxGroepen.Items.Add("Familie"); ComboBoxGroepen.Items.Add("Vrienden"); ComboBoxGroepen.Items.Add("Werk"); ComboBoxGroepen.SelectedIndex = 0; } private void ComboBoxGroepen_SelectionChanged(object sender, SelectionChangedEventArgs e) { ListBoxPersonen.Items.Clear(); foreach (Persoon dePersoon in personen) { if (ComboBoxGroepen.SelectedItem.ToString() == "Iedereen") { ListBoxPersonen.Items.Add(dePersoon); } else { if ((dePersoon.Groep == ComboBoxGroepen.SelectedItem.ToString())) ListBoxPersonen.Items.Add(dePersoon); } } } private void Button_Click(object sender, RoutedEventArgs e) { if (ListBoxPersonen.SelectedIndex >= 0) { Persoon beller = (Persoon)ListBoxPersonen.SelectedItem; if (MessageBox.Show("Wil je " + beller.Naam + " bellen \nop het nummer: " + beller.Telefoonnr, "Telefoon", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { SoundPlayer speler = new SoundPlayer("PHONE.wav"); speler.Play(); } } else { MessageBox.Show("Je moet eerst iemand selecteren", "Niemand gekozen",MessageBoxButton.OK,MessageBoxImage.Warning); } } } } <file_sep>using Microsoft.Win32; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Parkingbon { /// <summary> /// Interaction logic for ParkingbonWindow.xaml /// </summary> public partial class ParkingbonWindow : Window { public ParkingbonWindow() { InitializeComponent(); Nieuw(); } private void Nieuw() { DatumBon.SelectedDate = DateTime.Now; AankomstLabelTijd.Content = DateTime.Now.ToLongTimeString(); TeBetalenLabel.Content = "0 €"; VertrekLabelTijd.Content = AankomstLabelTijd.Content; StatusItem.Content = "nieuwe bon"; SaveEnAfdruk(false); } private void SaveEnAfdruk(Boolean actief) { PrintPreviewButton.IsEnabled = actief; SaveButton.IsEnabled = actief; BonAfdrukken.IsEnabled = actief; BonOpslaan.IsEnabled = actief; } private void NewExecuted(object sender, ExecutedRoutedEventArgs e) { Nieuw(); } private void OpenExecuted(object sender, ExecutedRoutedEventArgs e) { try { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Parkeerbonnen | *.bon"; if (dlg.ShowDialog() == true) { using (StreamReader invoer = new StreamReader(dlg.FileName)) { DatumBon.SelectedDate = Convert.ToDateTime(invoer.ReadLine()); AankomstLabelTijd.Content = invoer.ReadLine(); TeBetalenLabel.Content = invoer.ReadLine(); VertrekLabelTijd.Content = invoer.ReadLine(); } StatusItem.Content = dlg.FileName; SaveEnAfdruk(true); } } catch (Exception ex) { MessageBox.Show("opslaan mislukt: " + ex.Message); } } private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) { try { SaveFileDialog dlg = new SaveFileDialog(); DateTime tijd = (DateTime)DatumBon.SelectedDate; dlg.FileName = tijd.Day.ToString() + "-" + tijd.Month.ToString() + "-" + tijd.Year.ToString() + "om" + AankomstLabelTijd.Content.ToString().Replace(":", "-"); dlg.DefaultExt = ".bon"; dlg.Filter = "Parkeerbonnen | *.bon"; if (dlg.ShowDialog() == true) { using (StreamWriter uitvoer = new StreamWriter(dlg.FileName)) { uitvoer.WriteLine(tijd.ToShortDateString()); uitvoer.WriteLine(AankomstLabelTijd.Content); uitvoer.WriteLine(TeBetalenLabel.Content); uitvoer.WriteLine(VertrekLabelTijd.Content); } StatusItem.Content = dlg.FileName; } } catch (Exception ex) { MessageBox.Show("opslaan mislukt: " + ex.Message); } } private double vertPositie; private void PrintPreviewExecuted(object sender, ExecutedRoutedEventArgs e) { FixedDocument document = new FixedDocument(); document.DocumentPaginator.PageSize = new Size(640, 320); PageContent inhoud = new PageContent(); document.Pages.Add(inhoud); FixedPage pagina = new FixedPage(); inhoud.Child = pagina; pagina.Width = 640; pagina.Height = 320; Image logo = new Image(); logo.Source = logoImage.Source; logo.Margin = new Thickness(96); pagina.Children.Add(logo); vertPositie = 96; pagina.Children.Add(Regel("datum: " + DatumBon.Text)); pagina.Children.Add(Regel("starttijd : " + AankomstLabelTijd.Content)); pagina.Children.Add(Regel("eindtijd : " + VertrekLabelTijd.Content)); pagina.Children.Add(Regel("bedrag betaald : " + TeBetalenLabel.Content)); Afdrukvoorbeeld preview = new Afdrukvoorbeeld(); preview.Owner = this; preview.AfdrukDocument = document; preview.ShowDialog(); } private TextBlock Regel(string tekst) { TextBlock deRegel = new TextBlock(); deRegel.Margin = new Thickness(300, vertPositie, 96, 96); deRegel.FontSize = 18; vertPositie += 36; // 18 * 2 deRegel.Text = tekst; return deRegel; } private void CloseExecuted(object sender, ExecutedRoutedEventArgs e) { this.Close(); } private void minder_Click(object sender, RoutedEventArgs e) { int bedrag = Convert.ToInt32(TeBetalenLabel.Content.ToString().Replace("€", "")); if (bedrag > 0) bedrag -= 1; TeBetalenLabel.Content = bedrag.ToString() + " €"; VertrekLabelTijd.Content = Convert.ToDateTime(AankomstLabelTijd.Content).AddHours(0.5 * bedrag).ToLongTimeString(); SaveEnAfdruk(!(bedrag == 0)); } private void meer_Click(object sender, RoutedEventArgs e) { int bedrag = Convert.ToInt32(TeBetalenLabel.Content.ToString().Replace("€", "")); DateTime vertrekuur = Convert.ToDateTime(AankomstLabelTijd.Content).AddHours(0.5 * bedrag); if (vertrekuur.Hour < 22) bedrag += 1; TeBetalenLabel.Content = bedrag.ToString() + " €"; VertrekLabelTijd.Content = Convert.ToDateTime(AankomstLabelTijd.Content).AddHours(0.5 *bedrag).ToLongTimeString(); SaveEnAfdruk(!(bedrag == 0)); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Pizza { /// <summary> /// Interaction logic for PizzaWindow.xaml /// </summary> public partial class PizzaWindow : Window { public PizzaWindow() { InitializeComponent(); //bestelling.Content = PizzaBestelKnop.Source.GetValue(); } private void meer_Click(object sender, RoutedEventArgs e) { int aantal = Convert.ToInt16(aantalLabel.Content); if (aantal < 10) aantal++; aantalLabel.Content = aantal.ToString(); } private void minder_Click(object sender, RoutedEventArgs e) { int aantal = Convert.ToInt16(aantalLabel.Content); if (aantal > 1) aantal--; aantalLabel.Content = aantal.ToString(); } private void bestellen_Click(object sender, RoutedEventArgs e) { string tekst = " U heeft " + aantalLabel.Content + " "; string ingredienten = string.Empty; foreach (FrameworkElement kind in boxen.Children) { if (kind is RadioButton) { if (((RadioButton)kind).IsChecked == true) tekst += kind.Name + @" pizza('s) besteld met: "; } if (kind is CheckBox) if (((CheckBox)kind).IsChecked == true) ingredienten += kind.Name + ", "; } ingredienten = ingredienten.Substring(0, ingredienten.Length - 2); int k = ingredienten.LastIndexOf(","); ingredienten = ingredienten.Substring(0, k) + " en " + ingredienten.Substring(k + 2); tekst += ingredienten + "\n"; if (extrakorst.IsChecked == true) tekst += " met een extra dikke korst \n"; if (extrakaas.IsChecked == true) tekst += " overstrooid met extra kaas"; bestelling.Content = tekst; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Verkeerslicht { /// <summary> /// Interaction logic for VerkeerslichtMain.xaml /// </summary> public partial class VerkeerslichtMain : Window { public VerkeerslichtMain() { InitializeComponent(); Grid gridKnoppen = this.gridKnoppen; IEnumerable<Button> knoppen = gridKnoppen.Children.OfType<Button>(); Canvas canvasLicht = this.canvasLicht; IEnumerable<Ellipse> ellipses = canvasLicht.Children.OfType<Ellipse>(); foreach (Button knop in knoppen.Where(i=> i.Name!= "ButtonOrange")) { knop.IsEnabled = false; } foreach (Ellipse licht in ellipses.Where(i=> i.Name != "RedLight")) { licht.Visibility= System.Windows.Visibility.Hidden; } } private void Button_Click(object sender, RoutedEventArgs e) { Button knop = (Button)sender; Button knopGreen = this.ButtonGreen; Button knopOrange = this.ButtonOrange; Button knopRed = this.ButtonRed; knop.IsEnabled = false; //IEnumerable van alle lichten Canvas canvasLicht = this.canvasLicht; IEnumerable<Ellipse> ellipses = canvasLicht.Children.OfType<Ellipse>(); //welke knop is er gedrukt string tag = knop.Tag.ToString(); //kleur maken van de string Tag SolidColorBrush kleur = (SolidColorBrush)new BrushConverter().ConvertFromString(tag); //kleur op de achtergrond van de knop toepassen knop.Background = kleur; // stoplicht zichtbaarmaken Ellipse stoplicht = ellipses.First(x => x.Name.ToString() == (tag + "Light")); stoplicht.Visibility = System.Windows.Visibility.Visible; // alle andere lichten onzichtbaar maken var Lichten = ellipses .Where(x => x.Name.ToString() != (tag + "Light")) .ToList(); Lichten.ForEach(p => p.Visibility = System.Windows.Visibility.Hidden); // alle andere knoppen terug naar de default kleur zetten switch (tag) { case "Red": knopOrange.IsEnabled = true; knopOrange.Focus(); knopGreen.ClearValue(Control.BackgroundProperty); knopOrange.ClearValue(Control.BackgroundProperty); break; case "Orange": knopGreen.IsEnabled = true; knopGreen.Focus(); knopGreen.ClearValue(Control.BackgroundProperty); knopRed.ClearValue(Control.BackgroundProperty); break; case "Green": knopRed.IsEnabled = true; knopRed.Focus(); knopRed.ClearValue(Control.BackgroundProperty); knopOrange.ClearValue(Control.BackgroundProperty); break; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Globalization; using System.IO; using System.Reflection; using System.Windows.Navigation; using Microsoft.Win32; using System.Windows.Controls.Ribbon; namespace ParkingBonMVVM.View { /// <summary> /// Interaction logic for ParkingBonView.xaml /// </summary> public partial class ParkingBonView: RibbonWindow { public ParkingBonView() { InitializeComponent(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WPFOef.Model; namespace WPFOef.ViewModel { class VerkeerslichtVM { private Verkeerslicht obj = new Verkeerslicht(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Bars { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public static RoutedCommand mijnRoute = new RoutedCommand(); public Window1() { InitializeComponent(); } private void bExecuted(object sender, ExecutedRoutedEventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using Microsoft.Win32; using System.ComponentModel; using System.IO; namespace ParkingBonMVVM.ViewModel { class ParkingBonVM: ViewModelBase { private Model.ParkingBon parkingbon; public ParkingBonVM(Model.ParkingBon deParkingBon) { parkingbon = deParkingBon; } public DateTime Datum { get { return parkingbon.Datum; } set { parkingbon.Datum = value; RaisePropertyChanged("Datum"); } } public DateTime Aankomst { get { return parkingbon.Aankomst; } set { parkingbon.Aankomst = value; RaisePropertyChanged("Aankomst"); } } public DateTime Vertrek { get { return parkingbon.Vertrek; } set { parkingbon.Vertrek = value; RaisePropertyChanged("Vertrek"); } } public int Bedrag { get { return parkingbon.Bedrag; } set { parkingbon.Bedrag = value; RaisePropertyChanged("Bedrag"); } } public RelayCommand MeerCommand { get { return new RelayCommand(MeerBetalen); } } private void MeerBetalen() { if (Vertrek.Hour < 22) Bedrag++; Vertrek = Aankomst.AddHours(0.5 * Bedrag); } public RelayCommand MinderCommand { get { return new RelayCommand(MinderBetalen); } } private void MinderBetalen() { if (Bedrag > 0) Bedrag--; Vertrek = Aankomst.AddHours(0.5 * Bedrag); } public RelayCommand NieuwCommand { get { return new RelayCommand(NieuweBon); } } private void NieuweBon() { Bedrag = 0; Datum = DateTime.Today; Aankomst = DateTime.Now; Vertrek = DateTime.Now; } public RelayCommand OpenenCommand { get { return new RelayCommand(OpenenBon); } } private void OpenenBon() { try { OpenFileDialog dlg = new OpenFileDialog(); dlg.FileName = ""; dlg.DefaultExt = ".bon"; dlg.Filter = "Parkingbonnen |*.bon"; if (dlg.ShowDialog() == true) { using (StreamReader bestand = new StreamReader(dlg.FileName)) { Datum = Convert.ToDateTime(bestand.ReadLine()); Aankomst = Convert.ToDateTime(bestand.ReadLine()); Bedrag = Convert.ToInt32(bestand.ReadLine()); Vertrek = Convert.ToDateTime(bestand.ReadLine()); } } } catch (Exception ex) { MessageBox.Show("openen mislukt : " + ex.Message); } } public RelayCommand OpslaanCommand { get { return new RelayCommand(OpslaanBon); } } private void OpslaanBon() { try { string bestandsnaam; bestandsnaam = Datum.Day + "-" + Datum.Month + "-" + Datum.Year + "om" + Aankomst.Hour + "-" + Aankomst.Minute + ".bon"; SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = bestandsnaam; dlg.DefaultExt = ".bon"; dlg.Filter = "Parkingbonnen |*.bon"; if (dlg.ShowDialog() == true) { using (StreamWriter bestand = new StreamWriter(dlg.FileName)) { bestand.WriteLine(Datum.ToShortDateString()); bestand.WriteLine(Aankomst.ToShortTimeString()); bestand.WriteLine(Bedrag); bestand.WriteLine(Vertrek.ToShortTimeString()); } } } catch (Exception ex) { MessageBox.Show("opslaan mislukt : " + ex.Message); } } public RelayCommand AfsluitenCommand { get { return new RelayCommand(AfsluitenApp); } } public void AfsluitenApp() { Application.Current.MainWindow.Close(); } public RelayCommand<CancelEventArgs> AfsluitenEvent { get { return new RelayCommand<CancelEventArgs>(OnWindowClosing); } } public void OnWindowClosing(CancelEventArgs e) { if (MessageBox.Show("Afsluiten", "Wilt u het programma sluiten ?", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No) == MessageBoxResult.No) e.Cancel = true; } } }
b57e0d230560ae6f876add9f33da2819515fc3da
[ "C#" ]
10
C#
Hapkin/csharp
0944dcc2d32db5b244283aca88009f9dc840046a
230aae7d4f5989c1e3719865a97d23a286a749f9
refs/heads/master
<file_sep>class WestoncontrollerController < ApplicationController def amethod render json: "test" end end
e1d462110bbe62b7be5232019781777daa2c9181
[ "Ruby" ]
1
Ruby
WChambers/rails-ex
70b83e8ad544a28939eb48c0cd1f90635c7b663b
138634e268e57672837c41ac303404eeb7059177
refs/heads/main
<repo_name>cesarionto/treinamento-backend<file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/exceptions/error/ResourceNotAcceptableDetails.java package com.turingtecnologia.albatroz.backendalbatroz.exceptions.error; import lombok.Data; @Data public class ResourceNotAcceptableDetails { private String title; private int status; private String detail; private long timeStamp; public static final class Builder { private String title; private int status; private String detail; private long timeStamp; private Builder() { } public static Builder newBuilder() { return new Builder(); } public Builder title(String title) { this.title = title; return this; } public Builder status(int status) { this.status = status; return this; } public Builder detail(String detail) { this.detail = detail; return this; } public Builder timeStamp(long timeStamp) { this.timeStamp = timeStamp; return this; } public ResourceNotAcceptableDetails build() { ResourceNotAcceptableDetails resourceNotAcceptableDetails = new ResourceNotAcceptableDetails(); resourceNotAcceptableDetails.timeStamp = this.timeStamp; resourceNotAcceptableDetails.title = this.title; resourceNotAcceptableDetails.status = this.status; resourceNotAcceptableDetails.detail = this.detail; return resourceNotAcceptableDetails; } } } <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/dto/SendGridDTO.java package com.turingtecnologia.albatroz.backendalbatroz.dto; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; public class SendGridDTO { @NotBlank(message = "Email " + "{not.blank}") @Email(message = "{email.not.valid}") public String Email; @NotBlank(message = "Assunto " + "{not.blank}") public String Assunto; @NotBlank(message = "Messagem " + "{not.blank}") public String Menssagem; }<file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/BackendAlbatrozApplication.java package com.turingtecnologia.albatroz.backendalbatroz; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class BackendAlbatrozApplication { public static void main(String[] args) { SpringApplication.run(BackendAlbatrozApplication.class, args); } } <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/controller/ConsultaController.java package com.turingtecnologia.albatroz.backendalbatroz.controller; import javax.validation.Valid; import com.turingtecnologia.albatroz.backendalbatroz.dto.ConsultaDTO; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Consulta; import com.turingtecnologia.albatroz.backendalbatroz.services.interfaces.ConsultaService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.AllArgsConstructor; import org.modelmapper.ModelMapper; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController() @RequestMapping("/consultas") @AllArgsConstructor public class ConsultaController { private final ConsultaService consultaService; @ApiOperation(value = "Cadastro de consulta.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Consulta cadastrada com sucesso."), @ApiResponse(code = 400, message = "Falta dados para se realizar o cadastro."), @ApiResponse(code = 500, message = "Erro ao processar o cadastro.") }) @PostMapping public ResponseEntity<Consulta> salva(@Valid @RequestBody ConsultaDTO consultaDTO) { Consulta consulta = new ModelMapper().map(consultaDTO, Consulta.class); return new ResponseEntity<>(consultaService.addConsulta(consulta), HttpStatus.CREATED); } @ApiOperation(value = "Realizar uma busca de consulta, pelo id da consulta.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Busca realizada com sucesso."), @ApiResponse(code = 400, message = "Falta o dado(id) para se realizar a busca."), @ApiResponse(code = 500, message = "Erro ao processar a busca.") }) @GetMapping(value = "/{idConsulta}") public ResponseEntity<Consulta> busca(@PathVariable("idConsulta") Long id) { return new ResponseEntity<>(consultaService.findByIdConsulta(id), HttpStatus.OK); } @ApiOperation(value = "Deleta a consulta do banco de dados, pelo id da consulta.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Consulta deletada com sucesso."), @ApiResponse(code = 400, message = "Falta o dado(id) para deletar a consulta."), @ApiResponse(code = 500, message = "Erro ao processar o delete.") }) @DeleteMapping(value = "/{idConsulta}") public ResponseEntity<Void> desmarca(@PathVariable("idConsulta") Long id) { consultaService.remove(id); return new ResponseEntity<>(HttpStatus.CREATED); } @ApiOperation(value = "Atualiza a consulta no banco de dados.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Consulta atualizada com sucesso."), @ApiResponse(code = 400, message = "Falta dados para realizar a atualização."), @ApiResponse(code = 500, message = "Erro ao processar a atualização.") }) @PutMapping public ResponseEntity<Consulta> altera(@Valid @RequestBody ConsultaDTO consultaDTO) { Consulta consulta = new ModelMapper().map(consultaDTO, Consulta.class); return new ResponseEntity<>(consultaService.alteraConsulta(consulta), HttpStatus.CREATED); } } <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/services/ReportService.java package com.turingtecnologia.albatroz.backendalbatroz.services; import java.io.IOException; import java.io.InputStream; import java.sql.SQLException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Map; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.bind.annotation.RequestParam; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.util.JRLoader; @Service public class ReportService { @Autowired private DataSource dataSource; public String exportarRelatorio(String formatoRelatorio, HttpServletResponse response, @RequestParam(required = false) Map<String, Object> parametros) throws JRException, IOException, SQLException { InputStream jasperStream = this.getClass().getResourceAsStream("/RelatorioConsultaRealizada.jasper"); return setReport(formatoRelatorio, response, parametros, jasperStream); } public String exportarRelatorioData(String formatoRelatorio, HttpServletResponse response, @RequestParam Map<String, Object> parametros) throws JRException, IOException, SQLException, ParseException { parametros.put("dataInicial", new SimpleDateFormat("d/MM/yy").parse(parametros.get("dataInicial").toString())); parametros.put("dataFinal", new SimpleDateFormat("d/MM/yy").parse(parametros.get("dataFinal").toString())); InputStream jasperStream = this.getClass().getResourceAsStream("/RelatorioConsultaRealizadaData.jasper"); return setReport(formatoRelatorio, response, parametros, jasperStream); } private String setReport(String formatoRelatorio, HttpServletResponse response, @RequestParam Map<String, Object> parametros, InputStream jasperStream) throws JRException, SQLException, IOException { JasperReport jasperReport = (JasperReport) JRLoader.loadObject(jasperStream); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parametros, dataSource.getConnection()); if(formatoRelatorio.equalsIgnoreCase("pdf")) { response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=relatorioconsultasrealizadas.pdf"); final ServletOutputStream outStream = response.getOutputStream(); JasperExportManager.exportReportToPdfStream(jasperPrint, outStream); } if(formatoRelatorio.equalsIgnoreCase("xls")) { response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=relatorioconsultasrealizadas.xls"); final ServletOutputStream outStream = response.getOutputStream(); JasperExportManager.exportReportToXmlStream(jasperPrint, outStream); } return "Relatório Gerado"; } }<file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/model/jpaRepositoy/ConsultaRealizadaRepository.java package com.turingtecnologia.albatroz.backendalbatroz.model.jpaRepositoy; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Cliente; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.ConsultaRealizada; import org.springframework.data.jpa.repository.JpaRepository; import java.util.Calendar; import java.util.List; public interface ConsultaRealizadaRepository extends JpaRepository<ConsultaRealizada, Long> { List<ConsultaRealizada> findByClienteConsultaRealizada(Cliente cliente); List<ConsultaRealizada> findByDataConsultaRelizadaBetween(Calendar dataInicial, Calendar dataFinal); List<ConsultaRealizada> findByDataConsultaRelizadaOrderByNumeroFichaConsultaRelizada(Calendar dataConsultaRealizada); } <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/controller/AdministradorController.java package com.turingtecnologia.albatroz.backendalbatroz.controller; import com.turingtecnologia.albatroz.backendalbatroz.dto.ClienteDTO; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Cliente; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Consulta; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.ConsultaRealizada; import com.turingtecnologia.albatroz.backendalbatroz.services.ReportService; import com.turingtecnologia.albatroz.backendalbatroz.services.interfaces.AdministradorService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.AllArgsConstructor; import net.sf.jasperreports.engine.JRException; import org.modelmapper.ModelMapper; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.io.IOException; import java.sql.SQLException; import java.text.ParseException; import java.util.*; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; @RestController @RequestMapping(value = "/admin") @AllArgsConstructor public class AdministradorController { private final AdministradorService admService; private final ReportService reportService; @ApiOperation(value = "Gerar relatório completo.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Relatório gerado com sucesso."), @ApiResponse(code = 500, message = "Erro na geração do relatório.") }) @GetMapping(value = "/gerarRelatorio/{formato}") public String geradorRelatorio( @PathVariable(value = "formato") String formato, @RequestParam(required = false) Map<String, Object> parametros, HttpServletResponse response) throws JRException, IOException, SQLException { return reportService.exportarRelatorio(formato, response, parametros); } @ApiOperation(value = "Gerar relatório por periódo.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Relatório gerado com sucesso."), @ApiResponse(code = 500, message = "Erro na geração do relatório.") }) @GetMapping(value = "/gerarRelatorioData/{formato}") public String geradorRelatorioData( @PathVariable(value = "formato") String formato, @RequestParam Map<String, Object> parametros, HttpServletResponse response) throws JRException, IOException, SQLException, ParseException { return reportService.exportarRelatorioData(formato, response, parametros); } @ApiOperation(value = "Lista todos os clientes cadastrados.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retornado com sucesso os clientes."), @ApiResponse(code = 500, message = "Erro ao processar a listagem dos clientes.") }) @GetMapping(value = "/clientes") public ResponseEntity<List<Cliente>> listaClientes() { return new ResponseEntity<>(admService.findAllClientes(), HttpStatus.OK); } @ApiOperation(value = "Apaga o cliente do banco de dados.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Cliente apagado com sucesso"), @ApiResponse(code = 500, message = "Erro ao deletar o cliente.") }) @DeleteMapping(value = "/clientes") public ResponseEntity<Void> removeCliente(@Valid @RequestBody ClienteDTO clienteDTO) { Cliente cliente = new ModelMapper().map(clienteDTO, Cliente.class); admService.removeCliente(cliente); return new ResponseEntity<>(HttpStatus.CREATED); } @ApiOperation(value = "Atualiza os dados do cliente.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Dados atualizados com sucesso."), @ApiResponse(code = 400, message = "Estar faltando dados para realizar a atualização."), @ApiResponse(code = 500, message = "Erro ao atualizar o cliente.") }) @PutMapping(value = "/clientes") public ResponseEntity<Cliente> alteraCliente(@Valid @RequestBody ClienteDTO clienteDTO) { Cliente cliente = new ModelMapper().map(clienteDTO, Cliente.class); return new ResponseEntity<>(admService.alteraCliente(cliente), HttpStatus.CREATED); } @ApiOperation(value = "Atualiza o estado da consulta para marcada, pelo id da consulta.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Atualização do estado processada com sucesso"), @ApiResponse(code = 400, message = "Falta o dado(id) para atualizar o estado."), @ApiResponse(code = 500, message = "Erro ao processar a atualização.") }) @PutMapping(value = "/consultas/checkIn/{idConsulta}") public ResponseEntity<Consulta> checkIn(@PathVariable("idConsulta") Long idConsulta) { return new ResponseEntity<>(admService.marcaCheckIn(idConsulta), HttpStatus.CREATED); } @ApiOperation(value = "Atualiza o estado da consulta para desmarcada, pelo id da consulta.") @ApiResponses(value = { @ApiResponse(code = 201, message = "Atualização do estado processada com sucesso."), @ApiResponse(code = 400, message = "Falta o dado(id) para atualizar o estado."), @ApiResponse(code = 500, message = "Erro ao processar a atualização.") }) @DeleteMapping(value = "/consultas/checkOut/{idConsulta}") public ResponseEntity<Void> checkOut(@PathVariable("idConsulta") Long idConsulta) { admService.marcaCheckOut(idConsulta); return new ResponseEntity<>(HttpStatus.CREATED); } @ApiOperation(value = "Mostra todas as consultas cadastradas.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retornado com sucesso a lista de consultas."), @ApiResponse(code = 500, message = "Erro ao processar a listagem de consulta.") }) @GetMapping(value = "/consultas") public ResponseEntity<List<Consulta>> listaConsultas() { return new ResponseEntity<>(admService.findAllConsultas(), HttpStatus.OK); } @ApiOperation(value = "Mostra todas as consultas realizadas.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retornado com sucesso a lista de consultas."), @ApiResponse(code = 500, message = "Erro ao processar a listagem de consulta.") }) @GetMapping(value = "/consultasRealizadas") public ResponseEntity<List<ConsultaRealizada>> listaConsultasRealizadas() { return new ResponseEntity<>(admService.findAllConsultasRealizadas(), HttpStatus.OK); } @ApiOperation(value = "Mostra todas as consultas cadastradas pela data.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retornado com sucesso a lista de consultas."), @ApiResponse(code = 500, message = "Erro ao processar a listagem de consulta.") }) @GetMapping(value = "/consultas/{data}") public ResponseEntity<List<Cliente>> listaConsultasPorData(@PathVariable("data") String data) { return new ResponseEntity<>(admService.findConsultasPorData(data), HttpStatus.OK); } @ApiOperation(value = "Mostra todas as consultas cadastradas na data atual.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retornado com sucesso a lista de consultas."), @ApiResponse(code = 500, message = "Erro ao processar a listagem de consulta.") }) @GetMapping(value = "/consultas/consultasDoDia") public ResponseEntity<List<Cliente>> consultasDoDia() { return new ResponseEntity<>(admService.findConsultasDoDia(), HttpStatus.OK); } @ApiOperation(value = "Mostra todas as consultas realizadas em um dado período.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retornado com sucesso a lista de consultas."), @ApiResponse(code = 500, message = "Erro ao processar a listagem de consultas.") }) @GetMapping(value = "/consultasRealizadas/{dataInicial}/{dataFinal}") public ResponseEntity<List<ConsultaRealizada>> consultaRealizadasPorPeriodo(@PathVariable String dataInicial, @PathVariable String dataFinal) { return new ResponseEntity<>(admService.findConsultasRealizadasPorPeriodo(dataInicial, dataFinal), HttpStatus.OK); } } <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/dto/ClienteDTO.java package com.turingtecnologia.albatroz.backendalbatroz.dto; import lombok.Data; import javax.validation.constraints.*; @Data public class ClienteDTO { @NotBlank(message ="Contato " + "{not.blank}") private String contatoCliente; @NotNull(message = "{cpf.not.null}") @Digits(integer = 11, fraction = 0) @DecimalMax(value = "99999999999", message = "{cpf.limit.value}") @DecimalMin(value = "11111111111", message = "{cpf.limit.value}") private String cpfCliente; @NotBlank(message = "Email " + "{not.blank}") @Email(message = "{email.not.valid}") private String emailCliente; @NotBlank(message = "Endereço " + "{not.blank}") private String enderecoCliente; @NotBlank(message = "Nome do cliente " + "{not.blank}") private String nomeCliente; } <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/services/implementations/AdministradorServiceImplementation.java package com.turingtecnologia.albatroz.backendalbatroz.services.implementations; import com.sendgrid.*; import com.turingtecnologia.albatroz.backendalbatroz.exceptions.error.ResourceNotFoundException; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Cliente; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Consulta; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.ConsultaRealizada; import com.turingtecnologia.albatroz.backendalbatroz.model.jpaRepositoy.ClienteRepository; import com.turingtecnologia.albatroz.backendalbatroz.model.jpaRepositoy.ConsultaRealizadaRepository; import com.turingtecnologia.albatroz.backendalbatroz.model.jpaRepositoy.ConsultaRepository; import com.turingtecnologia.albatroz.backendalbatroz.services.interfaces.AdministradorService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; @Service @AllArgsConstructor public class AdministradorServiceImplementation implements AdministradorService { private final ConsultaRepository consultaRepository; private final ConsultaRealizadaRepository consultaRealizadaRepository; private final ClienteRepository clienteRepository; @Override public List<Cliente> findAllClientes() { List<Cliente> clientes = clienteRepository.findAll(); for (Cliente cliente : clientes) { cliente.getConsultasRealizadasCliente().clear(); } return clienteRepository.findAll(); } @Override public void removeCliente(Cliente cliente) { cliente.setIdCliente(clienteRepository. findByCpfCliente(cliente.getCpfCliente()).getIdCliente()); verificaClienteCPF(cliente.getCpfCliente()); removeConsultasCliente(cliente); clienteRepository.delete(cliente); } @Override public Cliente alteraCliente(Cliente cliente) { verificaClienteCPF(cliente.getCpfCliente()); cliente.setIdCliente(clienteRepository.findByCpfCliente(cliente.getCpfCliente()).getIdCliente()); return clienteRepository.save(cliente); } @Override public Consulta marcaCheckIn(Long idConsulta) { verificaConsultaId(idConsulta); Consulta consulta = consultaRepository.findByIdConsulta(idConsulta); List<Consulta> consultaList = consultaRepository.findByDataConsultaOrderByIdConsulta(consulta.getDataConsulta()); TimeZone timeZone = TimeZone.getTimeZone("America/Sao_Paulo"); TimeZone.setDefault(timeZone); Calendar currentDateTime = Calendar.getInstance(timeZone); Date hora = new Date(); hora.setTime(currentDateTime.getTimeInMillis()); consulta.setCheckInConsulta(hora); for (Consulta c : consultaList) { if (c.getNumeroFichaConsulta() == consulta.getNumeroFichaConsulta() + 1) { sendEmail(clienteRepository.findByCpfCliente(c.getClienteConsulta().getCpfCliente()).getEmailCliente()); } } return consultaRepository.save(consulta); } @Override public void marcaCheckOut(Long idConsulta) { verificaConsultaId(idConsulta); Consulta consulta = consultaRepository.findByIdConsulta(idConsulta); TimeZone timeZone = TimeZone.getTimeZone("Ameria/Sao_Paulo"); TimeZone.setDefault(timeZone); Calendar currentDateTime = Calendar.getInstance(timeZone); Date hora = new Date(); hora.setTime(currentDateTime.getTimeInMillis()); consulta.setCheckOutConsulta(hora); ConsultaRealizada consultaRealizada = new ConsultaRealizada(consulta); consultaRealizadaRepository.save(consultaRealizada); consultaRepository.delete(consulta); } @Override public List<Consulta> findAllConsultas() { return consultaRepository.findAll(); } @Override public List<ConsultaRealizada> findAllConsultasRealizadas() { return consultaRealizadaRepository.findAll(); } @Override public List<Cliente> findConsultasPorData(String data) { Date d1; Calendar dataConsulta = Calendar.getInstance(); try { d1 = new SimpleDateFormat("yyyy-MM-dd").parse(data); dataConsulta.setTime(d1); } catch (ParseException e) { e.printStackTrace(); } List<Consulta> consultas = consultaRepository.findByDataConsultaOrderByIdConsulta(dataConsulta); List<Cliente> clientes = new ArrayList<>(); for (int i = 0; i < consultas.size(); i++) { if (!(consultas.get(i).getClienteConsulta() == null)) { Cliente cliente = clienteRepository.findByCpfCliente(consultas.get(i).getClienteConsulta().getCpfCliente()); clientes.add(cliente); } clientes.get(i).getConsultasRealizadasCliente().clear(); } for (Cliente cliente : clientes) { cliente.getConsultasCliente().removeIf(consulta -> !consulta.getDataConsulta().equals(dataConsulta)); } LinkedHashSet<Cliente> hashSet = new LinkedHashSet<>(clientes); return new ArrayList<>(hashSet); } @Override public List<Cliente> findConsultasDoDia() { Calendar dataConsulta = geraDataAtual(); List<Consulta> consultas = consultaRepository.findByDataConsultaOrderByIdConsulta(dataConsulta); List<Cliente> clientes = new ArrayList<>(); for (int i = 0; i < consultas.size(); i++) { if (!(consultas.get(i).getClienteConsulta() == null)) { Cliente cliente = clienteRepository.findByCpfCliente(consultas.get(i).getClienteConsulta().getCpfCliente()); clientes.add(cliente); } clientes.get(i).getConsultasRealizadasCliente().clear(); } for (Cliente cliente : clientes) { cliente.getConsultasCliente().removeIf(consulta -> !datasIguais(consulta.getDataConsulta(), dataConsulta)); } LinkedHashSet<Cliente> hashSet = new LinkedHashSet<>(clientes); return new ArrayList<>(hashSet); } @Override public List<ConsultaRealizada> findConsultasRealizadasPorPeriodo(String dataInicial, String dataFinal) { Calendar data1 = Calendar.getInstance(); Calendar data2 = Calendar.getInstance(); try { Date d1 = new SimpleDateFormat("yyyy-MM-dd").parse(dataInicial); Date d2 = new SimpleDateFormat("yyyy-MM-dd").parse(dataFinal); data1.setTime(d1); data2.setTime(d2); } catch (ParseException ex) { ex.printStackTrace(); } return consultaRealizadaRepository.findByDataConsultaRelizadaBetween(data1, data2); } private boolean datasIguais(Calendar data1, Calendar data2) { int dia1 = data1.get(Calendar.DAY_OF_MONTH); int dia2 = data2.get(Calendar.DAY_OF_MONTH); int mes1 = data1.get(Calendar.MONTH); int mes2 = data2.get(Calendar.MONTH); int ano1 = data1.get(Calendar.YEAR); int ano2 = data1.get(Calendar.YEAR); return (ano1 == ano2 && mes1 == mes2 && dia1 == dia2); } private void sendEmail(String email) { Email from = new Email("<EMAIL>"); Email to = new Email(email); Content content = new Content("text/plain", "Você é próximo da fila! Por favor, compareça à clínica, assim que possível, para aguardar o seu atendimento."); Mail mail = new Mail(from, "Situação da fila de atendimentos da Clínica Sorrir", to, content); SendGrid sg = new SendGrid(System.getenv("SENDGRID_KEY_ACCESS")); Request request = new Request(); try { request.setMethod(Method.POST); request.setEndpoint("mail/send"); request.setBody(mail.build()); Response response = sg.api(request); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); System.out.println(response.getHeaders()); } catch (IOException e) { e.printStackTrace(); } } private void verificaConsultaId(long id) { if (consultaRepository.findByIdConsulta(id) == null) { throw new ResourceNotFoundException("Não existe consulta com esse ID = " + id); } } private void verificaClienteCPF(String cpf) { if (clienteRepository.findByCpfCliente(cpf) == null) { throw new ResourceNotFoundException("Não existe clinte com esse CPF = " + cpf); } } private void removeConsultasCliente(Cliente cliente) { List<Consulta> consultasMarcadas = consultaRepository.findByClienteConsulta(cliente); List<ConsultaRealizada> consultasRealizadas = consultaRealizadaRepository.findByClienteConsultaRealizada(cliente); for (ConsultaRealizada consultaRealizada : consultasRealizadas) { consultaRealizadaRepository.delete(consultaRealizada); } for (Consulta consulta : consultasMarcadas) { consultaRepository.delete(consulta); } } private Calendar geraDataAtual(){ Calendar data = Calendar.getInstance(); data.clear(); TimeZone timeZone = TimeZone.getTimeZone("America/Sao_Paulo"); TimeZone.setDefault(timeZone); data.set(Calendar.YEAR, Calendar.getInstance(timeZone).get(Calendar.YEAR)); data.set(Calendar.MONTH, Calendar.getInstance(timeZone).get(Calendar.MONTH)); data.set(Calendar.DAY_OF_MONTH, Calendar.getInstance(timeZone).get(Calendar.DAY_OF_MONTH)); data.set(Calendar.HOUR_OF_DAY, 0); data.set(Calendar.MINUTE, 0); data.set(Calendar.SECOND, 0); data.set(Calendar.MILLISECOND, 0); return data; } } <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/services/interfaces/ConsultaService.java package com.turingtecnologia.albatroz.backendalbatroz.services.interfaces; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Consulta; public interface ConsultaService { Consulta alteraConsulta(Consulta consulta); Consulta addConsulta(Consulta consulta); Consulta findByIdConsulta(Long id); void remove(Long id); } <file_sep>/README.md # Backend da aplicação da clínica de odontologia (codinome Albatroz). ## Como sou executado localmente? - instale o [Java](https://adoptopenjdk.net/) - instale o [PostgreSQL+pgAdmin](https://www.postgresql.org/download/), com senha. - crie a base de dados `albatroz` no PostgreSQL (Servers->PostgreSQL->Create->Database) - clone o projeto - modifique a senha do sgbd no arquivo src/main/resources/application.properties - execute `./mvnw clean package -DskipTests spring-boot:run` no terminal na pasta do projeto - os endpoints da API estarão disponíveis em: [http://localhost:8080/swagger-ui.html](http://localhost:8080/swagger-ui.html) *Obs. 1: Há restrição dos dias de salvar consultas para terças e quintas. Ao testar, remova a restrição na classe "ConsultaServiceImplementation.java"* *Obs. 2: O Albatroz foi testado com a OpenJDK 11(LTS)+JVM HotSpot. Em testes com a OpenJ9 ocorreu dump de memória. Não foi testado na GraalVM.* <file_sep>/src/main/java/com/turingtecnologia/albatroz/backendalbatroz/services/interfaces/ClienteService.java package com.turingtecnologia.albatroz.backendalbatroz.services.interfaces; import com.turingtecnologia.albatroz.backendalbatroz.model.entities.Cliente; public interface ClienteService { Cliente addCliente(Cliente cliente); Cliente findByCpfCliente(String cpf); } <file_sep>/src/main/resources/ValidationMessages.properties not.blank= não pode está em branco. cpf.not.null=CPF não deve estar em branco. email.not.valid=Endereço de email estar no formato errado. cpf.limit.value=CPF deve ter 11 digitos. cliente.not.null=Cliente não pode ser Null
44843e18a23ad3a533b93671fd05fdbafad6fcd6
[ "Markdown", "Java", "INI" ]
13
Java
cesarionto/treinamento-backend
139481bcc9b5204fde85d7904319bb7d64b8d3ad
533ceb3c857f904c4307ef206ae51834c4994980
refs/heads/main
<file_sep>class Car (var model : String, var year :Int) { } <file_sep>fun main() { var car1 = Car( model = "Toyota", year = 2022, ) println(car1.model + " " + car1.year) var book1 = arrayOf<Book>( Book("Game of Thrones","<NAME>",54.00), Book("We Were Liars", "<NAME>", 30.00) ) book1[0].bookDetails(true) book1[1].bookDetails(false) } <file_sep>class Book(var title: String, var author: String, var price: Double) { fun bookDetails(inStock: Boolean) { if (inStock) println("Book Details \nName :$title \nAuthor: $author \nPrice: $price \nAvailability : In stock") else println("Book Details \nName :$title \nAuthor: $author \nPrice: $price \nAvailability : Out stock") } }
4c0fda66c6118bc5419cb4322e6cf3f37b88492c
[ "Kotlin" ]
3
Kotlin
nja7m/HW_Week1_Day5_DefiningClasses
2ed008393f0967844f364a6e72b0fa33f21eb33e
ea40a036ba44c88dd441b77b97ad3b8381715117
refs/heads/master
<repo_name>stevarino/cmsc495<file_sep>/requirements.txt Django django-extensions pygraphviz pyparsing pydot<file_sep>/mac_app/migrations/0002_auto_20170413_1845.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-13 18:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mac_app', '0001_initial'), ] operations = [ migrations.AddField( model_name='ticketnote', name='from_state', field=models.CharField(choices=[('n', 'Emailed, awaiting response'), ('w', 'Emailed, awaiting response'), ('p', 'Work Acknowledged - In Progress'), ('c', 'Work has been documented complete')], default='n', max_length=1), preserve_default=False, ), migrations.AddField( model_name='ticketnote', name='to_state', field=models.CharField(choices=[('n', 'Emailed, awaiting response'), ('w', 'Emailed, awaiting response'), ('p', 'Work Acknowledged - In Progress'), ('c', 'Work has been documented complete')], default='n', max_length=1), preserve_default=False, ), migrations.AlterField( model_name='ticket', name='dsk_stage', field=models.CharField(choices=[('n', 'Emailed, awaiting response'), ('w', 'Emailed, awaiting response'), ('p', 'Work Acknowledged - In Progress'), ('c', 'Work has been documented complete')], default='n', max_length=1), ), migrations.AlterField( model_name='ticket', name='fac_stage', field=models.CharField(choices=[('n', 'Emailed, awaiting response'), ('w', 'Emailed, awaiting response'), ('p', 'Work Acknowledged - In Progress'), ('c', 'Work has been documented complete')], default='n', max_length=1), ), migrations.AlterField( model_name='ticket', name='net_stage', field=models.CharField(choices=[('n', 'Emailed, awaiting response'), ('w', 'Emailed, awaiting response'), ('p', 'Work Acknowledged - In Progress'), ('c', 'Work has been documented complete')], default='n', max_length=1), ), migrations.AlterField( model_name='tickettype', name='dsk_msg', field=models.TextField(blank=True, verbose_name='Desktop Message'), ), migrations.AlterField( model_name='tickettype', name='fac_msg', field=models.TextField(blank=True, verbose_name='Facilities Message'), ), migrations.AlterField( model_name='tickettype', name='net_msg', field=models.TextField(blank=True, verbose_name='Network Message'), ), ] <file_sep>/scripts/restart-web.sh docker-compose stop web docker-compose build web docker-compose run web python manage.py makemigrations docker-compose run web python manage.py migrate docker-compose up -d --no-deps web <file_sep>/mac_app/migrations/0009_auto_20170413_2226.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-13 22:26 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('mac_app', '0008_tickettype_code'), ] operations = [ migrations.RenameField( model_name='ticketnote', old_name='deptartment', new_name='department', ), ] <file_sep>/mac_app/migrations/0003_auto_20170413_1847.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-13 18:47 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mac_app', '0002_auto_20170413_1845'), ] operations = [ migrations.AddField( model_name='department', name='descrioption', field=models.CharField(default='', max_length=128), ), migrations.AlterField( model_name='department', name='name', field=models.CharField(max_length=10), ), ] <file_sep>/mac_app/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-13 18:29 from __future__ import unicode_literals import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion import mac_app.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Department', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128)), ], ), migrations.CreateModel( name='Profile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('domain', models.CharField(default='corp', max_length=128)), ('firstname', models.CharField(blank=True, max_length=128)), ('lastname', models.CharField(blank=True, max_length=128)), ('address', models.CharField(blank=True, max_length=256)), ('city', models.CharField(blank=True, max_length=128)), ('state', models.CharField(blank=True, max_length=128)), ('postal_code', models.CharField(blank=True, max_length=16)), ('phone', models.CharField(blank=True, max_length=16)), ('department', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='mac_app.Department')), ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Ticket', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('number', models.CharField(default=mac_app.models.get_new_ticket_number, max_length=32)), ('creation_date', models.DateTimeField(default=datetime.datetime.now, verbose_name='date created')), ('dsk_stage', models.IntegerField(default=0)), ('net_stage', models.IntegerField(default=0)), ('fac_stage', models.IntegerField(default=0)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets_started', to=settings.AUTH_USER_MODEL)), ('target', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets', to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='TicketNote', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('creation_date', models.DateTimeField(default=datetime.datetime.now, verbose_name='date created')), ('content', models.TextField(blank=True)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ('ticket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mac_app.Ticket')), ], ), migrations.CreateModel( name='TicketType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=16)), ('dsk_seq', models.IntegerField(default=0, verbose_name='Desktop Sequence')), ('dsk_msg', models.TextField(verbose_name='Desktop Message')), ('net_seq', models.IntegerField(default=0, verbose_name='Network Sequence')), ('net_msg', models.TextField(verbose_name='Network Message')), ('fac_seq', models.IntegerField(default=0, verbose_name='Facilities Sequence')), ('fac_msg', models.TextField(verbose_name='Facilities Message')), ], ), migrations.AddField( model_name='ticket', name='ticket_type', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='mac_app.TicketType'), ), ] <file_sep>/mac_app/views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, redirect, get_object_or_404 from django.http import HttpResponse, Http404 from django.core.exceptions import PermissionDenied from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from .models import Ticket, TicketType, TicketNote, Department from .forms import NewUserTicket, UserSearchForm def index(request): '''Unauthenticated login view''' context = {'no_sidebar': True} if 'username' in request.POST: username = request.POST['username'] password = request.POST['<PASSWORD>'] user = authenticate(username=username, password=<PASSWORD>) if user is not None: login(request, user) else: context['error'] = "Unrecognized Username/Password combination." if request.user.is_authenticated(): return redirect('tickets') return render(request, 'mac_app/login.html', context) def logout_view(request): '''Logout view. Unauthenticates user.''' logout(request) return redirect('index') # ticket list view @login_required(login_url='/') def tickets(request): '''Ticket Overview page (multiple tickets)''' context = {} user_dept = request.user.profile.department.name.lower() context['is_hr'] = request.user.is_superuser or user_dept == 'hr' context['departments'] = [] for d in ['dsk', 'fac', 'net']: dept = { 'department': Department.objects.get(name=d.upper()), 'user_in_dept': request.user.is_superuser or user_dept == d, 'tickets': [], } for t in Ticket.objects.filter(**{d+'_stage__in': ['w', 'p']}): dept['tickets'].append({ 'ticket': t, 'state': getattr(t, d+'_stage'), 'state_text': getattr(t, d+'_stage_text'), }) context['departments'].append(dept) context['tickets'] = Ticket.objects.order_by('-modification_date') return render(request, 'mac_app/tickets.html', context) # User view @login_required(login_url='/') def user_view(request, username): '''View user info.''' context = {} user = get_object_or_404(User, username=username) context['user'] = user context['tickets'] = Ticket.objects.filter(target=user).order_by( '-creation_date') context['notes'] = TicketNote.objects.filter(author=user).order_by( '-creation_date') user_dept = request.user.profile.department.name.lower() context['is_hr'] = request.user.is_superuser or user_dept == 'hr' return render(request, 'mac_app/user.html', context) # Ticket detail view @login_required(login_url='/') def ticket_detail(request, ticket_num): '''Ticket detail page (single ticket)''' context = {} ticket = get_object_or_404(Ticket, number=ticket_num) is_super = request.user.is_superuser or request.user.profile.department.name == 'admin' if request.method == 'POST': department = Department.objects.get(name=request.POST['dept'].upper()) require_dept(request, department) state = getattr(ticket, request.POST['dept']+'_stage') note = TicketNote(ticket=ticket, author=request.user, department=department, from_state=state, to_state=request.POST['state'], content=request.POST['notes']) note.save() ticket.set_dept_stage(request.POST['dept'], request.POST['state']) return redirect('ticket_detail', ticket_num=ticket.number) context['ticket'] = ticket context['is_hr'] = is_super or request.user.profile.department.name == 'HR' context['is_fac'] = is_super or request.user.profile.department.name == 'FAC' context['is_net'] = is_super or request.user.profile.department.name == 'NET' context['is_dsk'] = is_super or request.user.profile.department.name == 'DSK' context['departments'] = [ { 'name': "Facilities", 'status': ticket.fac_stage, 'status_text': ticket.fac_stage_text(), }, { 'name': "Desktop Support", 'status': ticket.dsk_stage, 'status_text': ticket.dsk_stage_text(), }, { 'name': "Network Admin", 'status': ticket.net_stage, 'status_text': ticket.net_stage_text(), }, ] return render(request, 'mac_app/ticket_detail.html', context) # New ticket view @login_required(login_url='/') def ticket_new(request): '''Creates a ticket for a new user.''' require_dept(request, 'HR') if request.method == 'POST': form = NewUserTicket(request.POST) if form.is_valid(): user = User.objects.create_user(form.cleaned_data['username'], '', form.cleaned_data['password']) user.first_name = form.cleaned_data['firstname'] user.last_name = form.cleaned_data['lastname'] for f in 'address city state postal_code phone department'.split(' '): setattr(user.profile, f, form.cleaned_data[f]) user.save() new_type = TicketType.objects.get(code='nw') ticket = Ticket(author=request.user, target=user, ticket_type=new_type) ticket.save() note = TicketNote(ticket=ticket, author=request.user, department=Department.objects.get(name='HR'), from_state='n', to_state='c', content=request.POST['notes']) note.save() ticket.enter_stage() return redirect('ticket_detail', ticket_num=ticket.number) else: form = NewUserTicket() return render(request, 'mac_app/ticket_new.html', {'form': form}) @login_required(login_url='/') def ticket_edit(request, action): '''Creates a user edit ticket with a sepcific action (move, remove)''' require_dept(request, 'HR') if action not in ['move_user', 'remove_user']: raise Http404("Action not found") users = [] form = UserSearchForm() if request.method == 'GET': form = UserSearchForm(request.GET) if form.is_valid(): users = form.get_users() return render(request, 'mac_app/user_search.html', {'form': form, 'users': users, 'action': action}) @login_required(login_url='/') def ticket_user(request, action, username): '''Creates a user edit ticket with a specific action and user''' require_dept(request, 'HR') types = {'move_user': 'mv', 'remove_user': 'rm'} user = get_object_or_404(User, username=username) if action not in types.keys(): raise Http404("Action not found") if request.method == 'POST' and 'notes' in request.POST: return create_ticket(request.user, types[action], user, notes=request.POST['notes']) return render(request, 'mac_app/ticket_user.html', { 'user': user, 'type': TicketType.objects.get(code=types[action]) }) # function to create a ticket for all three paths. def create_ticket(req_user, type_code, user, notes='', dept='HR'): '''Helper function to create a ticket.''' new_type = TicketType.objects.get(code=type_code) ticket = Ticket(author=req_user, target=user, ticket_type=new_type) ticket.save() note = TicketNote(ticket=ticket, author=req_user, department=Department.objects.get(name=dept), from_state='n', to_state='c', content=notes) note.save() ticket.enter_stage() return redirect('ticket_detail', ticket_num=ticket.number) def require_dept(request, dept): '''Helper function to check the authenticated user belongs to the given department (or is a super user)''' is_super = request.user.is_superuser or request.user.profile.department.name == 'admin' if not is_super and request.user.profile.department.name != dept: raise PermissionDenied @login_required(login_url='/') def users_view(request): '''User search form.''' users = [] form = UserSearchForm() if request.method == 'GET': form = UserSearchForm(request.GET) if form.is_valid(): users = form.get_users() return render(request, 'mac_app/user_search.html', {'form': form, 'users': users})<file_sep>/mac_app/migrations/0005_auto_20170413_1910.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-13 19:10 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mac_app', '0004_auto_20170413_1848'), ] operations = [ migrations.RemoveField( model_name='profile', name='firstname', ), migrations.RemoveField( model_name='profile', name='lastname', ), migrations.AlterField( model_name='ticket', name='dsk_stage', field=models.CharField(choices=[('n', 'Pending Assignment'), ('w', 'Awaiting Response'), ('p', 'In Progress'), ('c', 'Complete')], default='n', max_length=1, verbose_name='Desktop Support Stage'), ), migrations.AlterField( model_name='ticket', name='fac_stage', field=models.CharField(choices=[('n', 'Pending Assignment'), ('w', 'Awaiting Response'), ('p', 'In Progress'), ('c', 'Complete')], default='n', max_length=1, verbose_name='Facilities Stage'), ), migrations.AlterField( model_name='ticket', name='net_stage', field=models.CharField(choices=[('n', 'Pending Assignment'), ('w', 'Awaiting Response'), ('p', 'In Progress'), ('c', 'Complete')], default='n', max_length=1, verbose_name='Network Admin Stage'), ), migrations.AlterField( model_name='ticketnote', name='from_state', field=models.CharField(blank=True, choices=[('n', 'Pending Assignment'), ('w', 'Awaiting Response'), ('p', 'In Progress'), ('c', 'Complete')], max_length=1), ), migrations.AlterField( model_name='ticketnote', name='to_state', field=models.CharField(blank=True, choices=[('n', 'Pending Assignment'), ('w', 'Awaiting Response'), ('p', 'In Progress'), ('c', 'Complete')], max_length=1), ), ] <file_sep>/mac_app/templates/mac_app/ticket_detail.html {% extends 'mac_app/base.html' %} {% block head %} <style type='text/css'> .hidden_note { display: none; } .hidden_note td { text-align: left; padding: 1em 0; } .ticket_status td { padding: 0.2em 0.5em; } .row-label { font-weight: bold; text-align: right; } .no-header tr:first-child th, .no-header tr:first-child td, .table tr.hidden_note td { border-top: 0; } </style> <script type='text/javascript'> $(function() { $('.show_note').click(function(e) { e.preventDefault(); var id = "#"+$(this).attr('data-noteid'); if ($(id).is(':visible')) { $(this).text("Show Details"); } else { $(this).text("Hide Details"); } $(id).toggle() }); }); </script> {% endblock %} {% block content %} <h2>{{ ticket.number }}</h2> <h3>Current Status - {% if ticket.is_complete %} Closed {% else %} Open {%endif %} </h3> <table class='table'> <thead class='thead-default'> <tr><th>Department</th><th>Progress</th></tr> </thead> <tbody> {% for dept in departments %} <tr> <th scope="row" class='col-sm-3'>{{dept.name}}</th> <td> {% if dept.status == 'n' %} <span class="label label-default" style='margin-right: 0.5em'> <span class="glyphicon glyphicon-time"></span> </span> {% elif dept.status == 'w' %} <span class="label label-warning" style='margin-right: 0.5em'> <span class="glyphicon glyphicon-envelope"></span> </span> {% elif dept.status == 'p' %} <span class="label label-primary" style='margin-right: 0.5em'> <span class="glyphicon glyphicon-option-horizontal"></span> </span> {% elif dept.status == 'c' %} <span class="label label-success" style='margin-right: 0.5em'> <span class="glyphicon glyphicon-ok"></span> </span> {% endif %} {{dept.status_text}} </td> </tr> {% endfor %} </tbody> </table> <h3>Ticket Detail</h3> <table class='table no-header'> <tbody> <tr> <th scope='row' class='col-sm-3'>Ticket Type:</th> <td> {% if ticket.ticket_type.code == 'mv' %} Move User {% elif ticket.ticket_type.code == 'rm' %} Remove User {% elif ticket.ticket_type.code == 'nw' %} New User {% else %} Unknown {% endif %} </td> </tr> <tr> <th scope='row' class='col-sm-3'>Username:</th> <td> <a href="{% url 'user_view' username=ticket.target.username %}"> {{ticket.target.username}} </a> </td> </tr> <tr> <th scope='row' class='col-sm-3'>First Name:</th> <td>{{ticket.target.first_name}}</td> </tr> <tr> <th scope='row' class='col-sm-3'>Last Name:</th> <td>{{ticket.target.last_name}}</td> </tr> <tr> <th scope='row' class='col-sm-3'>Department:</th> <td>{{ticket.target.profile.department.description}}</td> </tr> <tr> <th scope='row' class='col-sm-3'>Requested By:</th> <td>{{ticket.author}}</td> </tr> </tbody> </table> <h3>Ticket History</h3> <table class='table'> <thead> <tr> <th>Date</th> <th>User</th> <th>From State</th> <th>To State</th> <th>Details</th> </tr> </thead> <tbody> {% for note in ticket.ticketnote_set.all %} <tr> <td>{{note.creation_date|date:"Y-m-d H:i:s"}}</td> <td> <a href="{% url 'user_view' username=note.author.username %}"> {{note.author.username}}</a> ({{note.department.name}})</td> <td>{{note.from_state_text}}</td> <td>{{note.to_state_text}}</td> <td>{% if note.content %} <a href="#" class='show_note' data-noteid='note_{{note.pk}}'>Show Details</a>{% endif %} </td> </tr> {% if note.content %} <tr class="hidden_note" id='note_{{note.pk}}'> <td colspan='5' class='detail'>{{note.content|linebreaks}}</td> </tr> {% endif %} {% endfor %} </tbody> </table> {% if is_fac and ticket.fac_stage == 'w' %} <h3>Facilities Operations</h3> <form method='post'>{% csrf_token %} <p><textarea name='notes' rows='10' cols='40'></textarea></p> <input type='hidden' name='dept' value='fac' /> <button type='submit' name='state' value='p' class='btn btn-primary btn-block'> Acknowledge Receipt </button> </form> {% endif %} {% if is_fac and ticket.fac_stage == 'p' %} <h3>Facilities Operations</h3> {{ ticket.ticket_type.fac_msg|linebreaks }} <form method='post'>{% csrf_token %} <p><textarea name='notes' rows='10' cols='40'></textarea></p> <input type='hidden' name='dept' value='fac' /> <button type='submit' name='state' value='c' class='btn btn-success btn-block'> Work Is Complete </button> <button type='submit' name='state' value='w' class='btn btn-danger btn-block'> Cancel Work </button> </form> {% endif %} {% if is_dsk and ticket.dsk_stage == 'w' %} <h3>Desktop Support</h3> <form method='post'>{% csrf_token %} <p><textarea name='notes' rows='10' cols='40'></textarea></p> <input type='hidden' name='dept' value='dsk' /> <button type='submit' name='state' value='p' class='btn btn-primary btn-block'> Acknowledge Receipt </button> </form> {% endif %} {% if is_dsk and ticket.dsk_stage == 'p' %} <h3>Desktop Support</h3> {{ ticket.ticket_type.dsk_msg|linebreaks }} <form method='post'>{% csrf_token %} <p><textarea name='notes' rows='10' cols='40'></textarea></p> <input type='hidden' name='dept' value='dsk' /> <button type='submit' name='state' value='c' class='btn btn-success btn-block'> Work Is Complete </button> <button type='submit' name='state' value='w' class='btn btn-danger btn-block'> Cancel Work </button> </form> {% endif %} {% if is_net and ticket.net_stage == 'w' %} <h3>Network Administration</h3> <form method='post'>{% csrf_token %} <p><textarea name='notes' rows='10' cols='40'></textarea></p> <input type='hidden' name='dept' value='net' /> <button type='submit' name='state' value='p' class='btn btn-primary btn-block'> Acknowledge Receipt </button> </form> {% endif %} {% if is_net and ticket.net_stage == 'p' %} <h3>Network Administration</h3> {{ ticket.ticket_type.net_msg|linebreaks }} <form method='post'>{% csrf_token %} <p><textarea name='notes' rows='10' cols='40'></textarea></p> <input type='hidden' name='dept' value='net' /> <button type='submit' name='state' value='c' class='btn btn-success btn-block'> Work Is Complete </button> <button type='submit' name='state' value='w' class='btn btn-danger btn-block'> Cancel Work </button> </form> {% endif %} {% endblock %}<file_sep>/README.md # CMSC 495 Final Project This is a work-process automation web application designed to assist with coordination of preexisting business processes between departments.<file_sep>/mac_app/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^logout$', views.logout_view, name='logout'), url(r'^tickets/$', views.tickets, name='tickets'), url(r'^tickets/(?P<ticket_num>TK-[^/]+)/$', views.ticket_detail, name='ticket_detail'), url(r'^tickets/new/add_user/$', views.ticket_new, name='ticket_new'), url(r'^tickets/new/(?P<action>[^/]+)/$', views.ticket_edit, name='ticket_edit'), #url(r'^tickets/new/move_user/$', views.ticket_move, name='ticket_move'), #url(r'^tickets/new/remove_user/$', views.ticket_remove, name='ticket_remove'), url(r'^tickets/new/(?P<action>[^/]+)/(?P<username>[^/]+)/$', views.ticket_user, name='ticket_user'), url(r'^users/$', views.users_view, name='users_view'), url(r'^users/(?P<username>[^/]+)/$', views.user_view, name='user_view'), ]<file_sep>/mac_app/migrations/0006_ticketnote_deptartment.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-13 20:19 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('mac_app', '0005_auto_20170413_1910'), ] operations = [ migrations.AddField( model_name='ticketnote', name='deptartment', field=models.ForeignKey(blank=True, default=1, on_delete=django.db.models.deletion.CASCADE, to='mac_app.Department'), preserve_default=False, ), ] <file_sep>/mac_app/admin.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin # Register your models here. from mac_app.models import Ticket, TicketType, TicketNote, Profile, Department admin.site.register(Ticket) admin.site.register(TicketType) admin.site.register(TicketNote) admin.site.register(Profile) admin.site.register(Department)<file_sep>/mac_app/forms.py from django import forms from django.contrib.auth.models import User from .models import Department class NewUserTicket(forms.Form): username = forms.CharField(label='Username', max_length=32) password = forms.CharField(label='Password', widget=forms.PasswordInput) firstname = forms.CharField(label='First Name', max_length=32, required=False) lastname = forms.CharField(label='Last Name', max_length=32, required=False) address = forms.CharField(max_length=256, required=False) city = forms.CharField(max_length=128, required=False) state = forms.CharField(max_length=128, required=False) postal_code = forms.CharField(max_length=16, required=False) phone = forms.CharField(max_length=16, required=False) department = forms.ModelChoiceField(Department.objects.all()) # form validator to ensure unique username def clean_username(self): username = self.cleaned_data['username'] try: user = User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(u'Username "{}" is already in use.'.format(username)) class UserSearchForm(forms.Form): username = forms.CharField(label='Username', max_length=32, required=False) first_name = forms.CharField(label='First Name', max_length=32, required=False) last_name = forms.CharField(label='Last Name', max_length=32, required=False) def get_users(self): users = User.objects is_filtered = False for f in ['first_name', 'last_name', 'username']: if self.cleaned_data[f]: is_filtered = True users = users.filter(**{ f+'__icontains': self.cleaned_data[f] }) if is_filtered: return users return []<file_sep>/mac_app/migrations/0010_auto_20170413_2317.py # -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-13 23:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mac_app', '0009_auto_20170413_2226'), ] operations = [ migrations.AddField( model_name='ticket', name='is_complete', field=models.BooleanField(default=False), ), migrations.AddField( model_name='ticket', name='stage', field=models.IntegerField(default=0, verbose_name='Current Step'), ), ] <file_sep>/mac_app/models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. from datetime import datetime import uuid def get_new_ticket_number(): id = str(uuid.uuid4()).replace('-','').upper() i = 6 while 0 < Ticket.objects.filter(number=id[0:i]).count(): i += 1 if i > 32: id = str(uuid.uuid4()).replace('-','').upper() i = 6 return "TK-"+id[0:i] ticket_state = ( ('n', 'Pending'), # new ('w', 'Awaiting Response'), # waiting ('p', 'In Progress'), # in progress ('c', 'Complete'), # complete ) # Create your models here. class Ticket(models.Model): number = models.CharField(max_length=32, default=get_new_ticket_number) creation_date = models.DateTimeField('date created', default=datetime.now) modification_date = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, related_name='tickets_started') target = models.ForeignKey(User, related_name='tickets') ticket_type = models.ForeignKey("TicketType") stage = models.IntegerField(default=0, verbose_name='Current Step') is_complete = models.BooleanField(default=False) dsk_stage = models.CharField(max_length=1, choices=ticket_state, default='n', verbose_name='Desktop Support Stage') net_stage = models.CharField(max_length=1, choices=ticket_state, default='n', verbose_name='Network Admin Stage') fac_stage = models.CharField(max_length=1, choices=ticket_state, default='n', verbose_name='Facilities Stage') def __str__(self): return self.number def dsk_stage_text(self): return dict(ticket_state)[self.dsk_stage] def net_stage_text(self): return dict(ticket_state)[self.net_stage] def fac_stage_text(self): return dict(ticket_state)[self.fac_stage] # department stage updated def set_dept_stage(self, dept, state): setattr(self, dept+'_stage', state) self.process_stage() # determines if the current stage is done and if so increment def process_stage(self): if (self.dsk_stage == 'c' and self.net_stage == 'c' and self.fac_stage == 'c'): self.is_complete = True self.save() return next_stage = True for dept in ['dsk', 'net', 'fac']: department = Department.objects.get(name=dept.upper()) if getattr(self.ticket_type, dept+'_seq') == self.stage: next_stage = next_stage and getattr(self, dept+'_stage') == 'c' if next_stage: self.stage += 1 self.enter_stage() self.save() # handled at beginning of each stage def enter_stage(self): for dept in ['dsk', 'net', 'fac']: department = Department.objects.get(name=dept.upper()) # mark non-required departments as complete if getattr(self.ticket_type, dept+'_seq') == -1: setattr(self, dept+'_stage', 'c') if getattr(self.ticket_type, dept+'_seq') == self.stage: if getattr(self, dept+'_stage') == 'n': # mark new steps as pending setattr(self, dept+'_stage', 'w') users = Profile.objects.filter(department=department) # TODO: email users self.save() class TicketType(models.Model): name = models.CharField(max_length=16) code = models.CharField(max_length=4, default='') dsk_seq = models.IntegerField(default=0, verbose_name='Desktop Sequence') dsk_msg = models.TextField(verbose_name='Desktop Message', blank=True) net_seq = models.IntegerField(default=0, verbose_name='Network Sequence') net_msg = models.TextField(verbose_name='Network Message', blank=True) fac_seq = models.IntegerField(default=0, verbose_name='Facilities Sequence') fac_msg = models.TextField(verbose_name='Facilities Message', blank=True) def __str__(self): return self.name class TicketNote(models.Model): ticket = models.ForeignKey("Ticket") author = models.ForeignKey(User) # department added as superuser will have multiple departments department = models.ForeignKey("Department", blank=True) creation_date = models.DateTimeField('date created', default=datetime.now) from_state = models.CharField(max_length=1, choices=ticket_state, blank=True) to_state = models.CharField(max_length=1, choices=ticket_state, blank=True) content = models.TextField(blank=True) def from_state_text(self): return dict(ticket_state)[self.from_state] def to_state_text(self): return dict(ticket_state)[self.to_state] def __str__(self): return "{} - {} [{}] {}".format(self.ticket.number, self.author, self.department.name, self.creation_date) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) domain = models.CharField(max_length=128, default='corp') address = models.CharField(max_length=256, blank=True) city = models.CharField(max_length=128, blank=True) state = models.CharField(max_length=128, blank=True) postal_code = models.CharField(max_length=16, blank=True) phone = models.CharField(max_length=16, blank=True) department = models.ForeignKey("Department", blank=True, null=True) def __str__(self): return "{}".format(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() class Department(models.Model): name = models.CharField(max_length=10) description = models.CharField(max_length=128, default='') def __str__(self): return "{} [{}]".format(self.description, self.name)
00f943712ce62d1eb2705022190c19492a469dfb
[ "HTML", "Markdown", "Python", "Text", "Shell" ]
16
Text
stevarino/cmsc495
47640a197d235ff2881123bfc4cf63213c034f5a
6d63412a4bdab7dc44890a3be698264dfc5e0990
refs/heads/master
<repo_name>chinacode/shardingsphere-3.1.0.fix<file_sep>/README.md # shardingsphere-3.1.0.fix shardingsphere-3.1.0.fix fix page bugs <file_sep>/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/sctl/ShardingCTLSetBackendHandler.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingproxy.backend.sctl; import com.google.common.base.Optional; import io.shardingsphere.shardingproxy.backend.AbstractBackendHandler; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.ErrPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.OKPacket; import io.shardingsphere.transaction.api.TransactionType; /** * Sharding CTL backend handler. * * @author zhaojun */ public final class ShardingCTLSetBackendHandler extends AbstractBackendHandler { private final String sql; private final BackendConnection backendConnection; public ShardingCTLSetBackendHandler(final String sql, final BackendConnection backendConnection) { this.sql = sql.toUpperCase().trim(); this.backendConnection = backendConnection; } @Override protected CommandResponsePackets execute0() { Optional<ShardingCTLSetStatement> shardingTCLStatement = new ShardingCTLSetParser(sql).doParse(); if (!shardingTCLStatement.isPresent()) { return new CommandResponsePackets(new ErrPacket(" please review your sctl format, should be sctl:set xxx=yyy.")); } switch (shardingTCLStatement.get().getKey()) { case "TRANSACTION_TYPE": backendConnection.setTransactionType(TransactionType.valueOf(shardingTCLStatement.get().getValue())); break; default: return new CommandResponsePackets(new ErrPacket(String.format(" could not support this sctl grammar [%s].", sql))); } return new CommandResponsePackets(new OKPacket(1)); } } <file_sep>/sharding-transaction/sharding-transaction-2pc/sharding-transaction-2pc-xa/src/main/java/io/shardingsphere/transaction/xa/manager/XADataSourceWrapper.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.transaction.xa.manager; import com.atomikos.beans.PropertyException; import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.core.rule.DataSourceParameter; import javax.sql.DataSource; import javax.sql.XADataSource; /** * XA data source wrapper. * * @author zhaojun */ public interface XADataSourceWrapper { /** * Get a wrapper datasource pool for XA. * * @param databaseType database type * @param xaDataSource xa data source * @param dataSourceName data source name * @param parameter data source parameter * @return wrapper xa data source pool * @throws PropertyException property exception */ DataSource wrap(DatabaseType databaseType, XADataSource xaDataSource, String dataSourceName, DataSourceParameter parameter) throws PropertyException; } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/registry/listener/PostShardingOrchestrationEventListener.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.registry.listener; import com.google.common.eventbus.EventBus; import io.shardingsphere.orchestration.internal.eventbus.ShardingOrchestrationEventBus; import io.shardingsphere.orchestration.reg.api.RegistryCenter; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType; import io.shardingsphere.orchestration.reg.listener.DataChangedEventListener; import lombok.RequiredArgsConstructor; import java.util.Arrays; import java.util.Collection; /** * Post sharding orchestration event listener. * * @author zhangliang * @author panjuan */ @RequiredArgsConstructor public abstract class PostShardingOrchestrationEventListener implements ShardingOrchestrationListener { private final EventBus eventBus = ShardingOrchestrationEventBus.getInstance(); private final RegistryCenter regCenter; private final String watchKey; @Override public final void watch(final ChangedType... watchedChangedTypes) { final Collection<ChangedType> watchedChangedTypeList = Arrays.asList(watchedChangedTypes); regCenter.watch(watchKey, new DataChangedEventListener() { @Override public void onChange(final DataChangedEvent dataChangedEvent) { if (watchedChangedTypeList.contains(dataChangedEvent.getChangedType())) { eventBus.post(createShardingOrchestrationEvent(dataChangedEvent)); } } }); } protected abstract ShardingOrchestrationEvent createShardingOrchestrationEvent(DataChangedEvent event); } <file_sep>/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/backend/sctl/ShardingCTLSetBackendHandlerTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingproxy.backend.sctl; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.ErrPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.OKPacket; import io.shardingsphere.transaction.api.TransactionType; import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ShardingCTLSetBackendHandlerTest { private BackendConnection backendConnection = new BackendConnection(TransactionType.LOCAL); @Test public void assertSwitchTransactionTypeXA() { backendConnection.setCurrentSchema("schema"); ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set transaction_type=XA", backendConnection); CommandResponsePackets actual = shardingCTLBackendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(OKPacket.class)); assertThat(backendConnection.getTransactionType(), is(TransactionType.XA)); } @Test public void assertSwitchTransactionTypeBASE() { backendConnection.setCurrentSchema("schema"); ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set transaction_type=BASE", backendConnection); CommandResponsePackets actual = shardingCTLBackendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(OKPacket.class)); assertThat(backendConnection.getTransactionType(), is(TransactionType.BASE)); } @Test public void assertSwitchTransactionTypeLOCAL() { backendConnection.setCurrentSchema("schema"); ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set transaction_type=LOCAL", backendConnection); CommandResponsePackets actual = shardingCTLBackendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(OKPacket.class)); assertThat(backendConnection.getTransactionType(), is(TransactionType.LOCAL)); } @Test public void assertSwitchTransactionTypeFailed() { backendConnection.setCurrentSchema("schema"); ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set transaction_type=XXX", backendConnection); CommandResponsePackets actual = shardingCTLBackendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(ErrPacket.class)); assertThat(backendConnection.getTransactionType(), is(TransactionType.LOCAL)); } @Test public void assertNotSupportedSCTL() { ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set @@session=XXX", backendConnection); CommandResponsePackets actual = shardingCTLBackendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(ErrPacket.class)); } @Test public void assertFormatErrorSCTL() { ShardingCTLSetBackendHandler shardingCTLBackendHandler = new ShardingCTLSetBackendHandler("sctl:set yyyyy", backendConnection); CommandResponsePackets actual = shardingCTLBackendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(ErrPacket.class)); } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/registry/listener/ShardingOrchestrationListener.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.registry.listener; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType; /** * Sharding orchestration listener. * * @author caohao * @author panjuan */ public interface ShardingOrchestrationListener { /** * Start to watch. * * @param watchedChangedTypes watched data change types */ void watch(ChangedType... watchedChangedTypes); } <file_sep>/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/runtime/schema/ShardingSchema.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingproxy.runtime.schema; import com.google.common.eventbus.Subscribe; import io.shardingsphere.api.config.rule.ShardingRuleConfiguration; import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.core.constant.properties.ShardingPropertiesConstant; import io.shardingsphere.core.metadata.ShardingMetaData; import io.shardingsphere.core.rule.DataSourceParameter; import io.shardingsphere.core.rule.MasterSlaveRule; import io.shardingsphere.core.rule.ShardingRule; import io.shardingsphere.orchestration.internal.registry.config.event.ShardingRuleChangedEvent; import io.shardingsphere.orchestration.internal.registry.state.event.DisabledStateChangedEvent; import io.shardingsphere.orchestration.internal.registry.state.schema.OrchestrationShardingSchema; import io.shardingsphere.orchestration.internal.rule.OrchestrationMasterSlaveRule; import io.shardingsphere.orchestration.internal.rule.OrchestrationShardingRule; import io.shardingsphere.shardingproxy.backend.BackendExecutorContext; import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.runtime.metadata.ProxyTableMetaDataConnectionManager; import lombok.Getter; import java.util.Collection; import java.util.Map; /** * Sharding schema. * * @author zhangliang * @author zhangyonglun * @author panjuan * @author zhaojun * @author wangkai */ @Getter public final class ShardingSchema extends LogicSchema { private ShardingRule shardingRule; private final ShardingMetaData metaData; public ShardingSchema(final String name, final Map<String, DataSourceParameter> dataSources, final ShardingRuleConfiguration shardingRuleConfig, final boolean isCheckingMetaData, final boolean isUsingRegistry) { super(name, dataSources); shardingRule = createShardingRule(shardingRuleConfig, dataSources.keySet(), isUsingRegistry); metaData = createShardingMetaData(isCheckingMetaData); } private ShardingRule createShardingRule(final ShardingRuleConfiguration shardingRuleConfig, final Collection<String> dataSourceNames, final boolean isUsingRegistry) { return isUsingRegistry ? new OrchestrationShardingRule(shardingRuleConfig, dataSourceNames) : new ShardingRule(shardingRuleConfig, dataSourceNames); } private ShardingMetaData createShardingMetaData(final boolean isCheckingMetaData) { return new ShardingMetaData(getDataSourceURLs(getDataSources()), shardingRule, DatabaseType.MySQL, BackendExecutorContext.getInstance().getExecuteEngine(), new ProxyTableMetaDataConnectionManager(getBackendDataSource()), GlobalRegistry.getInstance().getShardingProperties().<Integer>getValue(ShardingPropertiesConstant.MAX_CONNECTIONS_SIZE_PER_QUERY), isCheckingMetaData); } /** * Renew sharding rule. * * @param shardingRuleChangedEvent sharding rule changed event. */ @Subscribe public synchronized void renew(final ShardingRuleChangedEvent shardingRuleChangedEvent) { if (getName().equals(shardingRuleChangedEvent.getShardingSchemaName())) { shardingRule = new OrchestrationShardingRule(shardingRuleChangedEvent.getShardingRuleConfiguration(), getDataSources().keySet()); } } /** * Renew disabled data source names. * * @param disabledStateChangedEvent disabled state changed event */ @Subscribe public synchronized void renew(final DisabledStateChangedEvent disabledStateChangedEvent) { OrchestrationShardingSchema shardingSchema = disabledStateChangedEvent.getShardingSchema(); if (getName().equals(shardingSchema.getSchemaName())) { for (MasterSlaveRule each : shardingRule.getMasterSlaveRules()) { ((OrchestrationMasterSlaveRule) each).updateDisabledDataSourceNames(shardingSchema.getDataSourceName(), disabledStateChangedEvent.isDisabled()); } } } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/test/java/io/shardingsphere/orchestration/yaml/YamlDataSourceConfigurationTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.yaml; import org.junit.Test; import org.yaml.snakeyaml.Yaml; import java.util.LinkedHashMap; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public final class YamlDataSourceConfigurationTest { @Test public void assertLoadFromYaml() { YamlDataSourceConfiguration expected = new YamlDataSourceConfiguration(); expected.setDataSourceClassName("com.zaxxer.hikari.HikariDataSource"); expected.setProperties(new LinkedHashMap<String, Object>(4, 1)); expected.getProperties().put("driverClassName", "org.h2.Driver"); expected.getProperties().put("jdbcUrl", "jdbc:h2:mem:test_ds;"); expected.getProperties().put("username", "root"); expected.getProperties().put("password", null); assertYamlDataSourceConfiguration(loadYamlDataSourceConfiguration("/yaml/datasource-configuration.yaml"), expected); } private YamlDataSourceConfiguration loadYamlDataSourceConfiguration(final String yamlFile) { return new Yaml().loadAs(YamlDataSourceConfigurationTest.class.getResourceAsStream(yamlFile), YamlDataSourceConfiguration.class); } private void assertYamlDataSourceConfiguration(final YamlDataSourceConfiguration actual, final YamlDataSourceConfiguration expected) { assertThat(actual.getDataSourceClassName(), is(expected.getDataSourceClassName())); assertThat(actual.getProperties().size(), is(4)); assertTrue(actual.getProperties().containsKey("driverClassName")); assertThat(actual.getProperties().get("driverClassName"), is(expected.getProperties().get("driverClassName"))); assertTrue(actual.getProperties().containsKey("jdbcUrl")); assertThat(actual.getProperties().get("jdbcUrl"), is(expected.getProperties().get("jdbcUrl"))); assertTrue(actual.getProperties().containsKey("username")); assertThat(actual.getProperties().get("username"), is(expected.getProperties().get("username"))); assertTrue(actual.getProperties().containsKey("password")); assertThat(actual.getProperties().get("password"), is(expected.getProperties().get("password"))); } @Test public void assertWriteToYaml() { YamlDataSourceConfiguration actual = new YamlDataSourceConfiguration(); actual.setDataSourceClassName("com.zaxxer.hikari.HikariDataSource"); actual.setProperties(new LinkedHashMap<String, Object>(4, 1)); actual.getProperties().put("driverClassName", "org.h2.Driver"); actual.getProperties().put("jdbcUrl", "jdbc:h2:mem:test_ds;"); actual.getProperties().put("username", "root"); actual.getProperties().put("password", null); assertThat(new Yaml(new DefaultYamlRepresenter()).dump(actual), is( "!!io.shardingsphere.orchestration.yaml.YamlDataSourceConfiguration\n" + "dataSourceClassName: com.zaxxer.hikari.HikariDataSource\n" + "properties: {driverClassName: org.h2.Driver, jdbcUrl: 'jdbc:h2:mem:test_ds;', username: root,\n password: null}\n")); } } <file_sep>/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/frontend/common/executor/CommandExecutorSelector.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingproxy.frontend.common.executor; import io.netty.channel.ChannelId; import io.shardingsphere.transaction.api.TransactionType; import lombok.RequiredArgsConstructor; import java.util.concurrent.ExecutorService; /** * Executor group. * * @author zhangliang * @author zhaojun */ @RequiredArgsConstructor public final class CommandExecutorSelector { /** * Get executor service. * * @param transactionType transaction type * @param channelId channel id * @return executor service */ public static ExecutorService getExecutor(final TransactionType transactionType, final ChannelId channelId) { return TransactionType.XA == transactionType ? ChannelThreadExecutorGroup.getInstance().get(channelId) : UserExecutorGroup.getInstance().getExecutorService(); } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/test/java/io/shardingsphere/orchestration/internal/rule/OrchestrationMasterSlaveRuleTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.rule; import com.google.common.collect.Sets; import io.shardingsphere.api.algorithm.masterslave.RandomMasterSlaveLoadBalanceAlgorithm; import io.shardingsphere.api.config.rule.MasterSlaveRuleConfiguration; import io.shardingsphere.orchestration.util.FieldUtil; import org.hamcrest.CoreMatchers; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import static org.junit.Assert.assertThat; public final class OrchestrationMasterSlaveRuleTest { private final OrchestrationMasterSlaveRule orchestrationMasterSlaveRule = new OrchestrationMasterSlaveRule( new MasterSlaveRuleConfiguration("test_ms", "master_db", Arrays.asList("slave_db_0", "slave_db_1"), new RandomMasterSlaveLoadBalanceAlgorithm())); @Test public void assertGetSlaveDataSourceNamesWithoutDisabledDataSourceNames() { assertThat(orchestrationMasterSlaveRule.getSlaveDataSourceNames(), CoreMatchers.<Collection<String>>is(Arrays.asList("slave_db_0", "slave_db_1"))); } @Test public void assertGetSlaveDataSourceNamesWithDisabledDataSourceNames() { orchestrationMasterSlaveRule.updateDisabledDataSourceNames("slave_db_0", true); assertThat(orchestrationMasterSlaveRule.getSlaveDataSourceNames(), CoreMatchers.<Collection<String>>is(Collections.singletonList("slave_db_1"))); } @Test public void assertUpdateDisabledDataSourceNamesForDisabled() { orchestrationMasterSlaveRule.updateDisabledDataSourceNames("slave_db_0", true); assertThat((Collection) FieldUtil.getFieldValue(orchestrationMasterSlaveRule, "disabledDataSourceNames"), CoreMatchers.<Collection>is(Sets.newHashSet("slave_db_0"))); } @Test public void assertUpdateDisabledDataSourceNamesForEnabled() { orchestrationMasterSlaveRule.updateDisabledDataSourceNames("slave_db_0", true); orchestrationMasterSlaveRule.updateDisabledDataSourceNames("slave_db_0", false); assertThat((Collection) FieldUtil.getFieldValue(orchestrationMasterSlaveRule, "disabledDataSourceNames"), CoreMatchers.<Collection>is(Collections.emptySet())); } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/test/java/io/shardingsphere/orchestration/internal/registry/config/listener/PropertiesChangedListenerTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.registry.config.listener; import io.shardingsphere.orchestration.reg.api.RegistryCenter; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(MockitoJUnitRunner.class) public final class PropertiesChangedListenerTest { private static final String PROPERTIES_YAML = "executor.size: 16\nsql.show: true"; private PropertiesChangedListener propertiesChangedListener; @Mock private RegistryCenter regCenter; @Before public void setUp() { propertiesChangedListener = new PropertiesChangedListener("test", regCenter); } @Test public void assertCreateShardingOrchestrationEvent() { assertThat(propertiesChangedListener.createShardingOrchestrationEvent(new DataChangedEvent("test", PROPERTIES_YAML, ChangedType.UPDATED)).getProps().get("sql.show"), is((Object) true)); } } <file_sep>/sharding-transaction/sharding-transaction-2pc/sharding-transaction-2pc-xa/src/test/java/io/shardingsphere/transaction/xa/convert/datasource/dialect/SQLServerXAPropertiesTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.transaction.xa.convert.datasource.dialect; import org.junit.Test; import java.util.Properties; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public final class SQLServerXAPropertiesTest extends BaseXAPropertiesTest { @Test public void assertBuild() { getDataSourceParameter().setUrl("jdbc:sqlserver://db.sqlserver:1433;DatabaseName=test_db"); Properties actual = new SQLServerXAProperties().build(getDataSourceParameter()); assertThat(actual.getProperty("user"), is("root")); assertThat(actual.getProperty("password"), is("<PASSWORD>")); assertThat(actual.getProperty("serverName"), is("db.sqlserver")); assertThat(actual.getProperty("portNumber"), is("1433")); assertThat(actual.getProperty("databaseName"), is("test_db")); } } <file_sep>/sharding-proxy/src/main/java/io/shardingsphere/shardingproxy/backend/ShowDatabasesBackendHandler.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingproxy.backend; import io.shardingsphere.core.merger.MergedResult; import io.shardingsphere.core.merger.dal.show.ShowDatabasesMergedResult; import io.shardingsphere.shardingproxy.runtime.GlobalRegistry; import io.shardingsphere.shardingproxy.transport.mysql.constant.ColumnType; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.ColumnDefinition41Packet; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.FieldCountPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.QueryResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.EofPacket; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; /** * Show databases backend handler. * * @author chenqingyang * @author zhaojun */ public final class ShowDatabasesBackendHandler extends AbstractBackendHandler { private MergedResult mergedResult; private int currentSequenceId; private int columnCount; private final List<ColumnType> columnTypes = new LinkedList<>(); @Override protected CommandResponsePackets execute0() { return handleShowDatabasesStatement(); } private CommandResponsePackets handleShowDatabasesStatement() { mergedResult = new ShowDatabasesMergedResult(GlobalRegistry.getInstance().getSchemaNames()); int sequenceId = 0; FieldCountPacket fieldCountPacket = new FieldCountPacket(++sequenceId, 1); Collection<ColumnDefinition41Packet> columnDefinition41Packets = new ArrayList<>(1); columnDefinition41Packets.add(new ColumnDefinition41Packet(++sequenceId, "", "", "", "Database", "", 100, ColumnType.MYSQL_TYPE_VARCHAR, 0)); QueryResponsePackets queryResponsePackets = new QueryResponsePackets(fieldCountPacket, columnDefinition41Packets, new EofPacket(++sequenceId)); currentSequenceId = queryResponsePackets.getPackets().size(); columnCount = queryResponsePackets.getColumnCount(); columnTypes.addAll(queryResponsePackets.getColumnTypes()); return queryResponsePackets; } @Override public boolean next() throws SQLException { return null != mergedResult && mergedResult.next(); } @Override public ResultPacket getResultValue() throws SQLException { List<Object> data = new ArrayList<>(columnCount); for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) { data.add(mergedResult.getValue(columnIndex, Object.class)); } return new ResultPacket(++currentSequenceId, data, columnCount, columnTypes); } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/test/java/io/shardingsphere/orchestration/internal/registry/config/AllConfigTests.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.registry.config; import io.shardingsphere.orchestration.internal.registry.config.listener.AuthenticationChangedListenerTest; import io.shardingsphere.orchestration.internal.registry.config.listener.ConfigMapChangedListenerTest; import io.shardingsphere.orchestration.internal.registry.config.listener.ConfigurationChangedListenerManagerTest; import io.shardingsphere.orchestration.internal.registry.config.listener.PropertiesChangedListenerTest; import io.shardingsphere.orchestration.internal.registry.config.listener.SchemaChangedListenerTest; import io.shardingsphere.orchestration.internal.registry.config.node.ConfigurationNodeTest; import io.shardingsphere.orchestration.internal.registry.config.service.ConfigurationServiceTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; @RunWith(Suite.class) @SuiteClasses({ ConfigurationNodeTest.class, ConfigurationServiceTest.class, ConfigurationChangedListenerManagerTest.class, PropertiesChangedListenerTest.class, AuthenticationChangedListenerTest.class, ConfigMapChangedListenerTest.class, SchemaChangedListenerTest.class }) public final class AllConfigTests { } <file_sep>/sharding-transaction/sharding-transaction-2pc/sharding-transaction-2pc-xa/src/test/java/io/shardingsphere/transaction/xa/convert/datasource/dialect/BaseXAPropertiesTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.transaction.xa.convert.datasource.dialect; import io.shardingsphere.core.rule.DataSourceParameter; import lombok.Getter; import org.junit.Before; @Getter public abstract class BaseXAPropertiesTest { private DataSourceParameter dataSourceParameter; @Before public void setUp() { dataSourceParameter = new DataSourceParameter(); dataSourceParameter.setUsername("root"); dataSourceParameter.setPassword("<PASSWORD>"); dataSourceParameter.setMaxPoolSize(100); dataSourceParameter.setConnectionTimeoutMilliseconds(1000); dataSourceParameter.setIdleTimeoutMilliseconds(1000); dataSourceParameter.setMaxLifetimeMilliseconds(60000); } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/main/java/io/shardingsphere/orchestration/internal/registry/config/listener/ConfigurationChangedListenerManager.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.registry.config.listener; import io.shardingsphere.orchestration.reg.api.RegistryCenter; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType; import java.util.Collection; /** * Configuration changed listener manager. * * @author zhangliang * @author panjuan */ public final class ConfigurationChangedListenerManager { private final SchemaChangedListener schemaChangedListener; private final PropertiesChangedListener propertiesChangedListener; private final AuthenticationChangedListener authenticationChangedListener; private final ConfigMapChangedListener configMapChangedListener; public ConfigurationChangedListenerManager(final String name, final RegistryCenter regCenter, final Collection<String> shardingSchemaNames) { schemaChangedListener = new SchemaChangedListener(name, regCenter, shardingSchemaNames); propertiesChangedListener = new PropertiesChangedListener(name, regCenter); authenticationChangedListener = new AuthenticationChangedListener(name, regCenter); configMapChangedListener = new ConfigMapChangedListener(name, regCenter); } /** * Initialize all configuration changed listeners. */ public void initListeners() { schemaChangedListener.watch(ChangedType.UPDATED, ChangedType.DELETED); propertiesChangedListener.watch(ChangedType.UPDATED); authenticationChangedListener.watch(ChangedType.UPDATED); configMapChangedListener.watch(ChangedType.UPDATED); } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/test/java/io/shardingsphere/orchestration/internal/registry/state/listener/StateChangedListenerManagerTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.registry.state.listener; import io.shardingsphere.orchestration.reg.api.RegistryCenter; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType; import io.shardingsphere.orchestration.util.FieldUtil; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.verify; @RunWith(MockitoJUnitRunner.class) public final class StateChangedListenerManagerTest { @Mock private RegistryCenter regCenter; @Mock private InstanceStateChangedListener instanceStateChangedListener; @Mock private DataSourceStateChangedListener dataSourceStateChangedListener; @Test public void assertInitListeners() { StateChangedListenerManager actual = new StateChangedListenerManager("test", regCenter); FieldUtil.setField(actual, "instanceStateChangedListener", instanceStateChangedListener); FieldUtil.setField(actual, "dataSourceStateChangedListener", dataSourceStateChangedListener); actual.initListeners(); verify(instanceStateChangedListener).watch(ChangedType.UPDATED); verify(dataSourceStateChangedListener).watch(ChangedType.UPDATED, ChangedType.DELETED); } } <file_sep>/sharding-proxy/src/test/java/io/shardingsphere/shardingproxy/backend/sctl/ShardingCTLShowBackendHandlerTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.shardingproxy.backend.sctl; import io.shardingsphere.shardingproxy.backend.ResultPacket; import io.shardingsphere.shardingproxy.backend.jdbc.connection.BackendConnection; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.CommandResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.FieldCountPacket; import io.shardingsphere.shardingproxy.transport.mysql.packet.command.query.QueryResponsePackets; import io.shardingsphere.shardingproxy.transport.mysql.packet.generic.ErrPacket; import io.shardingsphere.transaction.api.TransactionType; import org.hamcrest.CoreMatchers; import org.junit.Test; import java.sql.SQLException; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public class ShardingCTLShowBackendHandlerTest { private BackendConnection backendConnection = new BackendConnection(TransactionType.LOCAL); @Test public void assertShowTransactionType() throws SQLException { backendConnection.setCurrentSchema("schema"); ShardingCTLShowBackendHandler backendHandler = new ShardingCTLShowBackendHandler("sctl:show transaction_type", backendConnection); CommandResponsePackets actual = backendHandler.execute(); assertThat(actual, instanceOf(QueryResponsePackets.class)); assertThat(actual.getHeadPacket(), instanceOf(FieldCountPacket.class)); assertThat(actual.getPackets().size(), is(3)); backendHandler.next(); ResultPacket resultPacket = backendHandler.getResultValue(); assertThat(resultPacket.getData().iterator().next(), CoreMatchers.<Object>is("LOCAL")); } @Test public void assertShowCachedConnections() throws SQLException { backendConnection.setCurrentSchema("schema"); ShardingCTLShowBackendHandler backendHandler = new ShardingCTLShowBackendHandler("sctl:show cached_connections", backendConnection); CommandResponsePackets actual = backendHandler.execute(); assertThat(actual, instanceOf(QueryResponsePackets.class)); assertThat(actual.getHeadPacket(), instanceOf(FieldCountPacket.class)); assertThat(actual.getPackets().size(), is(3)); backendHandler.next(); ResultPacket resultPacket = backendHandler.getResultValue(); assertThat(resultPacket.getData().iterator().next(), CoreMatchers.<Object>is(0)); } @Test public void assertShowCachedConnectionFailed() { backendConnection.setCurrentSchema("schema"); ShardingCTLShowBackendHandler backendHandler = new ShardingCTLShowBackendHandler("sctl:show cached_connectionss", backendConnection); CommandResponsePackets actual = backendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(ErrPacket.class)); ErrPacket errPacket = (ErrPacket) actual.getHeadPacket(); assertThat(errPacket.getErrorMessage(), containsString(" could not support this sctl grammar ")); } @Test public void assertShowCTLFormatError() { backendConnection.setCurrentSchema("schema"); ShardingCTLShowBackendHandler backendHandler = new ShardingCTLShowBackendHandler("sctl:show=xx", backendConnection); CommandResponsePackets actual = backendHandler.execute(); assertThat(actual.getHeadPacket(), instanceOf(ErrPacket.class)); ErrPacket errPacket = (ErrPacket) actual.getHeadPacket(); assertThat(errPacket.getErrorMessage(), containsString(" please review your sctl format")); } } <file_sep>/sharding-core/src/test/java/io/shardingsphere/core/keygen/DefaultKeyGeneratorTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.keygen; import io.shardingsphere.core.keygen.fixture.FixedTimeService; import lombok.SneakyThrows; import org.junit.Test; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertThat; public final class DefaultKeyGeneratorTest { static final long DEFAULT_SEQUENCE_BITS = 12L; static final int DEFAULT_KEY_AMOUNT = 10; @Test @SneakyThrows public void assertGenerateKeyWithMultipleThreads() { int threadNumber = Runtime.getRuntime().availableProcessors() << 1; ExecutorService executor = Executors.newFixedThreadPool(threadNumber); int taskNumber = threadNumber << 2; final DefaultKeyGenerator keyGenerator = new DefaultKeyGenerator(); Set<Number> actual = new HashSet<>(); for (int i = 0; i < taskNumber; i++) { actual.add(executor.submit(new Callable<Number>() { @Override public Number call() { return keyGenerator.generateKey(); } }).get()); } assertThat(actual.size(), is(taskNumber)); } @Test public void assertGenerateKeyWithSingleThread() { List<Number> expected = Arrays.<Number>asList(1L, 4194304L, 4194305L, 8388609L, 8388610L, 12582912L, 12582913L, 16777217L, 16777218L, 20971520L); DefaultKeyGenerator keyGenerator = new DefaultKeyGenerator(); DefaultKeyGenerator.setTimeService(new FixedTimeService(1)); List<Number> actual = new ArrayList<>(); for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) { actual.add(keyGenerator.generateKey()); } assertThat(actual, is(expected)); } @Test @SneakyThrows public void assertGenerateKeyWithClockCallBack() { List<Number> expected = Arrays.<Number>asList(4194305L, 8388608L, 8388609L, 12582913L, 12582914L, 16777216L, 16777217L, 20971521L, 20971522L, 25165824L); DefaultKeyGenerator keyGenerator = new DefaultKeyGenerator(); TimeService timeService = new FixedTimeService(1); DefaultKeyGenerator.setTimeService(timeService); setLastMilliseconds(keyGenerator, timeService.getCurrentMillis() + 2); List<Number> actual = new ArrayList<>(); for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) { actual.add(keyGenerator.generateKey()); } assertThat(actual, is(expected)); } @Test(expected = IllegalStateException.class) @SneakyThrows public void assertGenerateKeyWithClockCallBackBeyondTolerateTime() { DefaultKeyGenerator keyGenerator = new DefaultKeyGenerator(); TimeService timeService = new FixedTimeService(1); DefaultKeyGenerator.setTimeService(timeService); DefaultKeyGenerator.setMaxTolerateTimeDifferenceMilliseconds(0); setLastMilliseconds(keyGenerator, timeService.getCurrentMillis() + 2); List<Number> actual = new ArrayList<>(); for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) { actual.add(keyGenerator.generateKey()); } assertNotEquals(actual.size(), 10); } @Test public void assertGenerateKeyBeyondMaxSequencePerMilliSecond() { List<Number> expected = Arrays.<Number>asList(4194304L, 4194305L, 4194306L, 8388609L, 8388610L, 8388611L, 12582912L, 12582913L, 12582914L, 16777217L); final DefaultKeyGenerator keyGenerator = new DefaultKeyGenerator(); TimeService timeService = new FixedTimeService(2); DefaultKeyGenerator.setTimeService(timeService); setLastMilliseconds(keyGenerator, timeService.getCurrentMillis()); setSequence(keyGenerator, (1 << DEFAULT_SEQUENCE_BITS) - 1); List<Number> actual = new ArrayList<>(); for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) { actual.add(keyGenerator.generateKey()); } assertThat(actual, is(expected)); } @SneakyThrows private void setSequence(final DefaultKeyGenerator keyGenerator, final Number value) { Field sequence = DefaultKeyGenerator.class.getDeclaredField("sequence"); sequence.setAccessible(true); sequence.set(keyGenerator, value); } @SneakyThrows private void setLastMilliseconds(final DefaultKeyGenerator keyGenerator, final Number value) { Field lastMilliseconds = DefaultKeyGenerator.class.getDeclaredField("lastMilliseconds"); lastMilliseconds.setAccessible(true); lastMilliseconds.set(keyGenerator, value); } @Test(expected = IllegalArgumentException.class) public void assertSetWorkerIdFailureWhenNegative() { DefaultKeyGenerator.setWorkerId(-1L); } @Test(expected = IllegalArgumentException.class) public void assertSetWorkerIdFailureWhenTooMuch() { DefaultKeyGenerator.setWorkerId(-Long.MAX_VALUE); } @Test @SneakyThrows public void assertSetWorkerIdSuccess() { DefaultKeyGenerator.setWorkerId(1L); Field workerIdField = DefaultKeyGenerator.class.getDeclaredField("workerId"); workerIdField.setAccessible(true); assertThat(workerIdField.getLong(DefaultKeyGenerator.class), is(1L)); DefaultKeyGenerator.setWorkerId(0L); } @Test @SneakyThrows public void assertSetMaxTolerateTimeDifferenceMilliseconds() { DefaultKeyGenerator.setMaxTolerateTimeDifferenceMilliseconds(1); Field maxTolerateTimeDifferenceMillisecondsField = DefaultKeyGenerator.class.getDeclaredField("maxTolerateTimeDifferenceMilliseconds"); maxTolerateTimeDifferenceMillisecondsField.setAccessible(true); assertThat(maxTolerateTimeDifferenceMillisecondsField.getInt(DefaultKeyGenerator.class), is(1)); DefaultKeyGenerator.setMaxTolerateTimeDifferenceMilliseconds(10); } } <file_sep>/sharding-transaction/sharding-transaction-core/src/test/java/io/shardingsphere/transaction/core/loader/TransactionalDataSourceConverterSPILoaderTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.transaction.core.loader; import io.shardingsphere.transaction.api.TransactionType; import io.shardingsphere.transaction.fixture.FixedDataSourceConverter; import org.junit.Test; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; public final class TransactionalDataSourceConverterSPILoaderTest { @Test public void assertFindConverter() { assertTrue(TransactionalDataSourceConverterSPILoader.findConverter(TransactionType.XA).isPresent()); assertThat(TransactionalDataSourceConverterSPILoader.findConverter(TransactionType.XA).get(), instanceOf(FixedDataSourceConverter.class)); } @Test public void assertNotFindConverter() { assertFalse(TransactionalDataSourceConverterSPILoader.findConverter(TransactionType.LOCAL).isPresent()); } } <file_sep>/sharding-core/src/test/java/io/shardingsphere/core/routing/type/standard/StandardRoutingEngineForSubQueryTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.core.routing.type.standard; import io.shardingsphere.api.config.rule.ShardingRuleConfiguration; import io.shardingsphere.api.config.rule.TableRuleConfiguration; import io.shardingsphere.api.config.strategy.InlineShardingStrategyConfiguration; import io.shardingsphere.core.constant.DatabaseType; import io.shardingsphere.core.metadata.ShardingMetaData; import io.shardingsphere.core.metadata.datasource.ShardingDataSourceMetaData; import io.shardingsphere.core.metadata.table.ColumnMetaData; import io.shardingsphere.core.metadata.table.ShardingTableMetaData; import io.shardingsphere.core.metadata.table.TableMetaData; import io.shardingsphere.core.routing.PreparedStatementRoutingEngine; import io.shardingsphere.core.rule.ShardingRule; import org.junit.Ignore; import org.junit.Test; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; public final class StandardRoutingEngineForSubQueryTest { @Test(expected = IllegalStateException.class) public void assertOneTableError() { String sql = "select (select max(id) from t_order b where b.user_id =? ) from t_order a where user_id = ? "; List<Object> parameters = new LinkedList<>(); parameters.add(3); parameters.add(2); assertSubQuery(sql, parameters); } @Test public void assertOneTable() { String sql = "select (select max(id) from t_order b where b.user_id = ? and b.user_id = a.user_id) from t_order a where user_id = ? "; List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(1); assertSubQuery(sql, parameters); } @Test public void assertBindingTable() { String sql = "select (select max(id) from t_order_item b where b.user_id = ?) from t_order a where user_id = ? "; List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(1); assertSubQuery(sql, parameters); } @Test public void assertNotShardingTable() { String sql = "select (select max(id) from t_user b where b.id = ?) from t_user a where id = ? "; List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(1); assertSubQuery(sql, parameters); } @Test(expected = IllegalStateException.class) public void assertBindingTableWithDifferentValue() { String sql = "select (select max(id) from t_order_item b where b.user_id = ? ) from t_order a where user_id = ? "; List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(3); assertSubQuery(sql, parameters); } @Test(expected = IllegalStateException.class) public void assertTwoTableWithDifferentOperator() { List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(3); parameters.add(1); String sql = "select (select max(id) from t_order_item b where b.user_id in(?,?)) from t_order a where user_id = ? "; assertSubQuery(sql, parameters); } @Test(expected = IllegalStateException.class) public void assertTwoTableWithIn() { List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(3); parameters.add(1); parameters.add(3); String sql = "select (select max(id) from t_order_item b where b.user_id in(?,?)) from t_order a where user_id in(?,?) "; assertSubQuery(sql, parameters); } private void assertSubQuery(final String sql, final List<Object> parameters) { ShardingRule shardingRule = createShardingRule(); PreparedStatementRoutingEngine engine = new PreparedStatementRoutingEngine( sql, shardingRule, new ShardingMetaData(buildShardingDataSourceMetaData(), buildShardingTableMetaData()), DatabaseType.MySQL, true); assertThat(engine.route(parameters).getRouteUnits().size(), is(1)); } @Test(expected = IllegalStateException.class) public void assertSubQueryInSubQueryError() { List<Object> parameters = new LinkedList<>(); parameters.add(11); parameters.add(1); parameters.add(1); parameters.add(1); String sql = "select (select status from t_order b where b.user_id =? and status = (select status from t_order b where b.user_id =?)) as c from t_order a " + "where status = (select status from t_order b where b.user_id =? and status = (select status from t_order b where b.user_id =?))"; assertSubQuery(sql, parameters); } @Test public void assertSubQueryInSubQuery() { List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(1); parameters.add(1); parameters.add(1); String sql = "select (select status from t_order b where b.user_id =? and status = (select status from t_order b where b.user_id =?)) as c from t_order a " + "where status = (select status from t_order b where b.user_id =? and status = (select status from t_order b where b.user_id =?))"; assertSubQuery(sql, parameters); } @Test(expected = IllegalStateException.class) public void assertSubQueryInFromError() { String sql = "select status from t_order b join (select user_id,status from t_order b where b.user_id =?) c on b.user_id = c.user_id where b.user_id =? "; List<Object> parameters = new LinkedList<>(); parameters.add(11); parameters.add(1); assertSubQuery(sql, parameters); } @Test public void assertSubQueryInFrom() { String sql = "select status from t_order b join (select user_id,status from t_order b where b.user_id =?) c on b.user_id = c.user_id where b.user_id =? "; List<Object> parameters = new LinkedList<>(); parameters.add(1); parameters.add(1); assertSubQuery(sql, parameters); } @Test public void assertSubQueryForAggregation() { String sql = "select count(*) from t_order where c.user_id = (select user_id from t_order where user_id =?) "; List<Object> parameters = new LinkedList<>(); parameters.add(1); assertSubQuery(sql, parameters); } @Test public void assertSubQueryForBinding() { String sql = "select count(*) from t_order where user_id = (select user_id from t_order_item where user_id =?) "; List<Object> parameters = new LinkedList<>(); parameters.add(1); assertSubQuery(sql, parameters); } private ShardingDataSourceMetaData buildShardingDataSourceMetaData() { Map<String, String> shardingDataSourceURLs = new LinkedHashMap<>(); shardingDataSourceURLs.put("ds_0", "jdbc:mysql://127.0.0.1:3306/actual_db"); shardingDataSourceURLs.put("ds_1", "jdbc:mysql://127.0.0.1:3306/actual_db"); return new ShardingDataSourceMetaData(shardingDataSourceURLs, createShardingRule(), DatabaseType.MySQL); } private ShardingRule createShardingRule() { ShardingRuleConfiguration shardingRuleConfig = createShardingRuleConfiguration(); addTableRule(shardingRuleConfig, "t_order", "ds_${0..1}.t_order_${0..1}", "user_id", "t_order_${user_id % 2}", "ds_${user_id % 2}"); addTableRule(shardingRuleConfig, "t_order_item", "ds_${0..1}.t_order_item_${0..1}", "user_id", "t_order_item_${user_id % 2}", "ds_${user_id % 2}"); shardingRuleConfig.getBindingTableGroups().add("t_order,t_order_item"); return new ShardingRule(shardingRuleConfig, createDataSourceNames()); } private ShardingRuleConfiguration createShardingRuleConfiguration() { ShardingRuleConfiguration result = new ShardingRuleConfiguration(); result.setDefaultDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration("order_id", "ds_${user_id % 2}")); return result; } private Collection<String> createDataSourceNames() { return Arrays.asList("ds_0", "ds_1"); } private void addTableRule(final ShardingRuleConfiguration shardingRuleConfig, final String tableName, final String actualDataNodes, final String shardingColumn, final String tableAlgorithmExpression, final String dataSourceAlgorithmExpression) { TableRuleConfiguration orderTableRuleConfig = createTableRuleConfig(tableName, actualDataNodes, shardingColumn, tableAlgorithmExpression, dataSourceAlgorithmExpression); shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfig); } private TableRuleConfiguration createTableRuleConfig(final String tableName, final String actualDataNodes, final String shardingColumn, final String algorithmExpression, final String dataSourceAlgorithmExpression) { TableRuleConfiguration result = new TableRuleConfiguration(); result.setLogicTable(tableName); result.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration(shardingColumn, algorithmExpression)); result.setDatabaseShardingStrategyConfig(new InlineShardingStrategyConfiguration(shardingColumn, dataSourceAlgorithmExpression)); result.setActualDataNodes(actualDataNodes); return result; } private ShardingTableMetaData buildShardingTableMetaData() { Map<String, TableMetaData> tableMetaDataMap = new HashMap<>(3, 1); tableMetaDataMap.put("t_order", new TableMetaData(Arrays.asList(new ColumnMetaData("order_id", "int", true), new ColumnMetaData("user_id", "int", false), new ColumnMetaData("status", "int", false)))); tableMetaDataMap.put("t_order_item", new TableMetaData(Arrays.asList(new ColumnMetaData("item_id", "int", true), new ColumnMetaData("order_id", "int", false), new ColumnMetaData("user_id", "int", false), new ColumnMetaData("status", "varchar", false), new ColumnMetaData("c_date", "timestamp", false)))); return new ShardingTableMetaData(tableMetaDataMap); } } <file_sep>/sharding-orchestration/sharding-orchestration-core/src/test/java/io/shardingsphere/orchestration/internal/registry/config/listener/ConfigMapChangedListenerTest.java /* * Copyright 2016-2018 shardingsphere.io. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * </p> */ package io.shardingsphere.orchestration.internal.registry.config.listener; import io.shardingsphere.orchestration.reg.api.RegistryCenter; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent; import io.shardingsphere.orchestration.reg.listener.DataChangedEvent.ChangedType; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(MockitoJUnitRunner.class) public final class ConfigMapChangedListenerTest { private static final String CONFIG_MAP_YAML = "sharding-key1: sharding-value1"; private ConfigMapChangedListener configMapChangedListener; @Mock private RegistryCenter regCenter; @Before public void setUp() { configMapChangedListener = new ConfigMapChangedListener("test", regCenter); } @Test public void assertCreateShardingOrchestrationEvent() { assertThat(configMapChangedListener.createShardingOrchestrationEvent(new DataChangedEvent("test", CONFIG_MAP_YAML, ChangedType.UPDATED)).getConfigMap().size(), is(1)); } }
a08eedebfdfa963fd80bdfa43dfe9c2f316c0a7e
[ "Markdown", "Java" ]
22
Markdown
chinacode/shardingsphere-3.1.0.fix
73b3c2c0f0a18d23eb57a98612ac9d53dd0fc4f1
e23a01992e1a46e5a2eca66097aa6b6e79efdbf4
refs/heads/master
<repo_name>luantian/myapp<file_sep>/routes/login.js /* * @Author: Terence * @Date: 2018-05-26 00:18:50 * @Last Modified by: Terence * @Last Modified time: 2018-06-04 14:40:26 */ const express = require('express'); const router = express.Router(); const user_model = require('../models/user'); const login_legend = require('../api_legend/login'); const inspect_params = require('../utils/inspect_params'); router[login_legend['method'].toLowerCase()]('/', inspect_params, function(req, res, next) { /** * @var {Object} body 客户端传来的参数 * @var {Object} ret 返回给客户端的结果 * @var {Object} query_params 查询数据库的条件 * @var {Array} filter_keys 保存返回的ret的key值 * @var {Object} update 登录时需要更新的key值 */ let body = req.body, ret = {}, query_params = { username: body.username, password: <PASSWORD> }, filter_keys = []; update = { tLogin: new Date().getTime(), $inc: { loginCnt: 1 } }; for (let key in login_legend.ret) { if (key !== 'no') filter_keys.push(key); } user_model.findOneAndUpdate(query_params, update, function(error, user) { if (error) { ret.no = 405; } else { if (!user) { ret.no = 403; } else { ret.no = 200; } if (ret.no == 200) { ret.result = {}; /** * 设置返回给客户端的属性 */ for (let i = 0; i < filter_keys.length; i++) { ret.result[filter_keys[i]] = user[filter_keys[i]]; } ret.msg = login_legend.success[ret.no]; } else { ret.msg = login_legend.error[ret.no]; } } res.send(ret); }); }); module.exports = router;<file_sep>/db/db.js const mongoose = require('mongoose'); mongoose.connect('mongodb://127.0.0.1:27017/test'); const db = mongoose.connection; db.on('error', function(error) { console.log('error: ', error); }); db.once('open', function(callback) { console.log('test数据库连接成功'); });<file_sep>/models/user.js /* * @Author: Terence * @Date: 2018-05-29 12:58:08 * @Last Modified by: Terence * @Last Modified time: 2018-06-01 17:37:10 */ const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ uid: {type: Number}, username: {type: String}, password: {type: String}, email: {type: String}, tReg: {type: Number}, tel: {type: String}, loginCnt: {type: Number, default: 0}, tLogin: {type: Number}, age: {type: Number}, isVip: {type: Boolean}, sex: {type: Number} }, {collection: 'userInfo'}); const userInfo = mongoose.model('UserInfo', userSchema); module.exports = userInfo;<file_sep>/routes/reg.js /* * @Author: Terence * @Date: 2018-05-26 00:18:43 * @Last Modified by: Terence * @Last Modified time: 2018-06-04 14:38:07 */ const express = require('express'); const router = express.Router(); const user_model = require('../models/user'); const reg_legend = require('../api_legend/reg'); const inspect_params = require('../utils/inspect_params'); router[reg_legend['method'].toLowerCase()]('/', inspect_params, (req, res, next) => { let body = req.body; let ret = {}; let query_params = { username: body.username }; if (body.password !== <PASSWORD>) { ret.no = 406; ret.msg = reg_legend.error[ret.no]; res.send(ret); } find_user(query_params).then((user) => { if (user) { ret.no = 401; ret.msg = reg_legend.error[ret.no]; res.send(ret); } else { get_user_count().then((count) => { body.uid = ++count; save(body).then(() => { ret.no = 200; ret.msg = reg_legend.success[ret.no]; res.send(ret); }); }); } }); }); /** * 查找用户,看用户是否存在 * @param {Object} query_params 查询的参数 * @return {Promise} */ const find_user = async (query_params) => { return await new Promise((resolve, reject) => { user_model.findOne(query_params, (error, user) => { if (error) { reject(error); } else { resolve(user); } }); }); } /** * 获取所有用户的人数 * @return {Promise} */ const get_user_count = async () => { return await new Promise((resolve, reject) => { user_model.count({}, (error, count) => { if (error) { reject(error); } else { resolve(count); } }); }); } /** * //保存用户信息 * @param {Object} userData 准备保存的数据 * @return {Promise} */ const save = async (userData) => { return await new Promise((resolve, reject) => { let userModel = user_model(userData); userModel.save((error, newData) => { if (error) { reject(error); } else { resolve(newData); } }); }); } module.exports = router;<file_sep>/routes/index.js /* * @Author: Terence * @Date: 2018-05-26 00:18:57 * @Last Modified by: Terence * @Last Modified time: 2018-06-01 00:01:01 */ var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); module.exports = router; <file_sep>/routes/route.js /* * @Author: Terence * @Date: 2018-05-26 00:18:31 * @Last Modified by: Terence * @Last Modified time: 2018-06-01 00:12:58 */ const express = require('express'); const router = express.Router(); const index_router = require('./index'); const users_router = require('./users'); const login_router = require('./login'); const reg_router = require('./reg'); router.use('/', index_router); router.use('/users', users_router); router.use('/login', login_router); router.use('/reg', reg_router); module.exports = router;
c7de28a686768fe1b1c635480e8d634839398303
[ "JavaScript" ]
6
JavaScript
luantian/myapp
18b5f195772d115bca18f27dd59fd6af05ba9c87
1b071c1a61f4fb2e92158c66acefaee8a212e8d4
refs/heads/master
<repo_name>eliran-hackeru/Cymptom-Home-Task<file_sep>/src/app/models/count-log.ts export interface CountLog { value: number; timestamp: Date; } <file_sep>/e2e/src/app.e2e-spec.ts import { AppPage } from './app.po'; import { browser, logging } from 'protractor'; describe('workspace-project App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should render the page header', () => { page.navigateTo(); expect(page.getTitleText()).toEqual('QA Automation Task'); }); it('should render default value of 0 for the counter', () => { page.navigateTo(); expect(page.getCounterValue()).toBe('0'); }); it('should increase the counter value', () => { page.navigateTo; page.increaseButton(); page.increaseButton(); expect(page.getCounterValue()).toBe('2'); }) it('should decrease the counter value', () => { page.navigateTo; page.decreaseButton(); page.decreaseButton(); expect(page.getCounterValue()).toBe('0'); }) it('should increase and decrease the counter value', () => { page.navigateTo; page.increaseButton(); page.decreaseButton(); expect(page.getCounterValue()).toBe('0'); }) it('should be able to clear the counter', ()=> { page.navigateTo; page.increaseButton(); page.clearButton(); expect(page.getCounterValue()).toBe('0'); }) afterEach(async () => { // Assert that there are no errors emitted from the browser const logs = await browser.manage().logs().get(logging.Type.BROWSER); expect(logs).not.toContain(jasmine.objectContaining({ level: logging.Level.SEVERE, } as logging.Entry)); }); }); <file_sep>/src/app/components/counter/counter.component.spec.ts import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { CounterComponent } from './counter.component'; describe("CounterComponent", () => { let component: CounterComponent; let fixture: ComponentFixture<CounterComponent>; let htmlElement: HTMLElement; let inputElement: HTMLInputElement; let increaseButton: HTMLInputElement; let decreaseButton: HTMLInputElement; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [CounterComponent], imports: [FormsModule], }).compileComponents(); })); beforeEach(async(() => { fixture = TestBed.createComponent(CounterComponent); component = fixture.componentInstance; fixture.detectChanges(); // Get all of the HTML elements htmlElement = fixture.nativeElement as HTMLElement; inputElement = htmlElement.querySelector("#counter_input"); increaseButton = htmlElement.querySelector("#increase_btn"); decreaseButton = htmlElement.querySelector("#decrease_btn"); })); it("should create the counter component", () => { expect(component).toBeTruthy(); }); it("should render default value of 0", async(() => { expect(inputElement.value).toBe("0"); })); it("should increase the value to 1 and render it", fakeAsync(() => { increaseButton.click(); // Detect changes and wait for the to occur fixture.detectChanges(); tick(); // Check the new value expect(inputElement.value).toBe("1"); })); it("should increase the value to 1 using the arrow up key", fakeAsync(() => { // Simulate an arrow up event const keyDownEvent: KeyboardEvent = new KeyboardEvent("keydown", { key: "ArrowUp", }); inputElement.dispatchEvent(keyDownEvent); // Detect changes and wait for the to occur fixture.detectChanges(); tick(); // Check the new value expect(inputElement.value).toBe("1"); })); it("should not decrease the value to -1 and render it", fakeAsync(() => { decreaseButton.click(); // Detect changes and wait for the to occur fixture.detectChanges(); tick(); // Check the new value expect(inputElement.value).toBe("0"); })); it("should not decrease the value to -1 using the arrow down key", fakeAsync(() => { // Simulate an arrow down event const keyDownEvent: KeyboardEvent = new KeyboardEvent("keydown", { key: "ArrowDown", }); inputElement.dispatchEvent(keyDownEvent); // Detect changes and wait for the to occur fixture.detectChanges(); tick(); // Check the new value expect(inputElement.value).toBe("0"); })); it("should render the value directly by the keyboard", fakeAsync(() => { // Simulate a positive number inputElement.value = "100"; // Detect changes and wait for the to occur fixture.detectChanges(); tick(); // Check the new value expect(inputElement.value).toBe("100"); })); it("should not render the value directly if it's a negative number", fakeAsync(() => { // Simulate a positive number inputElement.value = "-100"; // Detect changes and wait for the to occur fixture.detectChanges(); tick(); // Check the new value expect(inputElement.value).toBe("0"); })); // TODO: Check all of the remaining cases, such as arrow keys input, custom values, etc... }); <file_sep>/e2e/src/app.po.ts import { browser, by, element, Key } from 'protractor'; export class AppPage { navigateTo(): Promise<unknown> { return browser.get(browser.baseUrl) as Promise<unknown>; } getTitleText(): Promise<string> { return element(by.css('#header')).getText() as Promise<string>; } selectUpKey() { browser .actions() .sendKeys(Key.ARROW_UP) .perform(); } selectDownKey() { browser .actions() .sendKeys(Key.ARROW_DOWN) .perform(); } getCounterValue() { return element(by.id('counter_input')).getAttribute('ng-reflect-model') as Promise<string>; } increaseButton() { return element(by.id('increase_btn')).click; } decreaseButton() { return element(by.id('decrease_btn')).click(); } clearButton() { return element(by.className('form-control mt-2')).click(); } } <file_sep>/README.md # Cymptom QA Automation Task In this task you will need to write a simple frontend automation tests, it includes the built in angular testing framework which is based on Jasmine + Karma, and e2e tests based on protractor. ## Component tests You will be presented with a simple 2 angular components: - CounterComponent - a simple counter which counts the number of clicks were made using the increase\decrease buttons or arrow keys. **The counter component minimum value should be 0 to infinite**. - LoggerComponent - which logs each click with it's timestamp, so on each value change, a new log will be created with the **exact time** the value was changed. **Make sure these requirements are being met, if you find any bugs, make sure to create automation tests for them! We DO NOT Expect all of the tests to pass.** Use the built-in angular testing framework to write the components tests. You will have a small example to start with at the CounterComponent spec file: ``` /src/app/components/counter/counter.component.spec.ts ``` Here is a link for some resources on getting started with angular component testing: [https://angular.io/guide/testing#component-test-basics](https://angular.io/guide/testing#component-test-basics) ## E2E (end-to-end) Tests end-to-end tests are comes built-in on Angular and are based on protractor. Write full e2e tests for the web UI. An e2e simple guide: [https://coryrylan.com/blog/introduction-to-e2e-testing-with-the-angular-cli-and-protractor](https://coryrylan.com/blog/introduction-to-e2e-testing-with-the-angular-cli-and-protractor) ## Prerequisites - NodeJS version 12 or above. ## Before you begin ### Installation Run the following commands to setup your environment: ```bash # Install angular globally npm install -g @angular/cli # Clone the automation task git clone <EMAIL>:cymptom/qa-automation-task.git # Go into the project directory cd qa-automation-task # Install missing dependencies npm install # Run the project ng serve ``` Now navigate on your browser to: ```bash http://localhost:4200 ``` If everything goes as planned, you will be presented with a fully working angular project. ### Running the tests To run component tests, use: ```bash ng test ``` To run e2e tests, use: ```bash ng e2e ``` <file_sep>/src/app/components/counter/counter.component.ts import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: "app-counter", templateUrl: "./counter.component.html", styleUrls: ["./counter.component.scss"], }) export class CounterComponent implements OnInit { private _value: number = 0; @Input() set value(value: number) { if (value === this._value) return; this._value = value; this.counterChange.next(value); } get value(): number { return this._value; } @Output() counterChange: EventEmitter<number> = new EventEmitter<number>(); constructor() {} ngOnInit(): void {} increaseCounter() { ++this.value; } decreaseCounter() { if (this.value - 1 < 0) return; // Don't allow minus values --this.value; } onInputValueChange(event: Event) { this.counterChange.next(this.value); } /** * Because by default, the arrow keys on input[type="number"] have their own logic * for increasing\decreasing the value, we override them and create our own logic. * @param $event */ onInputKeydown($event: KeyboardEvent) { // We want to change the behavior only of arrow keys const handledKeys = ["ArrowDown", "ArrowUp"]; if (handledKeys.indexOf($event.key) > -1) { $event.preventDefault(); switch ($event.key) { case "ArrowUp": ++this.value; break; case "ArrowDown": --this.value; break; } } } } <file_sep>/src/app/app.component.ts import { Component, ViewChild } from '@angular/core'; import { CounterComponent } from './components/counter/counter.component'; import { CountLog } from './models/count-log'; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"], }) export class AppComponent { @ViewChild(CounterComponent) counterComponent: CounterComponent; logs: CountLog[] = []; /** * When the counter was clicked and it's value changed, log each click. * @param value */ onCounterChange(value: number) { const loggedDate = new Date(); loggedDate.setSeconds(loggedDate.getSeconds() + 60); const log: CountLog = { value, timestamp: loggedDate }; this.logs.push(log); } /** * Clear the counter and logs. */ clear() { this.logs = []; this.counterComponent.value = 0; } } <file_sep>/src/app/components/logger/logger.component.spec.ts import { async, ComponentFixture, TestBed, tick } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { LoggerComponent } from './logger.component'; import { CounterComponent } from '../counter/counter.component' describe('LoggerComponent', () => { let component: LoggerComponent; let fixture: ComponentFixture<LoggerComponent>; let htmlElement: HTMLElement; let inputElement: HTMLInputElement; let increaseButton: HTMLInputElement; let decreaseButton: HTMLInputElement; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ LoggerComponent, CounterComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(LoggerComponent); component = fixture.componentInstance; fixture.detectChanges(); // Get all of the HTML elements htmlElement = fixture.nativeElement as HTMLElement; inputElement = htmlElement.querySelector("#counter_input"); increaseButton = htmlElement.querySelector("#increase_btn"); decreaseButton = htmlElement.querySelector("#decrease_btn"); }); it('should create the logger component', () => { expect(component).toBeTruthy(); }); it('should have no logs when initiate the app', () => { const loggerElement: HTMLElement = fixture.nativeElement; expect(loggerElement.textContent).toContain("No logs were found"); }); /*it('should increase the total to 1 and render it', () => { const loggerElement: HTMLElement = fixture.nativeElement; // Simulate an increase increaseButton.click(); // Detect changes and wait for the to occur fixture.detectChanges(); tick(); // Check the new value expect(loggerElement.textContent).toContain("with value 1"); });*/ }); <file_sep>/src/app/components/logger/logger.component.ts import { Component, Input, OnInit } from '@angular/core'; import { CountLog } from '../../models/count-log'; @Component({ selector: "app-logger", templateUrl: "./logger.component.html", styleUrls: ["./logger.component.scss"], }) export class LoggerComponent implements OnInit { @Input() logs: CountLog[] = []; constructor() {} ngOnInit(): void {} }
8d2b5acad0202b74487dee20b0b33342aa63f13e
[ "Markdown", "TypeScript" ]
9
TypeScript
eliran-hackeru/Cymptom-Home-Task
8db859592cf0fb1d85766feacc5461be075db134
860e2fb7bf11f63c71d828e56074fb65d321caef
refs/heads/master
<repo_name>hexator2/init<file_sep>/src/main/java/com/bluff/celebrytalk/repository/query/ManagerDTO.java package com.bluff.celebrytalk.repository.query; public class ManagerDTO { } <file_sep>/docker-compose.yml version: "3" services: jsp: container_name: celebrity_jsp image: hexator/celebrity ports: - 80:80 depends_on: - db - redis db: container_name: celebrity_mysql image: mysql:8.0.22 environment: MYSQL_DATABASE: celebrytalk MYSQL_ROOT_PASSWORD: root MYSQL_ROOT_HOST: '%' ports: - 3306:3306 redis: container_name: celebrity_redis image: redis:latest command: redis-server ports: - 6379:6379 <file_sep>/src/main/java/com/bluff/celebrytalk/repository/query/UserDTO.java package com.bluff.celebrytalk.repository.query; public class UserDTO { } <file_sep>/src/main/java/com/bluff/celebrytalk/repository/ManagerRepository.java package com.bluff.celebrytalk.repository; public class ManagerRepository { } <file_sep>/src/main/java/com/bluff/celebrytalk/domain/auth/Auth.java package com.bluff.celebrytalk.domain.auth; public class Auth { } <file_sep>/src/main/java/com/bluff/celebrytalk/domain/system/FirebaseLog.java package com.bluff.celebrytalk.domain.system; public class FirebaseLog { } <file_sep>/src/main/java/com/bluff/celebrytalk/domain/celebration/Celebration.java package com.bluff.celebrytalk.domain.celebration; public class Celebration { } <file_sep>/src/main/java/com/bluff/celebrytalk/domain/manager/ManagerIpAddress.java package com.bluff.celebrytalk.domain.manager; public class ManagerIpAddress { } <file_sep>/src/main/java/com/bluff/celebrytalk/service/ManagerService.java package com.bluff.celebrytalk.service; public class ManagerService { }
efac1649f6767116d84610a890412f798caafe13
[ "Java", "YAML" ]
9
Java
hexator2/init
1d4d6207fba9a1d1e5dc09f445fd2bfb32a928c2
9ecbf146164ef7b0461730c86f4d99e4a4d0648a
refs/heads/master
<repo_name>quanlj1989/ennew-user<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/MarketCateCertApplyServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.MarketCateCertApplyService; import cn.enn.ygego.sunny.user.dao.MarketCateCertApplyDao; import cn.enn.ygego.sunny.user.model.MarketCateCertApply; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * ClassName: MarketCateCertApply * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ @Service("marketCateCertApplyService") public class MarketCateCertApplyServiceImpl implements MarketCateCertApplyService{ @Autowired private MarketCateCertApplyDao marketCateCertApplyDao; public List<MarketCateCertApply> findAll(){ return marketCateCertApplyDao.selectAll(); } public List<MarketCateCertApply> findMarketCateCertApplys(MarketCateCertApply record){ return marketCateCertApplyDao.select(record); } public MarketCateCertApply getMarketCateCertApplyByPrimaryKey(Long certApplyDetailId){ return marketCateCertApplyDao.selectByPrimaryKey(certApplyDetailId); } public Integer deleteByPrimaryKey(Long certApplyDetailId){ return marketCateCertApplyDao.deleteByPrimaryKey(certApplyDetailId); } public Integer createMarketCateCertApply(MarketCateCertApply record){ return marketCateCertApplyDao.insertSelective(record); } public Integer deleteMarketCateCertApply(MarketCateCertApply record){ return marketCateCertApplyDao.delete(record); } public Integer removeMarketCateCertApply(MarketCateCertApply record){ return marketCateCertApplyDao.updateByPrimaryKeySelective(record); } public Integer updateMarketCateCertApplyByPrimaryKeySelective(MarketCateCertApply record){ return marketCateCertApplyDao.updateByPrimaryKeySelective(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntStore.java package cn.enn.ygego.sunny.user.model; import java.io.Serializable; /** * entity:EntStore * * @author gencode */ public class EntStore implements Serializable { private static final long serialVersionUID = 1614603172835057915L; private Long storeId; /* 店铺ID */ private Long memberId; /* 会员ID */ private String headBanner; /* 头部banner */ // Constructor public EntStore() { } /** * full Constructor */ public EntStore(Long storeId, Long memberId, String headBanner) { this.storeId = storeId; this.memberId = memberId; this.headBanner = headBanner; } public Long getStoreId() { return storeId; } public void setStoreId(Long storeId) { this.storeId = storeId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public String getHeadBanner() { return headBanner; } public void setHeadBanner(String headBanner) { this.headBanner = headBanner; } @Override public String toString() { return "EntStore [" + "storeId=" + storeId+ ", memberId=" + memberId+ ", headBanner=" + headBanner+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/MarketCateStandardChargeServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.MarketCateStandardChargeService; import cn.enn.ygego.sunny.user.dao.MarketCateStandardChargeDao; import cn.enn.ygego.sunny.user.model.MarketCateStandardCharge; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * ClassName: MarketCateStandardCharge * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ @Service("marketCateStandardChargeService") public class MarketCateStandardChargeServiceImpl implements MarketCateStandardChargeService{ @Autowired private MarketCateStandardChargeDao marketCateStandardChargeDao; public List<MarketCateStandardCharge> findAll(){ return marketCateStandardChargeDao.selectAll(); } public List<MarketCateStandardCharge> findMarketCateStandardCharges(MarketCateStandardCharge record){ return marketCateStandardChargeDao.select(record); } public MarketCateStandardCharge getMarketCateStandardChargeByPrimaryKey(Long chargeId){ return marketCateStandardChargeDao.selectByPrimaryKey(chargeId); } public Integer deleteByPrimaryKey(Long chargeId){ return marketCateStandardChargeDao.deleteByPrimaryKey(chargeId); } public Integer createMarketCateStandardCharge(MarketCateStandardCharge record){ return marketCateStandardChargeDao.insertSelective(record); } public Integer deleteMarketCateStandardCharge(MarketCateStandardCharge record){ return marketCateStandardChargeDao.delete(record); } public Integer removeMarketCateStandardCharge(MarketCateStandardCharge record){ return marketCateStandardChargeDao.updateByPrimaryKeySelective(record); } public Integer updateMarketCateStandardChargeByPrimaryKeySelective(MarketCateStandardCharge record){ return marketCateStandardChargeDao.updateByPrimaryKeySelective(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntSetDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.dto.vo.JoinCompanyQueryVO; import cn.enn.ygego.sunny.user.dto.vo.JoinCompanyVO; import cn.enn.ygego.sunny.user.model.EntSet; /** * dal Interface:EntSet * @author gencode */ public interface EntSetDao { Integer insert(EntSet record); Integer insertSelective(EntSet record); Integer insertList(List<EntSet> records); Integer delete(EntSet record); Integer deleteByPrimaryKey(@Param("setId") Long setId); Integer updateByPrimaryKey(EntSet record); List<EntSet> findAll(); List<EntSet> find(EntSet record); Integer getCount(EntSet record); EntSet getByPrimaryKey(@Param("setId") Long setId); /** * @Description 根据条件查询子公司总条数 * @author puanl * @date 2018年3月29日 上午10:54:56 * @param query * @return */ Integer getCompanyListCount(JoinCompanyQueryVO query); /** * @Description 根据条件查询子公司列表 * @author puanl * @date 2018年3月29日 上午10:58:43 * @param query * @return */ List<JoinCompanyVO> getCompanyList(JoinCompanyQueryVO query); /** * @Description 查询关联企业数量(子查父 / 父查子) * @author puanl * @date 2018年3月29日 下午4:21:50 * @param query * @return */ Integer getJoinCompanyListCount(JoinCompanyQueryVO query); /** * @Description 查询关联企业列表(子查父 / 父查子) * @author puanl * @date 2018年3月29日 下午4:22:34 * @param query * @return */ List<JoinCompanyVO> getJoinCompanyList(JoinCompanyQueryVO query); /** * * @Description 根据关系ID,查询子公司配置信息 * @author puanl * @date 2018年3月30日 上午9:34:52 * @param query * @return */ JoinCompanyVO getSunCompanyBySetId(JoinCompanyQueryVO query); /** * @Description 批量修改父级会员关联状态 * @author puanl * @date 2018年3月31日 上午9:25:29 * @param entSet * @return */ Integer updateEntSetByList(List<EntSet> entSet); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/BrandApplyDTO.java package cn.enn.ygego.sunny.user.dto; import java.io.Serializable; import java.util.Date; /** * DTO:DictBrand * * @author zx.dev * @date 2018-3-14 */ public class BrandApplyDTO implements Serializable { private static final long serialVersionUID = 1L; private Long applyId; /* 申请ID */ private Integer status; /* 状态 */ private String brandName; /* 品牌名称 */ private String brandEnName; /* 品牌英文名称 */ private String brandAlias; /* 品牌别名 */ private String companyName; /* 公司名称 */ private Integer country; /* 国家 */ private String brandLogo; /* 品牌logo */ private String brandDesc; /* 品牌描述 */ private Date createTime; /* 创建时间 */ private Long createAcctId; /* 创建人账户ID */ private Date approveTime; /* 审批时间 */ private Long approveAcctId; /* 审批人账户ID */ private String approveDesc; /* 审批描述 */ public Long getApplyId() { return applyId; } public void setApplyId(Long applyId) { this.applyId = applyId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getBrandEnName() { return brandEnName; } public void setBrandEnName(String brandEnName) { this.brandEnName = brandEnName; } public String getBrandAlias() { return brandAlias; } public void setBrandAlias(String brandAlias) { this.brandAlias = brandAlias; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public Integer getCountry() { return country; } public void setCountry(Integer country) { this.country = country; } public String getBrandLogo() { return brandLogo; } public void setBrandLogo(String brandLogo) { this.brandLogo = brandLogo; } public String getBrandDesc() { return brandDesc; } public void setBrandDesc(String brandDesc) { this.brandDesc = brandDesc; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public Date getApproveTime() { return approveTime; } public void setApproveTime(Date approveTime) { this.approveTime = approveTime; } public Long getApproveAcctId() { return approveAcctId; } public void setApproveAcctId(Long approveAcctId) { this.approveAcctId = approveAcctId; } public String getApproveDesc() { return approveDesc; } public void setApproveDesc(String approveDesc) { this.approveDesc = approveDesc; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/IndividualServiceApplyDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:IndividualServiceApply * * @author gencode * @date 2018-3-19 */ public class IndividualServiceApplyDTO implements Serializable { private static final long serialVersionUID = -5759562190665358390L; private Long serviceApplyId; /* 服务申请ID */ private Long memberId; /* 会员ID */ private Integer serviceType; /* 服务类型 */ private Integer status; /* 状态 */ private Date createTime; /* 创建时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ private Date auditTime; /* 审核时间 */ private String approveDesc; /* 审核结果描述 */ private Long approveAcctId; /* 审核人账户ID */ private Long approveMemberId; /* 审核人会员ID */ private String approveName; /* 审核人姓名 */ // Constructor public IndividualServiceApplyDTO() { } /** * full Constructor */ public IndividualServiceApplyDTO(Long serviceApplyId, Long memberId, Integer serviceType, Integer status, Date createTime, Long createMemberId, Long createAcctId, String createName, Date auditTime, String approveDesc, Long approveAcctId, Long approveMemberId, String approveName) { this.serviceApplyId = serviceApplyId; this.memberId = memberId; this.serviceType = serviceType; this.status = status; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; this.auditTime = auditTime; this.approveDesc = approveDesc; this.approveAcctId = approveAcctId; this.approveMemberId = approveMemberId; this.approveName = approveName; } public Long getServiceApplyId() { return serviceApplyId; } public void setServiceApplyId(Long serviceApplyId) { this.serviceApplyId = serviceApplyId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getServiceType() { return serviceType; } public void setServiceType(Integer serviceType) { this.serviceType = serviceType; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public Date getAuditTime() { return auditTime; } public void setAuditTime(Date auditTime) { this.auditTime = auditTime; } public String getApproveDesc() { return approveDesc; } public void setApproveDesc(String approveDesc) { this.approveDesc = approveDesc; } public Long getApproveAcctId() { return approveAcctId; } public void setApproveAcctId(Long approveAcctId) { this.approveAcctId = approveAcctId; } public Long getApproveMemberId() { return approveMemberId; } public void setApproveMemberId(Long approveMemberId) { this.approveMemberId = approveMemberId; } public String getApproveName() { return approveName; } public void setApproveName(String approveName) { this.approveName = approveName; } @Override public String toString() { return "IndividualServiceApplyDTO [" + "serviceApplyId=" + serviceApplyId + ", memberId=" + memberId + ", serviceType=" + serviceType + ", status=" + status + ", createTime=" + createTime + ", createMemberId=" + createMemberId + ", createAcctId=" + createAcctId + ", createName=" + createName + ", auditTime=" + auditTime + ", approveDesc=" + approveDesc + ", approveAcctId=" + approveAcctId + ", approveMemberId=" + approveMemberId + ", approveName=" + approveName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntCertApplyDetailService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntCertApplyDetail; /** * dal Interface:EntCertApplyDetail * @author gencode * @date 2018-3-28 */ public interface EntCertApplyDetailService { public List<EntCertApplyDetail> findAll(); public List<EntCertApplyDetail> findEntCertApplyDetails(EntCertApplyDetail record); public EntCertApplyDetail getEntCertApplyDetailByPrimaryKey(Long certApplyDetailId); public Integer createEntCertApplyDetail(EntCertApplyDetail record); public Integer removeEntCertApplyDetail(EntCertApplyDetail record); public Integer removeByPrimaryKey(Long certApplyDetailId); public Integer modifyEntCertApplyDetailByPrimaryKey(EntCertApplyDetail record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntAuthCertApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntAuthCertApply; /** * dal Interface:EntAuthCertApply * @author gencode */ public interface EntAuthCertApplyDao { Integer insert(EntAuthCertApply record); Integer insertSelective(EntAuthCertApply record); Integer delete(EntAuthCertApply record); Integer deleteByPrimaryKey(@Param("certApplyId") Long certApplyId); Integer updateByPrimaryKey(EntAuthCertApply record); List<EntAuthCertApply> findAll(); List<EntAuthCertApply> find(EntAuthCertApply record); Integer getCount(EntAuthCertApply record); EntAuthCertApply getByPrimaryKey(@Param("certApplyId") Long certApplyId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntCateCertFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntCateCertFile; /** * dal Interface:EntCateCertFile * @author gencode */ public interface EntCateCertFileDao { Integer insert(EntCateCertFile record); Integer insertSelective(EntCateCertFile record); Integer delete(EntCateCertFile record); Integer deleteByPrimaryKey(@Param("certFileId") Long certFileId); Integer updateByPrimaryKey(EntCateCertFile record); List<EntCateCertFile> findAll(); List<EntCateCertFile> find(EntCateCertFile record); Integer getCount(EntCateCertFile record); EntCateCertFile getByPrimaryKey(@Param("certFileId") Long certFileId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/ReceiveAddressDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.dto.ReceiveAddressDTO; import cn.enn.ygego.sunny.user.dto.vo.BaseQueryVO; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.ReceiveAddress; /** * dal Interface:ReceiveAddress * @author gencode */ public interface ReceiveAddressDao { Integer insert(ReceiveAddress record); Integer insertSelective(ReceiveAddress record); Integer delete(ReceiveAddress record); Integer deleteByPrimaryKey(@Param("receiveAddressId") Long receiveAddressId); Integer updateByPrimaryKey(ReceiveAddress record); List<ReceiveAddress> findAll(); List<ReceiveAddress> find(ReceiveAddress record); List<ReceiveAddressDTO> findPage(BaseQueryVO record); Integer getCount(ReceiveAddress record); ReceiveAddress getByPrimaryKey(@Param("receiveAddressId") Long receiveAddressId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketCateStandardChargeDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketCateStandardCharge; import org.springframework.stereotype.Repository; /** * ClassName: MarketCateStandardCharge * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketCateStandardChargeDao { List<MarketCateStandardCharge> selectAll(); List<MarketCateStandardCharge> select(MarketCateStandardCharge record); Integer selectCount(MarketCateStandardCharge record); MarketCateStandardCharge selectByPrimaryKey(Long chargeId); Integer deleteByPrimaryKey(Long chargeId); Integer delete(MarketCateStandardCharge record); Integer insertSelective(MarketCateStandardCharge record); Integer updateByPrimaryKeySelective(MarketCateStandardCharge record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/QuestionAttachServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.QuestionAttachService; import cn.enn.ygego.sunny.user.dao.QuestionAttachDao; import cn.enn.ygego.sunny.user.model.QuestionAttach; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:QuestionAttach * @author gencode * @date 2018-3-22 */ @Service public class QuestionAttachServiceImpl implements QuestionAttachService{ @Autowired private QuestionAttachDao questionAttachDao; public List<QuestionAttach> findAll(){ return questionAttachDao.findAll(); } public List<QuestionAttach> findQuestionAttachs(QuestionAttach record){ return questionAttachDao.find(record); } public QuestionAttach getQuestionAttachByPrimaryKey(Long questionAttachId){ return questionAttachDao.getByPrimaryKey(questionAttachId); } public Integer createQuestionAttach(QuestionAttach record){ return questionAttachDao.insert(record); } public Integer removeQuestionAttach(QuestionAttach record){ return questionAttachDao.delete(record); } public Integer removeByPrimaryKey(Long questionAttachId){ return questionAttachDao.deleteByPrimaryKey(questionAttachId); } public Integer modifyQuestionAttachByPrimaryKey(QuestionAttach record){ return questionAttachDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/IndividualCertFile.java package cn.enn.ygego.sunny.user.model; import java.io.Serializable; /** * entity:IndividualCertFile * * @author gencode */ public class IndividualCertFile implements Serializable { private static final long serialVersionUID = 3734316108563150479L; private Long certFileId; /* 资质文件信息ID */ private Long certInfoId; /* 资质信息ID */ private Integer certFileType; /* 资质文件类型 */ private Integer sortNum; /* 排序编号 */ private Long fileSize; /* 文件大小 */ private String fileUrl; /* 文件地址 */ // Constructor public IndividualCertFile() { } /** * full Constructor */ public IndividualCertFile(Long certFileId, Long certInfoId, Integer certFileType, Integer sortNum, Long fileSize, String fileUrl) { this.certFileId = certFileId; this.certInfoId = certInfoId; this.certFileType = certFileType; this.sortNum = sortNum; this.fileSize = fileSize; this.fileUrl = fileUrl; } public Long getCertFileId() { return certFileId; } public void setCertFileId(Long certFileId) { this.certFileId = certFileId; } public Long getCertInfoId() { return certInfoId; } public void setCertInfoId(Long certInfoId) { this.certInfoId = certInfoId; } public Integer getCertFileType() { return certFileType; } public void setCertFileType(Integer certFileType) { this.certFileType = certFileType; } public Integer getSortNum() { return sortNum; } public void setSortNum(Integer sortNum) { this.sortNum = sortNum; } public Long getFileSize() { return fileSize; } public void setFileSize(Long fileSize) { this.fileSize = fileSize; } public String getFileUrl() { return fileUrl; } public void setFileUrl(String fileUrl) { this.fileUrl = fileUrl; } @Override public String toString() { return "IndividualCertFile [" + "certFileId=" + certFileId+ ", certInfoId=" + certInfoId+ ", certFileType=" + certFileType+ ", sortNum=" + sortNum+ ", fileSize=" + fileSize+ ", fileUrl=" + fileUrl+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/SupplierBlackListServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.SupplierBlackListService; import cn.enn.ygego.sunny.user.dao.SupplierBlackListDao; import cn.enn.ygego.sunny.user.model.SupplierBlackList; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:SupplierBlackList * @author gencode * @date 2018-3-22 */ @Service public class SupplierBlackListServiceImpl implements SupplierBlackListService{ @Autowired private SupplierBlackListDao supplierBlackListDao; public List<SupplierBlackList> findAll(){ return supplierBlackListDao.findAll(); } public List<SupplierBlackList> findSupplierBlackLists(SupplierBlackList record){ return supplierBlackListDao.find(record); } public SupplierBlackList getSupplierBlackListByPrimaryKey(Long supplierListId){ return supplierBlackListDao.getByPrimaryKey(supplierListId); } public Integer createSupplierBlackList(SupplierBlackList record){ return supplierBlackListDao.insert(record); } public Integer removeSupplierBlackList(SupplierBlackList record){ return supplierBlackListDao.delete(record); } public Integer removeByPrimaryKey(Long supplierListId){ return supplierBlackListDao.deleteByPrimaryKey(supplierListId); } public Integer modifySupplierBlackListByPrimaryKey(SupplierBlackList record){ return supplierBlackListDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntCertFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntCertFile; /** * dal Interface:EntCertFile * @author gencode */ public interface EntCertFileDao { Integer insert(EntCertFile record); Integer insertSelective(EntCertFile record); Integer delete(EntCertFile record); Integer deleteByPrimaryKey(@Param("certFileId") Long certFileId); Integer updateByPrimaryKey(EntCertFile record); List<EntCertFile> findAll(); List<EntCertFile> find(EntCertFile record); Integer getCount(EntCertFile record); EntCertFile getByPrimaryKey(@Param("certFileId") Long certFileId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/SupplierBlackListDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.SupplierBlackList; /** * dal Interface:SupplierBlackList * @author gencode */ public interface SupplierBlackListDao { Integer insert(SupplierBlackList record); Integer insertSelective(SupplierBlackList record); Integer delete(SupplierBlackList record); Integer deleteByPrimaryKey(@Param("supplierListId") Long supplierListId); Integer updateByPrimaryKey(SupplierBlackList record); List<SupplierBlackList> findAll(); List<SupplierBlackList> find(SupplierBlackList record); Integer getCount(SupplierBlackList record); SupplierBlackList getByPrimaryKey(@Param("supplierListId") Long supplierListId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualServiceApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualServiceApply; /** * dal Interface:IndividualServiceApply * @author gencode */ public interface IndividualServiceApplyDao { Integer insert(IndividualServiceApply record); Integer insertSelective(IndividualServiceApply record); Integer delete(IndividualServiceApply record); Integer deleteByPrimaryKey(@Param("serviceApplyId") Long serviceApplyId); Integer updateByPrimaryKey(IndividualServiceApply record); List<IndividualServiceApply> findAll(); List<IndividualServiceApply> find(IndividualServiceApply record); Integer getCount(IndividualServiceApply record); IndividualServiceApply getByPrimaryKey(@Param("serviceApplyId") Long serviceApplyId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualBrandCertApplyFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualBrandCertApplyFile; /** * dal Interface:IndividualBrandCertApplyFile * @author gencode * @date 2018-3-22 */ public interface IndividualBrandCertApplyFileService { public List<IndividualBrandCertApplyFile> findAll(); public List<IndividualBrandCertApplyFile> findIndividualBrandCertApplyFiles(IndividualBrandCertApplyFile record); public IndividualBrandCertApplyFile getIndividualBrandCertApplyFileByPrimaryKey(Long certApplyFileId); public Integer createIndividualBrandCertApplyFile(IndividualBrandCertApplyFile record); public Integer removeIndividualBrandCertApplyFile(IndividualBrandCertApplyFile record); public Integer removeByPrimaryKey(Long certApplyFileId); public Integer modifyIndividualBrandCertApplyFileByPrimaryKey(IndividualBrandCertApplyFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/ChannelManRequestVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import cn.enn.ygego.sunny.user.dto.ChannelManageDTO; import java.io.Serializable; import java.util.Date; /** * DTO:ChannelManage * * @author gencode * @date 2018-3-26 */ public class ChannelManRequestVO extends ChannelManageDTO implements Serializable { private static final long serialVersionUID = 8877726588419034128L; private Long roleId; /* 角色标识 */ private String roleTitle; /* 角色名称 */ // Constructor public ChannelManRequestVO() { } public String getRoleTitle() { return roleTitle; } public void setRoleTitle(String roleTitle) { this.roleTitle = roleTitle; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/supermarket/SupermarketInfoVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.supermarket; import java.util.List; /** * 申请入驻超市信息详情描述类 * ClassName: SupermarketInfoVO * Description * Author zhangjiaqi * Date 2018-03-30 18:49 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-30 18:49 0.0.1 TODO */ public class SupermarketInfoVO { // 超市id private Long marketId; // 超市编码 private String supermarketCode; // 经营类型 private Integer serviceType; // 联系人 private String contact; // 联系电话 private String contactTel; // 仓库地址 private List<String> storageName; // 收费类型 private String chargeType; public SupermarketInfoVO() { super(); // TODO Auto-generated constructor stub } public SupermarketInfoVO(Long marketId, String supermarketCode, Integer serviceType, String contact, String contactTel, List<String> storageName, String chargeType) { super(); this.marketId = marketId; this.supermarketCode = supermarketCode; this.serviceType = serviceType; this.contact = contact; this.contactTel = contactTel; this.storageName = storageName; this.chargeType = chargeType; } public Long getMarketId() { return marketId; } public void setMarketId(Long marketId) { this.marketId = marketId; } public String getSupermarketCode() { return supermarketCode; } public void setSupermarketCode(String supermarketCode) { this.supermarketCode = supermarketCode; } public Integer getServiceType() { return serviceType; } public void setServiceType(Integer serviceType) { this.serviceType = serviceType; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel; } public List<String> getStorageName() { return storageName; } public void setStorageName(List<String> storageName) { this.storageName = storageName; } public String getChargeType() { return chargeType; } public void setChargeType(String chargeType) { this.chargeType = chargeType; } @Override public String toString() { return "SupermarketInfoVO [marketId=" + marketId + ", supermarketCode=" + supermarketCode + ", serviceType=" + serviceType + ", contact=" + contact + ", contactTel=" + contactTel + ", storageName=" + storageName + ", chargeType=" + chargeType + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntCateCertInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntCateCertInfo; /** * dal Interface:EntCateCertInfo * @author gencode */ public interface EntCateCertInfoDao { Integer insert(EntCateCertInfo record); Integer insertSelective(EntCateCertInfo record); Integer delete(EntCateCertInfo record); Integer deleteByPrimaryKey(@Param("certInfoId") Long certInfoId); Integer updateByPrimaryKey(EntCateCertInfo record); List<EntCateCertInfo> findAll(); List<EntCateCertInfo> find(EntCateCertInfo record); Integer getCount(EntCateCertInfo record); EntCateCertInfo getByPrimaryKey(@Param("certInfoId") Long certInfoId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/RoleOperPrivRelaDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:RoleOperPrivRela * * @author gencode * @date 2018-3-19 */ public class RoleOperPrivRelaDTO implements Serializable { private static final long serialVersionUID = 550169839665435240L; private Long relaId; /* 关系标识 */ private Long operId; /* 操作标识 */ private Long roleId; /* 角色标识 */ private Date createTime; /* 创建时间 */ private Date updateTime; /* 更新时间 */ private Integer relaState; /* 关系状态 */ private Integer isDelete; /* 是否删除 */ private String operPersonName; /* 操作人姓名 */ private Long operPersonId; /* 操作人标识 */ // Constructor public RoleOperPrivRelaDTO() { } /** * full Constructor */ public RoleOperPrivRelaDTO(Long relaId, Long operId, Long roleId, Date createTime, Date updateTime, Integer relaState, Integer isDelete, String operPersonName, Long operPersonId) { this.relaId = relaId; this.operId = operId; this.roleId = roleId; this.createTime = createTime; this.updateTime = updateTime; this.relaState = relaState; this.isDelete = isDelete; this.operPersonName = operPersonName; this.operPersonId = operPersonId; } public Long getRelaId() { return relaId; } public void setRelaId(Long relaId) { this.relaId = relaId; } public Long getOperId() { return operId; } public void setOperId(Long operId) { this.operId = operId; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Integer getRelaState() { return relaState; } public void setRelaState(Integer relaState) { this.relaState = relaState; } public Integer getIsDelete() { return isDelete; } public void setIsDelete(Integer isDelete) { this.isDelete = isDelete; } public String getOperPersonName() { return operPersonName; } public void setOperPersonName(String operPersonName) { this.operPersonName = operPersonName; } public Long getOperPersonId() { return operPersonId; } public void setOperPersonId(Long operPersonId) { this.operPersonId = operPersonId; } @Override public String toString() { return "RoleOperPrivRelaDTO [" + "relaId=" + relaId + ", operId=" + operId + ", roleId=" + roleId + ", createTime=" + createTime + ", updateTime=" + updateTime + ", relaState=" + relaState + ", isDelete=" + isDelete + ", operPersonName=" + operPersonName + ", operPersonId=" + operPersonId + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/SupplierWhiteListServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.SupplierWhiteListService; import cn.enn.ygego.sunny.user.dao.SupplierWhiteListDao; import cn.enn.ygego.sunny.user.model.SupplierWhiteList; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:SupplierWhiteList * @author gencode * @date 2018-3-22 */ @Service public class SupplierWhiteListServiceImpl implements SupplierWhiteListService{ @Autowired private SupplierWhiteListDao supplierWhiteListDao; public List<SupplierWhiteList> findAll(){ return supplierWhiteListDao.findAll(); } public List<SupplierWhiteList> findSupplierWhiteLists(SupplierWhiteList record){ return supplierWhiteListDao.find(record); } public SupplierWhiteList getSupplierWhiteListByPrimaryKey(Long supplierListId){ return supplierWhiteListDao.getByPrimaryKey(supplierListId); } public Integer createSupplierWhiteList(SupplierWhiteList record){ return supplierWhiteListDao.insert(record); } public Integer removeSupplierWhiteList(SupplierWhiteList record){ return supplierWhiteListDao.delete(record); } public Integer removeByPrimaryKey(Long supplierListId){ return supplierWhiteListDao.deleteByPrimaryKey(supplierListId); } public Integer modifySupplierWhiteListByPrimaryKey(SupplierWhiteList record){ return supplierWhiteListDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualBrandCertInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualBrandCertInfo; /** * dal Interface:IndividualBrandCertInfo * @author gencode */ public interface IndividualBrandCertInfoDao { Integer insert(IndividualBrandCertInfo record); Integer insertSelective(IndividualBrandCertInfo record); Integer delete(IndividualBrandCertInfo record); Integer deleteByPrimaryKey(@Param("brandCertId") Long brandCertId); Integer updateByPrimaryKey(IndividualBrandCertInfo record); List<IndividualBrandCertInfo> findAll(); List<IndividualBrandCertInfo> find(IndividualBrandCertInfo record); Integer getCount(IndividualBrandCertInfo record); IndividualBrandCertInfo getByPrimaryKey(@Param("brandCertId") Long brandCertId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntBrandInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntBrandInfo; /** * dal Interface:EntBrandInfo * @author gencode */ public interface EntBrandInfoDao { Integer insert(EntBrandInfo record); Integer insertSelective(EntBrandInfo record); Integer delete(EntBrandInfo record); Integer deleteByPrimaryKey(@Param("entBrandId") Long entBrandId); Integer updateByPrimaryKey(EntBrandInfo record); List<EntBrandInfo> findAll(); List<EntBrandInfo> find(EntBrandInfo record); Integer getCount(EntBrandInfo record); EntBrandInfo getByPrimaryKey(@Param("entBrandId") Long entBrandId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/SellerProdDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.SellerProd; /** * dal Interface:SellerProd * @author gencode */ public interface SellerProdDao { Integer insert(SellerProd record); Integer insertSelective(SellerProd record); Integer delete(SellerProd record); Integer deleteByPrimaryKey(@Param("sellerProdId") Long sellerProdId); Integer updateByPrimaryKey(SellerProd record); List<SellerProd> findAll(); List<SellerProd> find(SellerProd record); Integer getCount(SellerProd record); SellerProd getByPrimaryKey(@Param("sellerProdId") Long sellerProdId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/factory/InspectFactoryApplyInfoVO.java package cn.enn.ygego.sunny.user.dto.factory; import cn.enn.ygego.sunny.user.model.InspectFactoryApplyInfo; /** * * ClassName: InspectFactoryApplyInfoVO * Description 验证类目返回实体类 * Author zhengyang * Date 2018年3月30日 下午7:57:52 */ public class InspectFactoryApplyInfoVO extends InspectFactoryApplyInfo{ private static final long serialVersionUID = -5587804359610218552L; /**验厂类目的产品数量*/ private Integer productCount; /**审核时间显示字符串*/ private String createTimeStr; /**审核状态显示字符串*/ private String applyStatusStr; public Integer getProductCount() { return productCount; } public void setProductCount(Integer productCount) { this.productCount = productCount; } public String getCreateTimeStr() { return createTimeStr; } public void setCreateTimeStr(String createTimeStr) { this.createTimeStr = createTimeStr; } public String getApplyStatusStr() { return applyStatusStr; } public void setApplyStatusStr(String applyStatusStr) { this.applyStatusStr = applyStatusStr; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/enterpriseManage/EntAuthController.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.controller.enterpriseManage; import cn.enn.ygego.sunny.core.log.SearchableLoggerFactory; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.core.web.JsonResult; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.user.constant.EntCertApplyTypeEnum; import cn.enn.ygego.sunny.user.dto.EntAuthTypeApplyDTO; import cn.enn.ygego.sunny.user.dto.EntBrandAuthApplyDTO; import cn.enn.ygego.sunny.user.dto.EntBrandInfoDTO; import cn.enn.ygego.sunny.user.dto.EntCertApplyDTO; import cn.enn.ygego.sunny.user.dto.EntCertInfoDTO; import cn.enn.ygego.sunny.user.dto.EntCustInfoDTO; import cn.enn.ygego.sunny.user.dto.vo.EntAuthTypeApplyVO; import cn.enn.ygego.sunny.user.dto.vo.EntCateAndBrandVO; import cn.enn.ygego.sunny.user.dto.vo.EntCertApplyVO; import cn.enn.ygego.sunny.user.dto.vo.EntProdApplyVO; import cn.enn.ygego.sunny.user.dto.vo.EntQueryVO; import cn.enn.ygego.sunny.user.model.EntAuthTypeApply; import cn.enn.ygego.sunny.user.model.EntBrandAuthApply; import cn.enn.ygego.sunny.user.model.EntCertApply; import cn.enn.ygego.sunny.user.service.EntCertApplyService; import cn.enn.ygego.sunny.user.service.EntProdApplyService; import com.github.jsonzou.jmockdata.JMockData; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * ClassName: EntAuthController * Description: * Author: lizan * Date: 2018/3/20 13:51 * History: * <author> <time> <version> <desc> * lizan 2018/3/20 13:51 0.0.1 企业认证接口 */ @RestController @RequestMapping("/user/enterprise") @Api(value = "企业认证接口", description = "企业认证接口") public class EntAuthController { static final Logger logger = SearchableLoggerFactory.getDefaultLogger(); @Autowired private EntCertApplyService entCertApplyService; @Autowired private EntProdApplyService entProdApplyService; /** *个人认证企业状态列表入口 * @param jsonRequest * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("个人认证企业状态列表入口") @RequestMapping(value = "/personalEntAuthList", method = { RequestMethod.POST}) public JsonResponse<List<EntAuthTypeApplyDTO>> personalEntAuthList(@RequestBody JsonRequest<EntAuthTypeApplyDTO> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 List<EntAuthTypeApplyDTO> list = new ArrayList<EntAuthTypeApplyDTO>(); // JMockData模拟生成随机数据 EntAuthTypeApplyDTO entAuthTypeApplyDTO = JMockData.mock(EntAuthTypeApplyDTO.class); list.add(entAuthTypeApplyDTO); // 将对象保存到list中 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(list); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("提交企业认证接口") @RequestMapping(value = "/createAuth", method = { RequestMethod.POST}) public JsonResponse createAuth(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("供应商入驻信息(类目品牌,渠道,验厂)") @RequestMapping(value = "/getSupplierAuthInfo", method = { RequestMethod.POST}) public JsonResponse getSupplierAuthInfo(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("供应商认证类目列表") @RequestMapping(value = "/getGcAuthList", method = { RequestMethod.POST}) public JsonResponse<PageDTO<EntBrandInfoDTO>> getGcAuthList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 PageDTO pageDTO = new PageDTO(); // 返回的PageDTO对象 List<EntBrandInfoDTO> list = new ArrayList<EntBrandInfoDTO>(); // JMockData模拟生成随机数据 EntBrandInfoDTO entBrandInfoDTO = JMockData.mock(EntBrandInfoDTO.class); list.add(entBrandInfoDTO); // 将对象保存到list中 pageDTO.setResultData(list);// 将结果保存到page对象中 pageDTO.setPageNum(0); // 第0页 pageDTO.setPageSize(10); // 每页显示10条 pageDTO.setTotal(1); //共1条 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(pageDTO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("提交企业资质认证(结算商)") @RequestMapping(value = "/getClearAuth", method = { RequestMethod.POST}) public JsonResponse getClearAuth(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("提交企业资质认证(服务商)") @RequestMapping(value = "/createProviderAuth", method = { RequestMethod.POST}) public JsonResponse createProviderAuth(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业资质认证(服务商)") @RequestMapping(value = "/getProviderAuth", method = { RequestMethod.POST}) public JsonResponse<EntAuthTypeApplyVO> getProviderAuth(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 EntAuthTypeApplyVO entAuthTypeApplyVO = JMockData.mock(EntAuthTypeApplyVO.class); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(entAuthTypeApplyVO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业资质认证(结算商)") @RequestMapping(value = "/createClearAuth", method = { RequestMethod.POST}) public JsonResponse createClearAuth(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 EntAuthTypeApplyVO entAuthTypeApplyVO = JMockData.mock(EntAuthTypeApplyVO.class); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(entAuthTypeApplyVO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("提交企业类目及品牌认证") @RequestMapping(value = "/createBrandAuth", method = { RequestMethod.POST}) public JsonResponse createBrandAuth(@RequestBody JsonRequest<EntProdApplyVO> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 //-------------------TODO 传入会员信息等-------------------------- Long memberId = 9454l; Long acctId = 9454l; String name = "测试"; //-------------------------------------------------------------- Date date = new Date(); EntProdApplyVO entProdApplyVO = jsonRequest.getReqBody(); entProdApplyVO.setCreateTime(date); entProdApplyVO.setCreateAcctId(acctId); entProdApplyVO.setMemberId(memberId); entProdApplyVO.setCreateName(name); int result = -1; try { result = entProdApplyService.createEntProdApplyVO(entProdApplyVO); if(result == 1){ jsonResponse.setRetCode("0000000"); jsonResponse.setRetDesc("提交企业类目及品牌认证成功"); }else{ jsonResponse.setRetCode("0100000"); jsonResponse.setRetDesc("提交企业类目及品牌认证失败"); } jsonResponse.setRspBody(result); } catch (RuntimeException ex) { logger.error("addDeliverAddress: 提交企业类目及品牌认证接口报错!" + ex.getMessage(), ex); jsonResponse.setRetCode("0100000"); jsonResponse.setRetDesc(ex.getMessage()); jsonResponse.setRspBody(result); return jsonResponse; } return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业类目及品牌认证") @RequestMapping(value = "/getBrandAuth", method = { RequestMethod.POST}) public JsonResponse<EntProdApplyVO> getBrandAuth(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("设置结算账户") @RequestMapping(value = "/setClearAccount", method = { RequestMethod.POST}) public JsonResponse setClearAccount(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("提交企业基本信息认证接口") @RequestMapping(value = "/createEcInfo", method = { RequestMethod.POST}) public JsonResponse createEcInfo(@RequestBody JsonRequest<EntCertApply> jsonRequest) { EntCertApply entCertApply = jsonRequest.getReqBody(); JsonResponse jsonResponse = new JsonResponse(); EntCertApply result = new EntCertApply(); //设置为申请状态 entCertApply.setStatus(EntCertApplyTypeEnum.APPLY_STATUS_APPLY.getCode()); Date date = new Date(); entCertApply.setCreateTime(date); try { int operation = entCertApplyService.createEntCertApply(entCertApply); if(operation == 1){ jsonResponse.setRetCode("0000000"); jsonResponse.setRetDesc("提交企业基本信息认证接口成功"); result.setCertApplyId(entCertApply.getCertApplyId()); }else{ jsonResponse.setRetCode("0100000"); jsonResponse.setRetDesc("提交企业基本信息认证接口失败"); } jsonResponse.setRspBody(result); } catch (RuntimeException ex) { logger.error("addDeliverAddress: 提交企业基本信息认证接口报错!" + ex.getMessage(), ex); jsonResponse.setRetCode("0100000"); jsonResponse.setRetDesc(ex.getMessage()); jsonResponse.setRspBody(result); return jsonResponse; } return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("提交采购商申请角色接口") @RequestMapping(value = "/applyPurchase", method = { RequestMethod.POST}) public JsonResponse applyPurchase(@RequestBody JsonRequest<EntCertApply> jsonRequest) { EntCertApply entCertApply = jsonRequest.getReqBody(); JsonResponse jsonResponse = new JsonResponse(); EntCertApply result = new EntCertApply(); //设置为申请状态 entCertApply.setStatus(EntCertApplyTypeEnum.APPLY_STATUS_APPLY.getCode()); Date date = new Date(); entCertApply.setCreateTime(date); try { int operation = entCertApplyService.createEntCertApply(entCertApply); if(operation == 1){ jsonResponse.setRetCode("0000000"); jsonResponse.setRetDesc("提交企业基本信息认证接口成功"); result.setCertApplyId(entCertApply.getCertApplyId()); }else{ jsonResponse.setRetCode("0100000"); jsonResponse.setRetDesc("提交企业基本信息认证接口失败"); } jsonResponse.setRspBody(result); } catch (RuntimeException ex) { logger.error("addDeliverAddress: 提交企业基本信息认证接口报错!" + ex.getMessage(), ex); jsonResponse.setRetCode("0100000"); jsonResponse.setRetDesc(ex.getMessage()); jsonResponse.setRspBody(result); return jsonResponse; } return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业详情") @RequestMapping(value = "/entInfo", method = { RequestMethod.POST}) public JsonResponse<EntCertApplyVO> entInfo(@RequestBody JsonRequest<EntCertApplyDTO> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 EntCertApplyVO entCertApplyVO = JMockData.mock(EntCertApplyVO.class); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(entCertApplyVO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业认证详情接口") @RequestMapping(value = "/entAuthInfo", method = { RequestMethod.POST}) public JsonResponse entAuthInfo(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 EntCertInfoDTO entCertInfoDTO = JMockData.mock(EntCertInfoDTO.class); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(entCertInfoDTO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("导出企业认证列表Excel接口") @RequestMapping(value = "/expEntAuthList", method = { RequestMethod.POST}) public JsonResponse expEntAuthList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("更新用户质量接入标识接口") @RequestMapping(value = "/updateQualityFlag", method = { RequestMethod.POST}) public JsonResponse updateQualityFlag(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } /** * 个人企业列表 * 平台企业列表 * @param jsonRequest * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业列表接口") @RequestMapping(value = "/entList", method = { RequestMethod.POST}) public JsonResponse<PageDTO<EntCustInfoDTO>> entList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 PageDTO pageDTO = new PageDTO(); // 返回的PageDTO对象 List<EntCustInfoDTO> list = new ArrayList<EntCustInfoDTO>(); // JMockData模拟生成随机数据 EntCustInfoDTO entCustInfoDTO = JMockData.mock(EntCustInfoDTO.class); list.add(entCustInfoDTO); // 将对象保存到list中 pageDTO.setResultData(list);// 将结果保存到page对象中 pageDTO.setPageNum(0); // 第0页 pageDTO.setPageSize(10); // 每页显示10条 pageDTO.setTotal(1); //共1条 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(pageDTO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } /** * 个人查看企业认证列表 * 平台查看企业认证列表 * @param jsonRequest * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业认证列表接口") @RequestMapping(value = "/entAuthList", method = { RequestMethod.POST}) public JsonResponse<PageDTO<EntCertApplyDTO>> entAuthList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 PageDTO pageDTO = new PageDTO(); // 返回的PageDTO对象 List<EntCertApplyDTO> list = new ArrayList<EntCertApplyDTO>(); // JMockData模拟生成随机数据 EntCertApplyDTO entCertApplyDTO = JMockData.mock(EntCertApplyDTO.class); list.add(entCertApplyDTO); // 将对象保存到list中 pageDTO.setResultData(list);// 将结果保存到page对象中 pageDTO.setPageNum(0); // 第0页 pageDTO.setPageSize(10); // 每页显示10条 pageDTO.setTotal(1); //共1条 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(pageDTO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("通过类目查看企业列表(对外)") @RequestMapping(value = "/getEntListByGcId", method = { RequestMethod.POST}) public JsonResponse<EntCustInfoDTO> getEntListByGcId(@RequestBody JsonRequest<EntQueryVO> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 PageDTO pageDTO = new PageDTO(); // 返回的PageDTO对象 List<EntCustInfoDTO> list = new ArrayList<EntCustInfoDTO>(); // JMockData模拟生成随机数据 EntCustInfoDTO entCustInfoDTO = JMockData.mock(EntCustInfoDTO.class); list.add(entCustInfoDTO); // 将对象保存到list中 pageDTO.setResultData(list);// 将结果保存到page对象中 pageDTO.setPageNum(0); // 第0页 pageDTO.setPageSize(10); // 每页显示10条 pageDTO.setTotal(1); //共1条 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(pageDTO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看供应商企业认证审核列表接口") @RequestMapping(value = "/getSupplierList", method = { RequestMethod.POST}) public JsonResponse getSupplierList(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看结算商企业认证审核列表接口") @RequestMapping(value = "/getClearList", method = { RequestMethod.POST}) public JsonResponse getClearList(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看服务商企业认证审核列表接口") @RequestMapping(value = "/getProviderList", method = { RequestMethod.POST}) public JsonResponse getProviderList(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("个人查看企业类目及品牌认证资质列表") @RequestMapping(value = "/getPersonalBrand", method = { RequestMethod.POST}) public JsonResponse getPersonalBrand(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("审核企业资质认证(服务商结算商)") @RequestMapping(value = "/auditEntCert", method = { RequestMethod.POST}) public JsonResponse auditEntCert(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("审核企业基本信息认证接口(兼修改)") @RequestMapping(value = "/updateEntAuth", method = { RequestMethod.POST}) public JsonResponse updateEntAuth(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("审核企业类目及品牌认证接口(兼修改)") @RequestMapping(value = "/auditEntBrand", method = { RequestMethod.POST}) public JsonResponse auditEntBrand(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业认证大详情") @RequestMapping(value = "/getEntInfoAndAuth", method = { RequestMethod.POST}) public JsonResponse getEntInfoAndAuth(@RequestBody JsonResult jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看企业列表接口") @RequestMapping(value = "/entListByAuthenType", method = { RequestMethod.POST}) public JsonResponse<PageDTO<EntCustInfoDTO>> entListByAuthenType(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 PageDTO pageDTO = new PageDTO(); // 返回的PageDTO对象 List<EntCustInfoDTO> list = new ArrayList<EntCustInfoDTO>(); // JMockData模拟生成随机数据 EntCustInfoDTO entCustInfoDTO = JMockData.mock(EntCustInfoDTO.class); list.add(entCustInfoDTO); // 将对象保存到list中 pageDTO.setResultData(list);// 将结果保存到page对象中 pageDTO.setPageNum(0); // 第0页 pageDTO.setPageSize(10); // 每页显示10条 pageDTO.setTotal(1); //共1条 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(pageDTO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntChannelPermitApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.dto.vo.EntChannelPermitVO; import cn.enn.ygego.sunny.user.model.EntChannelPermitApply; /** * dal Interface:EntChannelPermitApply * @author gencode * @date 2018-3-28 */ public interface EntChannelPermitApplyService { public List<EntChannelPermitApply> findAll(); public List<EntChannelPermitApply> findEntChannelPermitApplys(EntChannelPermitApply record); public EntChannelPermitApply getEntChannelPermitApplyByPrimaryKey(Long channelApplyId); public Integer createEntChannelPermitApply(EntChannelPermitApply record); public Integer removeEntChannelPermitApply(EntChannelPermitApply record); public Integer removeByPrimaryKey(Long channelApplyId); public Integer modifyEntChannelPermitApplyByPrimaryKey(EntChannelPermitApply record); public Integer modifyEntChannelPermitApplyByPrimaryKey(EntChannelPermitVO record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/common/SmsTypeEnum.java package cn.enn.ygego.sunny.user.common; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 短信类型 * Created by dongbb on 2018/3/24. */ public enum SmsTypeEnum { REGISTER("1", "注册"), FAND_PASSWORD("2", "<PASSWORD>"), CHANGE_PHONE("3", "更改绑定手机号"); private String statusCode; private String statusName; SmsTypeEnum(String statusCode, String statusName) { this.statusCode = statusCode; this.statusName = statusName; } public String getStatusCode() { return statusCode; } public String getStatusName() { return statusName; } /** * 根据key查找对应的value * * @return */ public static String getStatusName(String statusCode) { SmsTypeEnum[] statusArr = SmsTypeEnum.values(); for (SmsTypeEnum status : statusArr) { if (status.getStatusCode().equals(statusCode)) { return status.statusName; } } return ""; } /** * 把数据封装成一个List * * @return */ public static List<Map<String, String>> convertToList() { List<Map<String, String>> result = new ArrayList<>(); SmsTypeEnum[] statusArr = SmsTypeEnum.values(); for (SmsTypeEnum status : statusArr) { Map<String, String> resultMap = new HashMap<>(); resultMap.put("statusCode", status.statusCode); resultMap.put("statusName", status.statusName); result.add(resultMap); } return result; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/LoginController.java package cn.enn.ygego.sunny.user.controller; import cn.enn.ygego.sunny.core.exception.BusinessException; import cn.enn.ygego.sunny.core.log.SearchableLoggerFactory; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.user.common.ResponseCodeEnum; import cn.enn.ygego.sunny.user.common.UserLoginWayEnum; import cn.enn.ygego.sunny.user.dto.company.CompanyAuthInfo; import cn.enn.ygego.sunny.user.dto.login.LoginRequest; import cn.enn.ygego.sunny.user.dto.login.LoginResponse; import cn.enn.ygego.sunny.user.dto.login.ThirdLoginBaseParam; import cn.enn.ygego.sunny.user.dto.login.ThirdLoginConfigResponse; import cn.enn.ygego.sunny.user.dto.register.UserBaseInfoRequest; import cn.enn.ygego.sunny.user.service.ThirdLoginConfigService; import cn.enn.ygego.sunny.user.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/user/") @Api(value = "登录方法", description = "主要用于登录等验证") public class LoginController { private static final Logger logger = SearchableLoggerFactory.getDefaultLogger(); @Autowired private UserService userService; @Autowired private ThirdLoginConfigService thirdLoginConfigService; /** * 用户登录 * * @param jsonRequest * @return */ @ApiOperation(value = "登录接口", notes = "验证是否能登录") @RequestMapping(value = "/login", method = {RequestMethod.POST}) public JsonResponse<LoginResponse> login(@RequestBody JsonRequest<LoginRequest> jsonRequest) { JsonResponse<LoginResponse> jsonResponse = new JsonResponse<>(); try { LoginRequest request = jsonRequest.getReqBody(); //平台登录 if (request.getLoginType().toString().equals(UserLoginWayEnum.PLATFORM.getStatusCode())) { LoginResponse response = userService.login(request.getUsername(), request.getPassword()); jsonResponse.setRspBody(response); } } catch (BusinessException e) { logger.error(e.getErrorCode()); jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc(e.getErrorCode()); } catch (Exception e) { logger.error("用户登录异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 查询所对应的企业信息以及企业对应的认证信息 * * @param jsonRequest * @return */ @ApiOperation(value = "查询所对应的企业信息以及企业对应的认证信息") @RequestMapping(value = "/findCompanyMember", method = {RequestMethod.POST}) public JsonResponse<List<CompanyAuthInfo>> findCompanyMember(@RequestBody JsonRequest<UserBaseInfoRequest> jsonRequest) { JsonResponse<List<CompanyAuthInfo>> jsonResponse = new JsonResponse<>(); try { UserBaseInfoRequest request = jsonRequest.getReqBody(); List<CompanyAuthInfo> companyAuthInfos = userService.findCompanyMember(request.getAcctId()); jsonResponse.setRspBody(companyAuthInfos); } catch (BusinessException e) { logger.error(e.getErrorCode()); jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc(e.getErrorCode()); } catch (Exception e) { logger.error(" 查询所对应的企业信息以及企业对应的认证信息异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 设置默认企业 * * @param jsonRequest * @return */ @ApiOperation(value = "设置默认企业") @RequestMapping(value = "/setDefaultCompany", method = {RequestMethod.POST}) public JsonResponse setDefaultCompany(@RequestBody JsonRequest<UserBaseInfoRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse<>(); try { UserBaseInfoRequest request = jsonRequest.getReqBody(); boolean result = userService.setDefaultCompany(request.getAcctId(), request.getCompanyMemberId()); if (result) { jsonResponse.setRetCode("设置默认企业成功!"); } else { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetCode("设置默认企业失败!"); } } catch (Exception e) { logger.error(" 查询所对应的企业信息以及企业对应的认证信息异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 获取第三方登陆配置信息接口 * * @param jsonRequest * @return */ @ApiOperation(value = "获取第三方登陆信息接口", notes = "获取第三方登陆信息接口") @RequestMapping(value = "/thirdLoginConfig", method = {RequestMethod.POST}) public JsonResponse<List<ThirdLoginConfigResponse>> thirdLoginConfig(@RequestBody JsonRequest jsonRequest) { JsonResponse<List<ThirdLoginConfigResponse>> jsonResponse = new JsonResponse<>(); try { List<ThirdLoginConfigResponse> response = thirdLoginConfigService.findEnabledConfigs(); jsonResponse.setRetCode("查询第三方登陆配置信息成功!"); jsonResponse.setRspBody(response); } catch (Exception e) { logger.error("获取第三方登陆配置信息接口异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 获取第三方登陆地址 * * @param jsonRequest * @return */ @ApiOperation(value = "获取第三方登陆地址", notes = "获取第三方登陆地址") @RequestMapping(value = "/thirdLoginUri", method = {RequestMethod.POST}) public JsonResponse<ThirdLoginBaseParam> thirdLoginUri(@RequestBody JsonRequest<ThirdLoginBaseParam> jsonRequest) { JsonResponse<ThirdLoginBaseParam> jsonResponse = new JsonResponse<>(); try { ThirdLoginBaseParam request = jsonRequest.getReqBody(); String thirdLoginUri = userService.getThirdLoginUri(request.getConfigId()); if (StringUtils.isBlank(thirdLoginUri)) { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("获取第三方登陆地址失败!"); } else { ThirdLoginBaseParam response = new ThirdLoginBaseParam(); response.setThirdLoginUri(thirdLoginUri); jsonResponse.setRspBody(response); jsonResponse.setRetDesc("获取第三方登陆地址成功!"); } } catch (Exception e) { logger.error("获取第三方登陆地址异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 获取第三方是否已在平台注册 * @param jsonRequest * @return */ @ApiOperation(value = "获取第三方是否已在平台注册", notes = "获取第三方是否已在平台注册") @RequestMapping(value = "/isRegisterThird", method = {RequestMethod.POST}) public JsonResponse isRegisterThird(@RequestBody JsonRequest jsonRequest) { return new JsonResponse(); } /** * 超级登录 * @param jsonRequest * @return */ @ApiOperation(value = "超级登录", notes = "超级登录") @RequestMapping(value = "/superLogin", method = {RequestMethod.POST}) public JsonResponse superLogin(@RequestBody JsonRequest jsonRequest) { return new JsonResponse(); } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/constant/FactoryApplyStatusEnum.java package cn.enn.ygego.sunny.user.constant; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * ClassName: FactoryApplyStatusEnum * Description 验厂审核状态类 * Author zhengyang * Date 2018年3月30日 下午7:22:07 */ public enum FactoryApplyStatusEnum { FACTORY_VERIFICATION("0", "验证中"), FACTORY_PASS("1", "审核通过"), FACTORY_FAILURE("2", "审核失败"), FACILITATOR("3", "已过期"); private String statusCode; private String statusName; FactoryApplyStatusEnum(String statusCode, String statusName) { this.statusCode = statusCode; this.statusName = statusName; } public String getStatusCode() { return statusCode; } public String getStatusName() { return statusName; } /** * 根据key查找对应的value * * @return */ public static String getStatusName(String statusCode) { FactoryApplyStatusEnum[] statusArr = FactoryApplyStatusEnum.values(); for (FactoryApplyStatusEnum status : statusArr) { if (status.getStatusCode().equals(statusCode)) { return status.statusName; } } return ""; } /** * 把数据封装成一个List * * @return */ public static List<Map<String, String>> convertToList() { List<Map<String, String>> result = new ArrayList<>(); FactoryApplyStatusEnum[] statusArr = FactoryApplyStatusEnum.values(); for (FactoryApplyStatusEnum status : statusArr) { Map<String, String> resultMap = new HashMap<>(); resultMap.put("statusCode", status.statusCode); resultMap.put("statusName", status.statusName); result.add(resultMap); } return result; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualDomainPermitApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualDomainPermitApply; /** * dal Interface:IndividualDomainPermitApply * @author gencode * @date 2018-3-22 */ public interface IndividualDomainPermitApplyService { public List<IndividualDomainPermitApply> findAll(); public List<IndividualDomainPermitApply> findIndividualDomainPermitApplys(IndividualDomainPermitApply record); public IndividualDomainPermitApply getIndividualDomainPermitApplyByPrimaryKey(Long domainApplyId); public Integer createIndividualDomainPermitApply(IndividualDomainPermitApply record); public Integer removeIndividualDomainPermitApply(IndividualDomainPermitApply record); public Integer removeByPrimaryKey(Long domainApplyId); public Integer modifyIndividualDomainPermitApplyByPrimaryKey(IndividualDomainPermitApply record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntCertApplyDetailServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntCertApplyDetailService; import cn.enn.ygego.sunny.user.dao.EntCertApplyDetailDao; import cn.enn.ygego.sunny.user.model.EntCertApplyDetail; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntCertApplyDetail * @author gencode * @date 2018-3-28 */ @Service public class EntCertApplyDetailServiceImpl implements EntCertApplyDetailService{ @Autowired private EntCertApplyDetailDao entCertApplyDetailDao; public List<EntCertApplyDetail> findAll(){ return entCertApplyDetailDao.findAll(); } public List<EntCertApplyDetail> findEntCertApplyDetails(EntCertApplyDetail record){ return entCertApplyDetailDao.find(record); } public EntCertApplyDetail getEntCertApplyDetailByPrimaryKey(Long certApplyDetailId){ return entCertApplyDetailDao.getByPrimaryKey(certApplyDetailId); } public Integer createEntCertApplyDetail(EntCertApplyDetail record){ return entCertApplyDetailDao.insert(record); } public Integer removeEntCertApplyDetail(EntCertApplyDetail record){ return entCertApplyDetailDao.delete(record); } public Integer removeByPrimaryKey(Long certApplyDetailId){ return entCertApplyDetailDao.deleteByPrimaryKey(certApplyDetailId); } public Integer modifyEntCertApplyDetailByPrimaryKey(EntCertApplyDetail record){ return entCertApplyDetailDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntProdApplyVO.java package cn.enn.ygego.sunny.user.dto.vo; import cn.enn.ygego.sunny.user.dto.EntApplyProdInfoDTO; import cn.enn.ygego.sunny.user.dto.EntProdApplyDTO; import java.util.List; /** * ClassName: EntProdApplyVO * Description: * Author: lizan * Date: 2018/3/30 10:03 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class EntProdApplyVO extends EntProdApplyDTO { private static final long serialVersionUID = 5424359541485017071L; private List<EntCateCertApplyVO> entCateCertApplyVOList; private List<EntApplyProducerAuthVO> entApplyProducerAuthVOList; private List<EntApplyProdInfoDTO> entApplyProdInfoDTOList; public List<EntCateCertApplyVO> getEntCateCertApplyVOList() { return entCateCertApplyVOList; } public void setEntCateCertApplyVOList(List<EntCateCertApplyVO> entCateCertApplyVOList) { this.entCateCertApplyVOList = entCateCertApplyVOList; } public List<EntApplyProducerAuthVO> getEntApplyProducerAuthVOList() { return entApplyProducerAuthVOList; } public void setEntApplyProducerAuthVOList(List<EntApplyProducerAuthVO> entApplyProducerAuthVOList) { this.entApplyProducerAuthVOList = entApplyProducerAuthVOList; } public List<EntApplyProdInfoDTO> getEntApplyProdInfoDTOList() { return entApplyProdInfoDTOList; } public void setEntApplyProdInfoDTOList(List<EntApplyProdInfoDTO> entApplyProdInfoDTOList) { this.entApplyProdInfoDTOList = entApplyProdInfoDTOList; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/RoleOperPrivRelaService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.RoleOperPrivRela; /** * dal Interface:RoleOperPrivRela * @author gencode * @date 2018-3-22 */ public interface RoleOperPrivRelaService { public List<RoleOperPrivRela> findAll(); public List<RoleOperPrivRela> findRoleOperPrivRelas(RoleOperPrivRela record); public RoleOperPrivRela getRoleOperPrivRelaByPrimaryKey(Long relaId); public Integer createRoleOperPrivRela(RoleOperPrivRela record); public Integer removeRoleOperPrivRela(RoleOperPrivRela record); public Integer removeByPrimaryKey(Long relaId); public Integer modifyRoleOperPrivRelaByPrimaryKey(RoleOperPrivRela record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntBrandCert.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:EntBrandCert * * @author gencode */ public class EntBrandCert implements Serializable { private static final long serialVersionUID = -45699003488266502L; private Long brandCertId; /* 品牌资质ID */ private Long entBrandId; /* 企业品牌ID */ private String certUrl; /* 资质地址 */ private Integer certType; /* 资质类型 */ private String certName; /* 资质名称 */ private String certNo; /* 资质号码 */ private Date certValidDate; /* 资质有效期 */ // Constructor public EntBrandCert() { } /** * full Constructor */ public EntBrandCert(Long brandCertId, Long entBrandId, String certUrl, Integer certType, String certName, String certNo, Date certValidDate) { this.brandCertId = brandCertId; this.entBrandId = entBrandId; this.certUrl = certUrl; this.certType = certType; this.certName = certName; this.certNo = certNo; this.certValidDate = certValidDate; } public Long getBrandCertId() { return brandCertId; } public void setBrandCertId(Long brandCertId) { this.brandCertId = brandCertId; } public Long getEntBrandId() { return entBrandId; } public void setEntBrandId(Long entBrandId) { this.entBrandId = entBrandId; } public String getCertUrl() { return certUrl; } public void setCertUrl(String certUrl) { this.certUrl = certUrl; } public Integer getCertType() { return certType; } public void setCertType(Integer certType) { this.certType = certType; } public String getCertName() { return certName; } public void setCertName(String certName) { this.certName = certName; } public String getCertNo() { return certNo; } public void setCertNo(String certNo) { this.certNo = certNo; } public Date getCertValidDate() { return certValidDate; } public void setCertValidDate(Date certValidDate) { this.certValidDate = certValidDate; } @Override public String toString() { return "EntBrandCert [" + "brandCertId=" + brandCertId+ ", entBrandId=" + entBrandId+ ", certUrl=" + certUrl+ ", certType=" + certType+ ", certName=" + certName+ ", certNo=" + certNo+ ", certValidDate=" + certValidDate+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualCertApplyFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualCertApplyFile; /** * dal Interface:IndividualCertApplyFile * @author gencode */ public interface IndividualCertApplyFileDao { Integer insert(IndividualCertApplyFile record); Integer insertSelective(IndividualCertApplyFile record); /* 批量插入数据 */ Integer insertList(List<IndividualCertApplyFile> record); Integer delete(IndividualCertApplyFile record); Integer deleteByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); Integer updateByPrimaryKey(IndividualCertApplyFile record); List<IndividualCertApplyFile> findAll(); List<IndividualCertApplyFile> find(IndividualCertApplyFile record); Integer getCount(IndividualCertApplyFile record); IndividualCertApplyFile getByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); /** * * @Description TODO * @author puanl * @date 2018年3月22日 下午3:41:11 * @param record * @return */ List<IndividualCertApplyFile> getByCertApplyDetailId(@Param("certApplyDetailId") Long certApplyDetailId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualServiceCertFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualServiceCertFile; /** * dal Interface:IndividualServiceCertFile * @author gencode * @date 2018-3-22 */ public interface IndividualServiceCertFileService { public List<IndividualServiceCertFile> findAll(); public List<IndividualServiceCertFile> findIndividualServiceCertFiles(IndividualServiceCertFile record); public IndividualServiceCertFile getIndividualServiceCertFileByPrimaryKey(Long certApplyFileId); public Integer createIndividualServiceCertFile(IndividualServiceCertFile record); public Integer removeIndividualServiceCertFile(IndividualServiceCertFile record); public Integer removeByPrimaryKey(Long certApplyFileId); public Integer modifyIndividualServiceCertFileByPrimaryKey(IndividualServiceCertFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/QuestionResponseDao.java package cn.enn.ygego.sunny.user.dao; import cn.enn.ygego.sunny.user.model.QuestionResponse; import org.apache.ibatis.annotations.Param; import java.util.List; /** * dal Interface:QuestionResponse * @author gencode */ public interface QuestionResponseDao { Integer insert(QuestionResponse record); Integer insertSelective(QuestionResponse record); Integer delete(QuestionResponse record); Integer deleteByPrimaryKey(@Param("responseId") Long responseId); Integer updateByPrimaryKey(QuestionResponse record); List<QuestionResponse> findAll(); List<QuestionResponse> find(QuestionResponse record); Integer getCount(QuestionResponse record); QuestionResponse getByPrimaryKey(@Param("responseId") Long responseId); List<QuestionResponse> getByQuestionId(Long questionId); Integer insertBatch(List<QuestionResponse> list); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/RelaChannelToRoleService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.RelaChannelToRole; /** * dal Interface:RelaChannelToRole * @author gencode * @date 2018-3-22 */ public interface RelaChannelToRoleService { public List<RelaChannelToRole> findAll(); public List<RelaChannelToRole> findRelaChannelToRoles(RelaChannelToRole record); public RelaChannelToRole getRelaChannelToRoleByPrimaryKey(Long relaId); public Integer createRelaChannelToRole(RelaChannelToRole record); public Integer removeRelaChannelToRole(RelaChannelToRole record); public Integer removeByPrimaryKey(Long relaId); public Integer modifyRelaChannelToRoleByPrimaryKey(RelaChannelToRole record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/AuthLogServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.AuthLogService; import cn.enn.ygego.sunny.user.dao.AuthLogDao; import cn.enn.ygego.sunny.user.model.AuthLog; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:AuthLog * @author gencode * @date 2018-3-22 */ @Service public class AuthLogServiceImpl implements AuthLogService{ @Autowired private AuthLogDao authLogDao; public List<AuthLog> findAll(){ return authLogDao.findAll(); } public List<AuthLog> findAuthLogs(AuthLog record){ return authLogDao.find(record); } public AuthLog getAuthLogByPrimaryKey(Long logId){ return authLogDao.getByPrimaryKey(logId); } public Integer createAuthLog(AuthLog record){ return authLogDao.insert(record); } public Integer removeAuthLog(AuthLog record){ return authLogDao.delete(record); } public Integer removeByPrimaryKey(Long logId){ return authLogDao.deleteByPrimaryKey(logId); } public Integer modifyAuthLogByPrimaryKey(AuthLog record){ return authLogDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/FunctionManageVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * entity:FunctionManage * * @author gencode */ public class FunctionManageVO implements Serializable { private static final long serialVersionUID = -9060855026677813416L; private Long functionId; /* 功能标识 */ private Long appId; /* 应用标识 */ private String functionCode; /* 功能编码 */ private String functionTitle; /* 功能名称 */ private Integer isLastLevel; /* 是否末级 */ private Long parentApplicationId; /* 父级功能标识 */ private List<OperLoginVO> operLoginVOS=new ArrayList<>();//操作列表 // Constructor public FunctionManageVO() { } public Long getFunctionId() { return functionId; } public void setFunctionId(Long functionId) { this.functionId = functionId; } public Long getAppId() { return appId; } public void setAppId(Long appId) { this.appId = appId; } public String getFunctionCode() { return functionCode; } public void setFunctionCode(String functionCode) { this.functionCode = functionCode; } public String getFunctionTitle() { return functionTitle; } public void setFunctionTitle(String functionTitle) { this.functionTitle = functionTitle; } public Integer getIsLastLevel() { return isLastLevel; } public void setIsLastLevel(Integer isLastLevel) { this.isLastLevel = isLastLevel; } public Long getParentApplicationId() { return parentApplicationId; } public void setParentApplicationId(Long parentApplicationId) { this.parentApplicationId = parentApplicationId; } public List<OperLoginVO> getOperLoginVOS() { return operLoginVOS; } public void setOperLoginVOS(List<OperLoginVO> operLoginVOS) { this.operLoginVOS = operLoginVOS; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntProdApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.dto.EntProdApplyDTO; import cn.enn.ygego.sunny.user.dto.vo.EntProdApplyVO; import cn.enn.ygego.sunny.user.model.EntProdApply; /** * dal Interface:EntProdApply * @author gencode * @date 2018-3-30 */ public interface EntProdApplyService { public List<EntProdApply> findAll(); public List<EntProdApply> findEntProdApplys(EntProdApply record); public EntProdApply getEntProdApplyByPrimaryKey(Long applyId); public Integer createEntProdApply(EntProdApply record); public Integer removeEntProdApply(EntProdApply record); public Integer removeByPrimaryKey(Long applyId); public Integer modifyEntProdApplyByPrimaryKey(EntProdApply record); public Integer createEntProdApplyVO(EntProdApplyVO record); public EntProdApplyVO getEntProdApplyVO(EntProdApplyDTO entProdApplyDTO); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/InspectFactoryApplyInfoServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.http.client.utils.DateUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.user.constant.FactoryApplyStatusEnum; import cn.enn.ygego.sunny.user.dao.InspectFactoryApplyInfoDao; import cn.enn.ygego.sunny.user.dto.factory.CategoryQueryVO; import cn.enn.ygego.sunny.user.dto.factory.InspectFactoryApplyInfoVO; import cn.enn.ygego.sunny.user.model.InspectFactoryApplyInfo; import cn.enn.ygego.sunny.user.service.InspectFactoryApplyInfoService; /** * dal Interface:InspectFactoryApplyInfo * @author gencode * @date 2018-3-30 */ @Service public class InspectFactoryApplyInfoServiceImpl implements InspectFactoryApplyInfoService{ @Autowired private InspectFactoryApplyInfoDao inspectFactoryApplyInfoDao; public List<InspectFactoryApplyInfo> findAll(){ return inspectFactoryApplyInfoDao.findAll(); } public List<InspectFactoryApplyInfo> findInspectFactoryApplyInfos(InspectFactoryApplyInfo record){ return inspectFactoryApplyInfoDao.find(record); } public InspectFactoryApplyInfo getInspectFactoryApplyInfoByPrimaryKey(Long applyId){ return inspectFactoryApplyInfoDao.getByPrimaryKey(applyId); } public Integer createInspectFactoryApplyInfo(InspectFactoryApplyInfo record){ return inspectFactoryApplyInfoDao.insert(record); } public Integer removeInspectFactoryApplyInfo(InspectFactoryApplyInfo record){ return inspectFactoryApplyInfoDao.delete(record); } public Integer removeByPrimaryKey(Long applyId){ return inspectFactoryApplyInfoDao.deleteByPrimaryKey(applyId); } public Integer modifyInspectFactoryApplyInfoByPrimaryKey(InspectFactoryApplyInfo record){ return inspectFactoryApplyInfoDao.updateByPrimaryKey(record); } @Override public PageDTO<InspectFactoryApplyInfoVO> getAuditCategoryList(CategoryQueryVO query) { PageDTO<InspectFactoryApplyInfoVO> page = new PageDTO<InspectFactoryApplyInfoVO>( query.getPageNum(), query.getPageSize()); query.setStartRow(page.getStartRow()); InspectFactoryApplyInfo record = new InspectFactoryApplyInfo(); if (StringUtils.isNotBlank(query.getCategoryId())) { record.setCategoryId(Integer.valueOf(query.getCategoryId())); } if (StringUtils.isNotBlank(query.getApplystatus())) { record.setApplyStatus(Integer.valueOf(query.getApplystatus())); } if (StringUtils.isNotBlank(query.getCreateMemberId())) { record.setCreateMemberId(Long.valueOf(query.getCreateMemberId())); } List<InspectFactoryApplyInfo> list = inspectFactoryApplyInfoDao .find(record); page.setResultData(new ArrayList<InspectFactoryApplyInfoVO> ()); if (list.size() > 0) { List<InspectFactoryApplyInfoVO> resultData = inspectFactoryApplyInfoDao .getAuditCategoryList(query); // 参数类型装换 for (int i = 0; i < resultData.size(); i++) { String dateStr = DateUtils.formatDate(resultData.get(i) .getCreateTime(), "yyyy-MM-dd"); resultData.get(i).setCreateTimeStr(dateStr); resultData.get(i).setApplyStatusStr(FactoryApplyStatusEnum .getStatusName(resultData.get(i).getApplyStatus()+"")); } page.setResultData(resultData); } page.setTotal(list.size()); return page; } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/AppsServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.AppsService; import cn.enn.ygego.sunny.user.dao.AppsDao; import cn.enn.ygego.sunny.user.model.Apps; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:Apps * @author gencode * @date 2018-3-22 */ @Service public class AppsServiceImpl implements AppsService{ @Autowired private AppsDao appsDao; public List<Apps> findAll(){ return appsDao.findAll(); } public List<Apps> findAppss(Apps record){ return appsDao.find(record); } public Apps getAppsByPrimaryKey(Long appId){ return appsDao.getByPrimaryKey(appId); } public Integer createApps(Apps record){ return appsDao.insert(record); } public Integer removeApps(Apps record){ return appsDao.delete(record); } public Integer removeByPrimaryKey(Long appId){ return appsDao.deleteByPrimaryKey(appId); } public Integer modifyAppsByPrimaryKey(Apps record){ return appsDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MaterialWhiteListDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.MaterialWhiteList; /** * dal Interface:MaterialWhiteList * @author gencode */ public interface MaterialWhiteListDao { Integer insert(MaterialWhiteList record); Integer insertSelective(MaterialWhiteList record); Integer delete(MaterialWhiteList record); Integer deleteByPrimaryKey(@Param("listId") Long listId); Integer updateByPrimaryKey(MaterialWhiteList record); List<MaterialWhiteList> findAll(); List<MaterialWhiteList> find(MaterialWhiteList record); Integer getCount(MaterialWhiteList record); MaterialWhiteList getByPrimaryKey(@Param("listId") Long listId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/JoinCompanyQueryVO.java package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; public class JoinCompanyQueryVO implements Serializable { private static final long serialVersionUID = -1307303042041577150L; private Long setId; /* 授权配置ID */ private Long memberId; /* 子公司会员ID */ private Long pareMemberId; /* 父级会员ID */ private String entName; /* 企业名称 */ private String acctName; /* 账户名称 */ private String name; /* 姓名 */ private String mobileNum; /* 手机号 */ private Integer applyType; /* 申请类型 (关系类型) 1:待确认 2:已确认 3:已拒绝 */ private Integer status; /* 状态(权限状态) 1:待确认 2:已确认 3:已拒绝 */ private Integer pageSize; private Integer pageNum; private Integer startRow; private boolean freeCompany; /* 是否绑定父公司 */ public Long getSetId() { return setId; } public void setSetId(Long setId) { this.setId = setId; } public boolean isFreeCompany() { return freeCompany; } public void setFreeCompany(boolean freeCompany) { this.freeCompany = freeCompany; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getPareMemberId() { return pareMemberId; } public void setPareMemberId(Long pareMemberId) { this.pareMemberId = pareMemberId; } public String getEntName() { return entName; } public void setEntName(String entName) { this.entName = entName; } public String getAcctName() { return acctName; } public void setAcctName(String acctName) { this.acctName = acctName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobileNum() { return mobileNum; } public void setMobileNum(String mobileNum) { this.mobileNum = mobileNum; } public Integer getApplyType() { return applyType; } public void setApplyType(Integer applyType) { this.applyType = applyType; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getStartRow() { return startRow; } public void setStartRow(Integer startRow) { this.startRow = startRow; } @Override public String toString() { return "JoinCompanyQueryVO [memberId=" + memberId + ", pareMemberId=" + pareMemberId + ", entName=" + entName + ", acctName=" + acctName + ", name=" + name + ", mobileNum=" + mobileNum + ", applyType=" + applyType + ", status=" + status + ", pageSize=" + pageSize + ", pageNum=" + pageNum + ", startRow=" + startRow + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/MarketAuthInfo.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * ClassName: MarketAuthInfo * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class MarketAuthInfo implements Serializable { private Long authId; /* 授权ID */ private Long memberId; /* 会员ID */ private String authFileNo; /* 授权书编号 */ private Long producerMemberId; /* 生产商会员ID */ private String producerName; /* 生产商名称 */ private Integer limitType; /* 期限类型 */ private Date certValidStartDate; /* 证件有效开始日期 */ private Date certValidEndDate; /* 证件有效截止日期 */ // Constructor public MarketAuthInfo() { } /** * full Constructor */ public MarketAuthInfo(Long authId, Long memberId, String authFileNo, Long producerMemberId, String producerName, Integer limitType, Date certValidStartDate, Date certValidEndDate) { this.authId = authId; this.memberId = memberId; this.authFileNo = authFileNo; this.producerMemberId = producerMemberId; this.producerName = producerName; this.limitType = limitType; this.certValidStartDate = certValidStartDate; this.certValidEndDate = certValidEndDate; } public Long getAuthId() { return authId; } public void setAuthId(Long authId) { this.authId = authId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public String getAuthFileNo() { return authFileNo; } public void setAuthFileNo(String authFileNo) { this.authFileNo = authFileNo; } public Long getProducerMemberId() { return producerMemberId; } public void setProducerMemberId(Long producerMemberId) { this.producerMemberId = producerMemberId; } public String getProducerName() { return producerName; } public void setProducerName(String producerName) { this.producerName = producerName; } public Integer getLimitType() { return limitType; } public void setLimitType(Integer limitType) { this.limitType = limitType; } public Date getCertValidStartDate() { return certValidStartDate; } public void setCertValidStartDate(Date certValidStartDate) { this.certValidStartDate = certValidStartDate; } public Date getCertValidEndDate() { return certValidEndDate; } public void setCertValidEndDate(Date certValidEndDate) { this.certValidEndDate = certValidEndDate; } @Override public String toString() { return "MarketAuthInfo [" + "authId=" + authId + ", memberId=" + memberId + ", authFileNo=" + authFileNo + ", producerMemberId=" + producerMemberId + ", producerName=" + producerName + ", limitType=" + limitType + ", certValidStartDate=" + certValidStartDate + ", certValidEndDate=" + certValidEndDate + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/MarketCateStandardCharge.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * ClassName: MarketCateStandardCharge * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class MarketCateStandardCharge implements Serializable { private Long chargeId; /* 费率ID */ private Long marketId; /* 超市ID */ private Long categoryId; /* 类目ID */ private String categoryName; /* 类目名称 */ private String categoryNamePath; /* 类目名称路径 */ private String categoryIdPath; /* 类目ID路径 */ private Integer standardPremiumRates; /* 标准费率 */ private Integer status; /* 状态 */ private String memo; /* 备注 */ private Date createTime; /* 创建时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ private Date modTime; /* 修改时间 */ // Constructor public MarketCateStandardCharge() { } /** * full Constructor */ public MarketCateStandardCharge(Long chargeId, Long marketId, Long categoryId, String categoryName, String categoryNamePath, String categoryIdPath, Integer standardPremiumRates, Integer status, String memo, Date createTime, Long createMemberId, Long createAcctId, String createName, Date modTime) { this.chargeId = chargeId; this.marketId = marketId; this.categoryId = categoryId; this.categoryName = categoryName; this.categoryNamePath = categoryNamePath; this.categoryIdPath = categoryIdPath; this.standardPremiumRates = standardPremiumRates; this.status = status; this.memo = memo; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; this.modTime = modTime; } public Long getChargeId() { return chargeId; } public void setChargeId(Long chargeId) { this.chargeId = chargeId; } public Long getMarketId() { return marketId; } public void setMarketId(Long marketId) { this.marketId = marketId; } public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getCategoryName() { return categoryName; } public void setCategoryName(String categoryName) { this.categoryName = categoryName; } public String getCategoryNamePath() { return categoryNamePath; } public void setCategoryNamePath(String categoryNamePath) { this.categoryNamePath = categoryNamePath; } public String getCategoryIdPath() { return categoryIdPath; } public void setCategoryIdPath(String categoryIdPath) { this.categoryIdPath = categoryIdPath; } public Integer getStandardPremiumRates() { return standardPremiumRates; } public void setStandardPremiumRates(Integer standardPremiumRates) { this.standardPremiumRates = standardPremiumRates; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public Date getModTime() { return modTime; } public void setModTime(Date modTime) { this.modTime = modTime; } @Override public String toString() { return "MarketCateStandardCharge [" + "chargeId=" + chargeId + ", marketId=" + marketId + ", categoryId=" + categoryId + ", categoryName=" + categoryName + ", categoryNamePath=" + categoryNamePath + ", categoryIdPath=" + categoryIdPath + ", standardPremiumRates=" + standardPremiumRates + ", status=" + status + ", memo=" + memo + ", createTime=" + createTime + ", createMemberId=" + createMemberId + ", createAcctId=" + createAcctId + ", createName=" + createName + ", modTime=" + modTime + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/constant/StatusConstant.java package cn.enn.ygego.sunny.user.constant; /** * ClassName: StatusConstant * Description: * Author: en3 * Date: 2018/3/24 15:17 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class StatusConstant { public static final int UNRELATIVE = -1;//业务不相关状态 public static final int INVALID = 0;//无效的 public static final int VALID = 1;//有效的 } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntAuthTypeApply.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:EntAuthTypeApply * * @author gencode */ public class EntAuthTypeApply implements Serializable { private static final long serialVersionUID = -6550878413474100700L; private Long authApplyId; /* 认证申请ID */ private Long memberId; /* 会员ID */ private Integer authenType; /* 认证类型 */ private Integer authState; /* 认证状态 */ private String approveDesc; /* 审核结果描述 */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ private Date createTime; /* 创建时间 */ // Constructor public EntAuthTypeApply() { } /** * full Constructor */ public EntAuthTypeApply(Long authApplyId, Long memberId, Integer authenType, Integer authState, String approveDesc, Long createAcctId, String createName, Date createTime) { this.authApplyId = authApplyId; this.memberId = memberId; this.authenType = authenType; this.authState = authState; this.approveDesc = approveDesc; this.createAcctId = createAcctId; this.createName = createName; this.createTime = createTime; } public Long getAuthApplyId() { return authApplyId; } public void setAuthApplyId(Long authApplyId) { this.authApplyId = authApplyId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getAuthenType() { return authenType; } public void setAuthenType(Integer authenType) { this.authenType = authenType; } public Integer getAuthState() { return authState; } public void setAuthState(Integer authState) { this.authState = authState; } public String getApproveDesc() { return approveDesc; } public void setApproveDesc(String approveDesc) { this.approveDesc = approveDesc; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "EntAuthTypeApply [" + "authApplyId=" + authApplyId+ ", memberId=" + memberId+ ", authenType=" + authenType+ ", authState=" + authState+ ", approveDesc=" + approveDesc+ ", createAcctId=" + createAcctId+ ", createName=" + createName+ ", createTime=" + createTime+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/DataPrivDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.DataPriv; /** * dal Interface:DataPriv * @author gencode */ public interface DataPrivDao { Integer insert(DataPriv record); Integer insertSelective(DataPriv record); Integer delete(DataPriv record); Integer deleteByPrimaryKey(@Param("privId") Long privId); Integer updateByPrimaryKey(DataPriv record); List<DataPriv> findAll(); List<DataPriv> find(DataPriv record); Integer getCount(DataPriv record); DataPriv getByPrimaryKey(@Param("privId") Long privId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/MarketDiscountMaterialServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.MarketDiscountMaterialService; import cn.enn.ygego.sunny.user.dao.MarketDiscountMaterialDao; import cn.enn.ygego.sunny.user.model.MarketDiscountMaterial; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * ClassName: MarketDiscountMaterial * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ @Service("marketDiscountMaterialService") public class MarketDiscountMaterialServiceImpl implements MarketDiscountMaterialService{ @Autowired private MarketDiscountMaterialDao marketDiscountMaterialDao; public List<MarketDiscountMaterial> findAll(){ return marketDiscountMaterialDao.selectAll(); } public List<MarketDiscountMaterial> findMarketDiscountMaterials(MarketDiscountMaterial record){ return marketDiscountMaterialDao.select(record); } public MarketDiscountMaterial getMarketDiscountMaterialByPrimaryKey(Long chargeId){ return marketDiscountMaterialDao.selectByPrimaryKey(chargeId); } public Integer deleteByPrimaryKey(Long chargeId){ return marketDiscountMaterialDao.deleteByPrimaryKey(chargeId); } public Integer createMarketDiscountMaterial(MarketDiscountMaterial record){ return marketDiscountMaterialDao.insertSelective(record); } public Integer deleteMarketDiscountMaterial(MarketDiscountMaterial record){ return marketDiscountMaterialDao.delete(record); } public Integer removeMarketDiscountMaterial(MarketDiscountMaterial record){ return marketDiscountMaterialDao.updateByPrimaryKeySelective(record); } public Integer updateMarketDiscountMaterialByPrimaryKeySelective(MarketDiscountMaterial record){ return marketDiscountMaterialDao.updateByPrimaryKeySelective(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntSetServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntSetService; import cn.enn.ygego.sunny.user.constant.JoinEntConstant; import cn.enn.ygego.sunny.user.dao.EntCustInfoDao; import cn.enn.ygego.sunny.user.dao.EntSetDao; import cn.enn.ygego.sunny.user.dto.vo.JoinCompanyQueryVO; import cn.enn.ygego.sunny.user.dto.vo.JoinCompanyVO; import cn.enn.ygego.sunny.user.model.EntCustInfo; import cn.enn.ygego.sunny.user.model.EntSet; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntSet * @author gencode * @date 2018-3-28 */ @Service public class EntSetServiceImpl implements EntSetService{ @Autowired private EntSetDao entSetDao; @Autowired private EntCustInfoDao entCustInfoDao; public List<EntSet> findAll(){ return entSetDao.findAll(); } public List<EntSet> findEntSets(EntSet record){ return entSetDao.find(record); } public EntSet getEntSetByPrimaryKey(Long setId){ return entSetDao.getByPrimaryKey(setId); } public Integer createEntSet(EntSet record){ return entSetDao.insert(record); } @Override public Integer createEntSetList(List<EntSet> records) { return entSetDao.insertList(records); } public Integer removeEntSet(EntSet record){ return entSetDao.delete(record); } public Integer removeByPrimaryKey(Long setId){ return entSetDao.deleteByPrimaryKey(setId); } public Integer modifyEntSetByPrimaryKey(EntSet record){ return entSetDao.updateByPrimaryKey(record); } @Override public Integer getFerrSunCompanyCount(JoinCompanyQueryVO query) { query.setFreeCompany(true); return entSetDao.getCompanyListCount(query); } @Override public List<JoinCompanyVO> getFerrSunCompanyList(JoinCompanyQueryVO query) { query.setFreeCompany(true); return entSetDao.getCompanyList(query); } @Override public Integer getJoinCompanyCount(JoinCompanyQueryVO query) { return entSetDao.getJoinCompanyListCount(query); } @Override public List<JoinCompanyVO> getJoinCompanyList(JoinCompanyQueryVO query) { return entSetDao.getJoinCompanyList(query); } @Override public JoinCompanyVO getSunCompanyDetail(JoinCompanyQueryVO query){ return entSetDao.getSunCompanyBySetId(query); } @Override public Integer agreeJoinCompanyAndSet(EntSet entSet) { // 查询所有申请加入企业 EntSet setQuery = new EntSet(); setQuery.setMemberId(entSet.getMemberId()); List<EntSet> entSetList = entSetDao.find(setQuery); // 修改企业授权设置状态 for(EntSet set : entSetList ){ if(set.getSetId() == entSet.getSetId()){ set.setApplyType(JoinEntConstant.SET_APPLYTYPE_AGREE); set.setStatus(JoinEntConstant.SET_STATUS_AGREE); }else{ set.setApplyType(JoinEntConstant.SET_APPLYTYPE_REFUSE); set.setStatus(JoinEntConstant.SET_STATUS_REFUSE); } } // 批量修改ENT_SET表状态 Integer operation = entSetDao.updateEntSetByList(entSetList); // 修改ENT_CUST_INFO 表 子公司配置 状态 EntCustInfo entCust = new EntCustInfo(); entCust.setMemberId(entSet.getMemberId()); // 子公司ID entCust.setPareMemberId(entSet.getPareMemberId()); // 父级会员ID设置 entCust.setBlackWhiteListSet(entSet.getBlackWhiteListSet()); // 黑白名单设置 entCust.setAgreementPriceId(entSet.getAgreementPriceId()); // 协议价设置 entCust.setCateMateId(entSet.getCateMateId()); // 类目物料设置 operation += entCustInfoDao.updateByPrimaryKey(entCust); return operation; } @Override public Integer agreeSetAccredit(EntSet entSet) { // 修改ENT_SET表状态 entSet.setApplyType(JoinEntConstant.SET_APPLYTYPE_AGREE); entSet.setStatus(JoinEntConstant.SET_STATUS_AGREE); Integer operation = entSetDao.updateByPrimaryKey(entSet); // 修改ENT_CUST_INFO 表状态 EntCustInfo entCust = new EntCustInfo(); entCust.setMemberId(entSet.getMemberId()); entCust.setBlackWhiteListSet(entSet.getBlackWhiteListSet()); // 黑白名单设置 entCust.setAgreementPriceId(entSet.getAgreementPriceId()); // 协议价设置 entCust.setCateMateId(entSet.getCateMateId()); // 类目物料设置 operation += entCustInfoDao.updateByPrimaryKey(entCust); return operation; } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/JoinCompanyVO.java package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.util.Date; public class JoinCompanyVO implements Serializable { private static final long serialVersionUID = -2405268154137447282L; private String memberIds; /* 子公司ID集合 */ private Long memberId; /* 子公司会员ID */ private Long pareMemberId; /* 父级会员ID */ private Long adminAcctId; /* 企业管理员账户ID */ private String acctName; /* 企业管理员账户名称 */ private String name; /* 企业管理员姓名 */ private String mobileNum; /* 手机号 */ private String entName; /* 企业名称 */ private String custCode; /* 客户编码 */ private String businessMode; /* 经营模式 */ private String legalPerson; /* 法人 */ private Integer legalPersonNationality; /* 法人国籍 */ private Date establishDate; /* 成立日期 */ private String entTel; /* 企业电话 */ private Integer supplierSet; /* 供应商设置 */ private String blackWhiteListSet; /* 黑白名单设置 */ private String agreementPriceId; /* 协议价设置 */ private Integer cateMateId; /* 类目物料设置 */ private Date authTime; /* 企业认证时间 */ private Long setMemberId; /* 会员ID */ private Long setPareMemberId; /* 父级会员ID */ private Long setId; /* 设置ID */ private String setBlackWhiteListSet; /* 黑白名单设置 */ private String setAgreementPriceId; /* 协议价设置 */ private Integer setCateMateId; /* 类目物料设置 */ private Integer applyType; /* 申请类型 (关系类型) 1:待确认 2:已确认 3:已拒绝 */ private Integer status; /* 状态(权限状态) 1:待确认 2:已确认 3:已拒绝 */ private Date setCreateTime; /* 创建时间 */ private Long setCreateAcctId; /* 创建人账户ID */ private String setCreateName; /* 创建人姓名 */ public String getMemberIds() { return memberIds; } public void setMemberIds(String memberIds) { this.memberIds = memberIds; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getPareMemberId() { return pareMemberId; } public void setPareMemberId(Long pareMemberId) { this.pareMemberId = pareMemberId; } public Long getAdminAcctId() { return adminAcctId; } public void setAdminAcctId(Long adminAcctId) { this.adminAcctId = adminAcctId; } public String getAcctName() { return acctName; } public void setAcctName(String acctName) { this.acctName = acctName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobileNum() { return mobileNum; } public void setMobileNum(String mobileNum) { this.mobileNum = mobileNum; } public String getEntName() { return entName; } public void setEntName(String entName) { this.entName = entName; } public String getCustCode() { return custCode; } public void setCustCode(String custCode) { this.custCode = custCode; } public String getBusinessMode() { return businessMode; } public void setBusinessMode(String businessMode) { this.businessMode = businessMode; } public String getLegalPerson() { return legalPerson; } public void setLegalPerson(String legalPerson) { this.legalPerson = legalPerson; } public Integer getLegalPersonNationality() { return legalPersonNationality; } public void setLegalPersonNationality(Integer legalPersonNationality) { this.legalPersonNationality = legalPersonNationality; } public Date getEstablishDate() { return establishDate; } public void setEstablishDate(Date establishDate) { this.establishDate = establishDate; } public String getEntTel() { return entTel; } public void setEntTel(String entTel) { this.entTel = entTel; } public Integer getSupplierSet() { return supplierSet; } public void setSupplierSet(Integer supplierSet) { this.supplierSet = supplierSet; } public String getBlackWhiteListSet() { return blackWhiteListSet; } public void setBlackWhiteListSet(String blackWhiteListSet) { this.blackWhiteListSet = blackWhiteListSet; } public String getAgreementPriceId() { return agreementPriceId; } public void setAgreementPriceId(String agreementPriceId) { this.agreementPriceId = agreementPriceId; } public Integer getCateMateId() { return cateMateId; } public void setCateMateId(Integer cateMateId) { this.cateMateId = cateMateId; } public Date getAuthTime() { return authTime; } public void setAuthTime(Date authTime) { this.authTime = authTime; } public Long getSetMemberId() { return setMemberId; } public void setSetMemberId(Long setMemberId) { this.setMemberId = setMemberId; } public Long getSetPareMemberId() { return setPareMemberId; } public void setSetPareMemberId(Long setPareMemberId) { this.setPareMemberId = setPareMemberId; } public Long getSetId() { return setId; } public void setSetId(Long setId) { this.setId = setId; } public String getSetBlackWhiteListSet() { return setBlackWhiteListSet; } public void setSetBlackWhiteListSet(String setBlackWhiteListSet) { this.setBlackWhiteListSet = setBlackWhiteListSet; } public String getSetAgreementPriceId() { return setAgreementPriceId; } public void setSetAgreementPriceId(String setAgreementPriceId) { this.setAgreementPriceId = setAgreementPriceId; } public Integer getSetCateMateId() { return setCateMateId; } public void setSetCateMateId(Integer setCateMateId) { this.setCateMateId = setCateMateId; } public Integer getApplyType() { return applyType; } public void setApplyType(Integer applyType) { this.applyType = applyType; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getSetCreateTime() { return setCreateTime; } public void setSetCreateTime(Date setCreateTime) { this.setCreateTime = setCreateTime; } public Long getSetCreateAcctId() { return setCreateAcctId; } public void setSetCreateAcctId(Long setCreateAcctId) { this.setCreateAcctId = setCreateAcctId; } public String getSetCreateName() { return setCreateName; } public void setSetCreateName(String setCreateName) { this.setCreateName = setCreateName; } @Override public String toString() { return "JoinCompanyVO [memberId=" + memberId + ", pareMemberId=" + pareMemberId + ", adminAcctId=" + adminAcctId + ", acctName=" + acctName + ", name=" + name + ", mobileNum=" + mobileNum + ", entName=" + entName + ", custCode=" + custCode + ", businessMode=" + businessMode + ", legalPerson=" + legalPerson + ", legalPersonNationality=" + legalPersonNationality + ", establishDate=" + establishDate + ", entTel=" + entTel + ", supplierSet=" + supplierSet + ", blackWhiteListSet=" + blackWhiteListSet + ", agreementPriceId=" + agreementPriceId + ", cateMateId=" + cateMateId + ", authTime=" + authTime + ", setMemberId=" + setMemberId + ", setPareMemberId=" + setPareMemberId + ", setId=" + setId + ", setBlackWhiteListSet=" + setBlackWhiteListSet + ", setAgreementPriceId=" + setAgreementPriceId + ", setCateMateId=" + setCateMateId + ", applyType=" + applyType + ", status=" + status + ", setCreateTime=" + setCreateTime + ", setCreateAcctId=" + setCreateAcctId + ", setCreateName=" + setCreateName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntDeptDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntDept; /** * dal Interface:EntDept * @author gencode */ public interface EntDeptDao { Integer insert(EntDept record); Integer insertSelective(EntDept record); Integer delete(EntDept record); Integer deleteByPrimaryKey(@Param("deptId") Long deptId); Integer updateByPrimaryKey(EntDept record); List<EntDept> findAll(); List<EntDept> find(EntDept record); Integer getCount(EntDept record); EntDept getByPrimaryKey(@Param("deptId") Long deptId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/QuestionFeedbackServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import cn.enn.ygego.sunny.user.dao.QuestionAttachDao; import cn.enn.ygego.sunny.user.dao.QuestionFeedbackDao; import cn.enn.ygego.sunny.user.dao.QuestionResponseDao; import cn.enn.ygego.sunny.user.dto.QuestionAttachDTO; import cn.enn.ygego.sunny.user.dto.QuestionFeedbackDTO; import cn.enn.ygego.sunny.user.dto.QuestionResponseDTO; import cn.enn.ygego.sunny.user.dto.vo.QuestionFeedbackVO; import cn.enn.ygego.sunny.user.dto.vo.QuestionResponseVO; import cn.enn.ygego.sunny.user.model.QuestionAttach; import cn.enn.ygego.sunny.user.model.QuestionFeedback; import cn.enn.ygego.sunny.user.model.QuestionResponse; import cn.enn.ygego.sunny.user.service.QuestionFeedbackService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * dal Interface:QuestionFeedback * @author gencode * @date 2018-3-22 */ @Service public class QuestionFeedbackServiceImpl implements QuestionFeedbackService{ @Autowired private QuestionFeedbackDao questionFeedbackDao; @Autowired private QuestionAttachDao questionAttachDao; @Autowired private QuestionResponseDao questionResponseDao; /** * @Description 回复状态 0:未回复 1:已回复 * @author liangchao * @date 2018/3/26 11:13 */ private static final Integer DIDREPLY = 0; private static final Integer HAVEREPLY = 1; private static final Integer DEFAULTSTATUS = 0; /** * @Description 问题编号前缀 * @author liangchao * @date 2018/3/26 17:47 */ private static final String CODEPREFIX = "WT_"; public List<QuestionFeedback> findAll(){ return questionFeedbackDao.findAll(); } public List<QuestionFeedback> findQuestionFeedbacks(QuestionFeedback record){ return questionFeedbackDao.find(record); } public QuestionFeedback getQuestionFeedbackByPrimaryKey(Long questionId){ return questionFeedbackDao.getByPrimaryKey(questionId); } public Integer createQuestionFeedback(QuestionFeedback record){ return questionFeedbackDao.insert(record); } public Integer removeQuestionFeedback(QuestionFeedback record){ return questionFeedbackDao.delete(record); } public Integer removeByPrimaryKey(Long questionId){ return questionFeedbackDao.deleteByPrimaryKey(questionId); } public Integer modifyQuestionFeedbackByPrimaryKey(QuestionFeedback record){ return questionFeedbackDao.updateByPrimaryKey(record); } /** * @Description * @author liangchao * @date 2018/3/23 15:12 * @param questionFeedbackDTO * @return */ @Override public void insertQuestion(QuestionFeedbackDTO questionFeedbackDTO) { QuestionFeedback questionFeedback =new QuestionFeedback(); BeanUtils.copyProperties(questionFeedbackDTO, questionFeedback); //TODO:CODEPREFIX QuestionCode . questionFeedback.setQuestionCode(this.CODEPREFIX); questionFeedback.setStatus(this.DEFAULTSTATUS); questionFeedback.setIsResponse(this.DIDREPLY); //保存反馈问题信息 questionFeedbackDao.insertReturnIdSelective(questionFeedback); Long questionId = questionFeedback.getQuestionId(); List<QuestionAttachDTO> attachDTOList = questionFeedbackDTO.getAttachList(); if(null != attachDTOList && !attachDTOList.isEmpty()) { List<QuestionAttach> attachDTOS = new ArrayList<>(); for (QuestionAttachDTO questionAttachDTO : attachDTOList) { questionAttachDTO.setQuestionId(questionId); QuestionAttach questionAttach = new QuestionAttach(); BeanUtils.copyProperties(questionAttachDTO, questionAttach); attachDTOS.add(questionAttach); } questionAttachDao.insertBatch(attachDTOS); } } /** * @Description * @author liangchao * @date 2018/3/23 15:02 * @param questionFeedbackDTO * @return */ @Override public List<QuestionFeedback> questionList(QuestionFeedbackDTO questionFeedbackDTO) { QuestionFeedback questionFeedback = new QuestionFeedback(); BeanUtils.copyProperties(questionFeedbackDTO, questionFeedback); return questionFeedbackDao.find(questionFeedback); } /** * @Description 回复反馈问题 * @author liangchao * @date 2018/3/22 15:01 * @param questionResponseDTO * @return */ @Override public void insertQuestionResponse(QuestionResponseDTO questionResponseDTO) { QuestionResponse questionResponse = new QuestionResponse(); BeanUtils.copyProperties(questionResponseDTO, questionResponse); questionResponseDao.insertSelective(questionResponse); } /** * @Description 批量回复信息 并更新信息状态和回复状态 * @author liangchao * @date 2018/3/26 11:13 * @param questionResponseVO * @return */ @Override public void insertBatchQuestionResponse(QuestionResponseVO questionResponseVO) { List<QuestionResponse> list = new ArrayList<>(); List<Long> idList = questionResponseVO.getIdList(); Date date = new Date(); for (Long questionId : idList) { QuestionResponse questionResponse = new QuestionResponse(); BeanUtils.copyProperties(questionResponseVO, questionResponse); questionResponse.setQuestionId(questionId); questionResponse.setCreateTime(date); list.add(questionResponse); } if(null != list && !list.isEmpty()) { //准备批量更改问题状态 QuestionFeedbackVO questionFeedbackVO = new QuestionFeedbackVO(); questionFeedbackVO.setStatus(questionResponseVO.getStatus()); questionFeedbackVO.setIsResponse(this.HAVEREPLY); questionFeedbackVO.setIdList(idList); //批量保存问题回复信息 questionResponseDao.insertBatch(list); //批量修改“问题状态”“回复状态” 问题状态前台传入 *回复状态还未有字段更改为已回复 0:未回复 1:已回复 questionFeedbackDao.updateBatchQuestion(questionFeedbackVO); } } @Override public void updateBatchQuestion(QuestionFeedbackVO questionFeedbackVO) { questionFeedbackDao.updateBatchQuestion(questionFeedbackVO); } /** * @Description 反馈问题分页查询 * @author liangchao * @date 2018/3/22 14:59 * @param questionVO * @return */ @Override public List<QuestionFeedbackDTO> findPage(QuestionFeedbackVO questionVO) { List<QuestionFeedbackDTO> questionFeedbackList = questionFeedbackDao.findPage(questionVO); return questionFeedbackList; } @Override public Long findPageCount(QuestionFeedbackVO questionVO) { Long pageCount = questionFeedbackDao.findPageCount(questionVO); return pageCount; } /** * @Description 反馈问题信息详情 * @author liangchao * @date 2018/3/23 14:59 * @param questionFeedbackVO * @return */ @Override public QuestionFeedbackDTO findQuestion(QuestionFeedbackVO questionFeedbackVO) { return questionFeedbackDao.getQuestionInfo(questionFeedbackVO); } /** * @Description questionAttachList转换questionAttachDTOList * @author liangchao * @date 2018/3/23 15:13 * @param questionAttachList * @return */ private List<QuestionAttachDTO> converQuestionAttachList(List<QuestionAttach> questionAttachList) { List<QuestionAttachDTO> questionAttachDTOList = new ArrayList<>(); for (QuestionAttach questionAttach : questionAttachList) { QuestionAttachDTO questionAttachDTO = new QuestionAttachDTO(); BeanUtils.copyProperties(questionAttach, questionAttachDTO); questionAttachDTOList.add(questionAttachDTO); } return questionAttachDTOList; } /** * @Description questionResponseList转换questionResponseDTOList * @author liangchao * @date 2018/3/23 15:13 * @param questionResponseList * @return */ private List<QuestionResponseDTO> converQuestionResponseDTOList(List<QuestionResponse> questionResponseList) { List<QuestionResponseDTO> questionAttachDTOList = new ArrayList<>(); for (QuestionResponse questionResponse : questionResponseList) { QuestionResponseDTO questionResponseDTO = new QuestionResponseDTO(); BeanUtils.copyProperties(questionResponse, questionResponseDTO); questionAttachDTOList.add(questionResponseDTO); } return questionAttachDTOList; } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketDiscountCateDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketDiscountCate; import org.springframework.stereotype.Repository; /** * ClassName: MarketDiscountCate * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketDiscountCateDao { List<MarketDiscountCate> selectAll(); List<MarketDiscountCate> select(MarketDiscountCate record); Integer selectCount(MarketDiscountCate record); MarketDiscountCate selectByPrimaryKey(Long discountId); Integer deleteByPrimaryKey(Long discountId); Integer delete(MarketDiscountCate record); Integer insertSelective(MarketDiscountCate record); Integer updateByPrimaryKeySelective(MarketDiscountCate record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualCustDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.dto.IndividualCustDTO; import cn.enn.ygego.sunny.user.dto.vo.PersonQueryVO; import cn.enn.ygego.sunny.user.dto.vo.PersonVO; import cn.enn.ygego.sunny.user.model.IndividualCust; /** * dal Interface:IndividualCust * @author gencode */ public interface IndividualCustDao { Integer insert(IndividualCust record); Integer insertSelective(IndividualCust record); Integer delete(IndividualCust record); Integer deleteByPrimaryKey(@Param("memberId") Long memberId); Integer updateByPrimaryKey(IndividualCust record); List<IndividualCust> findAll(); List<IndividualCust> find(IndividualCust record); Integer getCount(IndividualCust record); IndividualCust getByPrimaryKey(@Param("memberId") Long memberId); IndividualCustDTO getIndividualCustById(@Param("memberId") Long memberId); Integer getPersonCount(PersonQueryVO query); List<PersonVO> getPersonList(PersonQueryVO query); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/RelaMemberToAcctApply.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:RelaMemberToAcctApply * * @author gencode */ public class RelaMemberToAcctApply implements Serializable { private static final long serialVersionUID = -5110337023959191998L; private Long relaId; /* 关系ID */ private Long memberId; /* 会员ID */ private Long acctId; /* 账户ID */ private Integer memberType; /* 会员类型 */ private Integer status; /* 状态 */ private String applySpec; /* 申请说明 */ private Long approveAcctId; /* 审核人账户ID */ private String approveName; /* 审核人姓名 */ private Date auditTime; /* 审核时间 */ // Constructor public RelaMemberToAcctApply() { } /** * full Constructor */ public RelaMemberToAcctApply(Long relaId, Long memberId, Long acctId, Integer memberType, Integer status, String applySpec, Long approveAcctId, String approveName, Date auditTime) { this.relaId = relaId; this.memberId = memberId; this.acctId = acctId; this.memberType = memberType; this.status = status; this.applySpec = applySpec; this.approveAcctId = approveAcctId; this.approveName = approveName; this.auditTime = auditTime; } public Long getRelaId() { return relaId; } public void setRelaId(Long relaId) { this.relaId = relaId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getAcctId() { return acctId; } public void setAcctId(Long acctId) { this.acctId = acctId; } public Integer getMemberType() { return memberType; } public void setMemberType(Integer memberType) { this.memberType = memberType; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getApplySpec() { return applySpec; } public void setApplySpec(String applySpec) { this.applySpec = applySpec; } public Long getApproveAcctId() { return approveAcctId; } public void setApproveAcctId(Long approveAcctId) { this.approveAcctId = approveAcctId; } public String getApproveName() { return approveName; } public void setApproveName(String approveName) { this.approveName = approveName; } public Date getAuditTime() { return auditTime; } public void setAuditTime(Date auditTime) { this.auditTime = auditTime; } @Override public String toString() { return "RelaMemberToAcctApply [" + "relaId=" + relaId+ ", memberId=" + memberId+ ", acctId=" + acctId+ ", memberType=" + memberType+ ", status=" + status+ ", applySpec=" + applySpec+ ", approveAcctId=" + approveAcctId+ ", approveName=" + approveName+ ", auditTime=" + auditTime+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/MarketCateMaterial.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * ClassName: MarketCateMaterial * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class MarketCateMaterial implements Serializable { private Long cateMaterialId; /* 类目物料ID */ private Long marketId; /* 超市ID */ private Long memberId; /* 会员ID */ private Integer applyType; /* 申请类型 */ private String categoryNamePath; /* 类目名称路径 */ private String categoryIdPath; /* 类目ID路径 */ private Integer categoryId; /* 类目ID */ private Long materialId; /* 物料ID */ private Long brandId; /* 品牌ID */ private String brandName; /* 品牌名称 */ private Long producerMemberId; /* 生产商会员ID */ private String producerName; /* 生产商名称 */ private String materialCode; /* 物料编码 */ private String attrNameSerial; /* 属性名序列 */ private Date createTime; /* 创建时间 */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public MarketCateMaterial() { } /** * full Constructor */ public MarketCateMaterial(Long cateMaterialId, Long marketId, Long memberId, Integer applyType, String categoryNamePath, String categoryIdPath, Integer categoryId, Long materialId, Long brandId, String brandName, Long producerMemberId, String producerName, String materialCode, String attrNameSerial, Date createTime, Long createAcctId, String createName) { this.cateMaterialId = cateMaterialId; this.marketId = marketId; this.memberId = memberId; this.applyType = applyType; this.categoryNamePath = categoryNamePath; this.categoryIdPath = categoryIdPath; this.categoryId = categoryId; this.materialId = materialId; this.brandId = brandId; this.brandName = brandName; this.producerMemberId = producerMemberId; this.producerName = producerName; this.materialCode = materialCode; this.attrNameSerial = attrNameSerial; this.createTime = createTime; this.createAcctId = createAcctId; this.createName = createName; } public Long getCateMaterialId() { return cateMaterialId; } public void setCateMaterialId(Long cateMaterialId) { this.cateMaterialId = cateMaterialId; } public Long getMarketId() { return marketId; } public void setMarketId(Long marketId) { this.marketId = marketId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getApplyType() { return applyType; } public void setApplyType(Integer applyType) { this.applyType = applyType; } public String getCategoryNamePath() { return categoryNamePath; } public void setCategoryNamePath(String categoryNamePath) { this.categoryNamePath = categoryNamePath; } public String getCategoryIdPath() { return categoryIdPath; } public void setCategoryIdPath(String categoryIdPath) { this.categoryIdPath = categoryIdPath; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Long getMaterialId() { return materialId; } public void setMaterialId(Long materialId) { this.materialId = materialId; } public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public Long getProducerMemberId() { return producerMemberId; } public void setProducerMemberId(Long producerMemberId) { this.producerMemberId = producerMemberId; } public String getProducerName() { return producerName; } public void setProducerName(String producerName) { this.producerName = producerName; } public String getMaterialCode() { return materialCode; } public void setMaterialCode(String materialCode) { this.materialCode = materialCode; } public String getAttrNameSerial() { return attrNameSerial; } public void setAttrNameSerial(String attrNameSerial) { this.attrNameSerial = attrNameSerial; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "MarketCateMaterial [" + "cateMaterialId=" + cateMaterialId + ", marketId=" + marketId + ", memberId=" + memberId + ", applyType=" + applyType + ", categoryNamePath=" + categoryNamePath + ", categoryIdPath=" + categoryIdPath + ", categoryId=" + categoryId + ", materialId=" + materialId + ", brandId=" + brandId + ", brandName=" + brandName + ", producerMemberId=" + producerMemberId + ", producerName=" + producerName + ", materialCode=" + materialCode + ", attrNameSerial=" + attrNameSerial + ", createTime=" + createTime + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualCustServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualCertFileService; import cn.enn.ygego.sunny.user.service.IndividualCustService; import cn.enn.ygego.sunny.user.dao.IndividualCustDao; import cn.enn.ygego.sunny.user.dto.IndividualCustDTO; import cn.enn.ygego.sunny.user.dto.vo.PersonQueryVO; import cn.enn.ygego.sunny.user.dto.vo.PersonVO; import cn.enn.ygego.sunny.user.model.IndividualCertFile; import cn.enn.ygego.sunny.user.model.IndividualCust; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualCust * @author gencode * @date 2018-3-22 */ @Service public class IndividualCustServiceImpl implements IndividualCustService{ @Autowired private IndividualCustDao individualCustDao; @Autowired private IndividualCertFileService individualCertFileService; public List<IndividualCust> findAll(){ return individualCustDao.findAll(); } public List<IndividualCust> findIndividualCusts(IndividualCust record){ return individualCustDao.find(record); } public IndividualCust getIndividualCustByPrimaryKey(Long memberId){ return individualCustDao.getByPrimaryKey(memberId); } public Integer createIndividualCust(IndividualCust record){ return individualCustDao.insert(record); } public Integer removeIndividualCust(IndividualCust record){ return individualCustDao.delete(record); } public Integer removeByPrimaryKey(Long memberId){ return individualCustDao.deleteByPrimaryKey(memberId); } public Integer modifyIndividualCustByPrimaryKey(IndividualCust record){ return individualCustDao.updateByPrimaryKey(record); } @Override public IndividualCustDTO getIndividualCustById(Long memberId , boolean hasFile){ IndividualCustDTO resultDto = individualCustDao.getIndividualCustById(memberId); // 查询文件 if(hasFile && resultDto != null && resultDto.getCertInfoId() != null){ List<IndividualCertFile> files = individualCertFileService.getFilesByCertInfoId(resultDto.getCertInfoId()); resultDto.setIndividualCertFileList(files); } return resultDto; } @Override public Integer getPersonCount(PersonQueryVO query) { return individualCustDao.getPersonCount(query); } @Override public List<PersonVO> getPersonList(PersonQueryVO query) { return individualCustDao.getPersonList(query); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntTaxRateVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * ClassName: EntTaxRatePaySetVO * Description: * Author: liangchao * Date: 2018/3/23 20:19 * History: * <author> <time> <version> <desc> * liangc 修改时间 0.0.1 描述 */ public class EntTaxRateVO implements Serializable { private static final long serialVersionUID = 1729046615746325279L; private Integer pageSize; /* 每页显示条目 */ private Integer pageNum; /* 当前页码 */ private Integer startRow; /* 开始行 */ private Long memberId; /* 会员ID */ private Integer invoiceType; /* 发票类型 */ private Integer invoiceMethod; /* 发票方式 */ // private Integer startTaxRate; /* 发票税率开始区间 */ // private Integer endTaxRate; /* 发票税率开始区间 */ public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getStartRow() { return startRow; } public void setStartRow(Integer startRow) { this.startRow = startRow; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getInvoiceType() { return invoiceType; } public void setInvoiceType(Integer invoiceType) { this.invoiceType = invoiceType; } public Integer getInvoiceMethod() { return invoiceMethod; } public void setInvoiceMethod(Integer invoiceMethod) { this.invoiceMethod = invoiceMethod; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntDomainPermitApplyServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntDomainPermitApplyService; import cn.enn.ygego.sunny.user.dao.EntDomainPermitApplyDao; import cn.enn.ygego.sunny.user.model.EntDomainPermitApply; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntDomainPermitApply * @author gencode * @date 2018-3-28 */ @Service public class EntDomainPermitApplyServiceImpl implements EntDomainPermitApplyService{ @Autowired private EntDomainPermitApplyDao entDomainPermitApplyDao; public List<EntDomainPermitApply> findAll(){ return entDomainPermitApplyDao.findAll(); } public List<EntDomainPermitApply> findEntDomainPermitApplys(EntDomainPermitApply record){ return entDomainPermitApplyDao.find(record); } public EntDomainPermitApply getEntDomainPermitApplyByPrimaryKey(Long domainApplyId){ return entDomainPermitApplyDao.getByPrimaryKey(domainApplyId); } public Integer createEntDomainPermitApply(EntDomainPermitApply record){ return entDomainPermitApplyDao.insert(record); } public Integer removeEntDomainPermitApply(EntDomainPermitApply record){ return entDomainPermitApplyDao.delete(record); } public Integer removeByPrimaryKey(Long domainApplyId){ return entDomainPermitApplyDao.deleteByPrimaryKey(domainApplyId); } public Integer modifyEntDomainPermitApplyByPrimaryKey(EntDomainPermitApply record){ return entDomainPermitApplyDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntBrandApplyCertFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntBrandApplyCertFile; /** * dal Interface:EntBrandApplyCertFile * @author gencode * @date 2018-3-28 */ public interface EntBrandApplyCertFileService { public List<EntBrandApplyCertFile> findAll(); public List<EntBrandApplyCertFile> findEntBrandApplyCertFiles(EntBrandApplyCertFile record); public EntBrandApplyCertFile getEntBrandApplyCertFileByPrimaryKey(Long certApplyFileId); public Integer createEntBrandApplyCertFile(EntBrandApplyCertFile record); public Integer removeEntBrandApplyCertFile(EntBrandApplyCertFile record); public Integer removeByPrimaryKey(Long certApplyFileId); public Integer modifyEntBrandApplyCertFileByPrimaryKey(EntBrandApplyCertFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/supermarket/SupermarketCategoryVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.supermarket; /** * 申请入驻 - 超市类目详情描述类 * ClassName: SupermarketTypeVO * Description * Author zhangjiaqi * Date 2018-03-30 19:11 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-30 19:11 0.0.1 TODO */ public class SupermarketCategoryVO { // 一级类目 private String firstCategory; // 二级类目 private String secondCategory; // 三级类目 private String thirdCategory; public SupermarketCategoryVO() { super(); // TODO Auto-generated constructor stub } public SupermarketCategoryVO(String firstCategory, String secondCategory, String thirdCategory) { super(); this.firstCategory = firstCategory; this.secondCategory = secondCategory; this.thirdCategory = thirdCategory; } public String getFirstCategory() { return firstCategory; } public void setFirstCategory(String firstCategory) { this.firstCategory = firstCategory; } public String getSecondCategory() { return secondCategory; } public void setSecondCategory(String secondCategory) { this.secondCategory = secondCategory; } public String getThirdCategory() { return thirdCategory; } public void setThirdCategory(String thirdCategory) { this.thirdCategory = thirdCategory; } @Override public String toString() { return "SupermarketCategoryVO [firstCategory=" + firstCategory + ", secondCategory=" + secondCategory + ", thirdCategory=" + thirdCategory + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualDomainPermitServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualDomainPermitService; import cn.enn.ygego.sunny.user.dao.IndividualDomainPermitDao; import cn.enn.ygego.sunny.user.model.IndividualDomainPermit; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualDomainPermit * @author gencode * @date 2018-3-22 */ @Service public class IndividualDomainPermitServiceImpl implements IndividualDomainPermitService{ @Autowired private IndividualDomainPermitDao individualDomainPermitDao; public List<IndividualDomainPermit> findAll(){ return individualDomainPermitDao.findAll(); } public List<IndividualDomainPermit> findIndividualDomainPermits(IndividualDomainPermit record){ return individualDomainPermitDao.find(record); } public IndividualDomainPermit getIndividualDomainPermitByPrimaryKey(Long domainPermitId){ return individualDomainPermitDao.getByPrimaryKey(domainPermitId); } public Integer createIndividualDomainPermit(IndividualDomainPermit record){ return individualDomainPermitDao.insert(record); } public Integer removeIndividualDomainPermit(IndividualDomainPermit record){ return individualDomainPermitDao.delete(record); } public Integer removeByPrimaryKey(Long domainPermitId){ return individualDomainPermitDao.deleteByPrimaryKey(domainPermitId); } public Integer modifyIndividualDomainPermitByPrimaryKey(IndividualDomainPermit record){ return individualDomainPermitDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntBrandCertDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntBrandCert; /** * dal Interface:EntBrandCert * @author gencode */ public interface EntBrandCertDao { Integer insert(EntBrandCert record); Integer insertSelective(EntBrandCert record); Integer delete(EntBrandCert record); Integer deleteByPrimaryKey(@Param("brandCertId") Long brandCertId); Integer updateByPrimaryKey(EntBrandCert record); List<EntBrandCert> findAll(); List<EntBrandCert> find(EntBrandCert record); Integer getCount(EntBrandCert record); EntBrandCert getByPrimaryKey(@Param("brandCertId") Long brandCertId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/AcctRoleRelaServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.AcctRoleRelaService; import cn.enn.ygego.sunny.user.dao.AcctRoleRelaDao; import cn.enn.ygego.sunny.user.model.AcctRoleRela; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:AcctRoleRela * @author gencode * @date 2018-3-22 */ @Service public class AcctRoleRelaServiceImpl implements AcctRoleRelaService{ @Autowired private AcctRoleRelaDao acctRoleRelaDao; public List<AcctRoleRela> findAll(){ return acctRoleRelaDao.findAll(); } public List<AcctRoleRela> findAcctRoleRelas(AcctRoleRela record){ return acctRoleRelaDao.find(record); } public AcctRoleRela getAcctRoleRelaByPrimaryKey(Long relaId){ return acctRoleRelaDao.getByPrimaryKey(relaId); } public Integer createAcctRoleRela(AcctRoleRela record){ return acctRoleRelaDao.insert(record); } public Integer removeAcctRoleRela(AcctRoleRela record){ return acctRoleRelaDao.delete(record); } public Integer removeByPrimaryKey(Long relaId){ return acctRoleRelaDao.deleteByPrimaryKey(relaId); } public Integer modifyAcctRoleRelaByPrimaryKey(AcctRoleRela record){ return acctRoleRelaDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/gridSupermarket/SupermarketController.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.controller.gridSupermarket; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.utils.HTTPUtil; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; /** * 超市管理 * ClassName: SupermarketController * Description * Author zhangjiaqi * Date 2018-03-20 19:18 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-20 19:18 0.0.1 TODO */ @RestController @RequestMapping(value = "/user/supermarket/marketmgr") @Api(value = "超市管理", description = "超市管理") public class SupermarketController { @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据城市获取所有超市接口") @RequestMapping(value = "/getMarketByCity", method = { RequestMethod.POST }) public JsonResponse getMarketbyCity(@RequestBody JsonRequest<Map> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 Map reqBody = jsonRequest.getReqBody(); String result = HTTPUtil.get("http://www.ennew.alpha/business/warehouse/get/warehouseByRegionCode",reqBody); JSONObject jsonObject = JSON.parseObject(result); Object results = jsonObject.get("results"); jsonResponse.setRspBody(results); return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("获取根据城市聚合的所有超市") @RequestMapping(value = "/getMarketOfCity", method = { RequestMethod.POST }) public JsonResponse getMarketOfCity(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 String result = HTTPUtil.get("http://www.ennew.alpha/business/warehouse/area/list", new HashMap<String, String>()); JSONObject jsonObject = JSON.parseObject(result); Object results = jsonObject.get("results"); jsonResponse.setRspBody(results); return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据IP定位当前城市接口") @RequestMapping(value = "/getCityByIP", method = { RequestMethod.POST }) public JsonResponse getCityByIP(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 String result = HTTPUtil.get("http://www.ennew.alpha/business/warehouse/area/info", new HashMap<String, String>()); JSONObject jsonObject = JSON.parseObject(result); Object results = jsonObject.get("results"); jsonResponse.setRspBody(results); return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查询超市信息详情接口") @RequestMapping(value = "/getMarketDetail", method = { RequestMethod.POST }) public JsonResponse getMarketDetail(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("网格超市基本信息接口") @RequestMapping(value = "/getMarketInfo", method = { RequestMethod.POST }) public JsonResponse getMarketInfo(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据当前IP定位省级单位") @RequestMapping(value = "/getProvinceByIp", method = { RequestMethod.POST }) public JsonResponse getProvinceByIp(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查询超市列表接口") @RequestMapping(value = "/getMarketList", method = { RequestMethod.POST }) public JsonResponse getMarketList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("超市设置结算商的接口") @RequestMapping(value = "/setMarketSettlement", method = { RequestMethod.POST }) public JsonResponse setMarketSettlement(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("超市设置收费标准的接口") @RequestMapping(value = "/setMarketCostType", method = { RequestMethod.POST }) public JsonResponse setMarketCostType(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("获取仓储收费类型接口") @RequestMapping(value = "/getCostType", method = { RequestMethod.POST }) public JsonResponse getCostType(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据超市获取仓储服务费用接口") @RequestMapping(value = "/getMarketCost", method = { RequestMethod.POST }) public JsonResponse getMarketCost(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据超市id获取超市信息和可售类目信息(批量)") @RequestMapping(value = "/getMarketByIds", method = { RequestMethod.POST }) public JsonResponse getMarketByIds(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("添加超市接口(批量)") @RequestMapping(value = "/addMarket", method = { RequestMethod.POST }) public JsonResponse addMarket(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("获取当前超市所有入驻渠道") @RequestMapping(value = "/getChannelOfMarket", method = { RequestMethod.POST }) public JsonResponse getChannelOfMarket(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据加盟商获取所有超市接口(分页)") @RequestMapping(value = "/getMarketOfAlliance", method = { RequestMethod.POST }) public JsonResponse getMarketOfAlliance(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据省级单位标识获取当前省份所有网格超市") @RequestMapping(value = "/getMarketByProvince", method = { RequestMethod.POST }) public JsonResponse getMarketByProvince(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查询所有超市列表接口(不分页)") @RequestMapping(value = "/getMarketAllList", method = { RequestMethod.POST }) public JsonResponse getMarketAllList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据超市名称模糊查询超市id集合") @RequestMapping(value = "/getMarketIds", method = { RequestMethod.POST }) public JsonResponse getMarketIds(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/AcctLoginLogDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:AcctLoginLog * * @author gencode * @date 2018-3-28 */ public class AcctLoginLogDTO implements Serializable { private static final long serialVersionUID = 3478431020251706898L; private Long logId; /* 日志标识 */ private String logCode; /* 日志编码 */ private Date loginTime; /* 登录时间 */ private String ipAddr; /* IP地址 */ private Integer loginType; /* 登录类型 */ private Integer loginResult; /* 登录结果 */ private String loginDetail; /* 登录详情 */ private Long operMemberId; /* 操作人会员ID */ private Long operAcctId; /* 操作人账户ID */ private String operPersonName; /* 操作人姓名 */ private Long superMemberId; /* 超级会员ID */ private Long superAcctId; /* 超级账户ID */ private String superAcctName; /* 超级账户名 */ // Constructor public AcctLoginLogDTO() { } /** * full Constructor */ public AcctLoginLogDTO(Long logId, String logCode, Date loginTime, String ipAddr, Integer loginType, Integer loginResult, String loginDetail, Long operMemberId, Long operAcctId, String operPersonName, Long superMemberId, Long superAcctId, String superAcctName) { this.logId = logId; this.logCode = logCode; this.loginTime = loginTime; this.ipAddr = ipAddr; this.loginType = loginType; this.loginResult = loginResult; this.loginDetail = loginDetail; this.operMemberId = operMemberId; this.operAcctId = operAcctId; this.operPersonName = operPersonName; this.superMemberId = superMemberId; this.superAcctId = superAcctId; this.superAcctName = superAcctName; } public Long getLogId() { return logId; } public void setLogId(Long logId) { this.logId = logId; } public String getLogCode() { return logCode; } public void setLogCode(String logCode) { this.logCode = logCode; } public Date getLoginTime() { return loginTime; } public void setLoginTime(Date loginTime) { this.loginTime = loginTime; } public String getIpAddr() { return ipAddr; } public void setIpAddr(String ipAddr) { this.ipAddr = ipAddr; } public Integer getLoginType() { return loginType; } public void setLoginType(Integer loginType) { this.loginType = loginType; } public Integer getLoginResult() { return loginResult; } public void setLoginResult(Integer loginResult) { this.loginResult = loginResult; } public String getLoginDetail() { return loginDetail; } public void setLoginDetail(String loginDetail) { this.loginDetail = loginDetail; } public Long getOperMemberId() { return operMemberId; } public void setOperMemberId(Long operMemberId) { this.operMemberId = operMemberId; } public Long getOperAcctId() { return operAcctId; } public void setOperAcctId(Long operAcctId) { this.operAcctId = operAcctId; } public String getOperPersonName() { return operPersonName; } public void setOperPersonName(String operPersonName) { this.operPersonName = operPersonName; } public Long getSuperMemberId() { return superMemberId; } public void setSuperMemberId(Long superMemberId) { this.superMemberId = superMemberId; } public Long getSuperAcctId() { return superAcctId; } public void setSuperAcctId(Long superAcctId) { this.superAcctId = superAcctId; } public String getSuperAcctName() { return superAcctName; } public void setSuperAcctName(String superAcctName) { this.superAcctName = superAcctName; } @Override public String toString() { return "AcctLoginLogDTO [" + "logId=" + logId + ", logCode=" + logCode + ", loginTime=" + loginTime + ", ipAddr=" + ipAddr + ", loginType=" + loginType + ", loginResult=" + loginResult + ", loginDetail=" + loginDetail + ", operMemberId=" + operMemberId + ", operAcctId=" + operAcctId + ", operPersonName=" + operPersonName + ", superMemberId=" + superMemberId + ", superAcctId=" + superAcctId + ", superAcctName=" + superAcctName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualServiceApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualServiceApply; /** * dal Interface:IndividualServiceApply * @author gencode * @date 2018-3-22 */ public interface IndividualServiceApplyService { public List<IndividualServiceApply> findAll(); public List<IndividualServiceApply> findIndividualServiceApplys(IndividualServiceApply record); public IndividualServiceApply getIndividualServiceApplyByPrimaryKey(Long serviceApplyId); public Integer createIndividualServiceApply(IndividualServiceApply record); public Integer removeIndividualServiceApply(IndividualServiceApply record); public Integer removeByPrimaryKey(Long serviceApplyId); public Integer modifyIndividualServiceApplyByPrimaryKey(IndividualServiceApply record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/DeliverAddressService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.dto.DeliverAddressDTO; import cn.enn.ygego.sunny.user.dto.vo.BaseQueryVO; import cn.enn.ygego.sunny.user.model.DeliverAddress; /** * dal Interface:DeliverAddress * @author gencode * @date 2018-3-22 */ public interface DeliverAddressService { public List<DeliverAddress> findAll(); public List<DeliverAddress> findDeliverAddresss(DeliverAddress record); public List<DeliverAddressDTO> findDeliverAddresssPage(BaseQueryVO record); public DeliverAddress getDeliverAddressByPrimaryKey(Long deliverAddressId); public Integer createDeliverAddress(DeliverAddress record); public Integer removeDeliverAddress(DeliverAddress record); public Integer removeByPrimaryKey(Long deliverAddressId); public Integer modifyDeliverAddressByPrimaryKey(DeliverAddress record); public Integer getCount(DeliverAddress record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/enterpriseManage/SubsidiaryController.java package cn.enn.ygego.sunny.user.controller.enterpriseManage; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.alibaba.dubbo.common.utils.StringUtils; import cn.enn.ygego.sunny.core.log.SearchableLoggerFactory; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.user.constant.JoinEntConstant; import cn.enn.ygego.sunny.user.dto.EntSetDTO; import cn.enn.ygego.sunny.user.dto.vo.JoinCompanyQueryVO; import cn.enn.ygego.sunny.user.dto.vo.JoinCompanyVO; import cn.enn.ygego.sunny.user.model.EntCustInfo; import cn.enn.ygego.sunny.user.model.EntSet; import cn.enn.ygego.sunny.user.service.EntCustInfoService; import cn.enn.ygego.sunny.user.service.EntSetService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; /** * 子公司授权接口 * ClassName: SubsidiaryController * Description * Author puanl * Date 2018年3月17日 下午5:46:03 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ @RestController @RequestMapping("user/enterprise/subsidiary") @Api(value = "子公司授权接口", description = "子公司授权接口") public class SubsidiaryController { static final Logger logger = SearchableLoggerFactory.getDefaultLogger(); @Autowired private EntCustInfoService entCustInfoService; /* 企业信息服务 */ @Autowired private EntSetService entSetService; /* 子公司权限设置服务 */ /** * @Description 查询子公司授权详情接口(对外封装) * @author puanl * @date 2018年3月28日 上午10:59:50 * @param request * @return */ @RequestMapping(value="/getDetail", method = { RequestMethod.POST}) @ApiOperation("查询子公司授权详情接口(对外封装)") @ResponseBody public JsonResponse<EntCustInfo> getDetail(@RequestBody JsonRequest<JoinCompanyQueryVO> request){ JsonResponse<EntCustInfo> result = null; JoinCompanyQueryVO query = request.getReqBody(); if(query == null || query.getMemberId() == null){ result = new JsonResponse<>("502","查询 子公司ID不能为空"); } EntCustInfo entCustInfo = entCustInfoService.getEntCustInfoByPrimaryKey(query.getMemberId()); result = new JsonResponse<>(entCustInfo); return result; } /** * * @Description 查询可添加子公司列表(父) * @author puanl * @date 2018年3月28日 上午11:00:30 * @param request * @return */ @RequestMapping(value="/getCompanyList", method = { RequestMethod.POST}) @ApiOperation("查询可添加子公司列表(父)") @ResponseBody public JsonResponse<PageDTO<JoinCompanyVO>> getCompanyList(@RequestBody JsonRequest<JoinCompanyQueryVO> request){ JsonResponse<PageDTO<JoinCompanyVO>> result = null; JoinCompanyQueryVO query = request.getReqBody(); PageDTO<JoinCompanyVO> pageDto = null; Integer totalCount = entSetService.getFerrSunCompanyCount(query); pageDto = new PageDTO<>(query.getPageNum()==null?1:query.getPageNum(), query.getPageSize()==null?10:query.getPageSize()); pageDto.setTotal(totalCount); query.setStartRow(pageDto.getStartRow()); List<JoinCompanyVO> companyList = entSetService.getFerrSunCompanyList(query); pageDto.setResultData(companyList); result = new JsonResponse<>(pageDto); return result; } /** * @Description 申请添加子公司 批量(父) * @author puanl * @date 2018年3月28日 上午11:00:46 * @param request * @return */ @RequestMapping(value="/applyAddSumCompany", method = { RequestMethod.POST}) @ApiOperation("申请添加子公司(父)") @ResponseBody public JsonResponse<Boolean> applyAddSumCompany(@RequestBody JsonRequest<EntSetDTO> request){ JsonResponse<Boolean> result = null; EntSetDTO joinQuery = request.getReqBody(); if(joinQuery == null || StringUtils.isEmpty(joinQuery.getMemberIds()) ){ result = new JsonResponse<>("502","memberIds 不能为空"); return result; } try { String[] memberIds = joinQuery.getMemberIds().split(","); List<EntSet> entSetList = new ArrayList<>(memberIds.length); for(String memberId : memberIds){ EntSet entSet = new EntSet(); entSet.setMemberId(Long.valueOf(memberId)); // 子公司ID entSet.setPareMemberId(joinQuery.getPareMemberId()); // 父公司ID entSet.setApplyType(JoinEntConstant.SET_APPLYTYPE_SUBMIT); //申请状态 entSet.setCreateTime(new Date()); entSet.setCateMateId(joinQuery.getCateMateId()); entSet.setCreateName(joinQuery.getCreateName()); entSetList.add(entSet); } Integer operation = entSetService.createEntSetList(entSetList); if(operation > 0){ result = new JsonResponse<>(true); }else{ result = new JsonResponse<>("502","保存失败",false); } } catch (Exception e) { logger.error("SubsidiaryController.applyAddSumCompany: 申请添加子公司报错!" + e.getMessage(), e); result = new JsonResponse<>("0100502",e.getMessage()); return result; } return result; } /** * @Description 【查询子公司列表(父)】企业组织管理子公司 * @author puanl * @date 2018年3月28日 上午11:00:50 * @param request * @return */ @RequestMapping(value="/getSunCompanyList", method = { RequestMethod.POST}) @ApiOperation("企业组织管理子公司") @ResponseBody public JsonResponse<PageDTO<JoinCompanyVO>> getSunCompanyList(@RequestBody JsonRequest<JoinCompanyQueryVO> request){ JsonResponse<PageDTO<JoinCompanyVO>> result = null; JoinCompanyQueryVO query = request.getReqBody(); if(query == null || query.getPareMemberId() == null ){ result = new JsonResponse<>("502"," PareMemberId 不能为空"); return result; } query.setMemberId(null); // 清空子公司ID条件 PageDTO<JoinCompanyVO> pageDto = null; Integer totalCount = entSetService.getJoinCompanyCount(query); pageDto = new PageDTO<>(query.getPageNum()==null?1:query.getPageNum(), query.getPageSize()==null?10:query.getPageSize()); pageDto.setTotal(totalCount); query.setStartRow(pageDto.getStartRow()); List<JoinCompanyVO> companyList = entSetService.getJoinCompanyList(query); pageDto.setResultData(companyList); result = new JsonResponse<>(pageDto); return result; } /** * @Description 查询子公司详情(父) * @author puanl * @date 2018年3月28日 上午11:12:20 * @param request * @return */ @RequestMapping(value="/getSunCompanyDetail", method = { RequestMethod.POST}) @ApiOperation("查询子公司详情(父)") @ResponseBody public JsonResponse<JoinCompanyVO> getSunCompanyDetail(@RequestBody JsonRequest<JoinCompanyQueryVO> request){ JsonResponse<JoinCompanyVO> result = null; JoinCompanyQueryVO query = request.getReqBody(); if(query == null || query.getSetId() == null){ result = new JsonResponse<>("502","SetId 不能为空"); return result; } JoinCompanyVO sunCompany = entSetService.getSunCompanyDetail(query); result = new JsonResponse<>(sunCompany); return result; } /** * * @Description 【申请设置授权,或变更授权(父)】父公司授权子公司权限 * @author puanl * @date 2018年3月28日 上午11:17:59 * @param request * @return */ @RequestMapping(value="/applySetAccredit", method = { RequestMethod.POST}) @ApiOperation("父公司授权子公司权限") @ResponseBody public JsonResponse<EntSet> applySetAccredit(@RequestBody JsonRequest<JoinCompanyVO> request){ JsonResponse<EntSet> result = null; JoinCompanyVO entSetDto = request.getReqBody(); if(entSetDto == null || entSetDto.getSetId() == null){ result = new JsonResponse<>("502","SetId 不能为空"); return result; } try{ // 获取企业设置申请 EntSet entSet = entSetService.getEntSetByPrimaryKey(entSetDto.getSetId()); if(entSet.getApplyType() == JoinEntConstant.SET_APPLYTYPE_REFUSE){ result = new JsonResponse<>("502","子公司拒绝加入,无法配置授权信息"); return result; } // 更新设置信息 entSet.setBlackWhiteListSet(entSetDto.getSetBlackWhiteListSet()); // 黑白名单设置 entSet.setAgreementPriceId(entSetDto.getSetAgreementPriceId()); // 协议价设置 entSet.setCateMateId(entSetDto.getSetCateMateId()); // 类目物料设置 entSet.setStatus(JoinEntConstant.SET_STATUS_SUBMIT); // 申请状态为:待确认 Integer operation = entSetService.modifyEntSetByPrimaryKey(entSet); if(operation > 0){ result = new JsonResponse<>(entSet); }else{ result = new JsonResponse<>("502","修改失败"); } } catch (Exception e) { logger.error("SubsidiaryController.applySetAccredit: 设置子公司授权报错!" + e.getMessage(), e); result = new JsonResponse<>("0100502",e.getMessage()); return result; } return result; } /** * * @Description 授权申请详情查询 * @author puanl * @date 2018年3月28日 上午11:18:17 * @param request * @return */ @RequestMapping(value="/getApplySetDetail", method = { RequestMethod.POST}) @ApiOperation("授权申请详情查询") @ResponseBody public JsonResponse<JoinCompanyVO> getApplySetDetail(@RequestBody JsonRequest<JoinCompanyQueryVO> request){ JsonResponse<JoinCompanyVO> result = null; JoinCompanyQueryVO query = request.getReqBody(); if(query == null || query.getSetId() == null){ result = new JsonResponse<>("502","SetId 不能为空"); return result; } JoinCompanyVO sunCompany = entSetService.getSunCompanyDetail(query); result = new JsonResponse<>(sunCompany); return result; } /** * @Description 子公司审核(同意/不同意)授权(子) * @author puanl * @date 2018年3月28日 上午11:19:09 * @param request * @return */ @RequestMapping(value="/examineApplySet", method = { RequestMethod.POST}) @ApiOperation("子公司审核(同意/不同意)授权(子)") @ResponseBody public JsonResponse<Boolean> examineApplySet(@RequestBody JsonRequest<JoinCompanyVO> request){ JsonResponse<Boolean> result = null; JoinCompanyVO entSetDto = request.getReqBody(); if(entSetDto == null || entSetDto.getSetId() == null){ result = new JsonResponse<>("502","SetId 不能为空"); return result; } if(entSetDto.getStatus() == null || entSetDto.getStatus() == JoinEntConstant.SET_STATUS_SUBMIT){ result = new JsonResponse<>("502","请选择同意或拒绝"); return result; } // 获取企业设置申请 EntSet entSet = entSetService.getEntSetByPrimaryKey(entSetDto.getSetId()); if(entSet == null || entSet.getApplyType() == null || entSet.getApplyType() == JoinEntConstant.SET_APPLYTYPE_REFUSE){ result = new JsonResponse<>("502","已经拒绝加入企业"); return result; } try{ // 处理逻辑 Integer operation = null; if(entSet.getApplyType() == JoinEntConstant.SET_APPLYTYPE_AGREE && entSetDto.getStatus() == JoinEntConstant.SET_STATUS_AGREE){ // 已加入企业, 同意授权 operation = entSetService.agreeSetAccredit(entSet); }else if(entSet.getApplyType() == JoinEntConstant.SET_APPLYTYPE_AGREE && entSetDto.getStatus() == JoinEntConstant.SET_STATUS_REFUSE){ // 已加入企业, 拒绝授权 entSet.setStatus(JoinEntConstant.SET_STATUS_REFUSE); operation = entSetService.modifyEntSetByPrimaryKey(entSet); }else if(entSet.getApplyType() == JoinEntConstant.SET_APPLYTYPE_SUBMIT && entSetDto.getStatus() == JoinEntConstant.SET_STATUS_AGREE){ // 未加入企业, 同意授权 operation = entSetService.agreeJoinCompanyAndSet(entSet); }else if(entSet.getApplyType() == JoinEntConstant.SET_APPLYTYPE_SUBMIT && entSetDto.getStatus() == JoinEntConstant.SET_STATUS_REFUSE){ // 未加入企业, 拒绝授权 entSet.setApplyType(JoinEntConstant.SET_APPLYTYPE_REFUSE); entSet.setStatus(JoinEntConstant.SET_STATUS_REFUSE); operation = entSetService.modifyEntSetByPrimaryKey(entSet); } if(operation > 0){ result = new JsonResponse<>(true); }else{ result = new JsonResponse<>("502","审批失败",false); } }catch (Exception e) { logger.error("SubsidiaryController.examineApplySet: 子公司审核授权报错!" + e.getMessage(), e); result = new JsonResponse<>("0100502",e.getMessage()); return result; } return result; } /** * @Description 查询父公司列表,含未通过的(子) * @author puanl * @date 2018年3月28日 上午11:20:24 * @param request * @return */ @RequestMapping(value="/getParentEntList", method = { RequestMethod.POST}) @ApiOperation("查询父公司列表,含未通过的(子)") @ResponseBody public JsonResponse<PageDTO<JoinCompanyVO>> getParentEntList(@RequestBody JsonRequest<JoinCompanyQueryVO> request){ JsonResponse<PageDTO<JoinCompanyVO>> result = null; JoinCompanyQueryVO query = request.getReqBody(); if(query == null || query.getMemberId() == null ){ result = new JsonResponse<>("502"," MemberId 不能为空"); return result; } // 查询当前公司信息,判断是否存在父公司 EntCustInfo entCustInfo = entCustInfoService.getEntCustInfoByPrimaryKey(query.getMemberId()); // 添加父公司ID if(entCustInfo.getPareMemberId() != null){ query.setPareMemberId(entCustInfo.getPareMemberId()); }else{ query.setPareMemberId(null); // 清空父公司ID条件 } PageDTO<JoinCompanyVO> pageDto = null; Integer totalCount = entSetService.getJoinCompanyCount(query); pageDto = new PageDTO<>(query.getPageNum()==null?1:query.getPageNum(), query.getPageSize()==null?10:query.getPageSize()); pageDto.setTotal(totalCount); query.setStartRow(pageDto.getStartRow()); List<JoinCompanyVO> companyList = entSetService.getJoinCompanyList(query); pageDto.setResultData(companyList); result = new JsonResponse<>(pageDto); return result; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntProdApply.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:EntProdApply * * @author gencode */ public class EntProdApply implements Serializable { private static final long serialVersionUID = -1737807117252238138L; private Long applyId; /* 申请ID */ private Long memberId; /* 会员ID */ private Integer status; /* 状态 */ private String approveDesc; /* 审核结果描述 */ private Date createTime; /* 创建时间 */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public EntProdApply() { } /** * full Constructor */ public EntProdApply(Long applyId, Long memberId, Integer status, String approveDesc, Date createTime, Long createAcctId, String createName) { this.applyId = applyId; this.memberId = memberId; this.status = status; this.approveDesc = approveDesc; this.createTime = createTime; this.createAcctId = createAcctId; this.createName = createName; } public Long getApplyId() { return applyId; } public void setApplyId(Long applyId) { this.applyId = applyId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getApproveDesc() { return approveDesc; } public void setApproveDesc(String approveDesc) { this.approveDesc = approveDesc; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "EntProdApply [" + "applyId=" + applyId+ ", memberId=" + memberId+ ", status=" + status+ ", approveDesc=" + approveDesc+ ", createTime=" + createTime+ ", createAcctId=" + createAcctId+ ", createName=" + createName+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/whitelist/WhitelistController.java package cn.enn.ygego.sunny.user.controller.whitelist; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.user.common.ResponseCodeEnum; import cn.enn.ygego.sunny.user.dto.EntCertInfoDTO; import cn.enn.ygego.sunny.user.dto.MaterialBlackListDTO; import cn.enn.ygego.sunny.user.dto.MaterialWhiteListDTO; import cn.enn.ygego.sunny.user.dto.SupplierBlackListDTO; import com.github.jsonzou.jmockdata.JMockData; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * ClassName: EntAuthController * Description: * Author: dongbingbing * Date: 2018/3/20 13:51 * History: * <author> <time> <version> <desc> * dongbingbing 2018/3/20 18:51 0.0.1 企业白名单接口 */ @RequestMapping("/whitelist") @RestController @Api(value = "用户服务白名单接口", description = "用户服务白名单接口") public class WhitelistController { /** * 查看白名单列表分页接口 * @return */ @RequestMapping(value = "/list",method = RequestMethod.POST) @ApiOperation("查看白名单列表分页接口") public JsonResponse<PageDTO<MaterialWhiteListDTO>> list(@RequestBody JsonRequest jsonRequest){ JsonResponse<PageDTO<MaterialWhiteListDTO>> jsonResponse = new JsonResponse(); jsonResponse.setRetCode(ResponseCodeEnum.SUCCESS.getStatusCode()); PageDTO<MaterialWhiteListDTO> pageDTO = new PageDTO(); pageDTO.setPageSize(10); pageDTO.setTotal(3); pageDTO.setPageNum(1); pageDTO.setPages(1); List<MaterialWhiteListDTO> list = new ArrayList<>(); for(int i = 0; i<3 ;i ++){ MaterialWhiteListDTO material = JMockData.mock(MaterialWhiteListDTO.class); list.add(material); } pageDTO.setResultData(list); jsonResponse.setRspBody(pageDTO); return jsonResponse; } /** * 查看白名单信息详情接口 * @return */ @RequestMapping(value = "/info",method = RequestMethod.POST) @ApiOperation("查看白名单信息详情接口") public JsonResponse<List<SupplierBlackListDTO>> info(@RequestBody JsonRequest jsonRequest){ JsonResponse<List<SupplierBlackListDTO>> jsonResponse = new JsonResponse(); jsonResponse.setRetCode(ResponseCodeEnum.SUCCESS.getStatusCode()); List<SupplierBlackListDTO> list = new ArrayList<>(); for(int i = 0; i<3 ;i ++){ SupplierBlackListDTO SupplierBlackListDTO = JMockData.mock(SupplierBlackListDTO.class); list.add(SupplierBlackListDTO); } jsonResponse.setRspBody(list); return jsonResponse; } /** * 修改白名单信息接口 * @return */ @ApiOperation("修改白名单信息接口") @RequestMapping(value = "/updateInfo",method = RequestMethod.POST) public JsonResponse updateInfo(@RequestBody JsonRequest jsonRequest){ return new JsonResponse(); } /** * 查询是否添加过白名单接口 * @return */ @ApiOperation("查询是否添加过白名单接口") @RequestMapping(value = "/whetherAdd",method = RequestMethod.POST) public JsonResponse whetherAdd(@RequestBody JsonRequest jsonRequest){ return new JsonResponse(); } /** * 导出白名单Excel接口 * @return */ @RequestMapping(value = "/exportExcel",method = RequestMethod.POST) public JsonResponse exportExcel(@RequestBody JsonRequest jsonRequest){ return new JsonResponse(); } /** * 按物料添加白名单接口 * @return */ @ApiOperation("按物料添加白名单接口") @RequestMapping(value = "/addForMaterial",method = RequestMethod.POST) public JsonResponse addForMaterial(@RequestBody JsonRequest jsonRequest){ return new JsonResponse(); } /** * 按供应商添加白名单接口 * @return */ @ApiOperation("按供应商添加白名单接口") @RequestMapping(value = "/addForSupplier",method = RequestMethod.POST) public JsonResponse addForSupplier(@RequestBody JsonRequest jsonRequest){ return new JsonResponse(); } /** * 批量删除白名单接口 * @return */ @ApiOperation("批量删除白名单接口") @RequestMapping(value = "/batchDelete",method = RequestMethod.POST) public JsonResponse batchDelete(@RequestBody JsonRequest jsonRequest){ return new JsonResponse(); } /** * 按物料筛选白名单供应商接口 * @return */ @ApiOperation("按物料筛选白名单供应商接口") @RequestMapping(value = "/filterSupplier",method = RequestMethod.POST) public JsonResponse<List<SupplierBlackListDTO>> filterSupplier(@RequestBody JsonRequest jsonRequest){ JsonResponse<List<SupplierBlackListDTO>> jsonResponse = new JsonResponse(); jsonResponse.setRetCode(ResponseCodeEnum.SUCCESS.getStatusCode()); List<SupplierBlackListDTO> list = new ArrayList<>(); for(int i = 0; i<4 ;i ++){ SupplierBlackListDTO SupplierBlackListDTO = JMockData.mock(SupplierBlackListDTO.class); list.add(SupplierBlackListDTO); } jsonResponse.setRspBody(list); return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntDomainPermitApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntDomainPermitApply; /** * dal Interface:EntDomainPermitApply * @author gencode */ public interface EntDomainPermitApplyDao { Integer insert(EntDomainPermitApply record); Integer insertSelective(EntDomainPermitApply record); Integer delete(EntDomainPermitApply record); Integer deleteByPrimaryKey(@Param("domainApplyId") Long domainApplyId); Integer updateByPrimaryKey(EntDomainPermitApply record); List<EntDomainPermitApply> findAll(); List<EntDomainPermitApply> find(EntDomainPermitApply record); Integer getCount(EntDomainPermitApply record); EntDomainPermitApply getByPrimaryKey(@Param("domainApplyId") Long domainApplyId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntBrandInfoServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntBrandInfoService; import cn.enn.ygego.sunny.user.dao.EntBrandInfoDao; import cn.enn.ygego.sunny.user.model.EntBrandInfo; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntBrandInfo * @author gencode * @date 2018-3-28 */ @Service public class EntBrandInfoServiceImpl implements EntBrandInfoService{ @Autowired private EntBrandInfoDao entBrandInfoDao; public List<EntBrandInfo> findAll(){ return entBrandInfoDao.findAll(); } public List<EntBrandInfo> findEntBrandInfos(EntBrandInfo record){ return entBrandInfoDao.find(record); } public EntBrandInfo getEntBrandInfoByPrimaryKey(Long entBrandId){ return entBrandInfoDao.getByPrimaryKey(entBrandId); } public Integer createEntBrandInfo(EntBrandInfo record){ return entBrandInfoDao.insert(record); } public Integer removeEntBrandInfo(EntBrandInfo record){ return entBrandInfoDao.delete(record); } public Integer removeByPrimaryKey(Long entBrandId){ return entBrandInfoDao.deleteByPrimaryKey(entBrandId); } public Integer modifyEntBrandInfoByPrimaryKey(EntBrandInfo record){ return entBrandInfoDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntBrandCertFileServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntBrandCertFileService; import cn.enn.ygego.sunny.user.dao.EntBrandCertFileDao; import cn.enn.ygego.sunny.user.model.EntBrandCertFile; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntBrandCertFile * @author gencode * @date 2018-3-28 */ @Service public class EntBrandCertFileServiceImpl implements EntBrandCertFileService{ @Autowired private EntBrandCertFileDao entBrandCertFileDao; public List<EntBrandCertFile> findAll(){ return entBrandCertFileDao.findAll(); } public List<EntBrandCertFile> findEntBrandCertFiles(EntBrandCertFile record){ return entBrandCertFileDao.find(record); } public EntBrandCertFile getEntBrandCertFileByPrimaryKey(Long certApplyFileId){ return entBrandCertFileDao.getByPrimaryKey(certApplyFileId); } public Integer createEntBrandCertFile(EntBrandCertFile record){ return entBrandCertFileDao.insert(record); } public Integer removeEntBrandCertFile(EntBrandCertFile record){ return entBrandCertFileDao.delete(record); } public Integer removeByPrimaryKey(Long certApplyFileId){ return entBrandCertFileDao.deleteByPrimaryKey(certApplyFileId); } public Integer modifyEntBrandCertFileByPrimaryKey(EntBrandCertFile record){ return entBrandCertFileDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/ReceiveAddressServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.dto.ReceiveAddressDTO; import cn.enn.ygego.sunny.user.dto.vo.BaseQueryVO; import cn.enn.ygego.sunny.user.service.ReceiveAddressService; import cn.enn.ygego.sunny.user.dao.ReceiveAddressDao; import cn.enn.ygego.sunny.user.model.ReceiveAddress; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:ReceiveAddress * @author gencode * @date 2018-3-22 */ @Service public class ReceiveAddressServiceImpl implements ReceiveAddressService{ @Autowired private ReceiveAddressDao receiveAddressDao; public List<ReceiveAddress> findAll(){ return receiveAddressDao.findAll(); } public List<ReceiveAddress> findReceiveAddresss(ReceiveAddress record){ return receiveAddressDao.find(record); } public List<ReceiveAddressDTO> findReceiveAddresssPage(BaseQueryVO record) { return receiveAddressDao.findPage(record); } public ReceiveAddress getReceiveAddressByPrimaryKey(Long receiveAddressId){ return receiveAddressDao.getByPrimaryKey(receiveAddressId); } public Integer createReceiveAddress(ReceiveAddress record){ return receiveAddressDao.insert(record); } public Integer removeReceiveAddress(ReceiveAddress record){ return receiveAddressDao.delete(record); } public Integer removeByPrimaryKey(Long receiveAddressId){ return receiveAddressDao.deleteByPrimaryKey(receiveAddressId); } public Integer modifyReceiveAddressByPrimaryKey(ReceiveAddress record){ return receiveAddressDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntAuthApplyFile2.java package cn.enn.ygego.sunny.user.model; import java.io.Serializable; /** * entity:EntAuthApplyFile2 * * @author gencode */ public class EntAuthApplyFile2 implements Serializable { private static final long serialVersionUID = 1354015071909825386L; private Long applyFileId; /* 申请文件ID */ private Long authApplyId; /* 授权申请ID */ private Long fileSize; /* 文件大小 */ private String fileUrl; /* 文件地址 */ // Constructor public EntAuthApplyFile2() { } /** * full Constructor */ public EntAuthApplyFile2(Long applyFileId, Long authApplyId, Long fileSize, String fileUrl) { this.applyFileId = applyFileId; this.authApplyId = authApplyId; this.fileSize = fileSize; this.fileUrl = fileUrl; } public Long getApplyFileId() { return applyFileId; } public void setApplyFileId(Long applyFileId) { this.applyFileId = applyFileId; } public Long getAuthApplyId() { return authApplyId; } public void setAuthApplyId(Long authApplyId) { this.authApplyId = authApplyId; } public Long getFileSize() { return fileSize; } public void setFileSize(Long fileSize) { this.fileSize = fileSize; } public String getFileUrl() { return fileUrl; } public void setFileUrl(String fileUrl) { this.fileUrl = fileUrl; } @Override public String toString() { return "EntAuthApplyFile2 [" + "applyFileId=" + applyFileId+ ", authApplyId=" + authApplyId+ ", fileSize=" + fileSize+ ", fileUrl=" + fileUrl+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualServiceApplyCertFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualServiceApplyCertFile; /** * dal Interface:IndividualServiceApplyCertFile * @author gencode */ public interface IndividualServiceApplyCertFileDao { Integer insert(IndividualServiceApplyCertFile record); Integer insertSelective(IndividualServiceApplyCertFile record); Integer delete(IndividualServiceApplyCertFile record); Integer deleteByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); Integer updateByPrimaryKey(IndividualServiceApplyCertFile record); List<IndividualServiceApplyCertFile> findAll(); List<IndividualServiceApplyCertFile> find(IndividualServiceApplyCertFile record); Integer getCount(IndividualServiceApplyCertFile record); IndividualServiceApplyCertFile getByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntProdApplyServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.ArrayList; import java.util.List; import cn.enn.ygego.sunny.user.dao.EntApplyProdInfoDao; import cn.enn.ygego.sunny.user.dao.EntApplyProducerAuthDao; import cn.enn.ygego.sunny.user.dao.EntAuthApplyFile2Dao; import cn.enn.ygego.sunny.user.dao.EntCateCertApplyDao; import cn.enn.ygego.sunny.user.dao.EntCateCertApplyFileDao; import cn.enn.ygego.sunny.user.dto.EntApplyProdInfoDTO; import cn.enn.ygego.sunny.user.dto.EntProdApplyDTO; import cn.enn.ygego.sunny.user.dto.vo.EntApplyProducerAuthVO; import cn.enn.ygego.sunny.user.dto.vo.EntCateCertApplyVO; import cn.enn.ygego.sunny.user.dto.vo.EntProdApplyVO; import cn.enn.ygego.sunny.user.model.EntApplyProdInfo; import cn.enn.ygego.sunny.user.model.EntApplyProducerAuth; import cn.enn.ygego.sunny.user.model.EntAuthApplyFile2; import cn.enn.ygego.sunny.user.model.EntCateCertApply; import cn.enn.ygego.sunny.user.model.EntCateCertApplyFile; import cn.enn.ygego.sunny.user.service.EntCateCertApplyService; import cn.enn.ygego.sunny.user.service.EntProdApplyService; import cn.enn.ygego.sunny.user.dao.EntProdApplyDao; import cn.enn.ygego.sunny.user.model.EntProdApply; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; /** * dal Interface:EntProdApply * @author gencode * @date 2018-3-30 */ @Service public class EntProdApplyServiceImpl implements EntProdApplyService{ @Autowired private EntProdApplyDao entProdApplyDao; @Autowired private EntCateCertApplyDao entCateCertApplyDao; @Autowired private EntCateCertApplyFileDao entCateCertApplyFileDao; @Autowired private EntApplyProdInfoDao entApplyProdInfoDao; @Autowired private EntApplyProducerAuthDao entApplyProducerAuthDao; @Autowired private EntAuthApplyFile2Dao entAuthApplyFile2Dao; public List<EntProdApply> findAll(){ return entProdApplyDao.findAll(); } public List<EntProdApply> findEntProdApplys(EntProdApply record){ return entProdApplyDao.find(record); } public EntProdApply getEntProdApplyByPrimaryKey(Long applyId){ return entProdApplyDao.getByPrimaryKey(applyId); } public Integer createEntProdApply(EntProdApply record){ return entProdApplyDao.insert(record); } public Integer removeEntProdApply(EntProdApply record){ return entProdApplyDao.delete(record); } public Integer removeByPrimaryKey(Long applyId){ return entProdApplyDao.deleteByPrimaryKey(applyId); } public Integer modifyEntProdApplyByPrimaryKey(EntProdApply record){ return entProdApplyDao.updateByPrimaryKey(record); } public Integer createEntProdApplyVO(EntProdApplyVO record){ int result = -1; try{ //插入申请ID EntProdApply entProdApply = new EntProdApply(); BeanUtils.copyProperties(record,entProdApply); entProdApplyDao.insert(entProdApply); //插入类目申请 List<EntCateCertApplyVO> entCateCertApplyVOList = record.getEntCateCertApplyVOList(); for(EntCateCertApplyVO entCateCertApplyVO : entCateCertApplyVOList){ entCateCertApplyVO.setApplyId(entProdApply.getApplyId()); EntCateCertApply entCateCertApply = new EntCateCertApply(); BeanUtils.copyProperties(entCateCertApplyVO,entCateCertApply); entCateCertApplyDao.insert(entCateCertApply); List<EntCateCertApplyFile> entCateCertApplyFileList = entCateCertApplyVO.getEntCateCertApplyFileList(); for(EntCateCertApplyFile entCateCertApplyFile: entCateCertApplyFileList){ entCateCertApplyFile.setCertApplyDetailId(entCateCertApply.getCertApplyDetailId()); entCateCertApplyFileDao.insert(entCateCertApplyFile); } } //插入申请商品 List<EntApplyProdInfoDTO> entApplyProdInfoDTOList = record.getEntApplyProdInfoDTOList(); for(EntApplyProdInfoDTO entApplyProdInfoDTO:entApplyProdInfoDTOList){ EntApplyProdInfo entApplyProdInfo = new EntApplyProdInfo(); BeanUtils.copyProperties(entApplyProdInfoDTO,entApplyProdInfo); entApplyProdInfo.setApplyId(entProdApply.getApplyId()); entApplyProdInfoDao.insert(entApplyProdInfo); } //插入生产商授权 List<EntApplyProducerAuthVO> entApplyProducerAuthVOList = record.getEntApplyProducerAuthVOList(); for(EntApplyProducerAuthVO entApplyProducerAuthVO : entApplyProducerAuthVOList){ entApplyProducerAuthVO.setApplyId(entProdApply.getApplyId()); EntApplyProducerAuth entApplyProducerAuth = new EntApplyProducerAuth(); BeanUtils.copyProperties(entApplyProducerAuthVO,entApplyProducerAuth); entApplyProducerAuthDao.insert(entApplyProducerAuth); List<EntAuthApplyFile2> entAuthApplyFile2List = entApplyProducerAuthVO.getEntAuthApplyFile2List(); for(EntAuthApplyFile2 entAuthApplyFile2: entAuthApplyFile2List){ entAuthApplyFile2.setAuthApplyId(entApplyProducerAuth.getAuthApplyId()); entAuthApplyFile2Dao.insert(entAuthApplyFile2); } } result = 1; }catch (Exception e){ e.printStackTrace(); } return result; } public EntProdApplyVO getEntProdApplyVO(EntProdApplyDTO entProdApplyDTO){ //查询主数据 EntProdApplyVO entProdApplyVO = new EntProdApplyVO(); EntProdApply entProdApply = entProdApplyDao.getByPrimaryKey(entProdApplyDTO.getApplyId()); BeanUtils.copyProperties(entProdApply,entProdApplyVO); //查询类目认证 EntCateCertApply entCateCertApply = new EntCateCertApply(); entCateCertApply.setApplyId(entProdApplyDTO.getApplyId()); List<EntCateCertApplyVO> entCateCertApplyVOList = new ArrayList<EntCateCertApplyVO>(); List<EntCateCertApply> entCateCertApplyList = entCateCertApplyDao.find(entCateCertApply); for(EntCateCertApply entCateCertApply1 : entCateCertApplyList){ EntCateCertApplyVO entCateCertApplyVO = new EntCateCertApplyVO(); BeanUtils.copyProperties(entCateCertApply1,entCateCertApplyVO); EntCateCertApplyFile entCateCertApplyFile = new EntCateCertApplyFile(); entCateCertApplyFile.setCertApplyDetailId(entCateCertApply1.getCertApplyDetailId()); List<EntCateCertApplyFile> entCateCertApplyFileList1 = entCateCertApplyFileDao.find(entCateCertApplyFile); entCateCertApplyVO.setEntCateCertApplyFileList(entCateCertApplyFileList1); entCateCertApplyVOList.add(entCateCertApplyVO); } entProdApplyVO.setEntCateCertApplyVOList(entCateCertApplyVOList); //查询品牌 List<EntApplyProdInfoDTO> entApplyProdInfoDTOList = new ArrayList<EntApplyProdInfoDTO>(); EntApplyProdInfo entApplyProdInfo = new EntApplyProdInfo(); entApplyProdInfo.setApplyId(entProdApplyDTO.getApplyId()); List<EntApplyProdInfo> entApplyProdInfoList = entApplyProdInfoDao.find(entApplyProdInfo); for(EntApplyProdInfo entApplyProdInfo1 : entApplyProdInfoList){ EntApplyProdInfoDTO entApplyProdInfoDTO = new EntApplyProdInfoDTO(); BeanUtils.copyProperties(entApplyProdInfo1,entApplyProdInfoDTO); entApplyProdInfoDTOList.add(entApplyProdInfoDTO); } entProdApplyVO.setEntApplyProdInfoDTOList(entApplyProdInfoDTOList); //查询授权书 List<EntApplyProducerAuthVO> entApplyProducerAuthVOList = new ArrayList<EntApplyProducerAuthVO>(); EntApplyProducerAuth entApplyProducerAuth = new EntApplyProducerAuth(); entApplyProducerAuth.setApplyId(entProdApplyDTO.getApplyId()); List<EntApplyProducerAuth> entApplyProducerAuthList = entApplyProducerAuthDao.find(entApplyProducerAuth); for(EntApplyProducerAuth entApplyProducerAuth1 : entApplyProducerAuthList){ EntApplyProducerAuthVO entApplyProducerAuthVO = new EntApplyProducerAuthVO(); BeanUtils.copyProperties(entApplyProducerAuth1,entApplyProducerAuthVO); EntAuthApplyFile2 entAuthApplyFile2 = new EntAuthApplyFile2(); List<EntAuthApplyFile2> entAuthApplyFile2List = entAuthApplyFile2Dao.find(entAuthApplyFile2); entApplyProducerAuthVO.setEntAuthApplyFile2List(entAuthApplyFile2List); entApplyProducerAuthVOList.add(entApplyProducerAuthVO); } entProdApplyVO.setEntApplyProducerAuthVOList(entApplyProducerAuthVOList); return entProdApplyVO; } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntCertApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntCertApply; /** * dal Interface:EntCertApply * @author gencode * @date 2018-3-28 */ public interface EntCertApplyService { public List<EntCertApply> findAll(); public List<EntCertApply> findEntCertApplys(EntCertApply record); public EntCertApply getEntCertApplyByPrimaryKey(Long certApplyId); public Integer createEntCertApply(EntCertApply record); public Integer removeEntCertApply(EntCertApply record); public Integer removeByPrimaryKey(Long certApplyId); public Integer modifyEntCertApplyByPrimaryKey(EntCertApply record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntAuthCertApplyVO.java package cn.enn.ygego.sunny.user.dto.vo; import cn.enn.ygego.sunny.user.dto.EntAuthCertApplyDTO; import cn.enn.ygego.sunny.user.model.EntAuthApplyFile; import cn.enn.ygego.sunny.user.model.EntAuthCertApply; import java.util.List; /** * ClassName: EntAuthCertApplyVO * Description: * Author: en3 * Date: 2018/3/28 16:30 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class EntAuthCertApplyVO extends EntAuthCertApplyDTO { private static final long serialVersionUID = 8529218964724872904L; private List<EntAuthApplyFile> entAuthApplyFileList; public List<EntAuthApplyFile> getEntAuthApplyFileList() { return entAuthApplyFileList; } public void setEntAuthApplyFileList(List<EntAuthApplyFile> entAuthApplyFileList) { this.entAuthApplyFileList = entAuthApplyFileList; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntCateCertInfo.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:EntCateCertInfo * * @author gencode */ public class EntCateCertInfo implements Serializable { private static final long serialVersionUID = 5473688932016274447L; private Long certInfoId; /* 资质信息ID */ private Long memberId; /* 会员ID */ private String categoryNamePath; /* 类目名称路径 */ private String categoryIdPath; /* 类目ID路径 */ private Integer categoryId; /* 类目ID */ private Integer certType; /* 资质类型 */ private Integer limitType; /* 期限类型 */ private Date certValidStartDate; /* 证件有效开始日期 */ private Date certValidEndDate; /* 证件有效截止日期 */ private Date createTime; /* 创建时间 */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public EntCateCertInfo() { } /** * full Constructor */ public EntCateCertInfo(Long certInfoId, Long memberId, String categoryNamePath, String categoryIdPath, Integer categoryId, Integer certType, Integer limitType, Date certValidStartDate, Date certValidEndDate, Date createTime, Long createAcctId, String createName) { this.certInfoId = certInfoId; this.memberId = memberId; this.categoryNamePath = categoryNamePath; this.categoryIdPath = categoryIdPath; this.categoryId = categoryId; this.certType = certType; this.limitType = limitType; this.certValidStartDate = certValidStartDate; this.certValidEndDate = certValidEndDate; this.createTime = createTime; this.createAcctId = createAcctId; this.createName = createName; } public Long getCertInfoId() { return certInfoId; } public void setCertInfoId(Long certInfoId) { this.certInfoId = certInfoId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public String getCategoryNamePath() { return categoryNamePath; } public void setCategoryNamePath(String categoryNamePath) { this.categoryNamePath = categoryNamePath; } public String getCategoryIdPath() { return categoryIdPath; } public void setCategoryIdPath(String categoryIdPath) { this.categoryIdPath = categoryIdPath; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Integer getCertType() { return certType; } public void setCertType(Integer certType) { this.certType = certType; } public Integer getLimitType() { return limitType; } public void setLimitType(Integer limitType) { this.limitType = limitType; } public Date getCertValidStartDate() { return certValidStartDate; } public void setCertValidStartDate(Date certValidStartDate) { this.certValidStartDate = certValidStartDate; } public Date getCertValidEndDate() { return certValidEndDate; } public void setCertValidEndDate(Date certValidEndDate) { this.certValidEndDate = certValidEndDate; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "EntCateCertInfo [" + "certInfoId=" + certInfoId+ ", memberId=" + memberId+ ", categoryNamePath=" + categoryNamePath+ ", categoryIdPath=" + categoryIdPath+ ", categoryId=" + categoryId+ ", certType=" + certType+ ", limitType=" + limitType+ ", certValidStartDate=" + certValidStartDate+ ", certValidEndDate=" + certValidEndDate+ ", createTime=" + createTime+ ", createAcctId=" + createAcctId+ ", createName=" + createName+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/QuestionAttachService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.QuestionAttach; /** * dal Interface:QuestionAttach * @author gencode * @date 2018-3-22 */ public interface QuestionAttachService { public List<QuestionAttach> findAll(); public List<QuestionAttach> findQuestionAttachs(QuestionAttach record); public QuestionAttach getQuestionAttachByPrimaryKey(Long questionAttachId); public Integer createQuestionAttach(QuestionAttach record); public Integer removeQuestionAttach(QuestionAttach record); public Integer removeByPrimaryKey(Long questionAttachId); public Integer modifyQuestionAttachByPrimaryKey(QuestionAttach record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntCertInfoVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import cn.enn.ygego.sunny.user.dto.EntCertInfoDTO; import cn.enn.ygego.sunny.user.model.EntCertFile; import java.util.List; /** * ClassName: EntCertInfoVO * Description: * Author: en3 * Date: 2018/3/20 15:34 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class EntCertInfoVO extends EntCertInfoDTO { private static final long serialVersionUID = -3487920352291293366L; private List<EntCertFile> entCertFileList; public List<EntCertFile> getEntCertFileList() { return entCertFileList; } public void setEntCertFileList(List<EntCertFile> entCertFileList) { this.entCertFileList = entCertFileList; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/SellerProdDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:SellerProd * * @author gencode * @date 2018-3-28 */ public class SellerProdDTO implements Serializable { private static final long serialVersionUID = -8876628432924612306L; private Long sellerProdId; /* 商家产品ID */ private Long prodId; /* 产品ID */ private Long supplierMemberId; /* 供应商会员ID */ private Long producerMemberId; /* 生产商会员ID */ private String prodName; /* 产品名称 */ private Long materialId; /* 物料ID */ private Long brandId; /* 品牌ID */ private Integer status; /* 状态 */ private Date createTime; /* 创建时间 */ private Long createAcctId; /* 创建人账户ID */ // Constructor public SellerProdDTO() { } /** * full Constructor */ public SellerProdDTO(Long sellerProdId, Long prodId, Long supplierMemberId, Long producerMemberId, String prodName, Long materialId, Long brandId, Integer status, Date createTime, Long createAcctId) { this.sellerProdId = sellerProdId; this.prodId = prodId; this.supplierMemberId = supplierMemberId; this.producerMemberId = producerMemberId; this.prodName = prodName; this.materialId = materialId; this.brandId = brandId; this.status = status; this.createTime = createTime; this.createAcctId = createAcctId; } public Long getSellerProdId() { return sellerProdId; } public void setSellerProdId(Long sellerProdId) { this.sellerProdId = sellerProdId; } public Long getProdId() { return prodId; } public void setProdId(Long prodId) { this.prodId = prodId; } public Long getSupplierMemberId() { return supplierMemberId; } public void setSupplierMemberId(Long supplierMemberId) { this.supplierMemberId = supplierMemberId; } public Long getProducerMemberId() { return producerMemberId; } public void setProducerMemberId(Long producerMemberId) { this.producerMemberId = producerMemberId; } public String getProdName() { return prodName; } public void setProdName(String prodName) { this.prodName = prodName; } public Long getMaterialId() { return materialId; } public void setMaterialId(Long materialId) { this.materialId = materialId; } public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } @Override public String toString() { return "SellerProdDTO [" + "sellerProdId=" + sellerProdId + ", prodId=" + prodId + ", supplierMemberId=" + supplierMemberId + ", producerMemberId=" + producerMemberId + ", prodName=" + prodName + ", materialId=" + materialId + ", brandId=" + brandId + ", status=" + status + ", createTime=" + createTime + ", createAcctId=" + createAcctId + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/MarketAuthApplyFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketAuthApplyFile; import org.springframework.stereotype.Repository; /** * ClassName: MarketAuthApplyFile * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketAuthApplyFileService { public List<MarketAuthApplyFile> findAll(); public List<MarketAuthApplyFile> findMarketAuthApplyFiles(MarketAuthApplyFile record); public MarketAuthApplyFile getMarketAuthApplyFileByPrimaryKey(Long applyFileId); public Integer deleteByPrimaryKey(Long applyFileId); public Integer createMarketAuthApplyFile(MarketAuthApplyFile record); public Integer deleteMarketAuthApplyFile(MarketAuthApplyFile record); public Integer removeMarketAuthApplyFile(MarketAuthApplyFile record); public Integer updateMarketAuthApplyFileByPrimaryKeySelective(MarketAuthApplyFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/AuthLogDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.AuthLog; /** * dal Interface:AuthLog * @author gencode */ public interface AuthLogDao { Integer insert(AuthLog record); Integer insertSelective(AuthLog record); Integer delete(AuthLog record); Integer deleteByPrimaryKey(@Param("logId") Long logId); Integer updateByPrimaryKey(AuthLog record); List<AuthLog> findAll(); List<AuthLog> find(AuthLog record); Integer getCount(AuthLog record); AuthLog getByPrimaryKey(@Param("logId") Long logId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntQueryVO.java package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.util.List; /** * ClassName: EntQueryVO * Description: * Author: en3 * Date: 2018/3/28 15:16 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class EntQueryVO implements Serializable{ private static final long serialVersionUID = 6037496288292823536L; private List<Integer> categoryIds; /* 类目ID */ private Long memberId; /* 会员ID */ private String EntName; private Integer pageSize; private Integer pageNum; private Integer startRow; private String entType; public List<Integer> getCategoryIds() { return categoryIds; } public void setCategoryIds(List<Integer> categoryIds) { this.categoryIds = categoryIds; } public String getEntName() { return EntName; } public void setEntName(String entName) { EntName = entName; } public String getEntType() { return entType; } public void setEntType(String entType) { this.entType = entType; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getStartRow() { return startRow; } public void setStartRow(Integer startRow) { this.startRow = startRow; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntCertApplyFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntCertApplyFile; /** * dal Interface:EntCertApplyFile * @author gencode */ public interface EntCertApplyFileDao { Integer insert(EntCertApplyFile record); Integer insertSelective(EntCertApplyFile record); Integer delete(EntCertApplyFile record); Integer deleteByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); Integer updateByPrimaryKey(EntCertApplyFile record); List<EntCertApplyFile> findAll(); List<EntCertApplyFile> find(EntCertApplyFile record); Integer getCount(EntCertApplyFile record); EntCertApplyFile getByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/QuestionFeedback.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:QuestionFeedback * * @author gencode */ public class QuestionFeedback implements Serializable { private static final long serialVersionUID = 3183741197284715502L; private Long questionId; /* 问题ID */ private Integer questionType; /* 问题类型 */ private String questionCode; /* 问题编号 */ private String questionUrl; /* 问题网址 */ private String questionModule; /* 问题模块 */ private String questionDesc; /* 问题描述 */ private String entName; /* 企业名称 */ private Integer isResponse; /* 是否回复 */ private Integer status; /* 状态 */ private String contact; /* 联系人 */ private String contactTel; /* 联系电话 */ private String email; /* 电子邮件 */ private Date createTime; /* 创建时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public QuestionFeedback() { } /** * full Constructor */ public QuestionFeedback(Long questionId, Integer questionType, String questionCode, String questionUrl, String questionModule, String questionDesc, String entName, Integer isResponse, Integer status, String contact, String contactTel, String email, Date createTime, Long createMemberId, Long createAcctId, String createName) { this.questionId = questionId; this.questionType = questionType; this.questionCode = questionCode; this.questionUrl = questionUrl; this.questionModule = questionModule; this.questionDesc = questionDesc; this.entName = entName; this.isResponse = isResponse; this.status = status; this.contact = contact; this.contactTel = contactTel; this.email = email; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getQuestionId() { return questionId; } public void setQuestionId(Long questionId) { this.questionId = questionId; } public Integer getQuestionType() { return questionType; } public void setQuestionType(Integer questionType) { this.questionType = questionType; } public String getQuestionCode() { return questionCode; } public void setQuestionCode(String questionCode) { this.questionCode = questionCode; } public String getQuestionUrl() { return questionUrl; } public void setQuestionUrl(String questionUrl) { this.questionUrl = questionUrl; } public String getQuestionModule() { return questionModule; } public void setQuestionModule(String questionModule) { this.questionModule = questionModule; } public String getQuestionDesc() { return questionDesc; } public void setQuestionDesc(String questionDesc) { this.questionDesc = questionDesc; } public String getEntName() { return entName; } public void setEntName(String entName) { this.entName = entName; } public Integer getIsResponse() { return isResponse; } public void setIsResponse(Integer isResponse) { this.isResponse = isResponse; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "QuestionFeedback [" + "questionId=" + questionId+ ", questionType=" + questionType+ ", questionCode=" + questionCode+ ", questionUrl=" + questionUrl+ ", questionModule=" + questionModule+ ", questionDesc=" + questionDesc+ ", entName=" + entName+ ", isResponse=" + isResponse+ ", status=" + status+ ", contact=" + contact+ ", contactTel=" + contactTel+ ", email=" + email+ ", createTime=" + createTime+ ", createMemberId=" + createMemberId+ ", createAcctId=" + createAcctId+ ", createName=" + createName+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/InspectAuditLogDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.InspectAuditLog; /** * dal Interface:InspectAuditLog * @author gencode */ public interface InspectAuditLogDao { Integer insert(InspectAuditLog record); Integer insertSelective(InspectAuditLog record); Integer delete(InspectAuditLog record); Integer deleteByPrimaryKey(@Param("logId") Long logId); Integer updateByPrimaryKey(InspectAuditLog record); List<InspectAuditLog> findAll(); List<InspectAuditLog> find(InspectAuditLog record); Integer getCount(InspectAuditLog record); InspectAuditLog getByPrimaryKey(@Param("logId") Long logId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntAuthApplyFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntAuthApplyFile; /** * dal Interface:EntAuthApplyFile * @author gencode */ public interface EntAuthApplyFileDao { Integer insert(EntAuthApplyFile record); Integer insertSelective(EntAuthApplyFile record); Integer delete(EntAuthApplyFile record); Integer deleteByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); Integer updateByPrimaryKey(EntAuthApplyFile record); List<EntAuthApplyFile> findAll(); List<EntAuthApplyFile> find(EntAuthApplyFile record); Integer getCount(EntAuthApplyFile record); EntAuthApplyFile getByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketCateCertApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketCateCertApply; import org.springframework.stereotype.Repository; /** * ClassName: MarketCateCertApply * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketCateCertApplyDao { List<MarketCateCertApply> selectAll(); List<MarketCateCertApply> select(MarketCateCertApply record); Integer selectCount(MarketCateCertApply record); MarketCateCertApply selectByPrimaryKey(Long certApplyDetailId); Integer deleteByPrimaryKey(Long certApplyDetailId); Integer delete(MarketCateCertApply record); Integer insertSelective(MarketCateCertApply record); Integer updateByPrimaryKeySelective(MarketCateCertApply record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntBrandInfoService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntBrandInfo; /** * dal Interface:EntBrandInfo * @author gencode * @date 2018-3-28 */ public interface EntBrandInfoService { public List<EntBrandInfo> findAll(); public List<EntBrandInfo> findEntBrandInfos(EntBrandInfo record); public EntBrandInfo getEntBrandInfoByPrimaryKey(Long entBrandId); public Integer createEntBrandInfo(EntBrandInfo record); public Integer removeEntBrandInfo(EntBrandInfo record); public Integer removeByPrimaryKey(Long entBrandId); public Integer modifyEntBrandInfoByPrimaryKey(EntBrandInfo record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/StorageAddrDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; /** * DTO:StorageAddr * * @author gencode * @date 2018-3-20 */ @ApiModel(description = "采购工厂库存地") public class StorageAddrDTO implements Serializable { private static final long serialVersionUID = -4147145381537482736L; @ApiModelProperty("库存地ID") private Long storageAddrId; /* 库存地ID */ @ApiModelProperty("工厂ID") private Long factoryId; /* 工厂ID */ @ApiModelProperty("库存地代码") private String storageAddrCode; /* 库存地代码 */ @ApiModelProperty("库存地名称") private String storageAddrName; /* 库存地名称 */ @ApiModelProperty("创建时间") private Date createTime; /* 创建时间 */ @ApiModelProperty("创建人会员ID") private Long createMemberId; /* 创建人会员ID */ @ApiModelProperty("创建人账户ID") private Long createAcctId; /* 创建人账户ID */ @ApiModelProperty("创建人姓名") private String createName; /* 创建人姓名 */ // Constructor public StorageAddrDTO() { } /** * full Constructor */ public StorageAddrDTO(Long storageAddrId, Long factoryId, String storageAddrCode, String storageAddrName, Date createTime, Long createMemberId, Long createAcctId, String createName) { this.storageAddrId = storageAddrId; this.factoryId = factoryId; this.storageAddrCode = storageAddrCode; this.storageAddrName = storageAddrName; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getStorageAddrId() { return storageAddrId; } public void setStorageAddrId(Long storageAddrId) { this.storageAddrId = storageAddrId; } public Long getFactoryId() { return factoryId; } public void setFactoryId(Long factoryId) { this.factoryId = factoryId; } public String getStorageAddrCode() { return storageAddrCode; } public void setStorageAddrCode(String storageAddrCode) { this.storageAddrCode = storageAddrCode; } public String getStorageAddrName() { return storageAddrName; } public void setStorageAddrName(String storageAddrName) { this.storageAddrName = storageAddrName; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "StorageAddrDTO [" + "storageAddrId=" + storageAddrId + ", factoryId=" + factoryId + ", storageAddrCode=" + storageAddrCode + ", storageAddrName=" + storageAddrName + ", createTime=" + createTime + ", createMemberId=" + createMemberId + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntCertApplyDetailDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntCertApplyDetail; /** * dal Interface:EntCertApplyDetail * @author gencode */ public interface EntCertApplyDetailDao { Integer insert(EntCertApplyDetail record); Integer insertSelective(EntCertApplyDetail record); Integer delete(EntCertApplyDetail record); Integer deleteByPrimaryKey(@Param("certApplyDetailId") Long certApplyDetailId); Integer updateByPrimaryKey(EntCertApplyDetail record); List<EntCertApplyDetail> findAll(); List<EntCertApplyDetail> find(EntCertApplyDetail record); Integer getCount(EntCertApplyDetail record); EntCertApplyDetail getByPrimaryKey(@Param("certApplyDetailId") Long certApplyDetailId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/register/ChangeEmailRequest.java package cn.enn.ygego.sunny.user.dto.register; import java.io.Serializable; /** * 更新邮件请求入参 * Created by dongbb on 2018/3/24. */ public class ChangeEmailRequest implements Serializable { private Long acctId; //账号id private String email; //邮箱 public Long getAcctId() { return acctId; } public void setAcctId(Long acctId) { this.acctId = acctId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualCertApplyService.java package cn.enn.ygego.sunny.user.service; import java.lang.reflect.InvocationTargetException; import java.util.List; import cn.enn.ygego.sunny.user.dto.IndividualCertApplyDTO; import cn.enn.ygego.sunny.user.dto.vo.IndividualCertApplyVO; import cn.enn.ygego.sunny.user.dto.vo.PersonQueryVO; import cn.enn.ygego.sunny.user.model.IndividualCertApply; import cn.enn.ygego.sunny.user.model.IndividualCust; /** * dal Interface:IndividualCertApply * @author gencode * @date 2018-3-22 */ public interface IndividualCertApplyService { public List<IndividualCertApply> findAll(); public List<IndividualCertApply> findIndividualCertApplys(IndividualCertApply record); public IndividualCertApply getIndividualCertApplyByPrimaryKey(Long certApplyId); public IndividualCertApply getIndividualCertApplyByMemberId(Long memberId); public Integer createIndividualCertApply(IndividualCertApply record); public Integer removeIndividualCertApply(IndividualCertApply record); public Integer removeByPrimaryKey(Long certApplyId); public Integer modifyIndividualCertApplyByPrimaryKey(IndividualCertApply record); /** * @Description 查询个人审批信息列表总数量 * @author puanl * @date 2018年3月24日 上午12:04:50 * @param query * @return */ public Integer getAcctCertApplyCount(PersonQueryVO query); /** * @Description 查询个人审批列表 * @author puanl * @date 2018年3月24日 上午12:05:25 * @param query * @return */ public List<IndividualCertApplyVO> getAcctCertApplyList(PersonQueryVO query); /** * @Description 查询个人审批详情(根据审批ID查询) * @author puanl * @date 2018年3月24日 上午12:06:13 * @param certApplyId * @param memberId * @return */ public IndividualCertApplyDTO getCertApplyByApplyId(Long certApplyId , boolean hasFile); /** * * @Description 查询个人审批详情 (根据会员id查询) * @author puanl * @date 2018年3月24日 上午7:26:16 * @param memberId * @param hasFile * @return */ public IndividualCertApplyVO getCertApplyByMemberId(IndividualCertApplyVO memberId, boolean hasFile); /** * @Description 添加个人认证信息 * @author puanl * @date 2018年3月24日 上午12:25:26 * @param applyData * @return * @throws IllegalAccessException * @throws InvocationTargetException */ public IndividualCertApplyDTO addIndividualCertApply(IndividualCertApplyDTO applyData) throws IllegalAccessException, InvocationTargetException; public IndividualCertApplyDTO updateIndividualCertApply(IndividualCertApplyDTO applyData) throws IllegalAccessException, InvocationTargetException; public IndividualCust copyApplyToIndividualCust(IndividualCertApply record) throws IllegalAccessException, InvocationTargetException; }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/AcctOperPrivRelaServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.AcctOperPrivRelaService; import cn.enn.ygego.sunny.user.dao.AcctOperPrivRelaDao; import cn.enn.ygego.sunny.user.model.AcctOperPrivRela; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:AcctOperPrivRela * @author gencode * @date 2018-3-22 */ @Service public class AcctOperPrivRelaServiceImpl implements AcctOperPrivRelaService{ @Autowired private AcctOperPrivRelaDao acctOperPrivRelaDao; public List<AcctOperPrivRela> findAll(){ return acctOperPrivRelaDao.findAll(); } public List<AcctOperPrivRela> findAcctOperPrivRelas(AcctOperPrivRela record){ return acctOperPrivRelaDao.find(record); } public AcctOperPrivRela getAcctOperPrivRelaByPrimaryKey(Long relaId){ return acctOperPrivRelaDao.getByPrimaryKey(relaId); } public Integer createAcctOperPrivRela(AcctOperPrivRela record){ return acctOperPrivRelaDao.insert(record); } public Integer removeAcctOperPrivRela(AcctOperPrivRela record){ return acctOperPrivRelaDao.delete(record); } public Integer removeByPrimaryKey(Long relaId){ return acctOperPrivRelaDao.deleteByPrimaryKey(relaId); } public Integer modifyAcctOperPrivRelaByPrimaryKey(AcctOperPrivRela record){ return acctOperPrivRelaDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntCertInfoService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntCertInfo; /** * dal Interface:EntCertInfo * @author gencode * @date 2018-3-28 */ public interface EntCertInfoService { public List<EntCertInfo> findAll(); public List<EntCertInfo> findEntCertInfos(EntCertInfo record); public EntCertInfo getEntCertInfoByPrimaryKey(Long certInfoId); public Integer createEntCertInfo(EntCertInfo record); public Integer removeEntCertInfo(EntCertInfo record); public Integer removeByPrimaryKey(Long certInfoId); public Integer modifyEntCertInfoByPrimaryKey(EntCertInfo record); }<file_sep>/src/main/resources/application.properties spring.profiles.active=dev spring.application.name=services-user server.port=10200 spring.jackson.defaultPropertyInclusion=NON_NULL db.driverClassName=com.mysql.jdbc.Driver db.connectionTimeout=30000 db.validationTimeout=5000 db.idleTimeout=300000 db.maxLifetime=900000 db.maxPoolSize=10 db.minIdle=2 db.connectionTestQuery=SELECT 1 <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/QuestionAttachDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.QuestionAttach; /** * dal Interface:QuestionAttach * @author gencode */ public interface QuestionAttachDao { Integer insert(QuestionAttach record); Integer insertSelective(QuestionAttach record); Integer delete(QuestionAttach record); Integer deleteByPrimaryKey(@Param("questionAttachId") Long questionAttachId); Integer updateByPrimaryKey(QuestionAttach record); List<QuestionAttach> findAll(); List<QuestionAttach> find(QuestionAttach record); Integer getCount(QuestionAttach record); QuestionAttach getByPrimaryKey(@Param("questionAttachId") Long questionAttachId); void insertBatch(List<QuestionAttach> attachList); List<QuestionAttach> getByQuestionId(Long questionId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/MarketCateMaterialServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.MarketCateMaterialService; import cn.enn.ygego.sunny.user.dao.MarketCateMaterialDao; import cn.enn.ygego.sunny.user.model.MarketCateMaterial; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * ClassName: MarketCateMaterial * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ @Service("marketCateMaterialService") public class MarketCateMaterialServiceImpl implements MarketCateMaterialService{ @Autowired private MarketCateMaterialDao marketCateMaterialDao; public List<MarketCateMaterial> findAll(){ return marketCateMaterialDao.selectAll(); } public List<MarketCateMaterial> findMarketCateMaterials(MarketCateMaterial record){ return marketCateMaterialDao.select(record); } public MarketCateMaterial getMarketCateMaterialByPrimaryKey(Long cateMaterialId){ return marketCateMaterialDao.selectByPrimaryKey(cateMaterialId); } public Integer deleteByPrimaryKey(Long cateMaterialId){ return marketCateMaterialDao.deleteByPrimaryKey(cateMaterialId); } public Integer createMarketCateMaterial(MarketCateMaterial record){ return marketCateMaterialDao.insertSelective(record); } public Integer deleteMarketCateMaterial(MarketCateMaterial record){ return marketCateMaterialDao.delete(record); } public Integer removeMarketCateMaterial(MarketCateMaterial record){ return marketCateMaterialDao.updateByPrimaryKeySelective(record); } public Integer updateMarketCateMaterialByPrimaryKeySelective(MarketCateMaterial record){ return marketCateMaterialDao.updateByPrimaryKeySelective(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketAuthApplyFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketAuthApplyFile; import org.springframework.stereotype.Repository; /** * ClassName: MarketAuthApplyFile * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketAuthApplyFileDao { List<MarketAuthApplyFile> selectAll(); List<MarketAuthApplyFile> select(MarketAuthApplyFile record); Integer selectCount(MarketAuthApplyFile record); MarketAuthApplyFile selectByPrimaryKey(Long applyFileId); Integer deleteByPrimaryKey(Long applyFileId); Integer delete(MarketAuthApplyFile record); Integer insertSelective(MarketAuthApplyFile record); Integer updateByPrimaryKeySelective(MarketAuthApplyFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/MarketApplyInfoService.java package cn.enn.ygego.sunny.user.service; import cn.enn.ygego.sunny.user.model.MarketApplyInfo; import java.util.List; /** * ClassName: MarketApplyInfo * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketApplyInfoService { public List<MarketApplyInfo> findAll(); public List<MarketApplyInfo> findMarketApplyInfos(MarketApplyInfo record); public MarketApplyInfo getMarketApplyInfoByPrimaryKey(Long marketApplyId); public Integer deleteByPrimaryKey(Long marketApplyId); public Integer createMarketApplyInfo(MarketApplyInfo record); public Integer deleteMarketApplyInfo(MarketApplyInfo record); public Integer removeMarketApplyInfo(MarketApplyInfo record); public Integer updateMarketApplyInfoByPrimaryKeySelective(MarketApplyInfo record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualDomainPermitService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualDomainPermit; /** * dal Interface:IndividualDomainPermit * @author gencode * @date 2018-3-22 */ public interface IndividualDomainPermitService { public List<IndividualDomainPermit> findAll(); public List<IndividualDomainPermit> findIndividualDomainPermits(IndividualDomainPermit record); public IndividualDomainPermit getIndividualDomainPermitByPrimaryKey(Long domainPermitId); public Integer createIndividualDomainPermit(IndividualDomainPermit record); public Integer removeIndividualDomainPermit(IndividualDomainPermit record); public Integer removeByPrimaryKey(Long domainPermitId); public Integer modifyIndividualDomainPermitByPrimaryKey(IndividualDomainPermit record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/factory/AuditFactoryController.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.controller.factory; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import java.util.Date; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.user.dto.factory.CategoryQueryVO; import cn.enn.ygego.sunny.user.dto.factory.InspectFactoryApplyInfoVO; import cn.enn.ygego.sunny.user.service.InspectFactoryApplyInfoService; import com.alibaba.fastjson.JSONObject; /** * 验厂管理 * ClassName: AuditFactoryController * Description * Author zhangjiaqi * Date 2018-03-20 15:35 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-20 15:35 0.0.1 TODO */ @RequestMapping("/audit/factory") @RestController @Api(value = "验厂管理", description = "验厂管理") public class AuditFactoryController { private static final Integer DEFALUT_PAGE_SIZE = 10; private static final Integer DEFALUT_PAGE_NUM = 1; Logger logger = LoggerFactory.getLogger(AuditFactoryController.class); @Autowired private InspectFactoryApplyInfoService inspectFactoryApplyInfoService; /** * @Description 供应航验厂类目列表查询 * @author zhengyang * @date 2018年3月30日 下午8:31:01 * @param jsonRequest */ @SuppressWarnings({ "rawtypes", "unchecked" }) @RequestMapping(value = "/list", method = RequestMethod.POST) public JsonResponse<PageDTO<InspectFactoryApplyInfoVO>> list( @RequestBody JsonRequest<CategoryQueryVO> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); CategoryQueryVO query = jsonRequest.getReqBody(); // 分页参数校验 if (query.getPageSize() == null) { query.setPageSize(DEFALUT_PAGE_SIZE); } if (query.getPageNum() == null) { query.setPageNum(DEFALUT_PAGE_NUM); } try { PageDTO<InspectFactoryApplyInfoVO> page = inspectFactoryApplyInfoService .getAuditCategoryList(query); jsonResponse.setRetCode("0000000"); jsonResponse.setRspBody(page); jsonResponse.setRetDesc("查询列表数据成功!"); } catch (Exception e) { logger.error("查询列表数据,入参:{},方法名:{},异常信息:{}", JSONObject.toJSONString(jsonRequest), "list", e.getMessage()); jsonResponse.setRetCode("0000001"); // 操作码:操作成功 jsonResponse.setRetDesc("接口调用失败!"); // 返回值信息 } return jsonResponse; } /** * 查看验厂详情接口 * * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查看验厂详情") @RequestMapping(value = "/info", method = RequestMethod.POST) public JsonResponse info(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } /** * 修改验厂信息接口 * * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("修改验厂信息") @RequestMapping(value = "/updateInfo", method = RequestMethod.POST) public JsonResponse updateInfo(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } /** * 审核验厂接口 * * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("审核验厂信息") @RequestMapping(value = "/audit", method = RequestMethod.POST) public JsonResponse audit(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } /** * 提交验厂接口 * * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("提交验厂信息") @RequestMapping(value = "/commit", method = RequestMethod.POST) public JsonResponse commit(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } /** * 下载验厂资料接口 * * @return */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("下载验厂资料") @RequestMapping(value = "/download", method = RequestMethod.POST) public JsonResponse download(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntBrandAuthApplyCertVO.java package cn.enn.ygego.sunny.user.dto.vo; import cn.enn.ygego.sunny.user.dto.EntBrandAuthApplyCertDTO; import cn.enn.ygego.sunny.user.model.EntBrandApplyCertFile; import java.util.List; /** * ClassName: EntBrandAuthApplyCertVO * Description: * Author: en3 * Date: 2018/3/28 16:49 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class EntBrandAuthApplyCertVO extends EntBrandAuthApplyCertDTO { private static final long serialVersionUID = 2942067275327738035L; private List<EntBrandApplyCertFile> entBrandApplyCertFileList; public List<EntBrandApplyCertFile> getEntBrandApplyCertFileList() { return entBrandApplyCertFileList; } public void setEntBrandApplyCertFileList(List<EntBrandApplyCertFile> entBrandApplyCertFileList) { this.entBrandApplyCertFileList = entBrandApplyCertFileList; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/UserInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.UserInfo; /** * dal Interface:UserInfo * @author gencode */ public interface UserInfoDao { Integer insert(UserInfo record); Integer insertSelective(UserInfo record); Integer delete(UserInfo record); Integer deleteByPrimaryKey(@Param("userId") Long userId); Integer updateByPrimaryKey(UserInfo record); List<UserInfo> findAll(); List<UserInfo> find(UserInfo record); Integer getCount(UserInfo record); UserInfo getByPrimaryKey(@Param("userId") Long userId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/AcctOperLogDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:AcctOperLog * * @author gencode * @date 2018-3-28 */ public class AcctOperLogDTO implements Serializable { private static final long serialVersionUID = 599368560224412701L; private Long logId; /* 日志标识 */ private String logCode; /* 日志编码 */ private String ipAddr; /* IP地址 */ private Integer operType; /* 操作类型 */ private Integer operResult; /* 操作结果 */ private String operDetail; /* 操作详情 */ private Date operTime; /* 操作时间 */ private Long operMemberId; /* 操作人会员ID */ private Long operAcctId; /* 操作人账户ID */ private String operPersonName; /* 操作人姓名 */ private Long superMemberId; /* 超级会员ID */ private Long superAcctId; /* 超级账户ID */ private String superAcctName; /* 超级账户名 */ // Constructor public AcctOperLogDTO() { } /** * full Constructor */ public AcctOperLogDTO(Long logId, String logCode, String ipAddr, Integer operType, Integer operResult, String operDetail, Date operTime, Long operMemberId, Long operAcctId, String operPersonName, Long superMemberId, Long superAcctId, String superAcctName) { this.logId = logId; this.logCode = logCode; this.ipAddr = ipAddr; this.operType = operType; this.operResult = operResult; this.operDetail = operDetail; this.operTime = operTime; this.operMemberId = operMemberId; this.operAcctId = operAcctId; this.operPersonName = operPersonName; this.superMemberId = superMemberId; this.superAcctId = superAcctId; this.superAcctName = superAcctName; } public Long getLogId() { return logId; } public void setLogId(Long logId) { this.logId = logId; } public String getLogCode() { return logCode; } public void setLogCode(String logCode) { this.logCode = logCode; } public String getIpAddr() { return ipAddr; } public void setIpAddr(String ipAddr) { this.ipAddr = ipAddr; } public Integer getOperType() { return operType; } public void setOperType(Integer operType) { this.operType = operType; } public Integer getOperResult() { return operResult; } public void setOperResult(Integer operResult) { this.operResult = operResult; } public String getOperDetail() { return operDetail; } public void setOperDetail(String operDetail) { this.operDetail = operDetail; } public Date getOperTime() { return operTime; } public void setOperTime(Date operTime) { this.operTime = operTime; } public Long getOperMemberId() { return operMemberId; } public void setOperMemberId(Long operMemberId) { this.operMemberId = operMemberId; } public Long getOperAcctId() { return operAcctId; } public void setOperAcctId(Long operAcctId) { this.operAcctId = operAcctId; } public String getOperPersonName() { return operPersonName; } public void setOperPersonName(String operPersonName) { this.operPersonName = operPersonName; } public Long getSuperMemberId() { return superMemberId; } public void setSuperMemberId(Long superMemberId) { this.superMemberId = superMemberId; } public Long getSuperAcctId() { return superAcctId; } public void setSuperAcctId(Long superAcctId) { this.superAcctId = superAcctId; } public String getSuperAcctName() { return superAcctName; } public void setSuperAcctName(String superAcctName) { this.superAcctName = superAcctName; } @Override public String toString() { return "AcctOperLogDTO [" + "logId=" + logId + ", logCode=" + logCode + ", ipAddr=" + ipAddr + ", operType=" + operType + ", operResult=" + operResult + ", operDetail=" + operDetail + ", operTime=" + operTime + ", operMemberId=" + operMemberId + ", operAcctId=" + operAcctId + ", operPersonName=" + operPersonName + ", superMemberId=" + superMemberId + ", superAcctId=" + superAcctId + ", superAcctName=" + superAcctName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualChannelPermitServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualChannelPermitService; import cn.enn.ygego.sunny.user.dao.IndividualChannelPermitDao; import cn.enn.ygego.sunny.user.model.IndividualChannelPermit; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualChannelPermit * @author gencode * @date 2018-3-22 */ @Service public class IndividualChannelPermitServiceImpl implements IndividualChannelPermitService{ @Autowired private IndividualChannelPermitDao individualChannelPermitDao; public List<IndividualChannelPermit> findAll(){ return individualChannelPermitDao.findAll(); } public List<IndividualChannelPermit> findIndividualChannelPermits(IndividualChannelPermit record){ return individualChannelPermitDao.find(record); } public IndividualChannelPermit getIndividualChannelPermitByPrimaryKey(Long channelPermitId){ return individualChannelPermitDao.getByPrimaryKey(channelPermitId); } public Integer createIndividualChannelPermit(IndividualChannelPermit record){ return individualChannelPermitDao.insert(record); } public Integer removeIndividualChannelPermit(IndividualChannelPermit record){ return individualChannelPermitDao.delete(record); } public Integer removeByPrimaryKey(Long channelPermitId){ return individualChannelPermitDao.deleteByPrimaryKey(channelPermitId); } public Integer modifyIndividualChannelPermitByPrimaryKey(IndividualChannelPermit record){ return individualChannelPermitDao.updateByPrimaryKey(record); } }<file_sep>/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cn.enn.ygego.sunny</groupId> <artifactId>services-user</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <junit_version>4.12</junit_version> <shiro_version>1.2.4</shiro_version> <swagger.version>2.7.0</swagger.version> <!-- mysql mybatis --> <mysql_version>5.1.37</mysql_version> <mybatis_version>3.2.8</mybatis_version> <mybatis_spring>1.2.3</mybatis_spring> <spring_version>4.3.8.RELEASE</spring_version> <spring-boot.version>1.5.3.RELEASE</spring-boot.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>${spring-boot.version}</version> </dependency> <dependency> <groupId>cn.enn.ygego.sunny</groupId> <artifactId>core</artifactId> <version>${project.version}</version> </dependency> <!-- mysql mybatis start --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql_version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis_version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis_spring}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring_version}</version> </dependency> <!-- 数据库连接池 --> <!-- junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit_version}</version> <scope>test</scope> </dependency> <!-- springfox START --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency> <!-- springfox END --> <dependency> <groupId>com.github.jsonzou</groupId> <artifactId>jmockdata</artifactId> <version>3.0.1</version> </dependency> <!-- jmockdata END --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.8.RELEASE</version> </dependency> <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP-java7</artifactId> <version>2.4.12</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.4.2.RELEASE</version> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-deploy-plugin</artifactId> <version>2.4</version> <configuration> <skip>true</skip> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.4</version> <configuration> <excludes> <exclude>**/*.properties</exclude> </excludes> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> <dependencies> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-compiler-javac</artifactId> <version>1.8.1</version> </dependency> </dependencies> </plugin> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>2.6</version> <configuration> <encoding>UTF-8</encoding> </configuration> <executions> <execution> <id>copy-xmls</id> <phase>process-sources</phase> <goals> <goal>copy-resources</goal> </goals> <configuration> <outputDirectory>${basedir}/target/classes</outputDirectory> <resources> <resource> <directory>${basedir}/src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.10</version> <configuration> <skip>true</skip> <testFailureIgnore>true</testFailureIgnore> </configuration> </plugin> </plugins> </build> </project> <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/RelaMemberToAcctServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.RelaMemberToAcctService; import cn.enn.ygego.sunny.user.dao.RelaMemberToAcctDao; import cn.enn.ygego.sunny.user.dto.vo.EmployeeQueryVO; import cn.enn.ygego.sunny.user.dto.vo.EmployeeVO; import cn.enn.ygego.sunny.user.dto.vo.PersonQueryVO; import cn.enn.ygego.sunny.user.dto.vo.PersonVO; import cn.enn.ygego.sunny.user.model.MemberInfo; import cn.enn.ygego.sunny.user.model.RelaMemberToAcct; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:RelaMemberToAcct * @author gencode * @date 2018-3-24 */ @Service public class RelaMemberToAcctServiceImpl implements RelaMemberToAcctService{ @Autowired private RelaMemberToAcctDao relaMemberToAcctDao; public List<RelaMemberToAcct> findAll(){ return relaMemberToAcctDao.findAll(); } public List<RelaMemberToAcct> findRelaMemberToAccts(RelaMemberToAcct record){ return relaMemberToAcctDao.find(record); } public RelaMemberToAcct getRelaMemberToAcctByPrimaryKey(Long relaId){ return relaMemberToAcctDao.getByPrimaryKey(relaId); } public Integer createRelaMemberToAcct(RelaMemberToAcct record){ return relaMemberToAcctDao.insert(record); } public Integer removeRelaMemberToAcct(RelaMemberToAcct record){ return relaMemberToAcctDao.delete(record); } public Integer removeByPrimaryKey(Long relaId){ return relaMemberToAcctDao.deleteByPrimaryKey(relaId); } public Integer modifyRelaMemberToAcctByPrimaryKey(RelaMemberToAcct record){ return relaMemberToAcctDao.updateByPrimaryKey(record); } @Override public boolean modifyEntAdminRela(MemberInfo newAdminMember, RelaMemberToAcct oldRela) { boolean result = false; // TODO 删除原有关联 //1. 调用权限配置 //2. 删除关系数据 // TODO 建立新的关联 //1. 调用权限配置 return result; } @Override public Integer getEmployeeEntCount(EmployeeQueryVO query){ return relaMemberToAcctDao.getEmployeeEntCount(query); } @Override public List<EmployeeVO> getEmployeeEntList(EmployeeQueryVO query) { List<EmployeeVO> entList = relaMemberToAcctDao.getEmployeeEntList(query); // TODO for 循环查询用户角色 return entList; } @Override public Integer getPersonCount(PersonQueryVO query) { return relaMemberToAcctDao.getPersonCount(query); } @Override public List<PersonVO> getPersonList(PersonQueryVO query) { return relaMemberToAcctDao.getPersonList(query); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/supermarket/EnterSupplierVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.supermarket; import java.util.Date; /** * 超市入驻供应商描述类 * ClassName: EnterSupplierVO * Description * Author zhangjiaqi * Date 2018-03-31 10:35 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-31 10:35 0.0.1 TODO */ public class EnterSupplierVO { // 供应商id private Long supplierId; // 供应商名称 private String supplierName; // 提交时间 private Date applyDate; // 入驻时间 private Date enterDate; // 寄售商品数 private Integer consignGoodsNum; // 联营商品数 private Integer joinGoodsNum; // 本月销售额/万元 private Integer sales; public EnterSupplierVO() { super(); // TODO Auto-generated constructor stub } public EnterSupplierVO(Long supplierId, String supplierName, Date applyDate, Date enterDate, Integer consignGoodsNum, Integer joinGoodsNum, Integer sales) { super(); this.supplierId = supplierId; this.supplierName = supplierName; this.applyDate = applyDate; this.enterDate = enterDate; this.consignGoodsNum = consignGoodsNum; this.joinGoodsNum = joinGoodsNum; this.sales = sales; } public Long getSupplierId() { return supplierId; } public void setSupplierId(Long supplierId) { this.supplierId = supplierId; } public String getSupplierName() { return supplierName; } public void setSupplierName(String supplierName) { this.supplierName = supplierName; } public Date getApplyDate() { return applyDate; } public void setApplyDate(Date applyDate) { this.applyDate = applyDate; } public Date getEnterDate() { return enterDate; } public void setEnterDate(Date enterDate) { this.enterDate = enterDate; } public Integer getConsignGoodsNum() { return consignGoodsNum; } public void setConsignGoodsNum(Integer consignGoodsNum) { this.consignGoodsNum = consignGoodsNum; } public Integer getJoinGoodsNum() { return joinGoodsNum; } public void setJoinGoodsNum(Integer joinGoodsNum) { this.joinGoodsNum = joinGoodsNum; } public Integer getSales() { return sales; } public void setSales(Integer sales) { this.sales = sales; } @Override public String toString() { return "EnterSupplierVO [supplierId=" + supplierId + ", supplierName=" + supplierName + ", applyDate=" + applyDate + ", enterDate=" + enterDate + ", consignGoodsNum=" + consignGoodsNum + ", joinGoodsNum=" + joinGoodsNum + ", sales=" + sales + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntTaxRateService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntTaxRate; /** * dal Interface:EntTaxRate * @author gencode * @date 2018-3-28 */ public interface EntTaxRateService { public List<EntTaxRate> findAll(); public List<EntTaxRate> findEntTaxRates(EntTaxRate record); public EntTaxRate getEntTaxRateByPrimaryKey(Long taxRateId); public Integer createEntTaxRate(EntTaxRate record); public Integer removeEntTaxRate(EntTaxRate record); public Integer removeByPrimaryKey(Long taxRateId); public Integer modifyEntTaxRateByPrimaryKey(EntTaxRate record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntChannelPermitApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntChannelPermitApply; /** * dal Interface:EntChannelPermitApply * @author gencode */ public interface EntChannelPermitApplyDao { Integer insert(EntChannelPermitApply record); Integer insertSelective(EntChannelPermitApply record); Integer delete(EntChannelPermitApply record); Integer deleteByPrimaryKey(@Param("channelApplyId") Long channelApplyId); Integer updateByPrimaryKey(EntChannelPermitApply record); List<EntChannelPermitApply> findAll(); List<EntChannelPermitApply> find(EntChannelPermitApply record); Integer getCount(EntChannelPermitApply record); EntChannelPermitApply getByPrimaryKey(@Param("channelApplyId") Long channelApplyId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/MemberInfo.java package cn.enn.ygego.sunny.user.model; import java.io.Serializable; /** * entity:MemberInfo * * @author gencode */ public class MemberInfo implements Serializable { private static final long serialVersionUID = -3747143457958411155L; private Long memberId; /* 会员ID */ private Integer memberType; /* 会员类型 */ private Integer status; /* 状态 */ private Integer ygegoCoin ; /* 阳光币 */ // Constructor public MemberInfo() { } public MemberInfo(Long memberId, Integer memberType, Integer status, Integer ygegoCoin) { this.memberId = memberId; this.memberType = memberType; this.status = status; this.ygegoCoin = ygegoCoin; } @Override public String toString() { return "MemberInfo{" + "memberId=" + memberId + ", memberType=" + memberType + ", status=" + status + ", ygegoCoin=" + ygegoCoin + '}'; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getMemberType() { return memberType; } public void setMemberType(Integer memberType) { this.memberType = memberType; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getYgegoCoin() { return ygegoCoin; } public void setYgegoCoin(Integer ygegoCoin) { this.ygegoCoin = ygegoCoin; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/IndividualBrandInfoDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:IndividualBrandInfo * * @author gencode * @date 2018-3-19 */ public class IndividualBrandInfoDTO implements Serializable { private static final long serialVersionUID = -5180343356630558873L; private Long individualBrandId; /* 个人品牌ID */ private Long memberId; /* 会员ID */ private Integer categoryId; /* 类目ID */ private String categoryNamePath; /* 类目名称路径 */ private String categoryIdPath; /* 类目ID路径 */ private Integer brandId; /* 品牌ID */ private String brandName; /* 品牌名称 */ private String brandDesc; /* 品牌描述 */ private Date createTime; /* 创建时间 */ private Date modTime; /* 修改时间 */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public IndividualBrandInfoDTO() { } /** * full Constructor */ public IndividualBrandInfoDTO(Long individualBrandId, Long memberId, Integer categoryId, String categoryNamePath, String categoryIdPath, Integer brandId, String brandName, String brandDesc, Date createTime, Date modTime, Long createAcctId, String createName) { this.individualBrandId = individualBrandId; this.memberId = memberId; this.categoryId = categoryId; this.categoryNamePath = categoryNamePath; this.categoryIdPath = categoryIdPath; this.brandId = brandId; this.brandName = brandName; this.brandDesc = brandDesc; this.createTime = createTime; this.modTime = modTime; this.createAcctId = createAcctId; this.createName = createName; } public Long getIndividualBrandId() { return individualBrandId; } public void setIndividualBrandId(Long individualBrandId) { this.individualBrandId = individualBrandId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public String getCategoryNamePath() { return categoryNamePath; } public void setCategoryNamePath(String categoryNamePath) { this.categoryNamePath = categoryNamePath; } public String getCategoryIdPath() { return categoryIdPath; } public void setCategoryIdPath(String categoryIdPath) { this.categoryIdPath = categoryIdPath; } public Integer getBrandId() { return brandId; } public void setBrandId(Integer brandId) { this.brandId = brandId; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getBrandDesc() { return brandDesc; } public void setBrandDesc(String brandDesc) { this.brandDesc = brandDesc; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getModTime() { return modTime; } public void setModTime(Date modTime) { this.modTime = modTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "IndividualBrandInfoDTO [" + "individualBrandId=" + individualBrandId + ", memberId=" + memberId + ", categoryId=" + categoryId + ", categoryNamePath=" + categoryNamePath + ", categoryIdPath=" + categoryIdPath + ", brandId=" + brandId + ", brandName=" + brandName + ", brandDesc=" + brandDesc + ", createTime=" + createTime + ", modTime=" + modTime + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/ProdInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.ProdInfo; /** * dal Interface:ProdInfo * @author gencode */ public interface ProdInfoDao { Integer insert(ProdInfo record); Integer insertSelective(ProdInfo record); Integer delete(ProdInfo record); Integer deleteByPrimaryKey(@Param("prodId") Long prodId); Integer updateByPrimaryKey(ProdInfo record); List<ProdInfo> findAll(); List<ProdInfo> find(ProdInfo record); Integer getCount(ProdInfo record); ProdInfo getByPrimaryKey(@Param("prodId") Long prodId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/ThirdLoginConfig.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:ThirdLoginConfig * * @author gencode */ public class ThirdLoginConfig implements Serializable { private static final long serialVersionUID = 3628165385853938373L; private Long configId; /* 配置ID */ private String companyName; /* 公司名称 */ private String companyShortName; /* 公司简称 */ private String companyIconUri; /* 公司图标 */ private String redirectUri; /* 跳转路径 */ private String appId; /* 应用标识 */ private String appSecretKey; /* 应用秘钥 */ private String loginUri; /* 登录路径 */ private String getTokenUri; /* 获取token路径 */ private Integer status; /* 状态 */ private Integer sortNum; /* 排序 */ private Date createTime; /* 创建时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public ThirdLoginConfig() { } /** * full Constructor */ public ThirdLoginConfig(Long configId, String companyName, String companyShortName, String companyIconUri, String redirectUri, String appId, String appSecretKey, String loginUri, String getTokenUri, Integer status, Integer sortNum, Date createTime, Long createMemberId, Long createAcctId, String createName) { this.configId = configId; this.companyName = companyName; this.companyShortName = companyShortName; this.companyIconUri = companyIconUri; this.redirectUri = redirectUri; this.appId = appId; this.appSecretKey = appSecretKey; this.loginUri = loginUri; this.getTokenUri = getTokenUri; this.status = status; this.sortNum = sortNum; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getConfigId() { return configId; } public void setConfigId(Long configId) { this.configId = configId; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCompanyShortName() { return companyShortName; } public void setCompanyShortName(String companyShortName) { this.companyShortName = companyShortName; } public String getCompanyIconUri() { return companyIconUri; } public void setCompanyIconUri(String companyIconUri) { this.companyIconUri = companyIconUri; } public String getRedirectUri() { return redirectUri; } public void setRedirectUri(String redirectUri) { this.redirectUri = redirectUri; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAppSecretKey() { return appSecretKey; } public void setAppSecretKey(String appSecretKey) { this.appSecretKey = appSecretKey; } public String getLoginUri() { return loginUri; } public void setLoginUri(String loginUri) { this.loginUri = loginUri; } public String getGetTokenUri() { return getTokenUri; } public void setGetTokenUri(String getTokenUri) { this.getTokenUri = getTokenUri; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getSortNum() { return sortNum; } public void setSortNum(Integer sortNum) { this.sortNum = sortNum; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "ThirdLoginConfig [" + "configId=" + configId+ ", companyName=" + companyName+ ", companyShortName=" + companyShortName+ ", companyIconUri=" + companyIconUri+ ", redirectUri=" + redirectUri+ ", appId=" + appId+ ", appSecretKey=" + appSecretKey+ ", loginUri=" + loginUri+ ", getTokenUri=" + getTokenUri+ ", status=" + status+ ", sortNum=" + sortNum+ ", createTime=" + createTime+ ", createMemberId=" + createMemberId+ ", createAcctId=" + createAcctId+ ", createName=" + createName+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntMaterial.java package cn.enn.ygego.sunny.user.model; import java.io.Serializable; /** * entity:EntMaterial * * @author gencode */ public class EntMaterial implements Serializable { private static final long serialVersionUID = 1918871854394715697L; private Long entMaterialId; /* 企业物料ID */ private Long entCateId; /* 企业类目ID */ private Long memberId; /* 会员ID */ private Long materialId; /* 物料ID */ private Long categoryId; /* 类目ID */ private String materialName; /* 物料名称 */ private String attrNameSerial; /* 属性名序列 */ // Constructor public EntMaterial() { } /** * full Constructor */ public EntMaterial(Long entMaterialId, Long entCateId, Long memberId, Long materialId, Long categoryId, String materialName, String attrNameSerial) { this.entMaterialId = entMaterialId; this.entCateId = entCateId; this.memberId = memberId; this.materialId = materialId; this.categoryId = categoryId; this.materialName = materialName; this.attrNameSerial = attrNameSerial; } public Long getEntMaterialId() { return entMaterialId; } public void setEntMaterialId(Long entMaterialId) { this.entMaterialId = entMaterialId; } public Long getEntCateId() { return entCateId; } public void setEntCateId(Long entCateId) { this.entCateId = entCateId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getMaterialId() { return materialId; } public void setMaterialId(Long materialId) { this.materialId = materialId; } public Long getCategoryId() { return categoryId; } public void setCategoryId(Long categoryId) { this.categoryId = categoryId; } public String getMaterialName() { return materialName; } public void setMaterialName(String materialName) { this.materialName = materialName; } public String getAttrNameSerial() { return attrNameSerial; } public void setAttrNameSerial(String attrNameSerial) { this.attrNameSerial = attrNameSerial; } @Override public String toString() { return "EntMaterial [" + "entMaterialId=" + entMaterialId+ ", entCateId=" + entCateId+ ", memberId=" + memberId+ ", materialId=" + materialId+ ", categoryId=" + categoryId+ ", materialName=" + materialName+ ", attrNameSerial=" + attrNameSerial+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/OperAuthLoginLog.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:OperAuthLoginLog * * @author gencode */ public class OperAuthLoginLog implements Serializable { private static final long serialVersionUID = -4549450366196782948L; private Long logId; /* 日志标识 */ private String logCode; /* 日志编码 */ private Integer logType; /* 日志类型 */ private Long operPersonId; /* 操作人标识 */ private String operPersonName; /* 操作人姓名 */ private Long appId; /* 应用标识 */ private String appName; /* 应用名称 */ private Long operId; /* 操作标识 */ private String operTitle; /* 操作名称 */ private String ipAddr; /* IP地址 */ private Integer operResult; /* 操作结果 */ private String logContent; /* 日志内容 */ private Date recordTime; /* 记录时间 */ private Integer loginType; /* 登录类型 */ // Constructor public OperAuthLoginLog() { } /** * full Constructor */ public OperAuthLoginLog(Long logId, String logCode, Integer logType, Long operPersonId, String operPersonName, Long appId, String appName, Long operId, String operTitle, String ipAddr, Integer operResult, String logContent, Date recordTime, Integer loginType) { this.logId = logId; this.logCode = logCode; this.logType = logType; this.operPersonId = operPersonId; this.operPersonName = operPersonName; this.appId = appId; this.appName = appName; this.operId = operId; this.operTitle = operTitle; this.ipAddr = ipAddr; this.operResult = operResult; this.logContent = logContent; this.recordTime = recordTime; this.loginType = loginType; } public Long getLogId() { return logId; } public void setLogId(Long logId) { this.logId = logId; } public String getLogCode() { return logCode; } public void setLogCode(String logCode) { this.logCode = logCode; } public Integer getLogType() { return logType; } public void setLogType(Integer logType) { this.logType = logType; } public Long getOperPersonId() { return operPersonId; } public void setOperPersonId(Long operPersonId) { this.operPersonId = operPersonId; } public String getOperPersonName() { return operPersonName; } public void setOperPersonName(String operPersonName) { this.operPersonName = operPersonName; } public Long getAppId() { return appId; } public void setAppId(Long appId) { this.appId = appId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public Long getOperId() { return operId; } public void setOperId(Long operId) { this.operId = operId; } public String getOperTitle() { return operTitle; } public void setOperTitle(String operTitle) { this.operTitle = operTitle; } public String getIpAddr() { return ipAddr; } public void setIpAddr(String ipAddr) { this.ipAddr = ipAddr; } public Integer getOperResult() { return operResult; } public void setOperResult(Integer operResult) { this.operResult = operResult; } public String getLogContent() { return logContent; } public void setLogContent(String logContent) { this.logContent = logContent; } public Date getRecordTime() { return recordTime; } public void setRecordTime(Date recordTime) { this.recordTime = recordTime; } public Integer getLoginType() { return loginType; } public void setLoginType(Integer loginType) { this.loginType = loginType; } @Override public String toString() { return "OperAuthLoginLog [" + "logId=" + logId+ ", logCode=" + logCode+ ", logType=" + logType+ ", operPersonId=" + operPersonId+ ", operPersonName=" + operPersonName+ ", appId=" + appId+ ", appName=" + appName+ ", operId=" + operId+ ", operTitle=" + operTitle+ ", ipAddr=" + ipAddr+ ", operResult=" + operResult+ ", logContent=" + logContent+ ", recordTime=" + recordTime+ ", loginType=" + loginType+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketStockAlertSetDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketStockAlertSet; import org.springframework.stereotype.Repository; /** * ClassName: MarketStockAlertSet * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketStockAlertSetDao { List<MarketStockAlertSet> selectAll(); List<MarketStockAlertSet> select(MarketStockAlertSet record); Integer selectCount(MarketStockAlertSet record); MarketStockAlertSet selectByPrimaryKey(Long alertSetId); Integer deleteByPrimaryKey(Long alertSetId); Integer delete(MarketStockAlertSet record); Integer insertSelective(MarketStockAlertSet record); Integer updateByPrimaryKeySelective(MarketStockAlertSet record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/RoleInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.RoleInfo; /** * dal Interface:RoleInfo * @author gencode */ public interface RoleInfoDao { Integer insert(RoleInfo record); Integer insertSelective(RoleInfo record); Integer delete(RoleInfo record); Integer deleteByPrimaryKey(@Param("roleId") Long roleId); Integer updateByPrimaryKey(RoleInfo record); List<RoleInfo> findAll(); List<RoleInfo> find(RoleInfo record); Integer getCount(RoleInfo record); RoleInfo getByPrimaryKey(@Param("roleId") Long roleId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/PageVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; /** * 分页 * ClassName: PageVO * Description * Author zhangjiaqi * Date 2018-03-24 17:00 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-24 17:00 0.0.1 TODO */ public class PageVO implements Serializable { private Integer pageSize; private Integer pageNum; private Integer startRow; public PageVO() { super(); // TODO Auto-generated constructor stub } public PageVO(Integer pageSize, Integer pageNum, Integer startRow) { super(); this.pageSize = pageSize; this.pageNum = pageNum; this.startRow = startRow; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getPageNum() { return pageNum; } public void setPageNum(Integer pageNum) { this.pageNum = pageNum; } public Integer getStartRow() { return startRow; } public void setStartRow(Integer startRow) { this.startRow = startRow; } @Override public String toString() { return "PageVO [pageSize=" + pageSize + ", pageNum=" + pageNum + ", startRow=" + startRow + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/MarketAuthFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketAuthFile; import org.springframework.stereotype.Repository; /** * ClassName: MarketAuthFile * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketAuthFileService { public List<MarketAuthFile> findAll(); public List<MarketAuthFile> findMarketAuthFiles(MarketAuthFile record); public MarketAuthFile getMarketAuthFileByPrimaryKey(Long authFileId); public Integer deleteByPrimaryKey(Long authFileId); public Integer createMarketAuthFile(MarketAuthFile record); public Integer deleteMarketAuthFile(MarketAuthFile record); public Integer removeMarketAuthFile(MarketAuthFile record); public Integer updateMarketAuthFileByPrimaryKeySelective(MarketAuthFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualCertInfoServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualCertInfoService; import cn.enn.ygego.sunny.user.dao.IndividualCertInfoDao; import cn.enn.ygego.sunny.user.model.IndividualCertInfo; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualCertInfo * @author gencode * @date 2018-3-22 */ @Service public class IndividualCertInfoServiceImpl implements IndividualCertInfoService{ @Autowired private IndividualCertInfoDao individualCertInfoDao; public List<IndividualCertInfo> findAll(){ return individualCertInfoDao.findAll(); } public List<IndividualCertInfo> findIndividualCertInfos(IndividualCertInfo record){ return individualCertInfoDao.find(record); } public IndividualCertInfo getIndividualCertInfoByPrimaryKey(Long certInfoId){ return individualCertInfoDao.getByPrimaryKey(certInfoId); } public Integer createIndividualCertInfo(IndividualCertInfo record){ return individualCertInfoDao.insert(record); } public Integer removeIndividualCertInfo(IndividualCertInfo record){ return individualCertInfoDao.delete(record); } public Integer removeByPrimaryKey(Long certInfoId){ return individualCertInfoDao.deleteByPrimaryKey(certInfoId); } public Integer modifyIndividualCertInfoByPrimaryKey(IndividualCertInfo record){ return individualCertInfoDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualBrandInfoServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualBrandInfoService; import cn.enn.ygego.sunny.user.dao.IndividualBrandInfoDao; import cn.enn.ygego.sunny.user.model.IndividualBrandInfo; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualBrandInfo * @author gencode * @date 2018-3-22 */ @Service public class IndividualBrandInfoServiceImpl implements IndividualBrandInfoService{ @Autowired private IndividualBrandInfoDao individualBrandInfoDao; public List<IndividualBrandInfo> findAll(){ return individualBrandInfoDao.findAll(); } public List<IndividualBrandInfo> findIndividualBrandInfos(IndividualBrandInfo record){ return individualBrandInfoDao.find(record); } public IndividualBrandInfo getIndividualBrandInfoByPrimaryKey(Long individualBrandId){ return individualBrandInfoDao.getByPrimaryKey(individualBrandId); } public Integer createIndividualBrandInfo(IndividualBrandInfo record){ return individualBrandInfoDao.insert(record); } public Integer removeIndividualBrandInfo(IndividualBrandInfo record){ return individualBrandInfoDao.delete(record); } public Integer removeByPrimaryKey(Long individualBrandId){ return individualBrandInfoDao.deleteByPrimaryKey(individualBrandId); } public Integer modifyIndividualBrandInfoByPrimaryKey(IndividualBrandInfo record){ return individualBrandInfoDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntCateCertApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.dto.vo.EntCateAndBrandVO; import cn.enn.ygego.sunny.user.model.EntCateCertApply; /** * dal Interface:EntCateCertApply * @author gencode * @date 2018-3-28 */ public interface EntCateCertApplyService { public List<EntCateCertApply> findAll(); public List<EntCateCertApply> findEntCateCertApplys(EntCateCertApply record); public EntCateCertApply getEntCateCertApplyByPrimaryKey(Long certApplyDetailId); public Integer createEntCateCertApply(EntCateCertApply record); public Integer removeEntCateCertApply(EntCateCertApply record); public Integer removeByPrimaryKey(Long certApplyDetailId); public Integer modifyEntCateCertApplyByPrimaryKey(EntCateCertApply record); public Integer createEntCateAndBrandApply(EntCateAndBrandVO record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/QuestionResponseService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.QuestionResponse; /** * dal Interface:QuestionResponse * @author gencode * @date 2018-3-22 */ public interface QuestionResponseService { public List<QuestionResponse> findAll(); public List<QuestionResponse> findQuestionResponses(QuestionResponse record); public QuestionResponse getQuestionResponseByPrimaryKey(Long responseId); public Integer createQuestionResponse(QuestionResponse record); public Integer removeQuestionResponse(QuestionResponse record); public Integer removeByPrimaryKey(Long responseId); public Integer modifyQuestionResponseByPrimaryKey(QuestionResponse record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/OperLoginVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.util.Date; /** * DTO:OperManage * * @author gencode * @date 2018-3-19 */ public class OperLoginVO implements Serializable { private static final long serialVersionUID = 758329476498675534L; private Long operId; /* 操作标识 */ private String operTitle; /* 操作名称 */ private Long functionId; /* 功能标识 */ // Constructor public OperLoginVO() { } public Long getFunctionId() { return functionId; } public void setFunctionId(Long functionId) { this.functionId = functionId; } public Long getOperId() { return operId; } public void setOperId(Long operId) { this.operId = operId; } public String getOperTitle() { return operTitle; } public void setOperTitle(String operTitle) { this.operTitle = operTitle; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/supermarket/EntJoinMarketVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.supermarket; /** * 企业入驻超市描述类 * ClassName: EntJoinMarketVO * Description * Author zhangjiaqi * Date 2018-03-30 15:09 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-30 15:09 0.0.1 TODO */ public class EntJoinMarketVO { // 入驻id private Long joinId; // 超市编码 private String marketCode; // 超市名称 private String marketName; // 状态 private Integer status; public EntJoinMarketVO() { super(); // TODO Auto-generated constructor stub } public EntJoinMarketVO(Long joinId, String marketCode, String marketName, Integer status) { super(); this.joinId = joinId; this.marketCode = marketCode; this.marketName = marketName; this.status = status; } public Long getJoinId() { return joinId; } public void setJoinId(Long joinId) { this.joinId = joinId; } public String getMarketCode() { return marketCode; } public void setMarketCode(String marketCode) { this.marketCode = marketCode; } public String getMarketName() { return marketName; } public void setMarketName(String marketName) { this.marketName = marketName; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() { return "EntJoinMarketVO [joinId=" + joinId + ", marketCode=" + marketCode + ", marketName=" + marketName + ", status=" + status + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/LogServiceImpl.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.service.impl; import cn.enn.ygego.sunny.user.dao.AcctLoginLogDao; import cn.enn.ygego.sunny.user.dao.AcctOperLogDao; import cn.enn.ygego.sunny.user.dto.vo.AcctLoginLogVO; import cn.enn.ygego.sunny.user.dto.vo.AcctOperLogVO; import cn.enn.ygego.sunny.user.model.AcctLoginLog; import cn.enn.ygego.sunny.user.model.AcctOperLog; import cn.enn.ygego.sunny.user.service.LogService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * ClassName: LogServiceImpl * Description: * Author: liangchao * Date: 2018/3/28 18:55 * History: * <author> <time> <version> <desc> * liangc 修改时间 0.0.1 描述 */ @Service("logService") public class LogServiceImpl implements LogService { @Autowired private AcctLoginLogDao acctLoginLogDao; @Autowired private AcctOperLogDao acctOperLogDao; @Override public void insertLoginLog(AcctLoginLog acctLoginLog) { acctLoginLogDao.insertSelective(acctLoginLog); } @Override public void addOperationLog(AcctOperLog acctOperLog) { acctOperLogDao.insertSelective(acctOperLog); } @Override public Long queryLoginLogCount(AcctLoginLogVO acctLoginLogVO) { Long listCount = acctLoginLogDao.findPageCount(acctLoginLogVO); return listCount; } @Override public List<AcctLoginLog> queryLoginLog(AcctLoginLogVO acctLoginLogVO) { List<AcctLoginLog> list = acctLoginLogDao.findPage(acctLoginLogVO); return list; } @Override public Long queryOperLogCount(AcctOperLogVO acctOperLogVO) { Long listCount = acctOperLogDao.findPageCount(acctOperLogVO); return listCount; } @Override public List<AcctOperLog> queryOperLog(AcctOperLogVO acctOperLogVO) { List<AcctOperLog> list = acctOperLogDao.findPage(acctOperLogVO); return list; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualBrandApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualBrandApply; /** * dal Interface:IndividualBrandApply * @author gencode */ public interface IndividualBrandApplyDao { Integer insert(IndividualBrandApply record); Integer insertSelective(IndividualBrandApply record); Integer delete(IndividualBrandApply record); Integer deleteByPrimaryKey(@Param("brandApplyId") Integer brandApplyId); Integer updateByPrimaryKey(IndividualBrandApply record); List<IndividualBrandApply> findAll(); List<IndividualBrandApply> find(IndividualBrandApply record); Integer getCount(IndividualBrandApply record); IndividualBrandApply getByPrimaryKey(@Param("brandApplyId") Integer brandApplyId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/IndividualCustDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualCertFile; import java.io.Serializable; /** * DTO:IndividualCust * * @author gencode * @date 2018-3-19 */ public class IndividualCustDTO implements Serializable { private static final long serialVersionUID = -5552109070398241235L; private Long memberId; /* 会员ID */ private String name; /* 姓名 */ private Integer certType; /* 证件类型 */ private String certCode; /* 证件号码 */ private Integer status; /* 状态 */ private Date authTime; /* 认证时间 */ private Date createTime; /* 创建时间 */ private Date modTime; /* 修改时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ private Long certInfoId; /* 资质信息ID */ private String certNo; /* 资质号码 */ private String certName; /* 资质名称 */ private List<IndividualCertFile> individualCertFileList; /* 资质证明材料 */ // Constructor public IndividualCustDTO() { } /** * full Constructor */ public IndividualCustDTO(Long memberId, String name, Integer certType, String certCode, Integer status, Date authTime, Date createTime, Date modTime, Long createMemberId, Long createAcctId, String createName) { this.memberId = memberId; this.name = name; this.certType = certType; this.certCode = certCode; this.status = status; this.authTime = authTime; this.createTime = createTime; this.modTime = modTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCertType() { return certType; } public void setCertType(Integer certType) { this.certType = certType; } public String getCertCode() { return certCode; } public void setCertCode(String certCode) { this.certCode = certCode; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getAuthTime() { return authTime; } public void setAuthTime(Date authTime) { this.authTime = authTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getModTime() { return modTime; } public void setModTime(Date modTime) { this.modTime = modTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public Long getCertInfoId() { return certInfoId; } public void setCertInfoId(Long certInfoId) { this.certInfoId = certInfoId; } public String getCertNo() { return certNo; } public void setCertNo(String certNo) { this.certNo = certNo; } public String getCertName() { return certName; } public void setCertName(String certName) { this.certName = certName; } public List<IndividualCertFile> getIndividualCertFileList() { return individualCertFileList; } public void setIndividualCertFileList(List<IndividualCertFile> individualCertFileList) { this.individualCertFileList = individualCertFileList; } @Override public String toString() { return "IndividualCustDTO [" + "memberId=" + memberId + ", name=" + name + ", certType=" + certType + ", certCode=" + certCode + ", status=" + status + ", authTime=" + authTime + ", createTime=" + createTime + ", modTime=" + modTime + ", createMemberId=" + createMemberId + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/DeliverAddressServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.dto.DeliverAddressDTO; import cn.enn.ygego.sunny.user.dto.vo.BaseQueryVO; import cn.enn.ygego.sunny.user.service.DeliverAddressService; import cn.enn.ygego.sunny.user.dao.DeliverAddressDao; import cn.enn.ygego.sunny.user.model.DeliverAddress; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:DeliverAddress * @author gencode * @date 2018-3-22 */ @Service public class DeliverAddressServiceImpl implements DeliverAddressService{ @Autowired private DeliverAddressDao deliverAddressDao; public List<DeliverAddress> findAll(){ return deliverAddressDao.findAll(); } public List<DeliverAddress> findDeliverAddresss(DeliverAddress record){ return deliverAddressDao.find(record); } public List<DeliverAddressDTO> findDeliverAddresssPage(BaseQueryVO record) { return deliverAddressDao.findPage(record); } public DeliverAddress getDeliverAddressByPrimaryKey(Long deliverAddressId){ return deliverAddressDao.getByPrimaryKey(deliverAddressId); } public Integer createDeliverAddress(DeliverAddress record){ return deliverAddressDao.insert(record); } public Integer removeDeliverAddress(DeliverAddress record){ return deliverAddressDao.delete(record); } public Integer removeByPrimaryKey(Long deliverAddressId){ return deliverAddressDao.deleteByPrimaryKey(deliverAddressId); } public Integer modifyDeliverAddressByPrimaryKey(DeliverAddress record){ return deliverAddressDao.updateByPrimaryKey(record); } public Integer getCount(DeliverAddress record){ return deliverAddressDao.getCount(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/ThirdLoginConfigDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.dto.login.ThirdLoginConfigResponse; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.ThirdLoginConfig; /** * dal Interface:ThirdLoginConfig * @author gencode */ public interface ThirdLoginConfigDao { Integer insert(ThirdLoginConfig record); Integer insertSelective(ThirdLoginConfig record); Integer delete(ThirdLoginConfig record); Integer deleteByPrimaryKey(@Param("configId") Long configId); Integer updateByPrimaryKey(ThirdLoginConfig record); List<ThirdLoginConfig> findAll(); List<ThirdLoginConfig> find(ThirdLoginConfig record); Integer getCount(ThirdLoginConfig record); ThirdLoginConfig getByPrimaryKey(@Param("configId") Long configId); /** * 获取可用第三方登陆配置信息 * @return */ List<ThirdLoginConfigResponse> findEnabledConfigs(); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntStoreService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntStore; /** * dal Interface:EntStore * @author gencode * @date 2018-3-28 */ public interface EntStoreService { public List<EntStore> findAll(); public List<EntStore> findEntStores(EntStore record); public EntStore getEntStoreByPrimaryKey(Long storeId); public Integer createEntStore(EntStore record); public Integer removeEntStore(EntStore record); public Integer removeByPrimaryKey(Long storeId); public Integer modifyEntStoreByPrimaryKey(EntStore record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntDomainPermitService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntDomainPermit; /** * dal Interface:EntDomainPermit * @author gencode * @date 2018-3-28 */ public interface EntDomainPermitService { public List<EntDomainPermit> findAll(); public List<EntDomainPermit> findEntDomainPermits(EntDomainPermit record); public EntDomainPermit getEntDomainPermitByPrimaryKey(Long domainPermitId); public Integer createEntDomainPermit(EntDomainPermit record); public Integer removeEntDomainPermit(EntDomainPermit record); public Integer removeByPrimaryKey(Long domainPermitId); public Integer modifyEntDomainPermitByPrimaryKey(EntDomainPermit record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntAuthTypeApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntAuthTypeApply; /** * dal Interface:EntAuthTypeApply * @author gencode * @date 2018-3-28 */ public interface EntAuthTypeApplyService { public List<EntAuthTypeApply> findAll(); public List<EntAuthTypeApply> findEntAuthTypeApplys(EntAuthTypeApply record); public EntAuthTypeApply getEntAuthTypeApplyByPrimaryKey(Long authApplyId); public Integer createEntAuthTypeApply(EntAuthTypeApply record); public Integer removeEntAuthTypeApply(EntAuthTypeApply record); public Integer removeByPrimaryKey(Long authApplyId); public Integer modifyEntAuthTypeApplyByPrimaryKey(EntAuthTypeApply record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/MarketStorageApplyInfoService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketStorageApplyInfo; import org.springframework.stereotype.Repository; /** * ClassName: MarketStorageApplyInfo * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketStorageApplyInfoService { public List<MarketStorageApplyInfo> findAll(); public List<MarketStorageApplyInfo> findMarketStorageApplyInfos(MarketStorageApplyInfo record); public MarketStorageApplyInfo getMarketStorageApplyInfoByPrimaryKey(Long storageApplyId); public Integer deleteByPrimaryKey(Long storageApplyId); public Integer createMarketStorageApplyInfo(MarketStorageApplyInfo record); public Integer deleteMarketStorageApplyInfo(MarketStorageApplyInfo record); public Integer removeMarketStorageApplyInfo(MarketStorageApplyInfo record); public Integer updateMarketStorageApplyInfoByPrimaryKeySelective(MarketStorageApplyInfo record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntBrandApplyCertFileServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntBrandApplyCertFileService; import cn.enn.ygego.sunny.user.dao.EntBrandApplyCertFileDao; import cn.enn.ygego.sunny.user.model.EntBrandApplyCertFile; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntBrandApplyCertFile * @author gencode * @date 2018-3-28 */ @Service public class EntBrandApplyCertFileServiceImpl implements EntBrandApplyCertFileService{ @Autowired private EntBrandApplyCertFileDao entBrandApplyCertFileDao; public List<EntBrandApplyCertFile> findAll(){ return entBrandApplyCertFileDao.findAll(); } public List<EntBrandApplyCertFile> findEntBrandApplyCertFiles(EntBrandApplyCertFile record){ return entBrandApplyCertFileDao.find(record); } public EntBrandApplyCertFile getEntBrandApplyCertFileByPrimaryKey(Long certApplyFileId){ return entBrandApplyCertFileDao.getByPrimaryKey(certApplyFileId); } public Integer createEntBrandApplyCertFile(EntBrandApplyCertFile record){ return entBrandApplyCertFileDao.insert(record); } public Integer removeEntBrandApplyCertFile(EntBrandApplyCertFile record){ return entBrandApplyCertFileDao.delete(record); } public Integer removeByPrimaryKey(Long certApplyFileId){ return entBrandApplyCertFileDao.deleteByPrimaryKey(certApplyFileId); } public Integer modifyEntBrandApplyCertFileByPrimaryKey(EntBrandApplyCertFile record){ return entBrandApplyCertFileDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntCustInfoService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntCustInfo; /** * dal Interface:EntCustInfo * @author gencode * @date 2018-3-28 */ public interface EntCustInfoService { public List<EntCustInfo> findAll(); public List<EntCustInfo> findEntCustInfos(EntCustInfo record); public EntCustInfo getEntCustInfoByPrimaryKey(Long memberId); public Integer createEntCustInfo(EntCustInfo record); public Integer removeEntCustInfo(EntCustInfo record); public Integer removeByPrimaryKey(Long memberId); public Integer modifyEntCustInfoByPrimaryKey(EntCustInfo record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/RelaChannelToRoleServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.RelaChannelToRoleService; import cn.enn.ygego.sunny.user.dao.RelaChannelToRoleDao; import cn.enn.ygego.sunny.user.model.RelaChannelToRole; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:RelaChannelToRole * @author gencode * @date 2018-3-22 */ @Service public class RelaChannelToRoleServiceImpl implements RelaChannelToRoleService{ @Autowired private RelaChannelToRoleDao relaChannelToRoleDao; public List<RelaChannelToRole> findAll(){ return relaChannelToRoleDao.findAll(); } public List<RelaChannelToRole> findRelaChannelToRoles(RelaChannelToRole record){ return relaChannelToRoleDao.find(record); } public RelaChannelToRole getRelaChannelToRoleByPrimaryKey(Long relaId){ return relaChannelToRoleDao.getByPrimaryKey(relaId); } public Integer createRelaChannelToRole(RelaChannelToRole record){ return relaChannelToRoleDao.insert(record); } public Integer removeRelaChannelToRole(RelaChannelToRole record){ return relaChannelToRoleDao.delete(record); } public Integer removeByPrimaryKey(Long relaId){ return relaChannelToRoleDao.deleteByPrimaryKey(relaId); } public Integer modifyRelaChannelToRoleByPrimaryKey(RelaChannelToRole record){ return relaChannelToRoleDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualCertApplyDetailService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualCertApplyDetail; /** * dal Interface:IndividualCertApplyDetail * @author gencode * @date 2018-3-22 */ public interface IndividualCertApplyDetailService { public List<IndividualCertApplyDetail> findAll(); public List<IndividualCertApplyDetail> findIndividualCertApplyDetails(IndividualCertApplyDetail record); public IndividualCertApplyDetail getIndividualCertApplyDetailByPrimaryKey(Long certApplyDetailId); public Integer createIndividualCertApplyDetail(IndividualCertApplyDetail record); public Integer removeIndividualCertApplyDetail(IndividualCertApplyDetail record); public Integer removeByPrimaryKey(Long certApplyDetailId); public Integer modifyIndividualCertApplyDetailByPrimaryKey(IndividualCertApplyDetail record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/gridSupermarket/DictTreeDTO.java package cn.enn.ygego.sunny.user.dto.gridSupermarket; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * ClassName: DictTreeDTO * Description: 字典DTO * Author: 杨超 * Date: 2018/3/30 14:58 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class DictTreeDTO implements Serializable { /** * */ private static final long serialVersionUID = 2477787274313954535L; private DictTreeDTO parentNode; // 父节点 private String dictTreeCode; // 节点标识 private String parentCode; // 上级节点标识 private String dictTreeName; // 节点名称 private String iconUrl; /*图标*/ private List<DictTreeDTO> children = new ArrayList<DictTreeDTO>(); // 子节点 // Constructor public DictTreeDTO() { this.children = new ArrayList<DictTreeDTO>(); } public List<DictTreeDTO> getChildren() { return children; } public void setChildren(List<DictTreeDTO> children) { this.children = children; } public DictTreeDTO getParentNode() { return parentNode; } public void setParentNode(DictTreeDTO parentNode) { this.parentNode = parentNode; } public String getParentCode() { return parentCode; } public void setParentCode(String parentCode) { this.parentCode = parentCode; } public String getDictTreeCode() { return dictTreeCode; } public void setDictTreeCode(String dictTreeCode) { this.dictTreeCode = dictTreeCode; } public String getDictTreeName() { return dictTreeName; } public void setDictTreeName(String dictTreeName) { this.dictTreeName = dictTreeName; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } @Override public boolean equals(Object obj) { if (obj instanceof DictTreeDTO) { DictTreeDTO dictTree = (DictTreeDTO)obj; return dictTree.getDictTreeCode().equals(this.getDictTreeCode()); } return false; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualBrandCertFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualBrandCertFile; /** * dal Interface:IndividualBrandCertFile * @author gencode * @date 2018-3-22 */ public interface IndividualBrandCertFileService { public List<IndividualBrandCertFile> findAll(); public List<IndividualBrandCertFile> findIndividualBrandCertFiles(IndividualBrandCertFile record); public IndividualBrandCertFile getIndividualBrandCertFileByPrimaryKey(Long certApplyFileId); public Integer createIndividualBrandCertFile(IndividualBrandCertFile record); public Integer removeIndividualBrandCertFile(IndividualBrandCertFile record); public Integer removeByPrimaryKey(Long certApplyFileId); public Integer modifyIndividualBrandCertFileByPrimaryKey(IndividualBrandCertFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketAuthInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketAuthInfo; import org.springframework.stereotype.Repository; /** * ClassName: MarketAuthInfo * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketAuthInfoDao { List<MarketAuthInfo> selectAll(); List<MarketAuthInfo> select(MarketAuthInfo record); Integer selectCount(MarketAuthInfo record); MarketAuthInfo selectByPrimaryKey(Long authId); Integer deleteByPrimaryKey(Long authId); Integer delete(MarketAuthInfo record); Integer insertSelective(MarketAuthInfo record); Integer updateByPrimaryKeySelective(MarketAuthInfo record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/RelaChannelToRole.java package cn.enn.ygego.sunny.user.model; import java.io.Serializable; /** * entity:RelaChannelToRole * * @author gencode */ public class RelaChannelToRole implements Serializable { private static final long serialVersionUID = -8823988970810440385L; private Long relaId; /* 关系ID */ private Long channelId; /* 渠道ID */ private Long roleId; /* 角色标识 */ // Constructor public RelaChannelToRole() { } /** * full Constructor */ public RelaChannelToRole(Long relaId, Long channelId, Long roleId) { this.relaId = relaId; this.channelId = channelId; this.roleId = roleId; } public Long getRelaId() { return relaId; } public void setRelaId(Long relaId) { this.relaId = relaId; } public Long getChannelId() { return channelId; } public void setChannelId(Long channelId) { this.channelId = channelId; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } @Override public String toString() { return "RelaChannelToRole [" + "relaId=" + relaId+ ", channelId=" + channelId+ ", roleId=" + roleId+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/MarketStockAlertSetService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketStockAlertSet; import org.springframework.stereotype.Repository; /** * ClassName: MarketStockAlertSet * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketStockAlertSetService { public List<MarketStockAlertSet> findAll(); public List<MarketStockAlertSet> findMarketStockAlertSets(MarketStockAlertSet record); public MarketStockAlertSet getMarketStockAlertSetByPrimaryKey(Long alertSetId); public Integer deleteByPrimaryKey(Long alertSetId); public Integer createMarketStockAlertSet(MarketStockAlertSet record); public Integer deleteMarketStockAlertSet(MarketStockAlertSet record); public Integer removeMarketStockAlertSet(MarketStockAlertSet record); public Integer updateMarketStockAlertSetByPrimaryKeySelective(MarketStockAlertSet record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/QuestionFeedbackDTO.java package cn.enn.ygego.sunny.user.dto; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.user.model.QuestionAttach; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.Date; import java.io.Serializable; import java.util.List; /** * DTO:QuestionFeedback * * @author gencode * @date 2018-3-19 */ @ApiModel(description = "用于查询反馈信息的条件描述类") public class QuestionFeedbackDTO implements Serializable { private static final long serialVersionUID = 677027359325754786L; @ApiModelProperty("问题ID") private Long questionId; /* 问题ID */ @ApiModelProperty("问题类型") private Integer questionType; /* 问题类型 */ @ApiModelProperty("问题编号") private String questionCode; /* 问题编号 */ @ApiModelProperty("问题网址") private String questionUrl; /* 问题网址 */ @ApiModelProperty("问题模块") private String questionModule; /* 问题模块 */ @ApiModelProperty("问题描述") private String questionDesc; /* 问题描述 */ @ApiModelProperty("企业名称") private String entName; /* 企业名称 */ @ApiModelProperty("是否回复") private Integer isResponse; /* 是否回复 */ @ApiModelProperty("状态") private Integer status; /* 状态 */ @ApiModelProperty("联系人") private String contact; /* 联系人 */ @ApiModelProperty("联系电话") private String contactTel; /* 联系电话 */ @ApiModelProperty("电子邮件") private String email; /* 电子邮件 */ @ApiModelProperty("创建时间") private Date createTime; /* 创建时间 */ @ApiModelProperty("创建人会员ID") private Long createMemberId; /* 创建人会员ID */ @ApiModelProperty("创建人账户ID") private Long createAcctId; /* 创建人账户ID */ @ApiModelProperty("创建人姓名") private String createName; /* 创建人姓名 */ @ApiModelProperty("上传附件信息") private List<QuestionAttachDTO> attachList = new ArrayList<>(); private List<QuestionResponseDTO> responseList = new ArrayList<>(); public List<QuestionResponseDTO> getResponseList() { return responseList; } public void setResponseList(List<QuestionResponseDTO> responseList) { this.responseList = responseList; } public List<QuestionAttachDTO> getAttachList() { return attachList; } public void setAttachList(List<QuestionAttachDTO> attachList) { this.attachList = attachList; this.responseList = new ArrayList<>(); } // Constructor public QuestionFeedbackDTO() { this.attachList = new ArrayList<>(); this.responseList = new ArrayList<>(); } /** * full Constructor */ public QuestionFeedbackDTO(Long questionId, Integer questionType, String questionCode, String questionUrl, String questionModule, String questionDesc, String entName, Integer isResponse, Integer status, String contact, String contactTel, String email, Date createTime, Long createMemberId, Long createAcctId, String createName) { this.questionId = questionId; this.questionType = questionType; this.questionCode = questionCode; this.questionUrl = questionUrl; this.questionModule = questionModule; this.questionDesc = questionDesc; this.entName = entName; this.isResponse = isResponse; this.status = status; this.contact = contact; this.contactTel = contactTel; this.email = email; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getQuestionId() { return questionId; } public void setQuestionId(Long questionId) { this.questionId = questionId; } public Integer getQuestionType() { return questionType; } public void setQuestionType(Integer questionType) { this.questionType = questionType; } public String getQuestionCode() { return questionCode; } public void setQuestionCode(String questionCode) { this.questionCode = questionCode; } public String getQuestionUrl() { return questionUrl; } public void setQuestionUrl(String questionUrl) { this.questionUrl = questionUrl; } public String getQuestionModule() { return questionModule; } public void setQuestionModule(String questionModule) { this.questionModule = questionModule; } public String getQuestionDesc() { return questionDesc; } public void setQuestionDesc(String questionDesc) { this.questionDesc = questionDesc; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public String getEntName() { return entName; } public void setEntName(String entName) { this.entName = entName; } public Integer getIsResponse() { return isResponse; } public void setIsResponse(Integer isResponse) { this.isResponse = isResponse; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "QuestionFeedbackDTO [" + "questionId=" + questionId + ", questionType=" + questionType + ", questionCode=" + questionCode + ", questionUrl=" + questionUrl + ", questionModule=" + questionModule + ", questionDesc=" + questionDesc + ", status=" + status + ", contact=" + contact + ", contactTel=" + contactTel + ", createTime=" + createTime + ", createMemberId=" + createMemberId + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/OperManageServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.OperManageService; import cn.enn.ygego.sunny.user.dao.OperManageDao; import cn.enn.ygego.sunny.user.model.OperManage; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:OperManage * @author gencode * @date 2018-3-22 */ @Service public class OperManageServiceImpl implements OperManageService{ @Autowired private OperManageDao operManageDao; public List<OperManage> findAll(){ return operManageDao.findAll(); } public List<OperManage> findOperManages(OperManage record){ return operManageDao.find(record); } public OperManage getOperManageByPrimaryKey(Long operId){ return operManageDao.getByPrimaryKey(operId); } public Integer createOperManage(OperManage record){ return operManageDao.insert(record); } public Integer removeOperManage(OperManage record){ return operManageDao.delete(record); } public Integer removeByPrimaryKey(Long operId){ return operManageDao.deleteByPrimaryKey(operId); } public Integer modifyOperManageByPrimaryKey(OperManage record){ return operManageDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/QuestionResponseServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.QuestionResponseService; import cn.enn.ygego.sunny.user.dao.QuestionResponseDao; import cn.enn.ygego.sunny.user.model.QuestionResponse; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:QuestionResponse * @author gencode * @date 2018-3-22 */ @Service public class QuestionResponseServiceImpl implements QuestionResponseService{ @Autowired private QuestionResponseDao questionResponseDao; public List<QuestionResponse> findAll(){ return questionResponseDao.findAll(); } public List<QuestionResponse> findQuestionResponses(QuestionResponse record){ return questionResponseDao.find(record); } public QuestionResponse getQuestionResponseByPrimaryKey(Long responseId){ return questionResponseDao.getByPrimaryKey(responseId); } public Integer createQuestionResponse(QuestionResponse record){ return questionResponseDao.insert(record); } public Integer removeQuestionResponse(QuestionResponse record){ return questionResponseDao.delete(record); } public Integer removeByPrimaryKey(Long responseId){ return questionResponseDao.deleteByPrimaryKey(responseId); } public Integer modifyQuestionResponseByPrimaryKey(QuestionResponse record){ return questionResponseDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/login/ThirdLoginBaseParam.java package cn.enn.ygego.sunny.user.dto.login; import java.io.Serializable; /** * 第三方登陆基本参数信息 * Created by dongbb on 2018/3/30. */ public class ThirdLoginBaseParam implements Serializable { private Long configId; //配置ID private String thirdLoginUri; //请求登陆第三方地址 public Long getConfigId() { return configId; } public void setConfigId(Long configId) { this.configId = configId; } public String getThirdLoginUri() { return thirdLoginUri; } public void setThirdLoginUri(String thirdLoginUri) { this.thirdLoginUri = thirdLoginUri; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/InspectAuditLog.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:InspectAuditLog * * @author gencode */ public class InspectAuditLog implements Serializable { private static final long serialVersionUID = 1025667203195373232L; private Long logId; /* 日志ID */ private Long applyId; /* 申请标识 */ private Integer applyStatus; /* 申请状态 */ private String logDesc; /* 日志描述 */ private Date createTime; /* 创建时间 */ // Constructor public InspectAuditLog() { } /** * full Constructor */ public InspectAuditLog(Long logId, Long applyId, Integer applyStatus, String logDesc, Date createTime) { this.logId = logId; this.applyId = applyId; this.applyStatus = applyStatus; this.logDesc = logDesc; this.createTime = createTime; } public Long getLogId() { return logId; } public void setLogId(Long logId) { this.logId = logId; } public Long getApplyId() { return applyId; } public void setApplyId(Long applyId) { this.applyId = applyId; } public Integer getApplyStatus() { return applyStatus; } public void setApplyStatus(Integer applyStatus) { this.applyStatus = applyStatus; } public String getLogDesc() { return logDesc; } public void setLogDesc(String logDesc) { this.logDesc = logDesc; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "InspectAuditLog [" + "logId=" + logId+ ", applyId=" + applyId+ ", applyStatus=" + applyStatus+ ", logDesc=" + logDesc+ ", createTime=" + createTime+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketCateMaterialApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketCateMaterialApply; import org.springframework.stereotype.Repository; /** * ClassName: MarketCateMaterialApply * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketCateMaterialApplyDao { List<MarketCateMaterialApply> selectAll(); List<MarketCateMaterialApply> select(MarketCateMaterialApply record); Integer selectCount(MarketCateMaterialApply record); MarketCateMaterialApply selectByPrimaryKey(Long applyId); Integer deleteByPrimaryKey(Long applyId); Integer delete(MarketCateMaterialApply record); Integer insertSelective(MarketCateMaterialApply record); Integer updateByPrimaryKeySelective(MarketCateMaterialApply record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/BaseManage/InvioceTaxController.java package cn.enn.ygego.sunny.user.controller.BaseManage; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.user.dto.EntTaxRateDTO; import cn.enn.ygego.sunny.user.dto.vo.EntTaxRateVO; import cn.enn.ygego.sunny.user.service.InvioceTaxService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/base/tax") @Api(value="发票税率管理", description = "发票税率管理") public class InvioceTaxController { Logger logger = LoggerFactory.getLogger(InvioceTaxController.class); @Autowired private InvioceTaxService invioceTaxService; /** * @Description * @author liangchao * @date 2018/3/30 11:07 * @param jsonRequest * @return */ @ApiOperation(value="新建发票税率接口") @RequestMapping(value = "/createInvoiceTax", method = {RequestMethod.POST}) @ResponseBody public JsonResponse createInvoiceTax(@RequestBody JsonRequest<EntTaxRateDTO> jsonRequest) {//参数问题反馈对象 JsonResponse jsonResponse = new JsonResponse(); try{ EntTaxRateDTO entTaxRateDTO = jsonRequest.getReqBody(); invioceTaxService.insertInvoiceTax(entTaxRateDTO); } catch (Exception e) { logger.error("新建发票税率失败", e.getMessage()); jsonResponse.setRetCode("0111111"); jsonResponse.setRetDesc(e.getMessage()); } return jsonResponse; } /** * @Description * @author liangchao * @date 2018/3/30 11:07 * @param jsonRequest * @return */ @ApiOperation(value="查询发票税率信息接口") @RequestMapping(value = "/queryInvoiceTaxInfo", method = { RequestMethod.POST }) @ResponseBody public JsonResponse queryInvoiceTaxInfo(@RequestBody JsonRequest<EntTaxRateVO> jsonRequest) {//参数问题反馈对象 JsonResponse jsonResponse = new JsonResponse(); try { EntTaxRateVO entTaxRateVO = jsonRequest.getReqBody(); EntTaxRateDTO entTaxRateDTO = invioceTaxService.queryInvoiceTaxInfo(entTaxRateVO); jsonResponse.setRspBody(entTaxRateDTO); } catch (Exception e) { logger.error("查询发票税率信息失败", e.getMessage()); jsonResponse.setRetCode("0111111"); jsonResponse.setRetDesc(e.getMessage()); } return jsonResponse; } // @ApiOperation(value="查询发票税率列表") // @RequestMapping("/queryInvoiceTaxList") // @ResponseBody public JsonResponse queryInvoiceTaxList(@RequestBody JsonRequest<EntTaxRateDTO> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); return jsonResponse; } @ApiOperation(value="修改发票税率信息") @RequestMapping(value = "/modifyInvoiceTax", method = { RequestMethod.POST }) //Information details @ResponseBody public JsonResponse modifyInvoiceTax(@RequestBody JsonRequest<EntTaxRateDTO> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { EntTaxRateDTO entTaxRateDTO = jsonRequest.getReqBody(); invioceTaxService.modifyInvoiceTax(entTaxRateDTO); } catch (Exception e) { logger.error("修改发票税率信息失败", e.getMessage()); jsonResponse.setRetCode("0111111"); jsonResponse.setRetDesc(e.getMessage()); } return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/InspectFactoryMaterialService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.InspectFactoryMaterial; /** * dal Interface:InspectFactoryMaterial * @author gencode * @date 2018-3-30 */ public interface InspectFactoryMaterialService { public List<InspectFactoryMaterial> findAll(); public List<InspectFactoryMaterial> findInspectFactoryMaterials(InspectFactoryMaterial record); public InspectFactoryMaterial getInspectFactoryMaterialByPrimaryKey(Long inspectMaterialId); public Integer createInspectFactoryMaterial(InspectFactoryMaterial record); public Integer removeInspectFactoryMaterial(InspectFactoryMaterial record); public Integer removeByPrimaryKey(Long inspectMaterialId); public Integer modifyInspectFactoryMaterialByPrimaryKey(InspectFactoryMaterial record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntTaxRateDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.dto.EntTaxRateDTO; import cn.enn.ygego.sunny.user.dto.vo.EntTaxRateVO; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntTaxRate; /** * dal Interface:EntTaxRate * @author gencode */ public interface EntTaxRateDao { Integer insert(EntTaxRate record); Integer insertSelective(EntTaxRate record); Integer delete(EntTaxRate record); Integer deleteByPrimaryKey(@Param("taxRateId") Long taxRateId); Integer updateByPrimaryKey(EntTaxRate record); List<EntTaxRate> findAll(); List<EntTaxRate> find(EntTaxRate record); Integer getCount(EntTaxRate record); EntTaxRate getByPrimaryKey(@Param("taxRateId") Long taxRateId); List<EntTaxRate> findPage(EntTaxRateVO entTaxRateVO); EntTaxRateDTO getByMemberId(Long memberId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/AuthLog.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:AuthLog * * @author gencode */ public class AuthLog implements Serializable { private static final long serialVersionUID = 5961396844296826092L; private Long logId; /* 日志标识 */ private String logCode; /* 日志编码 */ private Long appId; /* 应用标识 */ private String appName; /* 应用名称 */ private Long serviceId; /* 服务标识 */ private String serviceCode; /* 服务编码 */ private String serviceName; /* 服务名称 */ private Long functionId; /* 功能标识 */ private String functionTitle; /* 功能名称 */ private Long operId; /* 操作标识 */ private String operTitle; /* 操作名称 */ private Integer authType; /* 鉴权类型 */ private Integer authenticationResult; /* 鉴权结果 */ private String acctCode; /* 账户编码 */ private Long operPersonId; /* 操作人标识 */ private String operPersonName; /* 操作人姓名 */ private String logContent; /* 日志内容 */ private Date createTime; /* 创建时间 */ // Constructor public AuthLog() { } /** * full Constructor */ public AuthLog(Long logId, String logCode, Long appId, String appName, Long serviceId, String serviceCode, String serviceName, Long functionId, String functionTitle, Long operId, String operTitle, Integer authType, Integer authenticationResult, String acctCode, Long operPersonId, String operPersonName, String logContent, Date createTime) { this.logId = logId; this.logCode = logCode; this.appId = appId; this.appName = appName; this.serviceId = serviceId; this.serviceCode = serviceCode; this.serviceName = serviceName; this.functionId = functionId; this.functionTitle = functionTitle; this.operId = operId; this.operTitle = operTitle; this.authType = authType; this.authenticationResult = authenticationResult; this.acctCode = acctCode; this.operPersonId = operPersonId; this.operPersonName = operPersonName; this.logContent = logContent; this.createTime = createTime; } public Long getLogId() { return logId; } public void setLogId(Long logId) { this.logId = logId; } public String getLogCode() { return logCode; } public void setLogCode(String logCode) { this.logCode = logCode; } public Long getAppId() { return appId; } public void setAppId(Long appId) { this.appId = appId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public Long getServiceId() { return serviceId; } public void setServiceId(Long serviceId) { this.serviceId = serviceId; } public String getServiceCode() { return serviceCode; } public void setServiceCode(String serviceCode) { this.serviceCode = serviceCode; } public String getServiceName() { return serviceName; } public void setServiceName(String serviceName) { this.serviceName = serviceName; } public Long getFunctionId() { return functionId; } public void setFunctionId(Long functionId) { this.functionId = functionId; } public String getFunctionTitle() { return functionTitle; } public void setFunctionTitle(String functionTitle) { this.functionTitle = functionTitle; } public Long getOperId() { return operId; } public void setOperId(Long operId) { this.operId = operId; } public String getOperTitle() { return operTitle; } public void setOperTitle(String operTitle) { this.operTitle = operTitle; } public Integer getAuthType() { return authType; } public void setAuthType(Integer authType) { this.authType = authType; } public Integer getAuthenticationResult() { return authenticationResult; } public void setAuthenticationResult(Integer authenticationResult) { this.authenticationResult = authenticationResult; } public String getAcctCode() { return acctCode; } public void setAcctCode(String acctCode) { this.acctCode = acctCode; } public Long getOperPersonId() { return operPersonId; } public void setOperPersonId(Long operPersonId) { this.operPersonId = operPersonId; } public String getOperPersonName() { return operPersonName; } public void setOperPersonName(String operPersonName) { this.operPersonName = operPersonName; } public String getLogContent() { return logContent; } public void setLogContent(String logContent) { this.logContent = logContent; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "AuthLog [" + "logId=" + logId+ ", logCode=" + logCode+ ", appId=" + appId+ ", appName=" + appName+ ", serviceId=" + serviceId+ ", serviceCode=" + serviceCode+ ", serviceName=" + serviceName+ ", functionId=" + functionId+ ", functionTitle=" + functionTitle+ ", operId=" + operId+ ", operTitle=" + operTitle+ ", authType=" + authType+ ", authenticationResult=" + authenticationResult+ ", acctCode=" + acctCode+ ", operPersonId=" + operPersonId+ ", operPersonName=" + operPersonName+ ", logContent=" + logContent+ ", createTime=" + createTime+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/QuestionResponseVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.util.Date; import java.util.List; /** * ClassName: QuestionResponseVO * Description: * Author: liangchao * Date: 2018/3/24 18:13 * History: * <author> <time> <version> <desc> * liangc 修改时间 0.0.1 描述 */ public class QuestionResponseVO implements Serializable { private static final long serialVersionUID = 4872046679596451292L; private Long responseId; /* 回复ID */ private Long questionId; /* 问题ID */ private String responseContent; /* 回复内容 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ private Integer status; /* 问题状态 */ private String email; /* 电子邮件 */ private List<Long> idList; /* idList */ public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getResponseId() { return responseId; } public void setResponseId(Long responseId) { this.responseId = responseId; } public Long getQuestionId() { return questionId; } public void setQuestionId(Long questionId) { this.questionId = questionId; } public String getResponseContent() { return responseContent; } public void setResponseContent(String responseContent) { this.responseContent = responseContent; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public List<Long> getIdList() { return idList; } public void setIdList(List<Long> idList) { this.idList = idList; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualBrandApplyCertServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualBrandApplyCertService; import cn.enn.ygego.sunny.user.dao.IndividualBrandApplyCertDao; import cn.enn.ygego.sunny.user.model.IndividualBrandApplyCert; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualBrandApplyCert * @author gencode * @date 2018-3-22 */ @Service public class IndividualBrandApplyCertServiceImpl implements IndividualBrandApplyCertService{ @Autowired private IndividualBrandApplyCertDao individualBrandApplyCertDao; public List<IndividualBrandApplyCert> findAll(){ return individualBrandApplyCertDao.findAll(); } public List<IndividualBrandApplyCert> findIndividualBrandApplyCerts(IndividualBrandApplyCert record){ return individualBrandApplyCertDao.find(record); } public IndividualBrandApplyCert getIndividualBrandApplyCertByPrimaryKey(Long brandApplyCertId){ return individualBrandApplyCertDao.getByPrimaryKey(brandApplyCertId); } public Integer createIndividualBrandApplyCert(IndividualBrandApplyCert record){ return individualBrandApplyCertDao.insert(record); } public Integer removeIndividualBrandApplyCert(IndividualBrandApplyCert record){ return individualBrandApplyCertDao.delete(record); } public Integer removeByPrimaryKey(Long brandApplyCertId){ return individualBrandApplyCertDao.deleteByPrimaryKey(brandApplyCertId); } public Integer modifyIndividualBrandApplyCertByPrimaryKey(IndividualBrandApplyCert record){ return individualBrandApplyCertDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MemberInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.dto.company.CompanyAuthInfo; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.MemberInfo; /** * dal Interface:MemberInfo * @author gencode */ public interface MemberInfoDao { Integer insert(MemberInfo record); Integer insertSelective(MemberInfo record); Integer delete(MemberInfo record); Integer deleteByPrimaryKey(@Param("memberId") Long memberId); Integer updateByPrimaryKey(MemberInfo record); List<MemberInfo> findAll(); List<MemberInfo> find(MemberInfo record); Integer getCount(MemberInfo record); MemberInfo getByPrimaryKey(@Param("memberId") Long memberId); /** * 根据acctId查询所有关联的审核通过并且可用的会员信息 * @param acctId 账号id * @return */ List<MemberInfo> findMemberInfosByAcctId(@Param("acctId") Long acctId); /** * 根据acctId查询所对应的个人会员信息 * @param acctId 账号id * @return */ MemberInfo findPersonMember(@Param("acctId") Long acctId); /** * 根据acctId查询所对应的企业信息以及企业对应的认证信息 * @param acctId 账号id * @return */ List<CompanyAuthInfo> findCompanyMember(@Param("acctId") Long acctId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/DeliverAddressDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:DeliverAddress * * @author gencode * @date 2018-3-22 */ public class DeliverAddressDTO implements Serializable { private static final long serialVersionUID = -5343668407419792405L; private Long deliverAddressId; /* 发货地址ID */ private Long memberId; /* 会员ID */ private Long areaId; /* 地区ID */ private String areaIdFullPath; /* 地区ID路径 */ private String areaNameFullPath; /* 地区名称路径 */ private String addressDetail; /* 详细地址 */ private String contact; /* 联系人 */ private String contactTel; /* 联系电话 */ private String fixedPhone; /* 固定电话 */ private Integer isDefaultDeliverAddr; /* 是否默认发货地 */ private Integer isDefaultRefundAddr; /* 是否默认退货地 */ private Date createTime; /* 创建时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public DeliverAddressDTO() { } /** * full Constructor */ public DeliverAddressDTO(Long deliverAddressId, Long memberId, Long areaId, String areaIdFullPath, String areaNameFullPath, String addressDetail, String contact, String contactTel, String fixedPhone, Integer isDefaultDeliverAddr, Integer isDefaultRefundAddr, Date createTime, Long createMemberId, Long createAcctId, String createName) { this.deliverAddressId = deliverAddressId; this.memberId = memberId; this.areaId = areaId; this.areaIdFullPath = areaIdFullPath; this.areaNameFullPath = areaNameFullPath; this.addressDetail = addressDetail; this.contact = contact; this.contactTel = contactTel; this.fixedPhone = fixedPhone; this.isDefaultDeliverAddr = isDefaultDeliverAddr; this.isDefaultRefundAddr = isDefaultRefundAddr; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getDeliverAddressId() { return deliverAddressId; } public void setDeliverAddressId(Long deliverAddressId) { this.deliverAddressId = deliverAddressId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getAreaIdFullPath() { return areaIdFullPath; } public void setAreaIdFullPath(String areaIdFullPath) { this.areaIdFullPath = areaIdFullPath; } public String getAreaNameFullPath() { return areaNameFullPath; } public void setAreaNameFullPath(String areaNameFullPath) { this.areaNameFullPath = areaNameFullPath; } public String getAddressDetail() { return addressDetail; } public void setAddressDetail(String addressDetail) { this.addressDetail = addressDetail; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel; } public String getFixedPhone() { return fixedPhone; } public void setFixedPhone(String fixedPhone) { this.fixedPhone = fixedPhone; } public Integer getIsDefaultDeliverAddr() { return isDefaultDeliverAddr; } public void setIsDefaultDeliverAddr(Integer isDefaultDeliverAddr) { this.isDefaultDeliverAddr = isDefaultDeliverAddr; } public Integer getIsDefaultRefundAddr() { return isDefaultRefundAddr; } public void setIsDefaultRefundAddr(Integer isDefaultRefundAddr) { this.isDefaultRefundAddr = isDefaultRefundAddr; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "DeliverAddressDTO [" + "deliverAddressId=" + deliverAddressId + ", memberId=" + memberId + ", areaId=" + areaId + ", areaIdFullPath=" + areaIdFullPath + ", areaNameFullPath=" + areaNameFullPath + ", addressDetail=" + addressDetail + ", contact=" + contact + ", contactTel=" + contactTel + ", fixedPhone=" + fixedPhone + ", isDefaultDeliverAddr=" + isDefaultDeliverAddr + ", isDefaultRefundAddr=" + isDefaultRefundAddr + ", createTime=" + createTime + ", createMemberId=" + createMemberId + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/RoleOperPrivRelaDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.RoleOperPrivRela; /** * dal Interface:RoleOperPrivRela * @author gencode */ public interface RoleOperPrivRelaDao { Integer insert(RoleOperPrivRela record); Integer insertSelective(RoleOperPrivRela record); Integer delete(RoleOperPrivRela record); Integer deleteByPrimaryKey(@Param("relaId") Long relaId); Integer updateByPrimaryKey(RoleOperPrivRela record); List<RoleOperPrivRela> findAll(); List<RoleOperPrivRela> find(RoleOperPrivRela record); Integer getCount(RoleOperPrivRela record); RoleOperPrivRela getByPrimaryKey(@Param("relaId") Long relaId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/MarketCateMaterialApplyService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketCateMaterialApply; import org.springframework.stereotype.Repository; /** * ClassName: MarketCateMaterialApply * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketCateMaterialApplyService { public List<MarketCateMaterialApply> findAll(); public List<MarketCateMaterialApply> findMarketCateMaterialApplys(MarketCateMaterialApply record); public MarketCateMaterialApply getMarketCateMaterialApplyByPrimaryKey(Long applyId); public Integer deleteByPrimaryKey(Long applyId); public Integer createMarketCateMaterialApply(MarketCateMaterialApply record); public Integer deleteMarketCateMaterialApply(MarketCateMaterialApply record); public Integer removeMarketCateMaterialApply(MarketCateMaterialApply record); public Integer updateMarketCateMaterialApplyByPrimaryKeySelective(MarketCateMaterialApply record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/MarketCateCertApply.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * ClassName: MarketCateCertApply * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class MarketCateCertApply implements Serializable { private Long certApplyDetailId; /* 资质申请明细ID */ private Long applyId; /* 申请ID */ private Integer certType; /* 资质类型 */ private Integer limitType; /* 期限类型 */ private Date certValidStartDate; /* 证件有效开始日期 */ private Date certValidEndDate; /* 证件有效截止日期 */ // Constructor public MarketCateCertApply() { } /** * full Constructor */ public MarketCateCertApply(Long certApplyDetailId, Long applyId, Integer certType, Integer limitType, Date certValidStartDate, Date certValidEndDate) { this.certApplyDetailId = certApplyDetailId; this.applyId = applyId; this.certType = certType; this.limitType = limitType; this.certValidStartDate = certValidStartDate; this.certValidEndDate = certValidEndDate; } public Long getCertApplyDetailId() { return certApplyDetailId; } public void setCertApplyDetailId(Long certApplyDetailId) { this.certApplyDetailId = certApplyDetailId; } public Long getApplyId() { return applyId; } public void setApplyId(Long applyId) { this.applyId = applyId; } public Integer getCertType() { return certType; } public void setCertType(Integer certType) { this.certType = certType; } public Integer getLimitType() { return limitType; } public void setLimitType(Integer limitType) { this.limitType = limitType; } public Date getCertValidStartDate() { return certValidStartDate; } public void setCertValidStartDate(Date certValidStartDate) { this.certValidStartDate = certValidStartDate; } public Date getCertValidEndDate() { return certValidEndDate; } public void setCertValidEndDate(Date certValidEndDate) { this.certValidEndDate = certValidEndDate; } @Override public String toString() { return "MarketCateCertApply [" + "certApplyDetailId=" + certApplyDetailId + ", applyId=" + applyId + ", certType=" + certType + ", limitType=" + limitType + ", certValidStartDate=" + certValidStartDate + ", certValidEndDate=" + certValidEndDate + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/AcctInfoServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.AcctInfoService; import cn.enn.ygego.sunny.user.dao.AcctInfoDao; import cn.enn.ygego.sunny.user.model.AcctInfo; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:AcctInfo * @author gencode * @date 2018-3-22 */ @Service public class AcctInfoServiceImpl implements AcctInfoService{ @Autowired private AcctInfoDao acctInfoDao; public List<AcctInfo> findAll(){ return acctInfoDao.findAll(); } public List<AcctInfo> findAcctInfos(AcctInfo record){ return acctInfoDao.find(record); } public AcctInfo getAcctInfoByPrimaryKey(Long acctId){ return acctInfoDao.getByPrimaryKey(acctId); } public Integer createAcctInfo(AcctInfo record){ return acctInfoDao.insert(record); } public Integer removeAcctInfo(AcctInfo record){ return acctInfoDao.delete(record); } public Integer removeByPrimaryKey(Long acctId){ return acctInfoDao.deleteByPrimaryKey(acctId); } public Integer modifyAcctInfoByPrimaryKey(AcctInfo record){ return acctInfoDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/MarketStorageApplyInfo.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * ClassName: MarketStorageApplyInfo * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class MarketStorageApplyInfo implements Serializable { private Long storageApplyId; /* 仓库申请ID */ private Long marketApplyId; /* 超市申请ID */ private Long memberId; /* 会员ID */ private Long marketId; /* 超市ID */ private String storageCode; /* 仓库编码 */ private String storageName; /* 仓库名称 */ private String contact; /* 联系人 */ private String contactTel; /* 联系电话 */ private String email; /* 电子邮件 */ private Integer status; /* 状态 */ private Long areaId; /* 地区ID */ private String areaIdFullPath; /* 地区ID路径 */ private String areaNameFullPath; /* 地区名称路径 */ private String addressDetail; /* 详细地址 */ private Integer insideArea; /* 室内面积 */ private Integer outsideArea; /* 室外面积 */ private Date createTime; /* 创建时间 */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public MarketStorageApplyInfo() { } /** * full Constructor */ public MarketStorageApplyInfo(Long storageApplyId, Long marketApplyId, Long memberId, Long marketId, String storageCode, String storageName, String contact, String contactTel, String email, Integer status, Long areaId, String areaIdFullPath, String areaNameFullPath, String addressDetail, Integer insideArea, Integer outsideArea, Date createTime, Long createAcctId, String createName) { this.storageApplyId = storageApplyId; this.marketApplyId = marketApplyId; this.memberId = memberId; this.marketId = marketId; this.storageCode = storageCode; this.storageName = storageName; this.contact = contact; this.contactTel = contactTel; this.email = email; this.status = status; this.areaId = areaId; this.areaIdFullPath = areaIdFullPath; this.areaNameFullPath = areaNameFullPath; this.addressDetail = addressDetail; this.insideArea = insideArea; this.outsideArea = outsideArea; this.createTime = createTime; this.createAcctId = createAcctId; this.createName = createName; } public Long getStorageApplyId() { return storageApplyId; } public void setStorageApplyId(Long storageApplyId) { this.storageApplyId = storageApplyId; } public Long getMarketApplyId() { return marketApplyId; } public void setMarketApplyId(Long marketApplyId) { this.marketApplyId = marketApplyId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getMarketId() { return marketId; } public void setMarketId(Long marketId) { this.marketId = marketId; } public String getStorageCode() { return storageCode; } public void setStorageCode(String storageCode) { this.storageCode = storageCode; } public String getStorageName() { return storageName; } public void setStorageName(String storageName) { this.storageName = storageName; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getAreaIdFullPath() { return areaIdFullPath; } public void setAreaIdFullPath(String areaIdFullPath) { this.areaIdFullPath = areaIdFullPath; } public String getAreaNameFullPath() { return areaNameFullPath; } public void setAreaNameFullPath(String areaNameFullPath) { this.areaNameFullPath = areaNameFullPath; } public String getAddressDetail() { return addressDetail; } public void setAddressDetail(String addressDetail) { this.addressDetail = addressDetail; } public Integer getInsideArea() { return insideArea; } public void setInsideArea(Integer insideArea) { this.insideArea = insideArea; } public Integer getOutsideArea() { return outsideArea; } public void setOutsideArea(Integer outsideArea) { this.outsideArea = outsideArea; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "MarketStorageApplyInfo [" + "storageApplyId=" + storageApplyId + ", marketApplyId=" + marketApplyId + ", memberId=" + memberId + ", marketId=" + marketId + ", storageCode=" + storageCode + ", storageName=" + storageName + ", contact=" + contact + ", contactTel=" + contactTel + ", email=" + email + ", status=" + status + ", areaId=" + areaId + ", areaIdFullPath=" + areaIdFullPath + ", areaNameFullPath=" + areaNameFullPath + ", addressDetail=" + addressDetail + ", insideArea=" + insideArea + ", outsideArea=" + outsideArea + ", createTime=" + createTime + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/BusiAcctInfoServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.BusiAcctInfoService; import cn.enn.ygego.sunny.user.dao.BusiAcctInfoDao; import cn.enn.ygego.sunny.user.model.BusiAcctInfo; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:BusiAcctInfo * @author gencode * @date 2018-3-22 */ @Service public class BusiAcctInfoServiceImpl implements BusiAcctInfoService{ @Autowired private BusiAcctInfoDao busiAcctInfoDao; public List<BusiAcctInfo> findAll(){ return busiAcctInfoDao.findAll(); } public List<BusiAcctInfo> findBusiAcctInfos(BusiAcctInfo record){ return busiAcctInfoDao.find(record); } public BusiAcctInfo getBusiAcctInfoByPrimaryKey(Long acctId){ return busiAcctInfoDao.getByPrimaryKey(acctId); } public Integer createBusiAcctInfo(BusiAcctInfo record){ return busiAcctInfoDao.insert(record); } public Integer removeBusiAcctInfo(BusiAcctInfo record){ return busiAcctInfoDao.delete(record); } public Integer removeByPrimaryKey(Long acctId){ return busiAcctInfoDao.deleteByPrimaryKey(acctId); } public Integer modifyBusiAcctInfoByPrimaryKey(BusiAcctInfo record){ return busiAcctInfoDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntChannelPermitServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntChannelPermitService; import cn.enn.ygego.sunny.user.dao.EntChannelPermitDao; import cn.enn.ygego.sunny.user.model.EntChannelPermit; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntChannelPermit * @author gencode * @date 2018-3-28 */ @Service public class EntChannelPermitServiceImpl implements EntChannelPermitService{ @Autowired private EntChannelPermitDao entChannelPermitDao; public List<EntChannelPermit> findAll(){ return entChannelPermitDao.findAll(); } public List<EntChannelPermit> findEntChannelPermits(EntChannelPermit record){ return entChannelPermitDao.find(record); } public EntChannelPermit getEntChannelPermitByPrimaryKey(Long channelPermitId){ return entChannelPermitDao.getByPrimaryKey(channelPermitId); } public Integer createEntChannelPermit(EntChannelPermit record){ return entChannelPermitDao.insert(record); } public Integer removeEntChannelPermit(EntChannelPermit record){ return entChannelPermitDao.delete(record); } public Integer removeByPrimaryKey(Long channelPermitId){ return entChannelPermitDao.deleteByPrimaryKey(channelPermitId); } public Integer modifyEntChannelPermitByPrimaryKey(EntChannelPermit record){ return entChannelPermitDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntTaxRateServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntTaxRateService; import cn.enn.ygego.sunny.user.dao.EntTaxRateDao; import cn.enn.ygego.sunny.user.model.EntTaxRate; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntTaxRate * @author gencode * @date 2018-3-28 */ @Service public class EntTaxRateServiceImpl implements EntTaxRateService{ @Autowired private EntTaxRateDao entTaxRateDao; public List<EntTaxRate> findAll(){ return entTaxRateDao.findAll(); } public List<EntTaxRate> findEntTaxRates(EntTaxRate record){ return entTaxRateDao.find(record); } public EntTaxRate getEntTaxRateByPrimaryKey(Long taxRateId){ return entTaxRateDao.getByPrimaryKey(taxRateId); } public Integer createEntTaxRate(EntTaxRate record){ return entTaxRateDao.insert(record); } public Integer removeEntTaxRate(EntTaxRate record){ return entTaxRateDao.delete(record); } public Integer removeByPrimaryKey(Long taxRateId){ return entTaxRateDao.deleteByPrimaryKey(taxRateId); } public Integer modifyEntTaxRateByPrimaryKey(EntTaxRate record){ return entTaxRateDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/IndividualDomainPermitApplyDTO.java package cn.enn.ygego.sunny.user.dto; import java.util.Date; import java.io.Serializable; /** * DTO:IndividualDomainPermitApply * * @author gencode * @date 2018-3-19 */ public class IndividualDomainPermitApplyDTO implements Serializable { private static final long serialVersionUID = 1153190787661314161L; private Long domainApplyId; /* 场申请ID */ private Long channelApplyId; /* 渠道申请ID */ private Long memberId; /* 会员ID */ private Long domainId; /* 场ID */ private Date createTime; /* 创建时间 */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public IndividualDomainPermitApplyDTO() { } /** * full Constructor */ public IndividualDomainPermitApplyDTO(Long domainApplyId, Long channelApplyId, Long memberId, Long domainId, Date createTime, Long createAcctId, String createName) { this.domainApplyId = domainApplyId; this.channelApplyId = channelApplyId; this.memberId = memberId; this.domainId = domainId; this.createTime = createTime; this.createAcctId = createAcctId; this.createName = createName; } public Long getDomainApplyId() { return domainApplyId; } public void setDomainApplyId(Long domainApplyId) { this.domainApplyId = domainApplyId; } public Long getChannelApplyId() { return channelApplyId; } public void setChannelApplyId(Long channelApplyId) { this.channelApplyId = channelApplyId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getDomainId() { return domainId; } public void setDomainId(Long domainId) { this.domainId = domainId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "IndividualDomainPermitApplyDTO [" + "domainApplyId=" + domainApplyId + ", channelApplyId=" + channelApplyId + ", memberId=" + memberId + ", domainId=" + domainId + ", createTime=" + createTime + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/OperAuthLoginLogDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.OperAuthLoginLog; /** * dal Interface:OperAuthLoginLog * @author gencode */ public interface OperAuthLoginLogDao { Integer insert(OperAuthLoginLog record); Integer insertSelective(OperAuthLoginLog record); Integer delete(OperAuthLoginLog record); Integer deleteByPrimaryKey(@Param("logId") Long logId); Integer updateByPrimaryKey(OperAuthLoginLog record); List<OperAuthLoginLog> findAll(); List<OperAuthLoginLog> find(OperAuthLoginLog record); Integer getCount(OperAuthLoginLog record); OperAuthLoginLog getByPrimaryKey(@Param("logId") Long logId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualServiceDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualService; /** * dal Interface:IndividualService * @author gencode */ public interface IndividualServiceDao { Integer insert(IndividualService record); Integer insertSelective(IndividualService record); Integer delete(IndividualService record); Integer deleteByPrimaryKey(@Param("serviceId") Long serviceId); Integer updateByPrimaryKey(IndividualService record); List<IndividualService> findAll(); List<IndividualService> find(IndividualService record); Integer getCount(IndividualService record); IndividualService getByPrimaryKey(@Param("serviceId") Long serviceId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/register/ChangePasswordRequest.java package cn.enn.ygego.sunny.user.dto.register; import java.io.Serializable; /** * 更改密码请求入参 * Created by dongbb on 2018/3/23. */ public class ChangePasswordRequest implements Serializable { private Long acctId; //账户id private String oldPassword; //原密码 private String newPassword; //新密码 public Long getAcctId() { return acctId; } public void setAcctId(Long acctId) { this.acctId = acctId; } public String getOldPassword() { return oldPassword; } public void setOldPassword(String oldPassword) { this.oldPassword = <PASSWORD>; } public String getNewPassword() { return newPassword; } public void setNewPassword(String newPassword) { this.newPassword = <PASSWORD>; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/supermarket/SupermarketDetailsVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.supermarket; import java.util.List; /** * ClassName: SupermarketDetailsVO * Description * Author zhangjiaqi * Date 2018-03-30 19:36 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-30 19:36 0.0.1 TODO */ public class SupermarketDetailsVO { // 超市名称 private String supermarketName; // 超市详情 private SupermarketInfoVO supermarketInfo; // 超市类目 private List<SupermarketCategoryVO> supermarketCategorys; public SupermarketDetailsVO() { super(); // TODO Auto-generated constructor stub } public SupermarketDetailsVO(String supermarketName, SupermarketInfoVO supermarketInfo, List<SupermarketCategoryVO> supermarketCategorys) { super(); this.supermarketName = supermarketName; this.supermarketInfo = supermarketInfo; this.supermarketCategorys = supermarketCategorys; } public String getSupermarketName() { return supermarketName; } public void setSupermarketName(String supermarketName) { this.supermarketName = supermarketName; } public SupermarketInfoVO getSupermarketInfo() { return supermarketInfo; } public void setSupermarketInfo(SupermarketInfoVO supermarketInfo) { this.supermarketInfo = supermarketInfo; } public List<SupermarketCategoryVO> getSupermarketCategorys() { return supermarketCategorys; } public void setSupermarketCategorys(List<SupermarketCategoryVO> supermarketCategorys) { this.supermarketCategorys = supermarketCategorys; } @Override public String toString() { return "SupermarketDetailsVO [supermarketName=" + supermarketName + ", supermarketInfo=" + supermarketInfo + ", supermarketCategorys=" + supermarketCategorys + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualBrandApplyCertService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualBrandApplyCert; /** * dal Interface:IndividualBrandApplyCert * @author gencode * @date 2018-3-22 */ public interface IndividualBrandApplyCertService { public List<IndividualBrandApplyCert> findAll(); public List<IndividualBrandApplyCert> findIndividualBrandApplyCerts(IndividualBrandApplyCert record); public IndividualBrandApplyCert getIndividualBrandApplyCertByPrimaryKey(Long brandApplyCertId); public Integer createIndividualBrandApplyCert(IndividualBrandApplyCert record); public Integer removeIndividualBrandApplyCert(IndividualBrandApplyCert record); public Integer removeByPrimaryKey(Long brandApplyCertId); public Integer modifyIndividualBrandApplyCertByPrimaryKey(IndividualBrandApplyCert record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntBrandApplyCertFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntBrandApplyCertFile; /** * dal Interface:EntBrandApplyCertFile * @author gencode */ public interface EntBrandApplyCertFileDao { Integer insert(EntBrandApplyCertFile record); Integer insertSelective(EntBrandApplyCertFile record); Integer delete(EntBrandApplyCertFile record); Integer deleteByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); Integer updateByPrimaryKey(EntBrandApplyCertFile record); List<EntBrandApplyCertFile> findAll(); List<EntBrandApplyCertFile> find(EntBrandApplyCertFile record); Integer getCount(EntBrandApplyCertFile record); EntBrandApplyCertFile getByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntCateCertApplyFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntCateCertApplyFile; /** * dal Interface:EntCateCertApplyFile * @author gencode * @date 2018-3-28 */ public interface EntCateCertApplyFileService { public List<EntCateCertApplyFile> findAll(); public List<EntCateCertApplyFile> findEntCateCertApplyFiles(EntCateCertApplyFile record); public EntCateCertApplyFile getEntCateCertApplyFileByPrimaryKey(Long certApplyFileId); public Integer createEntCateCertApplyFile(EntCateCertApplyFile record); public Integer removeEntCateCertApplyFile(EntCateCertApplyFile record); public Integer removeByPrimaryKey(Long certApplyFileId); public Integer modifyEntCateCertApplyFileByPrimaryKey(EntCateCertApplyFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntChannelPermitDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntChannelPermit; /** * dal Interface:EntChannelPermit * @author gencode */ public interface EntChannelPermitDao { Integer insert(EntChannelPermit record); Integer insertSelective(EntChannelPermit record); Integer delete(EntChannelPermit record); Integer deleteByPrimaryKey(@Param("channelPermitId") Long channelPermitId); Integer updateByPrimaryKey(EntChannelPermit record); List<EntChannelPermit> findAll(); List<EntChannelPermit> find(EntChannelPermit record); Integer getCount(EntChannelPermit record); EntChannelPermit getByPrimaryKey(@Param("channelPermitId") Long channelPermitId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/IndividualCertApplyVO.java package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.util.Date; import java.util.List; import cn.enn.ygego.sunny.user.model.IndividualCertApplyFile; import io.swagger.annotations.ApiModel; @ApiModel(description = "个人客户认证申请对象") public class IndividualCertApplyVO implements Serializable { private static final long serialVersionUID = -6620138749847674593L; private Long acctId; /* 账户ID */ private String acctName; /* 账户名称 */ private String acctCode; /* 账户编码 */ private Integer acctState; /* 账户状态 */ private Integer authState; /* 个人认证状态 */ private String logoUrl; /* LOGO_URL */ private Integer genderType; /* 性别 */ private Long deptId; /* 部门ID */ private String mobileNum; /* 手机号 */ private String email; /* 电子邮件 */ private Long areaId; /* 地区ID */ private String areaIdFullPath; /* 地区ID路径 */ private String areaNameFullPath; /* 地区名称路径 */ private String contactAddr; /* 联系地址 */ private String postCode; /* 邮编 */ private Date registerTime; /* 注册时间 */ private Long certApplyId; /* 资质申请ID */ private Long memberId; /* 会员ID */ private Integer applyType; /* 申请类型 */ private String name; /* 姓名 */ private Integer certType; /* 证件类型 */ private String certCode; /* 证件号码 */ private Integer status; /* 状态 */ private Date applyTime; /* 申请时间 */ private Date createTime; /* 创建时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ private Long approveAcctId; /* 审核人账户ID */ private String approveName; /* 审核人姓名 */ private Long approveMemberId; /* 审核人会员ID */ private Date auditTime; /* 审核时间 */ private String approveDesc; /* 审核结果描述 */ private Long certApplyDetailId; /* 资质申请明细ID */ private Date certValidDate; /* 资质有效期 */ private Integer sortNum; /* 排序编号 */ List<IndividualCertApplyFile> individualCertApplyFileList; /* 资质文件列表 */ public Integer getAuthState() { return authState; } public void setAuthState(Integer authState) { this.authState = authState; } public Long getAcctId() { return acctId; } public void setAcctId(Long acctId) { this.acctId = acctId; } public String getAcctName() { return acctName; } public void setAcctName(String acctName) { this.acctName = acctName; } public String getAcctCode() { return acctCode; } public void setAcctCode(String acctCode) { this.acctCode = acctCode; } public Integer getAcctState() { return acctState; } public void setAcctState(Integer acctState) { this.acctState = acctState; } public String getLogoUrl() { return logoUrl; } public void setLogoUrl(String logoUrl) { this.logoUrl = logoUrl; } public Integer getGenderType() { return genderType; } public void setGenderType(Integer genderType) { this.genderType = genderType; } public Long getDeptId() { return deptId; } public void setDeptId(Long deptId) { this.deptId = deptId; } public String getMobileNum() { return mobileNum; } public void setMobileNum(String mobileNum) { this.mobileNum = mobileNum; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getAreaIdFullPath() { return areaIdFullPath; } public void setAreaIdFullPath(String areaIdFullPath) { this.areaIdFullPath = areaIdFullPath; } public String getAreaNameFullPath() { return areaNameFullPath; } public void setAreaNameFullPath(String areaNameFullPath) { this.areaNameFullPath = areaNameFullPath; } public String getContactAddr() { return contactAddr; } public void setContactAddr(String contactAddr) { this.contactAddr = contactAddr; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public Date getRegisterTime() { return registerTime; } public void setRegisterTime(Date registerTime) { this.registerTime = registerTime; } public Long getCertApplyId() { return certApplyId; } public void setCertApplyId(Long certApplyId) { this.certApplyId = certApplyId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Integer getApplyType() { return applyType; } public void setApplyType(Integer applyType) { this.applyType = applyType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getCertType() { return certType; } public void setCertType(Integer certType) { this.certType = certType; } public String getCertCode() { return certCode; } public void setCertCode(String certCode) { this.certCode = certCode; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Date getApplyTime() { return applyTime; } public void setApplyTime(Date applyTime) { this.applyTime = applyTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } public Long getApproveAcctId() { return approveAcctId; } public void setApproveAcctId(Long approveAcctId) { this.approveAcctId = approveAcctId; } public String getApproveName() { return approveName; } public void setApproveName(String approveName) { this.approveName = approveName; } public Long getApproveMemberId() { return approveMemberId; } public void setApproveMemberId(Long approveMemberId) { this.approveMemberId = approveMemberId; } public Date getAuditTime() { return auditTime; } public void setAuditTime(Date auditTime) { this.auditTime = auditTime; } public String getApproveDesc() { return approveDesc; } public void setApproveDesc(String approveDesc) { this.approveDesc = approveDesc; } public Long getCertApplyDetailId() { return certApplyDetailId; } public void setCertApplyDetailId(Long certApplyDetailId) { this.certApplyDetailId = certApplyDetailId; } public Date getCertValidDate() { return certValidDate; } public void setCertValidDate(Date certValidDate) { this.certValidDate = certValidDate; } public Integer getSortNum() { return sortNum; } public void setSortNum(Integer sortNum) { this.sortNum = sortNum; } public List<IndividualCertApplyFile> getIndividualCertApplyFileList() { return individualCertApplyFileList; } public void setIndividualCertApplyFileList(List<IndividualCertApplyFile> individualCertApplyFileList) { this.individualCertApplyFileList = individualCertApplyFileList; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntCertApplyDetailVO.java package cn.enn.ygego.sunny.user.dto.vo; import cn.enn.ygego.sunny.user.dto.EntCertApplyDetailDTO; import cn.enn.ygego.sunny.user.model.EntCertApplyFile; import java.util.List; /** * ClassName: EntCertApplyDetailVO * Description: * Author: en3 * Date: 2018/3/28 16:34 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class EntCertApplyDetailVO extends EntCertApplyDetailDTO { private static final long serialVersionUID = -5177030253890710275L; private List<EntCertApplyFile> entCertApplyFileList; public List<EntCertApplyFile> getEntCertApplyFileList() { return entCertApplyFileList; } public void setEntCertApplyFileList(List<EntCertApplyFile> entCertApplyFileList) { this.entCertApplyFileList = entCertApplyFileList; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/EntApplyProdInfoDTO.java package cn.enn.ygego.sunny.user.dto; import java.io.Serializable; /** * DTO:EntApplyProdInfo * * @author gencode * @date 2018-3-30 */ public class EntApplyProdInfoDTO implements Serializable { private static final long serialVersionUID = 8558376845982853996L; private Long applyProdId; /* 申请产品ID */ private Long applyId; /* 申请ID */ private Integer categoryId; /* 类目ID */ private Long producerMemberId; /* 生产商会员ID */ private String producerName; /* 生产商名称 */ private String attrNameSerial; /* 属性名序列 */ private Long materialId; /* 物料ID */ private Long brandId; /* 品牌ID */ private String brandName; /* 品牌名称 */ // Constructor public EntApplyProdInfoDTO() { } /** * full Constructor */ public EntApplyProdInfoDTO(Long applyProdId, Long applyId, Integer categoryId, Long producerMemberId, String producerName, String attrNameSerial, Long materialId, Long brandId, String brandName) { this.applyProdId = applyProdId; this.applyId = applyId; this.categoryId = categoryId; this.producerMemberId = producerMemberId; this.producerName = producerName; this.attrNameSerial = attrNameSerial; this.materialId = materialId; this.brandId = brandId; this.brandName = brandName; } public Long getApplyProdId() { return applyProdId; } public void setApplyProdId(Long applyProdId) { this.applyProdId = applyProdId; } public Long getApplyId() { return applyId; } public void setApplyId(Long applyId) { this.applyId = applyId; } public Integer getCategoryId() { return categoryId; } public void setCategoryId(Integer categoryId) { this.categoryId = categoryId; } public Long getProducerMemberId() { return producerMemberId; } public void setProducerMemberId(Long producerMemberId) { this.producerMemberId = producerMemberId; } public String getProducerName() { return producerName; } public void setProducerName(String producerName) { this.producerName = producerName; } public String getAttrNameSerial() { return attrNameSerial; } public void setAttrNameSerial(String attrNameSerial) { this.attrNameSerial = attrNameSerial; } public Long getMaterialId() { return materialId; } public void setMaterialId(Long materialId) { this.materialId = materialId; } public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } @Override public String toString() { return "EntApplyProdInfoDTO [" + "applyProdId=" + applyProdId + ", applyId=" + applyId + ", categoryId=" + categoryId + ", producerMemberId=" + producerMemberId + ", producerName=" + producerName + ", attrNameSerial=" + attrNameSerial + ", materialId=" + materialId + ", brandId=" + brandId + ", brandName=" + brandName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntCateCertApplyDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntCateCertApply; /** * dal Interface:EntCateCertApply * @author gencode */ public interface EntCateCertApplyDao { Integer insert(EntCateCertApply record); Integer insertSelective(EntCateCertApply record); Integer delete(EntCateCertApply record); Integer deleteByPrimaryKey(@Param("certApplyDetailId") Long certApplyDetailId); Integer updateByPrimaryKey(EntCateCertApply record); List<EntCateCertApply> findAll(); List<EntCateCertApply> find(EntCateCertApply record); Integer getCount(EntCateCertApply record); EntCateCertApply getByPrimaryKey(@Param("certApplyDetailId") Long certApplyDetailId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/supermarket/SupermarketEnterPageVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.supermarket; import cn.enn.ygego.sunny.user.dto.vo.PageVO; /** * 入驻申请后的超市查询描述类 * ClassName: SupermarketEnterPageVO * Description * Author zhangjiaqi * Date 2018-03-30 14:56 * History: * <author> <time> <version> <desc> * zhangjiaqi 2018-03-30 14:56 0.0.1 TODO */ public class SupermarketEnterPageVO extends PageVO { // 超市名称 private String supermarketName; // 超市编码 private String supermarketCode; // 状态 private Integer status; public SupermarketEnterPageVO() { super(); // TODO Auto-generated constructor stub } public SupermarketEnterPageVO(Integer pageSize, Integer pageNum, Integer startRow) { super(pageSize, pageNum, startRow); // TODO Auto-generated constructor stub } public SupermarketEnterPageVO(String supermarketName, String supermarketCode, Integer status) { super(); this.supermarketName = supermarketName; this.supermarketCode = supermarketCode; this.status = status; } public String getSupermarketName() { return supermarketName; } public void setSupermarketName(String supermarketName) { this.supermarketName = supermarketName; } public String getSupermarketCode() { return supermarketCode; } public void setSupermarketCode(String supermarketCode) { this.supermarketCode = supermarketCode; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } @Override public String toString() { return "SupermarketEnterPageVO [supermarketName=" + supermarketName + ", supermarketCode=" + supermarketCode + ", status=" + status + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualBrandApplyServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualBrandApplyService; import cn.enn.ygego.sunny.user.dao.IndividualBrandApplyDao; import cn.enn.ygego.sunny.user.model.IndividualBrandApply; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualBrandApply * @author gencode * @date 2018-3-22 */ @Service public class IndividualBrandApplyServiceImpl implements IndividualBrandApplyService{ @Autowired private IndividualBrandApplyDao individualBrandApplyDao; public List<IndividualBrandApply> findAll(){ return individualBrandApplyDao.findAll(); } public List<IndividualBrandApply> findIndividualBrandApplys(IndividualBrandApply record){ return individualBrandApplyDao.find(record); } public IndividualBrandApply getIndividualBrandApplyByPrimaryKey(Integer brandApplyId){ return individualBrandApplyDao.getByPrimaryKey(brandApplyId); } public Integer createIndividualBrandApply(IndividualBrandApply record){ return individualBrandApplyDao.insert(record); } public Integer removeIndividualBrandApply(IndividualBrandApply record){ return individualBrandApplyDao.delete(record); } public Integer removeByPrimaryKey(Integer brandApplyId){ return individualBrandApplyDao.deleteByPrimaryKey(brandApplyId); } public Integer modifyIndividualBrandApplyByPrimaryKey(IndividualBrandApply record){ return individualBrandApplyDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/SampleController.java package cn.enn.ygego.sunny.user.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/sample") @Api(value = "用户测试接口", description = "用户测试接口") public class SampleController { @ApiOperation("你好的方法") @RequestMapping("/hello") @ResponseBody public String hello() { return "Hello, world!"; } @RequestMapping("test") @ResponseBody public String test(){ return "test"; } } <file_sep>/README.md # ennew-user <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/IndividualBrandCertApplyFileServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.IndividualBrandCertApplyFileService; import cn.enn.ygego.sunny.user.dao.IndividualBrandCertApplyFileDao; import cn.enn.ygego.sunny.user.model.IndividualBrandCertApplyFile; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:IndividualBrandCertApplyFile * @author gencode * @date 2018-3-22 */ @Service public class IndividualBrandCertApplyFileServiceImpl implements IndividualBrandCertApplyFileService{ @Autowired private IndividualBrandCertApplyFileDao individualBrandCertApplyFileDao; public List<IndividualBrandCertApplyFile> findAll(){ return individualBrandCertApplyFileDao.findAll(); } public List<IndividualBrandCertApplyFile> findIndividualBrandCertApplyFiles(IndividualBrandCertApplyFile record){ return individualBrandCertApplyFileDao.find(record); } public IndividualBrandCertApplyFile getIndividualBrandCertApplyFileByPrimaryKey(Long certApplyFileId){ return individualBrandCertApplyFileDao.getByPrimaryKey(certApplyFileId); } public Integer createIndividualBrandCertApplyFile(IndividualBrandCertApplyFile record){ return individualBrandCertApplyFileDao.insert(record); } public Integer removeIndividualBrandCertApplyFile(IndividualBrandCertApplyFile record){ return individualBrandCertApplyFileDao.delete(record); } public Integer removeByPrimaryKey(Long certApplyFileId){ return individualBrandCertApplyFileDao.deleteByPrimaryKey(certApplyFileId); } public Integer modifyIndividualBrandCertApplyFileByPrimaryKey(IndividualBrandCertApplyFile record){ return individualBrandCertApplyFileDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/package-info.java /** * Created by lgw on 2018/3/17. */ package cn.enn.ygego.sunny.user.dao;<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/EntCateCertFileService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.EntCateCertFile; /** * dal Interface:EntCateCertFile * @author gencode * @date 2018-3-28 */ public interface EntCateCertFileService { public List<EntCateCertFile> findAll(); public List<EntCateCertFile> findEntCateCertFiles(EntCateCertFile record); public EntCateCertFile getEntCateCertFileByPrimaryKey(Long certFileId); public Integer createEntCateCertFile(EntCateCertFile record); public Integer removeEntCateCertFile(EntCateCertFile record); public Integer removeByPrimaryKey(Long certFileId); public Integer modifyEntCateCertFileByPrimaryKey(EntCateCertFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/main/UserMain.java package cn.enn.ygego.sunny.user.main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.PropertySource; import org.springframework.transaction.annotation.EnableTransactionManagement; import springfox.documentation.swagger2.annotations.EnableSwagger2; import java.io.IOException; /** * ClassName: GoodsBootstrapMain * Description: * Author: majianguo * Date: 18-3-13 下午7:41 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ @ImportResource({ "classpath*:META-INF/spring/*.xml" }) @SpringBootApplication(scanBasePackages = {"cn.enn.ygego.sunny.user"}) @PropertySource({"classpath:/config/${spring.profiles.active}/enn.properties"}) @EnableSwagger2 public class UserMain { static Logger logger = LoggerFactory.getLogger(UserMain.class); public static void main(String[] args) throws IOException { SpringApplication application = new SpringApplication(UserMain.class); application.setBannerMode(Banner.Mode.OFF); application.run(args); logger.info("services-user start success"); } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntPaySetDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntPaySet; /** * dal Interface:EntPaySet * @author gencode */ public interface EntPaySetDao { Integer insert(EntPaySet record); Integer insertSelective(EntPaySet record); Integer delete(EntPaySet record); Integer deleteByPrimaryKey(@Param("paySetId") Long paySetId); Integer updateByPrimaryKey(EntPaySet record); List<EntPaySet> findAll(); List<EntPaySet> find(EntPaySet record); Integer getCount(EntPaySet record); EntPaySet getByPrimaryKey(@Param("paySetId") Long paySetId); Integer insertBatch(List<EntPaySet> paySets); void deleteByMemberId(@Param("memberId") Long memberId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/SysLogService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.SysLog; /** * dal Interface:SysLog * @author gencode * @date 2018-3-22 */ public interface SysLogService { public List<SysLog> findAll(); public List<SysLog> findSysLogs(SysLog record); public SysLog getSysLogByPrimaryKey(Long logId); public Integer createSysLog(SysLog record); public Integer removeSysLog(SysLog record); public Integer removeByPrimaryKey(Long logId); public Integer modifySysLogByPrimaryKey(SysLog record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/enterpriseManage/EntCategoryController.java package cn.enn.ygego.sunny.user.controller.enterpriseManage; import cn.enn.ygego.sunny.user.dto.EntMaterialDTO; import com.github.jsonzou.jmockdata.JMockData; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import org.springframework.web.multipart.MultipartFile; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * * 项目名称:services-users * 类名称:EntCategoryController * 类描述: 企业类目 * 创建人:杨清泉 * 创建时间:2018年3月28日 下午2:23:17 * 修改人:杨清泉 * 修改时间:2018年3月28日 下午2:23:17 * 修改备注: * @version * */ @SuppressWarnings("all") @RestController @RequestMapping(value = {"/user/entGc"}) @Api(value = "企业类目", description = "企业类目接口") public class EntCategoryController { @ApiOperation("增加类目接口") @RequestMapping(value = {"/addEntGc"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse addEntGc(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @ApiOperation("增加子类目接口") @RequestMapping(value = {"/addEntChildGc"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse addEntChildGc(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @ApiOperation("删除类目接口") @RequestMapping(value = {"/delEntGc"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse delEntGc(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @ApiOperation("删除类目根据子公司授权解绑接口") @RequestMapping(value = {"/delEntChildGc"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse delEntChildGc(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @ApiOperation("修改类目接口") @RequestMapping(value = {"/modifyEntGc"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse modifyEntGc(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @ApiOperation("查询类目列表(包括对外提供接口)") @RequestMapping(value = {"/getEntGcList"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse getEntGcList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @ApiOperation("查询类目详情接口") @RequestMapping(value = {"/getEntGcDetails"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse getEntGcDetails(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @ApiOperation("添加物料接口") @RequestMapping(value = {"/addMateriel"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse addMateriel(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 // jsonResponse.setRspBody(); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @ApiOperation("删除物料接口") @RequestMapping(value = {"/delMateriel"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse delMateriel(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 // jsonResponse.setRspBody(); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @ApiOperation("删除物料根据子公司授权解绑接口") @RequestMapping(value = {"/delMaterielBySubsidiary"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse delMaterielBySubsidiary(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 // jsonResponse.setRspBody(); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @ApiOperation("修改物料接口") @RequestMapping(value = {"/updateMateriel"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse updateMateriel(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 // jsonResponse.setRspBody(); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @ApiOperation("查询物料列表(包括对外提供接口)接口") @RequestMapping(value = {"/getMaterielList"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse getMaterielList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 List<EntMaterialDTO> list = new ArrayList<EntMaterialDTO>(); //JMockData生成模拟数据 EntMaterialDTO entMaterialDTO = JMockData.mock(EntMaterialDTO.class); list.add(entMaterialDTO); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(list); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @ApiOperation("查询物料详情接口") @RequestMapping(value = {"/getMaterielDetails"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse getMaterielDetails(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 //JMockData生成模拟数据 EntMaterialDTO entMaterialDTO = JMockData.mock(EntMaterialDTO.class); jsonResponse.setRetCode("0103001"); // 操作码:操作成功 jsonResponse.setRspBody(entMaterialDTO); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @ApiOperation("批量导入物料接口") @RequestMapping(value = {"/batchImportMaterials"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse batchImportMaterials(@RequestParam(value = "file") MultipartFile file) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 // jsonResponse.setRspBody(); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @ApiOperation("导出物料接口") @RequestMapping(value = {"/exportMaterial"}, method = { RequestMethod.POST}) public @ResponseBody JsonResponse exportMaterial(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0103001"); // 操作码:操作成功 // jsonResponse.setRspBody(); // 将查询到的对象返回去 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/IndividualCustService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.dto.IndividualCustDTO; import cn.enn.ygego.sunny.user.dto.vo.PersonQueryVO; import cn.enn.ygego.sunny.user.dto.vo.PersonVO; import cn.enn.ygego.sunny.user.model.IndividualCust; /** * dal Interface:IndividualCust * @author gencode * @date 2018-3-22 */ public interface IndividualCustService { public List<IndividualCust> findAll(); public List<IndividualCust> findIndividualCusts(IndividualCust record); public IndividualCust getIndividualCustByPrimaryKey(Long memberId); public Integer createIndividualCust(IndividualCust record); public Integer removeIndividualCust(IndividualCust record); public Integer removeByPrimaryKey(Long memberId); public Integer modifyIndividualCustByPrimaryKey(IndividualCust record); /** * @Description 查询用户资质认证详情 * @author puanl * @date 2018年3月24日 下午3:58:29 * @param memberId * @param hasFile * @return */ public IndividualCustDTO getIndividualCustById(Long memberId , boolean hasFile); /** * @Description 分页查询列表总数 * @author puanl * @date 2018年3月24日 下午5:23:42 * @param query * @return */ Integer getPersonCount(PersonQueryVO query); /** * @Description 查询用户列表数据 * @author puanl * @date 2018年3月24日 下午3:58:00 * @param query * @return */ public List<PersonVO> getPersonList(PersonQueryVO query); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntAuthApplyFileServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntAuthApplyFileService; import cn.enn.ygego.sunny.user.dao.EntAuthApplyFileDao; import cn.enn.ygego.sunny.user.model.EntAuthApplyFile; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntAuthApplyFile * @author gencode * @date 2018-3-28 */ @Service public class EntAuthApplyFileServiceImpl implements EntAuthApplyFileService{ @Autowired private EntAuthApplyFileDao entAuthApplyFileDao; public List<EntAuthApplyFile> findAll(){ return entAuthApplyFileDao.findAll(); } public List<EntAuthApplyFile> findEntAuthApplyFiles(EntAuthApplyFile record){ return entAuthApplyFileDao.find(record); } public EntAuthApplyFile getEntAuthApplyFileByPrimaryKey(Long certApplyFileId){ return entAuthApplyFileDao.getByPrimaryKey(certApplyFileId); } public Integer createEntAuthApplyFile(EntAuthApplyFile record){ return entAuthApplyFileDao.insert(record); } public Integer removeEntAuthApplyFile(EntAuthApplyFile record){ return entAuthApplyFileDao.delete(record); } public Integer removeByPrimaryKey(Long certApplyFileId){ return entAuthApplyFileDao.deleteByPrimaryKey(certApplyFileId); } public Integer modifyEntAuthApplyFileByPrimaryKey(EntAuthApplyFile record){ return entAuthApplyFileDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualServiceCertFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualServiceCertFile; /** * dal Interface:IndividualServiceCertFile * @author gencode */ public interface IndividualServiceCertFileDao { Integer insert(IndividualServiceCertFile record); Integer insertSelective(IndividualServiceCertFile record); Integer delete(IndividualServiceCertFile record); Integer deleteByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); Integer updateByPrimaryKey(IndividualServiceCertFile record); List<IndividualServiceCertFile> findAll(); List<IndividualServiceCertFile> find(IndividualServiceCertFile record); Integer getCount(IndividualServiceCertFile record); IndividualServiceCertFile getByPrimaryKey(@Param("certApplyFileId") Long certApplyFileId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/register/UserBaseInfoRequest.java package cn.enn.ygego.sunny.user.dto.register; import java.io.Serializable; /** * 用户基本信息(封装对多个请求通用参数的封装) * Created by dongbb on 2018/3/26. */ public class UserBaseInfoRequest implements Serializable { private Long acctId; //账号id private Long memberId; //个人会员id private Long companyMemberId; //企业会员id public Long getAcctId() { return acctId; } public void setAcctId(Long acctId) { this.acctId = acctId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getCompanyMemberId() { return companyMemberId; } public void setCompanyMemberId(Long companyMemberId) { this.companyMemberId = companyMemberId; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/EntBrandAuthApplyCertDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.EntBrandAuthApplyCert; /** * dal Interface:EntBrandAuthApplyCert * @author gencode */ public interface EntBrandAuthApplyCertDao { Integer insert(EntBrandAuthApplyCert record); Integer insertSelective(EntBrandAuthApplyCert record); Integer delete(EntBrandAuthApplyCert record); Integer deleteByPrimaryKey(@Param("brandApplyCertId") Long brandApplyCertId); Integer updateByPrimaryKey(EntBrandAuthApplyCert record); List<EntBrandAuthApplyCert> findAll(); List<EntBrandAuthApplyCert> find(EntBrandAuthApplyCert record); Integer getCount(EntBrandAuthApplyCert record); EntBrandAuthApplyCert getByPrimaryKey(@Param("brandApplyCertId") Long brandApplyCertId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketChargeStandardDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketChargeStandard; import org.springframework.stereotype.Repository; /** * ClassName: MarketChargeStandard * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketChargeStandardDao { List<MarketChargeStandard> selectAll(); List<MarketChargeStandard> select(MarketChargeStandard record); Integer selectCount(MarketChargeStandard record); MarketChargeStandard selectByPrimaryKey(Long chargeStandardId); Integer deleteByPrimaryKey(Long chargeStandardId); Integer delete(MarketChargeStandard record); Integer insertSelective(MarketChargeStandard record); Integer updateByPrimaryKeySelective(MarketChargeStandard record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/InspectFactoryApplyInfoService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.user.dto.factory.CategoryQueryVO; import cn.enn.ygego.sunny.user.dto.factory.InspectFactoryApplyInfoVO; import cn.enn.ygego.sunny.user.model.InspectFactoryApplyInfo; /** * dal Interface:InspectFactoryApplyInfo * @author gencode * @date 2018-3-30 */ public interface InspectFactoryApplyInfoService { public List<InspectFactoryApplyInfo> findAll(); public List<InspectFactoryApplyInfo> findInspectFactoryApplyInfos(InspectFactoryApplyInfo record); public InspectFactoryApplyInfo getInspectFactoryApplyInfoByPrimaryKey(Long applyId); public Integer createInspectFactoryApplyInfo(InspectFactoryApplyInfo record); public Integer removeInspectFactoryApplyInfo(InspectFactoryApplyInfo record); public Integer removeByPrimaryKey(Long applyId); public Integer modifyInspectFactoryApplyInfoByPrimaryKey(InspectFactoryApplyInfo record); /** * @Description 查询供应商的验厂类目信息 * @author zhengyang * @date 2018年3月30日 下午8:07:02 * @param query * @return */ public PageDTO<InspectFactoryApplyInfoVO> getAuditCategoryList(CategoryQueryVO query); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/MarketCateCertApplyFileDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketCateCertApplyFile; import org.springframework.stereotype.Repository; /** * ClassName: MarketCateCertApplyFile * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketCateCertApplyFileDao { List<MarketCateCertApplyFile> selectAll(); List<MarketCateCertApplyFile> select(MarketCateCertApplyFile record); Integer selectCount(MarketCateCertApplyFile record); MarketCateCertApplyFile selectByPrimaryKey(Long certApplyFileId); Integer deleteByPrimaryKey(Long certApplyFileId); Integer delete(MarketCateCertApplyFile record); Integer insertSelective(MarketCateCertApplyFile record); Integer updateByPrimaryKeySelective(MarketCateCertApplyFile record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/InspectFactoryMaterial.java package cn.enn.ygego.sunny.user.model; import java.io.Serializable; /** * entity:InspectFactoryMaterial * * @author gencode */ public class InspectFactoryMaterial implements Serializable { private static final long serialVersionUID = -8814374493872862218L; private Long inspectMaterialId; /* 验厂物料ID */ private Long applyId; /* 申请标识 */ private Long brandId; /* 品牌ID */ private String dictBrand; /* 品牌 */ private Long materialId; /* 物料ID */ private String materialCode; /* 物料编码 */ private String materialName; /* 物料名称 */ // Constructor public InspectFactoryMaterial() { } /** * full Constructor */ public InspectFactoryMaterial(Long inspectMaterialId, Long applyId, Long brandId, String dictBrand, Long materialId, String materialCode, String materialName) { this.inspectMaterialId = inspectMaterialId; this.applyId = applyId; this.brandId = brandId; this.dictBrand = dictBrand; this.materialId = materialId; this.materialCode = materialCode; this.materialName = materialName; } public Long getInspectMaterialId() { return inspectMaterialId; } public void setInspectMaterialId(Long inspectMaterialId) { this.inspectMaterialId = inspectMaterialId; } public Long getApplyId() { return applyId; } public void setApplyId(Long applyId) { this.applyId = applyId; } public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public String getDictBrand() { return dictBrand; } public void setDictBrand(String dictBrand) { this.dictBrand = dictBrand; } public Long getMaterialId() { return materialId; } public void setMaterialId(Long materialId) { this.materialId = materialId; } public String getMaterialCode() { return materialCode; } public void setMaterialCode(String materialCode) { this.materialCode = materialCode; } public String getMaterialName() { return materialName; } public void setMaterialName(String materialName) { this.materialName = materialName; } @Override public String toString() { return "InspectFactoryMaterial [" + "inspectMaterialId=" + inspectMaterialId+ ", applyId=" + applyId+ ", brandId=" + brandId+ ", dictBrand=" + dictBrand+ ", materialId=" + materialId+ ", materialCode=" + materialCode+ ", materialName=" + materialName+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/RegisterController.java package cn.enn.ygego.sunny.user.controller; import cn.enn.ygego.sunny.core.exception.BusinessException; import cn.enn.ygego.sunny.core.log.SearchableLoggerFactory; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import cn.enn.ygego.sunny.user.common.ResponseCodeEnum; import cn.enn.ygego.sunny.user.dto.register.*; import cn.enn.ygego.sunny.user.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/user/") @Api(value = "平台注册、发送接口、验证接口", description = "平台注册、发送接口、验证接口") public class RegisterController { private static final Logger logger = SearchableLoggerFactory.getDefaultLogger(); @Autowired private UserService userService; /** * 用户注册接口 * * @param jsonRequest * @return */ @ApiOperation(value = "注册接口", notes = "输入用户名、密码等信息") @RequestMapping(value = "/register", method = {RequestMethod.POST}) public JsonResponse register(@RequestBody JsonRequest<UserRegisterRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { UserRegisterRequest request = jsonRequest.getReqBody(); boolean checkOldPhone = userService.checkValidCode(request.getMobilePhone(), request.getValidCode(), request.getSmsType()); if (checkOldPhone == false) { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("手机号验证码输入有误!"); return jsonResponse; } userService.registerUser(request); jsonResponse.setRetDesc("恭喜注册成功!"); } catch (BusinessException e) { logger.error(e.getErrorCode()); jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc(e.getErrorCode()); } catch (Exception e) { logger.error("注册用户信息异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 更改密码 * * @param jsonRequest * @return */ @ApiOperation(value = "更改密码") @RequestMapping(value = "/changePassword", method = {RequestMethod.POST}) public JsonResponse changePassword(@RequestBody JsonRequest<ChangePasswordRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { ChangePasswordRequest request = jsonRequest.getReqBody(); userService.changePassword(request.getAcctId(), request.getOldPassword(), request.getNewPassword()); jsonResponse.setRetDesc("更改密码成功!"); } catch (BusinessException e) { logger.error(e.getErrorCode()); jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc(e.getErrorCode()); } catch (Exception e) { logger.error("更改密码异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 更改邮件 * * @param jsonRequest * @return */ @ApiOperation(value = "更改邮件") @RequestMapping(value = "/changeEmail", method = {RequestMethod.POST}) public JsonResponse changeEmail(@RequestBody JsonRequest<ChangeEmailRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { ChangeEmailRequest request = jsonRequest.getReqBody(); userService.changeEmail(request.getAcctId(), request.getEmail()); jsonResponse.setRetDesc("更改邮件成功!"); } catch (BusinessException e) { logger.error(e.getErrorCode()); jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc(e.getErrorCode()); } catch (Exception e) { logger.error("更改邮件异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 发送短信 * * @param jsonRequest * @return */ @ApiOperation(value = "发送短信接口", notes = "根据不同业务类型发送不同模板的短信") @RequestMapping(value = "/sendSms", method = {RequestMethod.POST}) public JsonResponse<SendSmsResponse> sendSms(@RequestBody JsonRequest<SendSmsRequest> jsonRequest) { JsonResponse<SendSmsResponse> jsonResponse = new JsonResponse(); try { SendSmsRequest request = jsonRequest.getReqBody(); SendSmsResponse response = userService.sendSms(request.getMobilePhone(), request.getSmsType()); jsonResponse.setRspBody(response); } catch (BusinessException e) { logger.error(e.getErrorCode()); jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc(e.getErrorCode()); } catch (Exception e) { logger.error("更新邮件异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 校验用户名是否已注册 * * @param jsonRequest * @return */ @ApiOperation(value = "校验用户名是否已注册", notes = "校验用户名是否已注册") @RequestMapping(value = "/checkUsername", method = {RequestMethod.POST}) public JsonResponse checkUsername(@RequestBody JsonRequest<UserRegisterRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { UserRegisterRequest request = jsonRequest.getReqBody(); boolean result = userService.checkUsername(request.getUsername()); if (result) { jsonResponse.setRetDesc("该用户名可以注册!"); } else { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("该用户名已注册!"); } } catch (Exception e) { logger.error("校验用户名是否已注册异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 校验手机号是否已注册 * * @param jsonRequest * @return */ @ApiOperation(value = "校验手机号是否已注册", notes = "校验手机号是否已注册") @RequestMapping(value = "/checkMobilePhone", method = {RequestMethod.POST}) public JsonResponse checkMobilePhone(@RequestBody JsonRequest<UserRegisterRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { UserRegisterRequest request = jsonRequest.getReqBody(); boolean result = userService.checkMobilePhone(request.getMobilePhone()); if (result) { jsonResponse.setRetDesc("该手机号可以注册!"); } else { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("该手机号已注册!"); } } catch (Exception e) { logger.error("校验手机号是否已注册异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 校验邮箱是否已注册 * * @param jsonRequest * @return */ @ApiOperation(value = "校验邮箱是否已注册", notes = "校验手机号是否已注册") @RequestMapping(value = "/checkEmail", method = {RequestMethod.POST}) public JsonResponse checkEmail(@RequestBody JsonRequest<UserRegisterRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { UserRegisterRequest request = jsonRequest.getReqBody(); boolean result = userService.checkEmail(request.getEmail()); if (result) { jsonResponse.setRetDesc("该邮箱可以注册!"); } else { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("该邮箱已注册!"); } } catch (Exception e) { logger.error("校验邮箱是否已注册异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 校验手机验证码输入是否正确 * * @param jsonRequest * @return */ @ApiOperation(value = "校验验证码是否正确", notes = "校验验证码是否正确") @RequestMapping(value = "/checkValidCode", method = {RequestMethod.POST}) public JsonResponse checkValidCode(@RequestBody JsonRequest<SendSmsResponse> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { SendSmsResponse request = jsonRequest.getReqBody(); boolean result = userService.checkValidCode(request.getMobilePhone(), request.getValidCode(), request.getSmsType()); if (result) { jsonResponse.setRetDesc("验证码校验通过!"); } else { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("验证码输入错误!"); } } catch (Exception e) { logger.error("校验邮箱是否已注册异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 重置密码(找回密码) * * @param jsonRequest * @return */ @ApiOperation(value = "重置密码(找回密码)") @RequestMapping(value = "/resetPassword", method = {RequestMethod.POST}) public JsonResponse resetPassword(@RequestBody JsonRequest<ChangePasswordRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { ChangePasswordRequest request = jsonRequest.getReqBody(); boolean result = userService.resetPassword(request.getAcctId(), request.getNewPassword()); if (result) { jsonResponse.setRetDesc("重置密码成功!"); } else { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("重置密码失败!"); } } catch (Exception e) { logger.error("重置密码异常", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } /** * 绑定手机号(修改手机号) * * @param jsonRequest * @return */ @ApiOperation(value = "绑定手机号(修改手机号)") @RequestMapping(value = "/bindPhone", method = {RequestMethod.POST}) public JsonResponse bindPhone(@RequestBody JsonRequest<BindPhoneRequest> jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); try { BindPhoneRequest request = jsonRequest.getReqBody(); boolean checkOldPhone = userService.checkValidCode(request.getOldPhone(), request.getOldVaildCode(), request.getSmsType()); if (checkOldPhone == false) { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("原手机号验证码输入有误!"); return jsonResponse; } boolean checkNewPhone = userService.checkValidCode(request.getNewPhone(), request.getNewValidCode(), request.getSmsType()); if (checkNewPhone == false) { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("新手机号验证码输入有误!"); return jsonResponse; } boolean result = userService.changePhone(request.getAcctId(), request.getNewPhone()); if (result) { jsonResponse.setRetDesc("绑定新手机号成功!"); } else { jsonResponse.setRetCode(ResponseCodeEnum.FAIL.getStatusCode()); jsonResponse.setRetDesc("绑定新手机号失败!"); } } catch (Exception e) { logger.error("绑定新手机号异常!", e); jsonResponse.setRetCode(ResponseCodeEnum.EXCEPTION.getStatusCode()); jsonResponse.setRetDesc(ResponseCodeEnum.EXCEPTION.getStatusName()); } return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/QuestionResponseDTO.java package cn.enn.ygego.sunny.user.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; import java.io.Serializable; /** * DTO:QuestionResponse * * @author gencode * @date 2018-3-19 */ @ApiModel(description = "用于查询回复反馈信息的条件描述类") public class QuestionResponseDTO implements Serializable { private static final long serialVersionUID = 4939487311253395281L; @ApiModelProperty("回复ID") private Long responseId; /* 回复ID */ @ApiModelProperty("问题ID") private Long questionId; /* 问题ID */ @ApiModelProperty("回复内容") private String responseContent; /* 回复内容 */ @ApiModelProperty("创建时间") private Date createTime; /* 创建时间 */ @ApiModelProperty("创建人会员ID") private Long createMemberId; /* 创建人会员ID */ @ApiModelProperty("创建人账户ID") private Long createAcctId; /* 创建人账户ID */ @ApiModelProperty("创建人姓名") private String createName; /* 创建人姓名 */ // Constructor public QuestionResponseDTO() { } /** * full Constructor */ public QuestionResponseDTO(Long responseId, Long questionId, String responseContent, Date createTime, Long createMemberId, Long createAcctId, String createName) { this.responseId = responseId; this.questionId = questionId; this.responseContent = responseContent; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getResponseId() { return responseId; } public void setResponseId(Long responseId) { this.responseId = responseId; } public Long getQuestionId() { return questionId; } public void setQuestionId(Long questionId) { this.questionId = questionId; } public String getResponseContent() { return responseContent; } public void setResponseContent(String responseContent) { this.responseContent = responseContent; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "QuestionResponseDTO [" + "responseId=" + responseId + ", questionId=" + questionId + ", responseContent=" + responseContent + ", createTime=" + createTime + ", createMemberId=" + createMemberId + ", createAcctId=" + createAcctId + ", createName=" + createName + "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/InspectFactoryApplyInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.dto.factory.CategoryQueryVO; import cn.enn.ygego.sunny.user.dto.factory.InspectFactoryApplyInfoVO; import cn.enn.ygego.sunny.user.model.InspectFactoryApplyInfo; /** * dal Interface:InspectFactoryApplyInfo * @author gencode */ public interface InspectFactoryApplyInfoDao { Integer insert(InspectFactoryApplyInfo record); Integer insertSelective(InspectFactoryApplyInfo record); Integer delete(InspectFactoryApplyInfo record); Integer deleteByPrimaryKey(@Param("applyId") Long applyId); Integer updateByPrimaryKey(InspectFactoryApplyInfo record); List<InspectFactoryApplyInfo> findAll(); List<InspectFactoryApplyInfo> find(InspectFactoryApplyInfo record); Integer getCount(InspectFactoryApplyInfo record); InspectFactoryApplyInfo getByPrimaryKey(@Param("applyId") Long applyId); /** * @Description 查询供应航的验厂类目信息 * @author zhengyang * @date 2018年3月30日 下午8:16:47 * @param query * @return */ List<InspectFactoryApplyInfoVO> getAuditCategoryList(CategoryQueryVO query); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/FunctionManageDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.FunctionManage; /** * dal Interface:FunctionManage * @author gencode */ public interface FunctionManageDao { Integer insert(FunctionManage record); Integer insertSelective(FunctionManage record); Integer delete(FunctionManage record); Integer deleteByPrimaryKey(@Param("functionId") Long functionId); Integer updateByPrimaryKey(FunctionManage record); List<FunctionManage> findAll(); List<FunctionManage> find(FunctionManage record); Integer getCount(FunctionManage record); FunctionManage getByPrimaryKey(@Param("functionId") Long functionId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/ChannelRoleVO.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.dto.vo; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * DTO:ChannelManage * * @author gencode * @date 2018-3-26 */ public class ChannelRoleVO implements Serializable { private static final long serialVersionUID = 8877726588419034128L; private Long channelId; /* 渠道ID */ private String channelName; /* 渠道名称 */ private List<FunctionManageVO> functionManageVOS=new ArrayList<>(); public List<FunctionManageVO> getFunctionManageVOS() { return functionManageVOS; } public void setFunctionManageVOS(List<FunctionManageVO> functionManageVOS) { this.functionManageVOS = functionManageVOS; } // Constructor public ChannelRoleVO() { } public Long getChannelId() { return channelId; } public void setChannelId(Long channelId) { this.channelId = channelId; } public String getChannelName() { return channelName; } public void setChannelName(String channelName) { this.channelName = channelName; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/ReceiveAddress.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:ReceiveAddress * * @author gencode */ public class ReceiveAddress implements Serializable { private static final long serialVersionUID = 7365661255971686765L; private Long receiveAddressId; /* 收货地址ID */ private Long memberId; /* 会员ID */ private Long areaId; /* 地区ID */ private String areaIdFullPath; /* 地区ID路径 */ private String areaNameFullPath; /* 地区名称路径 */ private String addressDetail; /* 详细地址 */ private String contact; /* 联系人 */ private String contactTel; /* 联系电话 */ private String fixedPhone; /* 固定电话 */ private Integer isDefaultReceiveAddr; /* 是否默认收货地 */ private Date createTime; /* 创建时间 */ private Long createMemberId; /* 创建人会员ID */ private Long createAcctId; /* 创建人账户ID */ private String createName; /* 创建人姓名 */ // Constructor public ReceiveAddress() { } /** * full Constructor */ public ReceiveAddress(Long receiveAddressId, Long memberId, Long areaId, String areaIdFullPath, String areaNameFullPath, String addressDetail, String contact, String contactTel, String fixedPhone, Integer isDefaultReceiveAddr, Date createTime, Long createMemberId, Long createAcctId, String createName) { this.receiveAddressId = receiveAddressId; this.memberId = memberId; this.areaId = areaId; this.areaIdFullPath = areaIdFullPath; this.areaNameFullPath = areaNameFullPath; this.addressDetail = addressDetail; this.contact = contact; this.contactTel = contactTel; this.fixedPhone = fixedPhone; this.isDefaultReceiveAddr = isDefaultReceiveAddr; this.createTime = createTime; this.createMemberId = createMemberId; this.createAcctId = createAcctId; this.createName = createName; } public Long getReceiveAddressId() { return receiveAddressId; } public void setReceiveAddressId(Long receiveAddressId) { this.receiveAddressId = receiveAddressId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getAreaId() { return areaId; } public void setAreaId(Long areaId) { this.areaId = areaId; } public String getAreaIdFullPath() { return areaIdFullPath; } public void setAreaIdFullPath(String areaIdFullPath) { this.areaIdFullPath = areaIdFullPath; } public String getAreaNameFullPath() { return areaNameFullPath; } public void setAreaNameFullPath(String areaNameFullPath) { this.areaNameFullPath = areaNameFullPath; } public String getAddressDetail() { return addressDetail; } public void setAddressDetail(String addressDetail) { this.addressDetail = addressDetail; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getContactTel() { return contactTel; } public void setContactTel(String contactTel) { this.contactTel = contactTel; } public String getFixedPhone() { return fixedPhone; } public void setFixedPhone(String fixedPhone) { this.fixedPhone = fixedPhone; } public Integer getIsDefaultReceiveAddr() { return isDefaultReceiveAddr; } public void setIsDefaultReceiveAddr(Integer isDefaultReceiveAddr) { this.isDefaultReceiveAddr = isDefaultReceiveAddr; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Long getCreateMemberId() { return createMemberId; } public void setCreateMemberId(Long createMemberId) { this.createMemberId = createMemberId; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public String getCreateName() { return createName; } public void setCreateName(String createName) { this.createName = createName; } @Override public String toString() { return "ReceiveAddress [" + "receiveAddressId=" + receiveAddressId+ ", memberId=" + memberId+ ", areaId=" + areaId+ ", areaIdFullPath=" + areaIdFullPath+ ", areaNameFullPath=" + areaNameFullPath+ ", addressDetail=" + addressDetail+ ", contact=" + contact+ ", contactTel=" + contactTel+ ", fixedPhone=" + fixedPhone+ ", isDefaultReceiveAddr=" + isDefaultReceiveAddr+ ", createTime=" + createTime+ ", createMemberId=" + createMemberId+ ", createAcctId=" + createAcctId+ ", createName=" + createName+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/SupplierWhiteListDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.SupplierWhiteList; /** * dal Interface:SupplierWhiteList * @author gencode */ public interface SupplierWhiteListDao { Integer insert(SupplierWhiteList record); Integer insertSelective(SupplierWhiteList record); Integer delete(SupplierWhiteList record); Integer deleteByPrimaryKey(@Param("supplierListId") Long supplierListId); Integer updateByPrimaryKey(SupplierWhiteList record); List<SupplierWhiteList> findAll(); List<SupplierWhiteList> find(SupplierWhiteList record); Integer getCount(SupplierWhiteList record); SupplierWhiteList getByPrimaryKey(@Param("supplierListId") Long supplierListId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/EntProducerAuth.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:EntProducerAuth * * @author gencode */ public class EntProducerAuth implements Serializable { private static final long serialVersionUID = -6364754175939317116L; private Long authId; /* 授权ID */ private Long memberId; /* 会员ID */ private Long producerMemberId; /* 生产商会员ID */ private String producerName; /* 生产商名称 */ private String authFileNo; /* 授权书编号 */ private Long createAcctId; /* 创建人账户ID */ private Date createTime; /* 创建时间 */ // Constructor public EntProducerAuth() { } /** * full Constructor */ public EntProducerAuth(Long authId, Long memberId, Long producerMemberId, String producerName, String authFileNo, Long createAcctId, Date createTime) { this.authId = authId; this.memberId = memberId; this.producerMemberId = producerMemberId; this.producerName = producerName; this.authFileNo = authFileNo; this.createAcctId = createAcctId; this.createTime = createTime; } public Long getAuthId() { return authId; } public void setAuthId(Long authId) { this.authId = authId; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } public Long getProducerMemberId() { return producerMemberId; } public void setProducerMemberId(Long producerMemberId) { this.producerMemberId = producerMemberId; } public String getProducerName() { return producerName; } public void setProducerName(String producerName) { this.producerName = producerName; } public String getAuthFileNo() { return authFileNo; } public void setAuthFileNo(String authFileNo) { this.authFileNo = authFileNo; } public Long getCreateAcctId() { return createAcctId; } public void setCreateAcctId(Long createAcctId) { this.createAcctId = createAcctId; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "EntProducerAuth [" + "authId=" + authId+ ", memberId=" + memberId+ ", producerMemberId=" + producerMemberId+ ", producerName=" + producerName+ ", authFileNo=" + authFileNo+ ", createAcctId=" + createAcctId+ ", createTime=" + createTime+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/constant/EntCertApplyTypeEnum.java package cn.enn.ygego.sunny.user.constant; /** * ClassName: EntCertApplyTypeEnum * Description: * Author: en3 * Date: 2018/3/26 17:13 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public enum EntCertApplyTypeEnum { // 申请状态: 1申请2变更3认证升级 APPLY_STATUS_APPLY(1,"申请"), APPLY_STATUS_CHANGE(2,"变更"), APPLY_STATUS_UP(3,"认证升级"); private Integer code; private String desc; EntCertApplyTypeEnum(Integer code, String desc) { this.code = code; this.desc = desc; } public Integer getCode() { return code; } public String getDesc() { return desc; } public static ChannelAuthStatusEnum getByCode(Integer code) { if (code == null) { return null; } for (ChannelAuthStatusEnum reasonEnum : ChannelAuthStatusEnum.values()) { if (reasonEnum.getCode() == code) { return reasonEnum; } } return null; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/controller/gridSupermarket/WarehouseController.java /* * Copyright: Copyright (c) 2017-2020 * Company: ygego */ package cn.enn.ygego.sunny.user.controller.gridSupermarket; import java.util.Date; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import cn.enn.ygego.sunny.core.page.PageDTO; import cn.enn.ygego.sunny.core.web.json.JsonRequest; import cn.enn.ygego.sunny.core.web.json.JsonResponse; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @RestController @RequestMapping(value = "/user/supermarket/warehousemgr") @Api(value = "仓库管理 ", description = "仓库管理 ") public class WarehouseController { @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("wms仓库数据同步接口") @RequestMapping(value = "/syncWarehouseInfoForWMS", method = { RequestMethod.POST }) public JsonResponse syncWarehouseInfoForWMS(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查询库房详情") @RequestMapping(value = "/getWarehouseDetail", method = { RequestMethod.POST }) public JsonResponse getWarehouseDetail(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0000000"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("查询所有库房列表(分页)") @RequestMapping(value = "/getWarehouseList", method = { RequestMethod.POST }) public JsonResponse<PageDTO> getWarehouseList(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0000000"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("根据仓库id获取超市信息接口") @RequestMapping(value = "/getMarketByWarehouse", method = { RequestMethod.POST }) public JsonResponse getMarketByWarehouse(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("wms客商数据同步接口") @RequestMapping(value = "/syncBusinessInfoForWMS", method = { RequestMethod.POST }) public JsonResponse syncBusinessInfoForWMS(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 return jsonResponse; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation("新增库房接口(批量新增)") @RequestMapping(value = "/addWarehouse", method = { RequestMethod.POST }) public JsonResponse<PageDTO> addWarehouse(@RequestBody JsonRequest jsonRequest) { JsonResponse jsonResponse = new JsonResponse(); // 返回的对象 jsonResponse.setRetCode("0000000"); // 操作码:操作成功 jsonResponse.setRetDesc("成功"); // 返回值信息 jsonResponse.setTimestamp(new Date()); // 接口响应的时间 return jsonResponse; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dto/vo/EntCustBasicInfoVO.java package cn.enn.ygego.sunny.user.dto.vo; import cn.enn.ygego.sunny.user.dto.EntCustInfoDTO; import java.util.List; /** * ClassName: EntCustBasicInfoVO * Description: * Author: en3 * Date: 2018/3/28 16:23 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public class EntCustBasicInfoVO extends EntCustInfoDTO { private static final long serialVersionUID = -4143007245624690585L; private List<EntCertInfoVO> entCertInfoVOList; public List<EntCertInfoVO> getEntCertInfoVOList() { return entCertInfoVOList; } public void setEntCertInfoVOList(List<EntCertInfoVO> entCertInfoVOList) { this.entCertInfoVOList = entCertInfoVOList; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualBrandInfoDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualBrandInfo; /** * dal Interface:IndividualBrandInfo * @author gencode */ public interface IndividualBrandInfoDao { Integer insert(IndividualBrandInfo record); Integer insertSelective(IndividualBrandInfo record); Integer delete(IndividualBrandInfo record); Integer deleteByPrimaryKey(@Param("individualBrandId") Long individualBrandId); Integer updateByPrimaryKey(IndividualBrandInfo record); List<IndividualBrandInfo> findAll(); List<IndividualBrandInfo> find(IndividualBrandInfo record); Integer getCount(IndividualBrandInfo record); IndividualBrandInfo getByPrimaryKey(@Param("individualBrandId") Long individualBrandId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/model/ThirdLoginInfo.java package cn.enn.ygego.sunny.user.model; import java.util.Date; import java.io.Serializable; /** * entity:ThirdLoginInfo * * @author gencode */ public class ThirdLoginInfo implements Serializable { private static final long serialVersionUID = -7947768371646723628L; private String loginId; /* 登录ID */ private Long acctId; /* 账户ID */ private Long configId; /* 配置ID */ private String name; /* 姓名 */ private String mobileNum; /* 手机号 */ private String email; /* 电子邮件 */ private Date createTime; /* 创建时间 */ // Constructor public ThirdLoginInfo() { } /** * full Constructor */ public ThirdLoginInfo(String loginId, Long acctId, Long configId, String name, String mobileNum, String email, Date createTime) { this.loginId = loginId; this.acctId = acctId; this.configId = configId; this.name = name; this.mobileNum = mobileNum; this.email = email; this.createTime = createTime; } public String getLoginId() { return loginId; } public void setLoginId(String loginId) { this.loginId = loginId; } public Long getAcctId() { return acctId; } public void setAcctId(Long acctId) { this.acctId = acctId; } public Long getConfigId() { return configId; } public void setConfigId(Long configId) { this.configId = configId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMobileNum() { return mobileNum; } public void setMobileNum(String mobileNum) { this.mobileNum = mobileNum; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "ThirdLoginInfo [" + "loginId=" + loginId+ ", acctId=" + acctId+ ", configId=" + configId+ ", name=" + name+ ", mobileNum=" + mobileNum+ ", email=" + email+ ", createTime=" + createTime+ "]"; } } <file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/FunctionManageService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.FunctionManage; /** * dal Interface:FunctionManage * @author gencode * @date 2018-3-22 */ public interface FunctionManageService { public List<FunctionManage> findAll(); public List<FunctionManage> findFunctionManages(FunctionManage record); public FunctionManage getFunctionManageByPrimaryKey(Long functionId); public Integer createFunctionManage(FunctionManage record); public Integer removeFunctionManage(FunctionManage record); public Integer removeByPrimaryKey(Long functionId); public Integer modifyFunctionManageByPrimaryKey(FunctionManage record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/MarketMaterialStandardChargeService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.MarketMaterialStandardCharge; import org.springframework.stereotype.Repository; /** * ClassName: MarketMaterialStandardCharge * Description: * Author: 杨超 * Date: 2018-3-31 * History: * <author> <time> <version> <desc> * 作者姓名 修改时间 版本号 描述 */ public interface MarketMaterialStandardChargeService { public List<MarketMaterialStandardCharge> findAll(); public List<MarketMaterialStandardCharge> findMarketMaterialStandardCharges(MarketMaterialStandardCharge record); public MarketMaterialStandardCharge getMarketMaterialStandardChargeByPrimaryKey(Long chargeId); public Integer deleteByPrimaryKey(Long chargeId); public Integer createMarketMaterialStandardCharge(MarketMaterialStandardCharge record); public Integer deleteMarketMaterialStandardCharge(MarketMaterialStandardCharge record); public Integer removeMarketMaterialStandardCharge(MarketMaterialStandardCharge record); public Integer updateMarketMaterialStandardChargeByPrimaryKeySelective(MarketMaterialStandardCharge record); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/InspectFactoryApplyAttachDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.InspectFactoryApplyAttach; /** * dal Interface:InspectFactoryApplyAttach * @author gencode */ public interface InspectFactoryApplyAttachDao { Integer insert(InspectFactoryApplyAttach record); Integer insertSelective(InspectFactoryApplyAttach record); Integer delete(InspectFactoryApplyAttach record); Integer deleteByPrimaryKey(@Param("attaId") Long attaId); Integer updateByPrimaryKey(InspectFactoryApplyAttach record); List<InspectFactoryApplyAttach> findAll(); List<InspectFactoryApplyAttach> find(InspectFactoryApplyAttach record); Integer getCount(InspectFactoryApplyAttach record); InspectFactoryApplyAttach getByPrimaryKey(@Param("attaId") Long attaId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntMaterialServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntMaterialService; import cn.enn.ygego.sunny.user.dao.EntMaterialDao; import cn.enn.ygego.sunny.user.model.EntMaterial; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntMaterial * @author gencode * @date 2018-3-28 */ @Service public class EntMaterialServiceImpl implements EntMaterialService{ @Autowired private EntMaterialDao entMaterialDao; public List<EntMaterial> findAll(){ return entMaterialDao.findAll(); } public List<EntMaterial> findEntMaterials(EntMaterial record){ return entMaterialDao.find(record); } public EntMaterial getEntMaterialByPrimaryKey(Long entMaterialId){ return entMaterialDao.getByPrimaryKey(entMaterialId); } public Integer createEntMaterial(EntMaterial record){ return entMaterialDao.insert(record); } public Integer removeEntMaterial(EntMaterial record){ return entMaterialDao.delete(record); } public Integer removeByPrimaryKey(Long entMaterialId){ return entMaterialDao.deleteByPrimaryKey(entMaterialId); } public Integer modifyEntMaterialByPrimaryKey(EntMaterial record){ return entMaterialDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/dao/IndividualServiceApplyCertDao.java package cn.enn.ygego.sunny.user.dao; import java.util.List; import org.apache.ibatis.annotations.Param; import cn.enn.ygego.sunny.user.model.IndividualServiceApplyCert; /** * dal Interface:IndividualServiceApplyCert * @author gencode */ public interface IndividualServiceApplyCertDao { Integer insert(IndividualServiceApplyCert record); Integer insertSelective(IndividualServiceApplyCert record); Integer delete(IndividualServiceApplyCert record); Integer deleteByPrimaryKey(@Param("serviceApplyCertId") Long serviceApplyCertId); Integer updateByPrimaryKey(IndividualServiceApplyCert record); List<IndividualServiceApplyCert> findAll(); List<IndividualServiceApplyCert> find(IndividualServiceApplyCert record); Integer getCount(IndividualServiceApplyCert record); IndividualServiceApplyCert getByPrimaryKey(@Param("serviceApplyCertId") Long serviceApplyCertId); }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/impl/EntDomainPermitServiceImpl.java package cn.enn.ygego.sunny.user.service.impl; import java.util.List; import cn.enn.ygego.sunny.user.service.EntDomainPermitService; import cn.enn.ygego.sunny.user.dao.EntDomainPermitDao; import cn.enn.ygego.sunny.user.model.EntDomainPermit; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; /** * dal Interface:EntDomainPermit * @author gencode * @date 2018-3-28 */ @Service public class EntDomainPermitServiceImpl implements EntDomainPermitService{ @Autowired private EntDomainPermitDao entDomainPermitDao; public List<EntDomainPermit> findAll(){ return entDomainPermitDao.findAll(); } public List<EntDomainPermit> findEntDomainPermits(EntDomainPermit record){ return entDomainPermitDao.find(record); } public EntDomainPermit getEntDomainPermitByPrimaryKey(Long domainPermitId){ return entDomainPermitDao.getByPrimaryKey(domainPermitId); } public Integer createEntDomainPermit(EntDomainPermit record){ return entDomainPermitDao.insert(record); } public Integer removeEntDomainPermit(EntDomainPermit record){ return entDomainPermitDao.delete(record); } public Integer removeByPrimaryKey(Long domainPermitId){ return entDomainPermitDao.deleteByPrimaryKey(domainPermitId); } public Integer modifyEntDomainPermitByPrimaryKey(EntDomainPermit record){ return entDomainPermitDao.updateByPrimaryKey(record); } }<file_sep>/src/main/java/cn/enn/ygego/sunny/user/service/SupplierBlackListService.java package cn.enn.ygego.sunny.user.service; import java.util.List; import cn.enn.ygego.sunny.user.model.SupplierBlackList; /** * dal Interface:SupplierBlackList * @author gencode * @date 2018-3-22 */ public interface SupplierBlackListService { public List<SupplierBlackList> findAll(); public List<SupplierBlackList> findSupplierBlackLists(SupplierBlackList record); public SupplierBlackList getSupplierBlackListByPrimaryKey(Long supplierListId); public Integer createSupplierBlackList(SupplierBlackList record); public Integer removeSupplierBlackList(SupplierBlackList record); public Integer removeByPrimaryKey(Long supplierListId); public Integer modifySupplierBlackListByPrimaryKey(SupplierBlackList record); }
add99a80ef59c98c2316720f196f3dad8115c5c4
[ "Markdown", "Java", "Maven POM", "INI" ]
230
Java
quanlj1989/ennew-user
3eace485bc2db3ba3fe3abd79ee443c604b54c19
42391b4e12122ccaeead4e6492ba0eae4f923821
refs/heads/master
<repo_name>kosamasan/nasdaqapp<file_sep>/app/Http/Controllers/SearchController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use View; use Response; use Mail; class SearchController extends Controller { public function index() { return view('home'); } public function submit(Request $request) { //validation with the rules of the fields $this->validate($request, [ 'company_symbol' => 'required|alpha', 'datefrom' => 'required|date', 'dateto' => 'required|date|after:datefrom', 'email' => 'required|email' ]); //assign data to valiables and some transformations for the email and the request to nasdaq.com $symbol = strtoupper($request->input('company_symbol')); $datefrom = $request->input('datefrom'); $fromforemail = date("Y-d-m", strtotime($datefrom)); $datefromfin = date("M%20d,%20Y", strtotime($datefrom)); $dateto = $request->input('dateto'); $toforemail = date("Y-d-m", strtotime($dateto)); $datetofin = date("M%20d,%20Y", strtotime($dateto)); $recip = $request->input('email'); //last check if the symbol is related to a company $checkForComp = 'http://www.nasdaq.com/screening/companies-by-name.aspx?&render=download'; $rows = array_map('str_getcsv', file($checkForComp)); $header = array_shift($rows); $csv = array(); foreach ($rows as $row) { $csv[] = array_combine($header, $row); } $array = json_encode($csv); $compName = ''; foreach($csv as $key => $value) { if ($value['Symbol'] == $symbol) { $compName = $value['Name']; } } //return the error if the symbol is not valid. Otherwise move to results and send the email. if(empty($compName)) { return redirect()->back()->withInput()->withErrors(['company_symbol' => 'Invalid company symbol.']); } else { $url = 'https://finance.google.com/finance/historical?output=csv&q='.$symbol.'&startdate='.$datefromfin.'&enddate='.$datetofin; $rows = array_map('str_getcsv', file($url)); $header = array_shift($rows); $csv = array(); foreach ($rows as $row) { $csv[] = array_combine($header, $row); } $array = json_encode($csv); $foremail = array('email'=>$recip, 'subject'=>$compName); Mail::raw('From '.$fromforemail.' to '.$toforemail, function($message) use ($foremail){ $message->to($foremail['email'])->subject($foremail['subject']); }); //csv variables holds the data collected from the csv an compName holds the company name. return view('results')->with('days', $csv)->with('company', $compName); } } } <file_sep>/tests/Feature/BasicTest.php <?php namespace Tests\Feature; use Tests\TestCase; use Illuminate\Foundation\Testing\WithoutMiddleware; use Illuminate\Foundation\Testing\DatabaseMigrations; use Illuminate\Foundation\Testing\DatabaseTransactions; class BasicTest extends TestCase { /** * A basic test example. * * @return void */ public function testExample() { $this->assertTrue(true); } //this test will check if nasdaq website is ok public function testnasdaq() { $header_check = get_headers("http://www.nasdaq.com"); $response_code = $header_check[0]; $this->assertTrue(strpos($response_code, 'OK') !== false); } //this test will check if google finance website is ok public function testgooglefin() { $header_check = get_headers("https://finance.google.com/finance"); $response_code = $header_check[0]; $this->assertTrue(strpos($response_code, 'OK') !== false); } public function testindexmethodview() { $response = $this->get('/'); $response->assertViewIs('home'); } }
4112bce9afd06b74d00c502e4fa46423c521756a
[ "PHP" ]
2
PHP
kosamasan/nasdaqapp
b48505755aeaaf6aee34227713f92311e6ac7981
dd81de2dd358a2317662907b23ea369a38dd7550
refs/heads/master
<repo_name>hrwilliams/doctors-office<file_sep>/spec/integration_spec.rb require('capybara/rspec') require('./app') Capybara.app = Sinatra::Application set(:show_exceptions, false) describe('adding a new doctor', {:type => :feature}) do it('allows administrator to click a doctor to see the name and specialty') do visit('/') click_link('Add New Doctor') fill_in('name', :with => 'Dr. Deodhar') click_button('Add Specialty') expect(page).to have_content('Success!') end end <file_sep>/lib/doctor.rb class Doctor attr_reader(:name, :specialty_id, :id) define_method(:initialize) do |attributes| @name = attributes.fetch(:name) @specialty_id = attributes.fetch(:specialty_id) @id = attributes.fetch(:id) end define_singleton_method(:all) do returned_doctors = DB.exec("SELECT * FROM doctors;") doctors = [] returned_doctors.each() do |doctor| name = doctor.fetch("name") specialty_id = doctor.fetch("specialty_id").to_i() id = doctor.fetch("id").to_i() doctors.push(Doctor.new({:name => name, :specialty_id => specialty_id, :id => id})) end doctors end define_method(:save) do doctor = DB.exec("INSERT INTO doctors (name, specialty_id) VALUES ('#{@name}', '#{@specialty_id}') RETURNING id;") @id = doctor.first.fetch('id').to_i() end define_method(:==) do |another_doctor| self.name().==(another_doctor.name()).&(self.specialty_id().==(another_doctor.specialty_id())).&(self.id().==(another_doctor.id())) end define_method(:patients_doctor_assignment) do patients_list = [] returned_patient_list = DB.exec("SELECT * FROM patients WHERE doctor_id = #{self.id()};") returned_patient_list.each() do |patient| name = patient.fetch("name") birth_date = patient.fetch("birth_date") doctor_id = patient.fetch("doctor_id").to_i() patients_list.push(Patient.new({:name => name, :birth_date => birth_date, :doctor_id => doctor_id, :id => id})) end patients_list end end <file_sep>/app.rb require("sinatra") require("sinatra/reloader") also_reload("lib/**/*.rb") require("./lib/doctor") require("./lib/patient") require("./lib/specialty") DB = PG.connect({:dbname => "doctors_office"}) get("/") do erb(:index) end get("doctors/new") do erb(:doctor_form) end post("/doctors") do name = params.fetch("name") specialty = Specialty.new({:name => name, :id => id}) specialty.save() erb(:doctor_success) end <file_sep>/spec/doctor_spec.rb require("spec_helper") describe(Doctor) do describe ('#name') do it ('tells you the doctors name') do test_doctor = Doctor.new({:name => 'Dr. Smith', :specialty_id => nil, :id => nil}) expect(test_doctor.name()).to(eq('Dr. Smith')) end end describe('#specialty_id') do it('tells you the doctors specialty id') do test_doctor = Doctor.new({:name => 'Dr. Smith', :id => nil, :specialty_id => 1}) expect(test_doctor.specialty_id()).to(eq(1)) end end describe('.all') do it('will remain empty at first') do expect(Doctor.all()).to(eq([])) end end describe('#save') do it('add a doctor to the array of saved doctors') do test_doctor = Doctor.new({:name => '<NAME>', :id => nil, :specialty_id => 1}) test_doctor.save() expect(Doctor.all()).to(eq([test_doctor])) end end describe('#patients_doctor_assignment') do it('will display a list of patients assigned to a particular doctor') do test_doctor = Doctor.new({:name => 'Dr. Deodhar', :id => nil, :specialty_id => 1}) test_doctor.save patient1 = Patient.new({:name => 'HRW', :birth_date => '1980-01-01', :doctor_id => test_doctor.id()}) patient1.save() patient2 = Patient.new({:name => 'DRW', :birth_date => '1977-02-02', :doctor_id => test_doctor.id()}) patient2.save() expect(test_doctor.patients_doctor_assignment()).to(eq([patient1, patient2])) end end describe("#==") do it("is the same dr if the info matches") do task1 = Doctor.new({:name => 'Dr. Smith', :specialty_id => nil, :id => nil}) task2 = Doctor.new({:name => 'Dr. Smith', :specialty_id => nil, :id => nil}) expect(task1).to(eq(task2)) end end end <file_sep>/spec/patient_spec.rb require ('spec_helper') describe(Patient) do describe('#name') do it('will display the patients name') do test_patient = Patient.new({:name => 'HRW', :birth_date => '1980-01-01', :doctor_id => nil}) expect(test_patient.name()).to(eq('HRW')) end end describe('#birth_date') do it('will display the patients birth_date') do test_patient = Patient.new({:name => 'HRW', :birth_date => '1980-01-01', :doctor_id => nil}) expect(test_patient.birth_date()).to(eq('1980-01-01')) end end describe('.all') do it('starts off with nothing in the array') do expect(Patient.all()).to(eq([])) end end describe('#save') do it('will save the patients info') do test_patient = Patient.new({:name => 'HRW', :birth_date => '1980-01-01', :doctor_id => 1}) test_patient.save() expect(Patient.all()).to(eq([test_patient])) end end describe("#==") do it("is the same patient if the info matches") do patient1 = Patient.new({:name => 'HRW', :birth_date => '1980-01-01-01', :doctor_id => nil}) patient2 = Patient.new({:name => 'HRW', :birth_date => '1980-01-01-01', :doctor_id => nil}) expect(patient1).to(eq(patient2)) end end describe('#doctor_id') do it('will assign a doctor to the patient') do test_patient = Patient.new({:name => 'HRW', :birth_date => '199--01-01', :doctor_id => 1}) test_patient.save() expect(test_patient.doctor_id()).to(eq(1)) end end end
eb4d8fc354fe494acb587ac0f891a5c9685e5f31
[ "Ruby" ]
5
Ruby
hrwilliams/doctors-office
461a56f4a8e4f9077b9d227e3819e1f7805625a8
89add422a6a496f6835235a10c98b438a0ff97d1
refs/heads/master
<file_sep><?php ini_set('max_execution_time', 120); // $gsid = ""; // $aid = ""; $token = ""; function fetch($url,$cookie=null,$postdata=null){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$url); if (!is_null($postdata)) curl_setopt($ch, CURLOPT_POSTFIELDS,$postdata); if (!is_null($cookie)) curl_setopt($ch, CURLOPT_COOKIE,$cookie); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 20); $re = curl_exec($ch); curl_close($ch); return $re; } /** * @author 昌维<<EMAIL>> * @param array * @return array */ function array_add($a1,$a2){ $n = 0; foreach ($a1 as $key => $value) { $re[$n] = $value; $n++; } foreach ($a2 as $key => $value) { $re[$n] = $value; $n++; } return $re; } function get_friends($uid,$uname,$uimg,$ulocation){ global $i; global $j; global $result; global $count; global $deep; $j++; if ($j > $deep) { return $result; } $guanzhu = json_decode(file_get_contents("http://api.weibo.cn/2/friendships/friends?networktype=wifi&trim_status=0&uicode=10000195&moduleID=700&featurecode=10000001&c=android&i=39b3e35&s=7427c218&ua=Meizu-M578C__weibo__6.4.0__android__android5.1&wm=9848_0009&aid=01Ao_lf0wQkI08S7yJExcs03HqldztOkKI2wqQUlgKhIiopmA.&uid={$uid}&v_f=2&from=1064095010&gsid=_2A256Fw-cDeRxGeNP6VUZ8C_MwjWIHXVWhQRUrDV6PUJbrdAKLVjmkWpLHeugwfkkKAubZPEgKa8Pn5L8mZKi0g..&lang=zh_CN&lfid=1076033198740351_-_WEIBO_SECOND_PROFILE_WEIBO&page=1&skin=default&sort=1&has_pages=1&count=20&oldwm=19005_0019&sflag=1&luicode=10000198&has_top=0&has_relation=1&has_member=1&lastmblog=1"),1); // /2/friendships/friends?networktype=wifi&trim_status=0&uicode=10000195&moduleID=700&featurecode=10000001&c=android&i=39b3e35&s=7427c218&ua=Meizu-M578C__weibo__6.4.0__android__android5.1&wm=9848_0009&aid=01Ao_lf0wQkI08S7yJExcs03HqldztOkKI2wqQUlgKhIiopmA.&uid=3198740351&v_f=2&from=1064095010&gsid=_2A256Fw-cDeRxGeNP6VUZ8C_MwjWIHXVWhQRUrDV6PUJbrdAKLVjmkWpLHeugwfkkKAubZPEgKa8Pn5L8mZKi0g..&lang=zh_CN&lfid=1076033198740351_-_WEIBO_SECOND_PROFILE_WEIBO&page=1&skin=default&sort=1&has_pages=1&count=20&oldwm=19005_0019&sflag=1&luicode=10000198&has_top=0&has_relation=1&has_member=1&lastmblog=1 // $re = array_add($fensi['users'],$guanzhu['users']); // print_r($re); // $i = 0; // print_r("进入get函数 此时变量i为{$i},j变量为{$j},开始抓取【{$uid}】的粉丝--------------------------------------------------\n"); foreach ($guanzhu['users'] as $key => $value) { $result[$i]['source_uid'] = $uid; $result[$i]['source_name'] = $uname; $result[$i]['source_img'] = $uimg; $result[$i]['source_location'] = $ulocation; $result[$i]['target_uid'] = $value['id']; $result[$i]['target_name'] = $value['screen_name']; $result[$i]['target_img'] = $value['profile_image_url']; $result[$i]['target_location'] = $value['location']; $i++; // print_r($result); // print_r("进入get函数 此时变量i为{$i},j变量为{$j},开始抓取【".$value['name']."】的粉丝--------------------------------------------------\n"); $result = get_friends($value['id'],$value['screen_name'],$value['profile_image_url'],$value['location']); // print_r("进入get函数 此时变量i为{$i},j变量为{$j}--------------------------------------------------\n"); } // print_r("退出foreach 此时变量i为{$i},j变量为{$j},结束抓取--------------------------------------------------\n"); return $result; } function get_followers($uid,$uname,$uimg,$ulocation){ global $i; global $j; global $result; global $count; global $deep; $j++; if ($j > $deep) { return $result; } $fensi = json_decode(file_get_contents("http://api.weibo.cn/2/friendships/followers?networktype=wifi&trim_status=0&uicode=10000081&moduleID=700&featurecode=10000001&c=android&i=39b3e35&s=7427c218&ua=Meizu-M578C__weibo__6.4.0__android__android5.1&wm=9848_0009&aid=01Ao_lf0wQkI08S7yJExcs03HqldztOkKI2wqQUlgKhIiopmA.&uid={$uid}&v_f=2&from=1064095010&gsid=_2A256Fw-cDeRxGeNP6VUZ8C_MwjWIHXVWhQRUrDV6PUJbrdAKLVjmkWpLHeugwfkkKAubZPEgKa8Pn5L8mZKi0g..&lang=zh_CN&lfid=1076033198740351_-_WEIBO_SECOND_PROFILE_WEIBO&page=1&skin=default&sort=3&has_pages=0&count=20&oldwm=19005_0019&sflag=1&luicode=10000198&has_top=0&has_relation=1&has_member=1&lastmblog=1"),1); // /2/friendships/followers?networktype=wifi&trim_status=0&uicode=10000081&moduleID=700&featurecode=10000001&c=android&i=39b3e35&s=7427c218&ua=Meizu-M578C__weibo__6.4.0__android__android5.1&wm=9848_0009&aid=01Ao_lf0wQkI08S7yJExcs03HqldztOkKI2wqQUlgKhIiopmA.&uid=3198740351&v_f=2&from=1064095010&gsid=_2A256Fw-cDeRxGeNP6VUZ8C_MwjWIHXVWhQRUrDV6PUJbrdAKLVjmkWpLHeugwfkkKAubZPEgKa8Pn5L8mZKi0g..&lang=zh_CN&lfid=1076033198740351_-_WEIBO_SECOND_PROFILE_WEIBO&page=1&skin=default&sort=3&has_pages=0&count=20&oldwm=19005_0019&sflag=1&luicode=10000198&has_top=0&has_relation=1&has_member=1&lastmblog=1 // $re = array_add($fensi['users'],$guanzhu['users']); // print_r($re); // $i = 0; // print_r("进入get函数 此时变量i为{$i},j变量为{$j},开始抓取【{$uid}】的粉丝--------------------------------------------------\n"); foreach ($fensi['users'] as $key => $value) { $result[$i]['target_uid'] = $uid; $result[$i]['target_name'] = $uname; $result[$i]['target_img'] = $uimg; $result[$i]['target_location'] = $ulocation; $result[$i]['source_uid'] = $value['id']; $result[$i]['source_name'] = $value['screen_name']; $result[$i]['source_img'] = $value['profile_image_url']; $result[$i]['source_location'] = $value['location']; $i++; // print_r($result); // print_r("进入get函数 此时变量i为{$i},j变量为{$j},开始抓取【".$value['name']."】的粉丝--------------------------------------------------\n"); $result = get_followers($value['id'],$value['screen_name'],$value['profile_image_url'],$value['location']); // print_r("进入get函数 此时变量i为{$i},j变量为{$j}--------------------------------------------------\n"); } // print_r("退出foreach 此时变量i为{$i},j变量为{$j},结束抓取--------------------------------------------------\n"); return $result; } $url = 'https://api.weibo.com/2/users/show.json?screen_name='.urlencode($_GET['weiboid']).'&access_token='.$token; // $user_info = fetch($url); $user_info = json_decode(file_get_contents($url),1); // print_r(json_decode($user_info));exit(); $result = array(); $i = 0; $j = 0; $count = $_GET['count']; $deep = $_GET['deep']; $option_data = get_friends($user_info['id'],$_GET['weiboid'],$user_info['profile_image_url'],$user_info['location']); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title><?php echo $_GET['weiboid'] ?>的微博关系网</title> </head> <body> <!-- 为ECharts准备一个具备大小(宽高)的Dom --> <div id="main" style="width: <?php echo $_GET['width'] ?>px;height: <?php echo $_GET['height'] ?>px"></div> <!-- ECharts单文件引入 --> <script src="http://echarts.baidu.com/build/dist/echarts.js"></script> <script type="text/javascript"> // 路径配置 require.config({ paths: { echarts: 'http://echarts.baidu.com/build/dist' } }); // 使用 require( [ 'echarts', 'echarts/chart/force' // 使用柱状图就加载bar模块,按需加载 ], function (ec) { // 基于准备好的dom,初始化echarts图表 var myChart = ec.init(document.getElementById('main')); option = { title : { text: '新浪微博关系网', subtext: 'www.changwei.me', x:'right', y:'bottom' }, tooltip : { trigger: 'item', formatter: '{a} : {b}' }, toolbox: { show : true, feature : { restore : {show: true}, magicType: {show: true, type: ['force', 'chord']}, saveAsImage : {show: true} } }, legend: { x: 'left', data:['家人','朋友'] }, series : [ { type:'force', name : "人物关系", ribbonType: false, categories : [/* { name: '人物' }, { name: '家人', symbol: 'diamond' }, { name:'朋友' }*/ ], itemStyle: { normal: { label: { show: true, textStyle: { color: '#333' } }, nodeStyle : { brushType : 'both', borderColor : 'rgba(255,215,0,0.4)', borderWidth : 1 } }, emphasis: { label: { show: false // textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE }, nodeStyle : { //r: 30 }, linkStyle : {} } }, minRadius : <?php echo $_GET['minRadius'] ?>, maxRadius : <?php echo $_GET['maxRadius'] ?>, gravity: <?php echo $_GET['gravity'] ?>, scaling: <?php echo $_GET['scaling'] ?>, draggable: true, linkSymbol: 'arrow', steps: 10, coolDown: 0.9, //preventOverlap: true, // size: 50%, nodes:[ <?php foreach ($option_data as $key => $value) { ?> {category:1, name: '<?php echo $value['source_name'] ?>',value : 2}, {category:2, name: '<?php echo $value['target_name'] ?>',value : 2}, <?php } ?> ], links : [ // {source : '丽萨-乔布斯', target : '乔布斯', weight : 1, name: '女儿', itemStyle: { // normal: { // width: 1.5, // color: 'red' // } // }}, // {source : '乔布斯', target : '丽萨-乔布斯', weight : 1, name: '父亲', itemStyle: { // normal: { color: 'red' } // }}, <?php foreach ($option_data as $key => $value) { ?> {source : '<?php echo $value['source_name'] ?>', target : '<?php echo $value['target_name'] ?>', weight : 1, name: ''}, <?php } ?> ] } ] }; // 为echarts对象加载数据 myChart.setOption(option); } ); </script> </body> </html><file_sep># weibo-relationship 微博关系网绘制工具 开发时间:2016/2/3 一个使用PHP和Echarts2.0开发的微博关系网生成器,已不再维护。 获取粉丝接口为客户端抓包得到,其中的access_token等参数需要抓包获取 后续将会有重写版本
051775e19db6a406ca48c3202ed2ffc9d314d2a1
[ "Markdown", "PHP" ]
2
PHP
cw1997/weibo-relationship
90f91c250c7075d20046d6ae30e732a39ec176bb
b1f6d99a4382b773a9448b95cb369cc4023be067
refs/heads/master
<file_sep># TestDemo 自己学习中的一些笔记和demo <file_sep>platform :ios,'7.0' target'TestDemo' do pod 'YYKit', '~>1.0' pod 'SSKeychain', '~>1.0' pod 'MJRefresh', '~>3.1.10' pod 'JSONModel', '~> 1.2.0' pod 'SDWebImage', '~>3.8' pod 'IQKeyboardManager' pod 'MBProgressHUD', '~> 1.0.0' pod 'Masonry', '~> 1.0.1' pod 'MJExtension' pod 'FDFullscreenPopGesture','~>1.1' pod ‘FMDB’ end
3cdaeb59efc4cc80c752925c4fba2789f68b7bad
[ "Markdown", "Ruby" ]
2
Markdown
yangxinliang/TestDemo
008ead1ce92566f8289ff55c7f18ae1fe26281b1
c1dd8cee3d682828fe4ffb81e4ceeca7437a6a5d
refs/heads/main
<repo_name>LuizaQFernandes/Cadastro-de-Estudantes<file_sep>/src/app/student.ts export interface Student { id: number ra: number; name: string; age: number; sala: string; parent: string; }
01c4ceba5f139b0123884364198db25c1241e184
[ "TypeScript" ]
1
TypeScript
LuizaQFernandes/Cadastro-de-Estudantes
27191c72483ccf07eef77bb7cef599cd31abd238
875c5abb15fc560d38d9a653829dcf90074f0d53
refs/heads/master
<repo_name>revenant20/onlineChat<file_sep>/src/server/AuthServiceWithoutDB.java package server; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class AuthServiceWithoutDB implements AuthService { private Map<String,User> users; public AuthServiceWithoutDB() { this.users = Collections.synchronizedMap(new HashMap<>()); for (int i = 1; i < 11; i++) { users.put("l"+i,new User("l"+i,"p"+i,"nick"+i)); } } @Override public void start() { System.out.println("Service start"); } @Override public String getNameByLoginAndPassword(String login, String password) { User user = users.get(login); if(user != null){ if(user.isSamePassword(password)){ return user.getNick(); } } return null; } @Override public void stop() { System.out.println("Service stop"); } } <file_sep>/src/server/Server.java package server; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.*; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.CopyOnWriteArrayList; public class Server { private ServerSocket server; private final String ADDRES = "localhost"; private final int PORT = 8189; private List<ClientHandler> clients; private AuthService authService; private HistoryWriter history; public AuthService getAuthService() { return authService; } public Server() { Socket socket; try { server = new ServerSocket(PORT); clients = new CopyOnWriteArrayList<>(); history = new HistoryWriter(new ConcurrentLinkedDeque<>(),10); authService = new AuthServiceWithoutDB(); System.out.println("Cервер подключился"); authService.start(); while (true) { socket = server.accept(); System.out.println("клиент подключился " + socket); new ClientHandler(this, socket); } } catch (IOException e) { e.printStackTrace(); } finally { authService.stop(); try { server.close(); } catch (IOException e) { e.printStackTrace(); } } } public void subscribe(ClientHandler client) { sendAllClientsMsg(client.getName() + " зашел в чат."); clients.add(client); sendAllClientsListOfUsers(); sendHistory(client); } private void sendHistory(ClientHandler client){ Collection<String> hist = history.get(); for (String historyMsg : hist) { client.sendMsg(historyMsg); } } public void unsubscribe(ClientHandler clientHandler) { if (clients.contains(clientHandler)) { sendAllClientsMsg(clientHandler.getName() + " вышел из чата."); clients.remove(clientHandler); sendAllClientsListOfUsers(); } } public boolean isNameBusy(String name) { for (ClientHandler client : clients) { if (client.getName().equals(name)) { return true; } } return false; } private String getCurrentTime() { return "" + Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + Calendar.getInstance().get(Calendar.MINUTE) + " "; } public void sendAllClientsMsg(String msg) { String outMsg = getCurrentTime() + msg; for (ClientHandler client : clients) { client.sendMsg(outMsg); } history.add(outMsg); } public void sendAllClientsListOfUsers() { StringBuilder sb = new StringBuilder("/clients "); for (ClientHandler client : clients) { sb.append(client.getName()).append(" "); } String userList = sb.toString(); for (ClientHandler client : clients) { client.sendMsg(userList); } } public void sendPrivateMsg(ClientHandler client, String userName, String msg) { String time = getCurrentTime(); for (ClientHandler o : clients) { if (o.getName().equals(userName)) { o.sendMsg(time + "от " + client.getName() + ": " + msg); client.sendMsg(time + "клиенту " + userName + ": " + msg); return; } } client.sendMsg(time + "клиент " + userName + " отсутствует в чате."); } } <file_sep>/src/server/HistoryWriterService.java package server; import java.util.Collection; import java.util.Deque; import java.util.List; public interface HistoryWriterService { void add(String string); Collection<String> get(); }
a08ff0c8b1372b6ad11e4f3282e5d62d80d1bf3e
[ "Java" ]
3
Java
revenant20/onlineChat
fac14b652a1d182ba3aeee95312c31b6b7e734d9
3ad231a379d8011c600a78db067921b59eb0f08a
refs/heads/master
<file_sep>using System; namespace TSAPILIB2 { public class EventArg<T1> { public T1 Result = default(T1); public EventArg() { } public EventArg(object a1) { Result = (T1)a1; } public EventArg(T1 a1) { Result = a1; } public void Set(T1 data) { Result = data; } } public class UniversalFailureEventArg : EventArgs { public ACSUniversalFailure_t Error { get; set; } public PrivateData_t Pd { get; set; } public uint InvokeID { get; set; } } public class UniversalFailureSys : EventArgs { public ACSUniversalFailure_t Error { get; set; } public eventTypeACS EventType { get; set; } } public class AgentStateEventArgs : EventArgs { public ATTQueryAgentStateConfEvent_t Mode { get; set; } } }<file_sep>using System; using System.Collections.Concurrent; using System.Linq; using System.Threading.Tasks; namespace TSAPILIB2 { public class CbTask<T> : ConcurrentDictionary<T, MyTask> { private readonly int _maxCapasiti; public CbTask(int maxCapasiti) { _maxCapasiti = maxCapasiti; } public string CurrentCommand() { return ToArray().Select(c=> $"{c.Key}:{c.Value.Command}").Aggregate("" ,(s, s1) => s + "\n" + s1); } public CbTask() { } public Task<object> Add(T key, MyTask task = null, string command = null, Int32 timeoutMs = 30) { var t = task ?? new MyTask(timeoutMs, command); t.OnTimeout += myTask => { MyTask cb; TryRemove(key, out cb); }; if (_maxCapasiti != 0 && Count >= _maxCapasiti) { t.SetError(CSTAUniversalFailure_t.CBTaskIsFull); } else { if (!TryAdd(key, t)) { t.SetError(CSTAUniversalFailure_t.genericOperationRejection); } } return t.Task; } public bool Set(T invokeId, object ret) { MyTask cb; if (!TryRemove(invokeId, out cb)) return false; cb.Set(ret); cb.Dispose(); return true; } public bool SetError(T invokeId, CSTAUniversalFailure_t error) { MyTask cb; if (!TryRemove(invokeId, out cb)) return false; cb.SetError(error); cb.Dispose(); return true; } public bool UpdateTimeout(T invokeId) { MyTask cb; if (!TryGetValue(invokeId, out cb)) return false; cb.UpdateTimeout(); return true; } public MyTask GeTask(T invokeId) { MyTask cb; if (!TryRemove(invokeId, out cb)) return null; cb.UpdateTimeout(); return cb; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TSAPILIB2 { public class DeviceExeption : Exception { public String device; public DeviceExeption(String device,String error) :base (String.Format("Device {0}. Error: '{1}'" ,device,error)) { this.device = device; } } public class Device { protected TSAPI tsapi; protected String device; protected CSTAQueryDeviceInfoConfEvent_t device_info; protected ATTQueryDeviceInfoConfEvent_t device_associated_info; public DeviceType_t type{get{ return this.device_info.deviceType;}} public DeviceClass_t classe{get{ return this.device_info.deviceClass;}} public ATTExtensionClass_t associatedClass{get{ return this.device_associated_info.associatedClass;}} public String associatedDevice{get{ return this.device_associated_info.associatedDevice;}} public Device(TSAPI tsapi, String device) { this.tsapi = tsapi; this.device = device; resultQueryDeviceInfo inf = new resultQueryDeviceInfo(this.initDevice); this.tsapi.getQueryDeviceInfoAsync(this.device, this.initDevice); this.tsapi.getQueryDeviceInfoAsync(this.device, this.initDevice); } protected void initDevice(QueryDeviceInfoEventArg arg) { Console.WriteLine(arg.error); if (arg.error == CSTAUniversalFailure_t.allOK) { this.device_info = arg.arg; this.device_associated_info = arg.att_arg; }else{ throw new DeviceExeption(this.device,"initDevice "+arg.error); } } public String getDeviceId() { return this.device; } } } <file_sep>[Telephony Servers] 192.168.208.6=450 ; This is a list of the servers offering Telephony Services via TCP/IP. ; Either domain name or IP address may be used; default port number is 450 ; The form is: host_name=port_number For example: ; ; tserver.mydomain.com=450 ; 127.0.0.1=450 ; [Shared Admin] ; Instead of each workstation maintaining its own list of servers, a shared ; tslib.ini file may be placed on a network file system, for example: ; ; tslib.ini=n:\csta\tslib.ini ; ; This entry overrides the [Telephony Servers] section, if any. <file_sep>using System; using System.Linq; using System.Threading; using System.Collections.Concurrent; using System.Threading.Tasks; namespace TSAPILIB2 { public class MyTask:IDisposable { private readonly string _command; private readonly int _timeoutMs; private Timer _time; private readonly object _locktask = new object(); private readonly TaskCompletionSource<object> _task = new TaskCompletionSource<object>(); public Task<object> Task { get { return _task.Task; } } public string Command { get { return _command; } } public Int32 CountElapsend = 0; private bool _disposed; public MyTask( Int32 timeoutMs, String command) { _command = command; _timeoutMs = timeoutMs*1000; _time = new Timer(SetTimeout, this, _timeoutMs, Timeout.Infinite); } private void SetTimeout(object state) { lock (_locktask) { if (!_task.Task.IsCompleted) _task.SetException(new CSTAExeption(CSTAUniversalFailure_t.operationTimeout)); } } public void UpdateTimeout() { lock (_locktask) { if (_time != null) { _time.Change(_timeoutMs, Timeout.Infinite); } } } protected virtual void Dispose(Boolean disposing) { if (_disposed)return; // Ресурсы уже освобождены if (disposing) { lock (_locktask) { _time.Dispose(); _time = null; } } _disposed = true; } public void Dispose() { Dispose(true); } public void Set(object ret) { lock (_locktask) { _task.TrySetResult(ret); } } public void SetError( CSTAUniversalFailure_t error) { lock (_locktask) { _task.TrySetException(new CSTAExeption(error)); } } } public class CBTask<T> : ConcurrentDictionary<T, MyTask> { private readonly int _maxCapasiti; public CBTask(Int32 maxCapasiti) { _maxCapasiti = maxCapasiti; } public String CurrentCommand() { return ToArray().Select(c=>String.Format("{0}:{1}",c.Key,c.Value.Command)).Aggregate("" ,(s, s1) => s + "\n" + s1); } public CBTask() { } public Task<object> Add(T key, MyTask task = null, string command = null, Int32 timeoutMs = 30) { var t =task ?? new MyTask(timeoutMs, command); if (_maxCapasiti != 0 && Count >= _maxCapasiti) { t.SetError(CSTAUniversalFailure_t.CBTaskIsFull); } else { if (!TryAdd(key, t)) { t.SetError(CSTAUniversalFailure_t.genericOperationRejection); } } return t.Task; } public Boolean Set(T invokeID, object ret) { MyTask cb; if (!TryRemove(invokeID, out cb)) return false; cb.Set(ret); cb.Dispose(); return true; } public Boolean SetError(T invokeID, CSTAUniversalFailure_t error) { MyTask cb; if (!TryRemove(invokeID, out cb)) return false; cb.SetError(error); cb.Dispose(); return true; } public Boolean UpdateTimeout(T invokeID) { MyTask cb; if (!TryGetValue(invokeID, out cb)) return false; cb.UpdateTimeout(); return true; } public MyTask GeTask(T invokeID) { MyTask cb; if (!TryRemove(invokeID, out cb)) return null; cb.UpdateTimeout(); return cb; } } } <file_sep>using System; using System.Linq; using System.Runtime.InteropServices; namespace TSAPILIB2 { [Serializable,StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)] public struct AcsUnsolicitedEvent { private readonly eventTypeACS _type; public ACSUniversalFailureEvent_t failureEvent; public AcsUnsolicitedEvent(IntPtr point, eventTypeACS type) { _type = type; failureEvent = (ACSUniversalFailureEvent_t) Marshal.PtrToStructure(point, typeof (ACSUniversalFailureEvent_t)); } public eventTypeACS GetTypeEvent() { return _type; } } [Serializable,StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ACSConfirmationEvent { public uint invokeID; public ACSOpenStreamConfEvent_t ascOpen; public ACSCloseStreamConfEvent_t acsclose; public ACSUniversalFailureConfEvent_t failureEvent; public ACSConfirmationEvent(IntPtr point, eventTypeACS type) { ascOpen = new ACSOpenStreamConfEvent_t(); acsclose = new ACSCloseStreamConfEvent_t(); failureEvent = new ACSUniversalFailureConfEvent_t(); invokeID = (uint) Marshal.ReadInt32(point); point = IntPtr.Add(point, Marshal.SizeOf(invokeID)); switch (type) { case eventTypeACS.ACS_OPEN_STREAM_CONF: ascOpen = (ACSOpenStreamConfEvent_t) Marshal.PtrToStructure(point, typeof (ACSOpenStreamConfEvent_t)); break; case eventTypeACS.ACS_CLOSE_STREAM_CONF: acsclose = (ACSCloseStreamConfEvent_t) Marshal.PtrToStructure(point, typeof (ACSCloseStreamConfEvent_t)); break; case eventTypeACS.ACS_UNIVERSAL_FAILURE_CONF: failureEvent = (ACSUniversalFailureConfEvent_t) Marshal.PtrToStructure(point, typeof (ACSUniversalFailureConfEvent_t)); break; } } } [Serializable,StructLayout(LayoutKind.Sequential, Pack = 1)] public struct AcsConfirmationEvent { public uint invokeID; public ACSOpenStreamConfEvent_t ascOpen; public ACSCloseStreamConfEvent_t acsclose; public ACSUniversalFailureConfEvent_t failureEvent; public AcsConfirmationEvent(IntPtr point, eventTypeACS type) { ascOpen = new ACSOpenStreamConfEvent_t(); acsclose = new ACSCloseStreamConfEvent_t(); failureEvent = new ACSUniversalFailureConfEvent_t(); invokeID = (uint) Marshal.ReadInt32(point); point = IntPtr.Add(point, Marshal.SizeOf(invokeID)); switch (type) { case eventTypeACS.ACS_OPEN_STREAM_CONF: ascOpen = (ACSOpenStreamConfEvent_t) Marshal.PtrToStructure(point, typeof (ACSOpenStreamConfEvent_t)); break; case eventTypeACS.ACS_CLOSE_STREAM_CONF: acsclose = (ACSCloseStreamConfEvent_t) Marshal.PtrToStructure(point, typeof (ACSCloseStreamConfEvent_t)); break; case eventTypeACS.ACS_UNIVERSAL_FAILURE_CONF: failureEvent = (ACSUniversalFailureConfEvent_t) Marshal.PtrToStructure(point, typeof (ACSUniversalFailureConfEvent_t)); break; } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CstaRequestEvent { public uint invokeID; public CSTARouteRequestEvent_t routeRequest; public CSTARouteRequestExtEvent_t routeRequestExt; public CSTAReRouteRequest_t reRouteRequest; public CSTAEscapeSvcReqEvent_t escapeSvcReqeust; public CSTASysStatReqEvent_t sysStatRequest; public CstaRequestEvent(IntPtr point, eventTypeCSTA type) { routeRequest = new CSTARouteRequestEvent_t(); routeRequestExt = new CSTARouteRequestExtEvent_t(); reRouteRequest = new CSTAReRouteRequest_t(); escapeSvcReqeust = new CSTAEscapeSvcReqEvent_t(); sysStatRequest = new CSTASysStatReqEvent_t(); invokeID = (uint) Marshal.ReadInt32(point); point = IntPtr.Add(point, Marshal.SizeOf(invokeID)); switch (type) { case eventTypeCSTA.CSTA_ROUTE_REQUEST: routeRequest = (CSTARouteRequestEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteRequestEvent_t)); break; case eventTypeCSTA.CSTA_ROUTE_SELECT_REQUEST: break; case eventTypeCSTA.CSTA_RE_ROUTE_REQUEST: reRouteRequest = (CSTAReRouteRequest_t) Marshal.PtrToStructure(point, typeof (CSTAReRouteRequest_t)); break; case eventTypeCSTA.CSTA_ROUTE_END_REQUEST: break; case eventTypeCSTA.CSTA_ESCAPE_SVC: break; case eventTypeCSTA.CSTA_ESCAPE_SVC_CONF: break; case eventTypeCSTA.CSTA_ESCAPE_SVC_REQ: break; case eventTypeCSTA.CSTA_ESCAPE_SVC_REQ_CONF: escapeSvcReqeust = (CSTAEscapeSvcReqEvent_t) Marshal.PtrToStructure(point, typeof (CSTAEscapeSvcReqEvent_t)); break; case eventTypeCSTA.CSTA_REQ_SYS_STAT: break; case eventTypeCSTA.CSTA_SYS_STAT_REQ: sysStatRequest = (CSTASysStatReqEvent_t) Marshal.PtrToStructure(point, typeof (CSTASysStatReqEvent_t)); break; case eventTypeCSTA.CSTA_SYS_STAT_START: break; case eventTypeCSTA.CSTA_SYS_STAT_START_CONF: break; case eventTypeCSTA.CSTA_SYS_STAT_STOP: break; case eventTypeCSTA.CSTA_SYS_STAT_STOP_CONF: break; case eventTypeCSTA.CSTA_REQ_SYS_STAT_CONF: break; case eventTypeCSTA.CSTA_ROUTE_REQUEST_EXT: routeRequestExt = (CSTARouteRequestExtEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteRequestExtEvent_t)); break; case eventTypeCSTA.CSTA_ROUTE_USED_EXT: break; case eventTypeCSTA.CSTA_ROUTE_SELECT_INV_REQUEST: break; case eventTypeCSTA.CSTA_ROUTE_END_INV_REQUEST: break; } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CstaUnsolicitedEvent { private readonly eventTypeCSTA _type; public uint monitorCrossRefId; public CSTACallClearedEvent_t callCleared; public CSTAConferencedEvent_t conferenced; public CSTAConnectionClearedEvent_t connectionCleared; public CSTADeliveredEvent_t delivered; public CSTADivertedEvent_t diverted; public CSTAEstablishedEvent_t established; public CSTAFailedEvent_t failed; public CSTAHeldEvent_t held; public CSTANetworkReachedEvent_t networkReached; public CSTAOriginatedEvent_t originated; public CSTAQueuedEvent_t queued; public CSTARetrievedEvent_t retrieved; public CSTAServiceInitiatedEvent_t serviceInitiated; public CSTATransferredEvent_t transferred; public CSTACallInformationEvent_t callInformation; public CSTADoNotDisturbEvent_t doNotDisturb; public CSTAForwardingEvent_t forwarding; public CSTAMessageWaitingEvent_t messageWaiting; public CSTALoggedOnEvent_t loggedOn; public CSTALoggedOffEvent_t loggedOff; public CSTANotReadyEvent_t notReady; public CSTAReadyEvent_t ready; public CSTAWorkNotReadyEvent_t workNotReady; public CSTAWorkReadyEvent_t workReady; public CSTABackInServiceEvent_t backInService; public CSTAOutOfServiceEvent_t outOfService; public CSTAPrivateStatusEvent_t privateStatus; public CSTAMonitorEndedEvent_t monitorEnded; public eventTypeCSTA GetTypeEvent() { return _type; } public CstaUnsolicitedEvent(IntPtr point, eventTypeCSTA type) { _type = type; monitorCrossRefId = (uint) Marshal.ReadInt32(point); point = IntPtr.Add(point, Marshal.SizeOf(monitorCrossRefId)); callCleared = new CSTACallClearedEvent_t(); connectionCleared = new CSTAConnectionClearedEvent_t(); conferenced = new CSTAConferencedEvent_t(); transferred = new CSTATransferredEvent_t(); callCleared = new CSTACallClearedEvent_t(); conferenced = new CSTAConferencedEvent_t(); connectionCleared = new CSTAConnectionClearedEvent_t(); delivered = new CSTADeliveredEvent_t(); diverted = new CSTADivertedEvent_t(); established = new CSTAEstablishedEvent_t(); failed = new CSTAFailedEvent_t(); held = new CSTAHeldEvent_t(); networkReached = new CSTANetworkReachedEvent_t(); originated = new CSTAOriginatedEvent_t(); queued = new CSTAQueuedEvent_t(); retrieved = new CSTARetrievedEvent_t(); serviceInitiated = new CSTAServiceInitiatedEvent_t(); transferred = new CSTATransferredEvent_t(); callInformation = new CSTACallInformationEvent_t(); doNotDisturb = new CSTADoNotDisturbEvent_t(); forwarding = new CSTAForwardingEvent_t(); messageWaiting = new CSTAMessageWaitingEvent_t(); loggedOn = new CSTALoggedOnEvent_t(); loggedOff = new CSTALoggedOffEvent_t(); notReady = new CSTANotReadyEvent_t(); ready = new CSTAReadyEvent_t(); workNotReady = new CSTAWorkNotReadyEvent_t(); workReady = new CSTAWorkReadyEvent_t(); privateStatus = new CSTAPrivateStatusEvent_t(); backInService = new CSTABackInServiceEvent_t(); outOfService = new CSTAOutOfServiceEvent_t(); monitorEnded = new CSTAMonitorEndedEvent_t(); switch (type) { case eventTypeCSTA.CSTA_CLEAR_CALL: callCleared = (CSTACallClearedEvent_t) Marshal.PtrToStructure(point, typeof (CSTACallClearedEvent_t)); break; case eventTypeCSTA.CSTA_CLEAR_CONNECTION: connectionCleared = (CSTAConnectionClearedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAConnectionClearedEvent_t)); break; case eventTypeCSTA.CSTA_CONFERENCE_CALL: conferenced = (CSTAConferencedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAConferencedEvent_t)); break; case eventTypeCSTA.CSTA_TRANSFER_CALL: transferred = (CSTATransferredEvent_t) Marshal.PtrToStructure(point, typeof (CSTATransferredEvent_t)); break; case eventTypeCSTA.CSTA_CALL_CLEARED: callCleared = (CSTACallClearedEvent_t) Marshal.PtrToStructure(point, typeof (CSTACallClearedEvent_t)); break; case eventTypeCSTA.CSTA_CONFERENCED: conferenced = (CSTAConferencedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAConferencedEvent_t)); break; case eventTypeCSTA.CSTA_CONNECTION_CLEARED: connectionCleared = (CSTAConnectionClearedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAConnectionClearedEvent_t)); break; case eventTypeCSTA.CSTA_DELIVERED: delivered = (CSTADeliveredEvent_t) Marshal.PtrToStructure(point, typeof (CSTADeliveredEvent_t)); break; case eventTypeCSTA.CSTA_DIVERTED: diverted = (CSTADivertedEvent_t) Marshal.PtrToStructure(point, typeof (CSTADivertedEvent_t)); break; case eventTypeCSTA.CSTA_ESTABLISHED: established = (CSTAEstablishedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAEstablishedEvent_t)); break; case eventTypeCSTA.CSTA_FAILED: failed = (CSTAFailedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAFailedEvent_t)); break; case eventTypeCSTA.CSTA_HELD: held = (CSTAHeldEvent_t) Marshal.PtrToStructure(point, typeof (CSTAHeldEvent_t)); break; case eventTypeCSTA.CSTA_NETWORK_REACHED: networkReached = (CSTANetworkReachedEvent_t) Marshal.PtrToStructure(point, typeof (CSTANetworkReachedEvent_t)); break; case eventTypeCSTA.CSTA_ORIGINATED: originated = (CSTAOriginatedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAOriginatedEvent_t)); break; case eventTypeCSTA.CSTA_QUEUED: queued = (CSTAQueuedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueuedEvent_t)); break; case eventTypeCSTA.CSTA_RETRIEVED: retrieved = (CSTARetrievedEvent_t) Marshal.PtrToStructure(point, typeof (CSTARetrievedEvent_t)); break; case eventTypeCSTA.CSTA_SERVICE_INITIATED: serviceInitiated = (CSTAServiceInitiatedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAServiceInitiatedEvent_t)); break; case eventTypeCSTA.CSTA_TRANSFERRED: transferred = (CSTATransferredEvent_t) Marshal.PtrToStructure(point, typeof (CSTATransferredEvent_t)); break; case eventTypeCSTA.CSTA_CALL_INFORMATION: callInformation = (CSTACallInformationEvent_t) Marshal.PtrToStructure(point, typeof (CSTACallInformationEvent_t)); break; case eventTypeCSTA.CSTA_DO_NOT_DISTURB: doNotDisturb = (CSTADoNotDisturbEvent_t) Marshal.PtrToStructure(point, typeof (CSTADoNotDisturbEvent_t)); break; case eventTypeCSTA.CSTA_FORWARDING: forwarding = (CSTAForwardingEvent_t) Marshal.PtrToStructure(point, typeof (CSTAForwardingEvent_t)); break; case eventTypeCSTA.CSTA_MESSAGE_WAITING: messageWaiting = (CSTAMessageWaitingEvent_t) Marshal.PtrToStructure(point, typeof (CSTAMessageWaitingEvent_t)); break; case eventTypeCSTA.CSTA_LOGGED_ON: loggedOn = (CSTALoggedOnEvent_t) Marshal.PtrToStructure(point, typeof (CSTALoggedOnEvent_t)); break; case eventTypeCSTA.CSTA_LOGGED_OFF: loggedOff = (CSTALoggedOffEvent_t) Marshal.PtrToStructure(point, typeof (CSTALoggedOffEvent_t)); break; case eventTypeCSTA.CSTA_NOT_READY: notReady = (CSTANotReadyEvent_t) Marshal.PtrToStructure(point, typeof (CSTANotReadyEvent_t)); break; case eventTypeCSTA.CSTA_READY: ready = (CSTAReadyEvent_t) Marshal.PtrToStructure(point, typeof (CSTAReadyEvent_t)); break; case eventTypeCSTA.CSTA_WORK_NOT_READY: workNotReady = (CSTAWorkNotReadyEvent_t) Marshal.PtrToStructure(point, typeof (CSTAWorkNotReadyEvent_t)); break; case eventTypeCSTA.CSTA_WORK_READY: workReady = (CSTAWorkReadyEvent_t) Marshal.PtrToStructure(point, typeof (CSTAWorkReadyEvent_t)); break; case eventTypeCSTA.CSTA_PRIVATE_STATUS: privateStatus = (CSTAPrivateStatusEvent_t) Marshal.PtrToStructure(point, typeof (CSTAPrivateStatusEvent_t)); break; case eventTypeCSTA.CSTA_SEND_PRIVATE: break; case eventTypeCSTA.CSTA_BACK_IN_SERVICE: backInService = (CSTABackInServiceEvent_t) Marshal.PtrToStructure(point, typeof (CSTABackInServiceEvent_t)); break; case eventTypeCSTA.CSTA_OUT_OF_SERVICE: outOfService = (CSTAOutOfServiceEvent_t) Marshal.PtrToStructure(point, typeof (CSTAOutOfServiceEvent_t)); break; case eventTypeCSTA.CSTA_REQ_SYS_STAT: break; case eventTypeCSTA.CSTA_MONITOR_ENDED: monitorEnded = (CSTAMonitorEndedEvent_t) Marshal.PtrToStructure(point, typeof (CSTAMonitorEndedEvent_t)); break; } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CstaConfirmationEvent { public uint invokeID; public CSTAAlternateCallConfEvent_t alternateCall; public CSTAAnswerCallConfEvent_t answerCall; public CSTACallCompletionConfEvent_t callCompletion; public CSTAClearCallConfEvent_t clearCall; public CSTAClearConnectionConfEvent_t clearConnection; public CSTAConferenceCallConfEvent_t conferenceCall; public CSTAConsultationCallConfEvent_t consultationCall; public CSTADeflectCallConfEvent_t deflectCall; public CSTAPickupCallConfEvent_t pickupCall; public CSTAGroupPickupCallConfEvent_t groupPickupCall; public CSTAHoldCallConfEvent_t holdCall; public CSTAMakeCallConfEvent_t makeCall; public CSTAMakePredictiveCallConfEvent_t makePredictiveCall; public CSTAQueryMwiConfEvent_t queryMwi; public CSTAQueryDndConfEvent_t queryDnd; public CSTAQueryFwdConfEvent_t queryFwd; public CSTAQueryAgentStateConfEvent_t queryAgentState; public CSTAQueryLastNumberConfEvent_t queryLastNumber; public CSTAQueryDeviceInfoConfEvent_t queryDeviceInfo; public CSTAReconnectCallConfEvent_t reconnectCall; public CSTARetrieveCallConfEvent_t retrieveCall; public CSTASetMwiConfEvent_t setMwi; public CSTASetDndConfEvent_t setDnd; public CSTASetFwdConfEvent_t setFwd; public CSTASetAgentStateConfEvent_t setAgentState; public CSTATransferCallConfEvent_t transferCall; public CSTAUniversalFailureConfEvent_t universalFailure; public CSTAMonitorConfEvent_t monitorStart; public CSTAChangeMonitorFilterConfEvent_t changeMonitorFilter; public CSTAMonitorStopConfEvent_t monitorStop; public CSTASnapshotDeviceConfEvent_t snapshotDevice; public CSTASnapshotCallConfEvent_t snapshotCall; public CSTARouteRegisterReqConfEvent_t routeRegister; public CSTARouteRegisterCancelConfEvent_t routeCancel; public CSTAEscapeSvcConfEvent_t escapeService; public CSTASysStatReqConfEvent_t sysStatReq; public CSTASysStatStartConfEvent_t sysStatStart; public CSTASysStatStopConfEvent_t sysStatStop; public CSTAChangeSysStatFilterConfEvent_t changeSysStatFilter; public CSTAGetAPICapsConfEvent_t getAPICaps; public CSTAGetDeviceListConfEvent_t getDeviceList; public CSTAQueryCallMonitorConfEvent_t queryCallMonitor; public CstaConfirmationEvent(IntPtr point, eventTypeCSTA type) { alternateCall = new CSTAAlternateCallConfEvent_t(); answerCall = new CSTAAnswerCallConfEvent_t(); callCompletion = new CSTACallCompletionConfEvent_t(); clearCall = new CSTAClearCallConfEvent_t(); clearConnection = new CSTAClearConnectionConfEvent_t(); conferenceCall = new CSTAConferenceCallConfEvent_t(); consultationCall = new CSTAConsultationCallConfEvent_t(); deflectCall = new CSTADeflectCallConfEvent_t(); pickupCall = new CSTAPickupCallConfEvent_t(); groupPickupCall = new CSTAGroupPickupCallConfEvent_t(); holdCall = new CSTAHoldCallConfEvent_t(); makeCall = new CSTAMakeCallConfEvent_t(); makePredictiveCall = new CSTAMakePredictiveCallConfEvent_t(); queryMwi = new CSTAQueryMwiConfEvent_t(); queryDnd = new CSTAQueryDndConfEvent_t(); queryFwd = new CSTAQueryFwdConfEvent_t(); queryAgentState = new CSTAQueryAgentStateConfEvent_t(); queryLastNumber = new CSTAQueryLastNumberConfEvent_t(); queryDeviceInfo = new CSTAQueryDeviceInfoConfEvent_t(); reconnectCall = new CSTAReconnectCallConfEvent_t(); retrieveCall = new CSTARetrieveCallConfEvent_t(); setMwi = new CSTASetMwiConfEvent_t(); setDnd = new CSTASetDndConfEvent_t(); setFwd = new CSTASetFwdConfEvent_t(); setAgentState = new CSTASetAgentStateConfEvent_t(); transferCall = new CSTATransferCallConfEvent_t(); universalFailure = new CSTAUniversalFailureConfEvent_t(); monitorStart = new CSTAMonitorConfEvent_t(); changeMonitorFilter = new CSTAChangeMonitorFilterConfEvent_t(); monitorStop = new CSTAMonitorStopConfEvent_t(); snapshotDevice = new CSTASnapshotDeviceConfEvent_t(); snapshotCall = new CSTASnapshotCallConfEvent_t(); routeRegister = new CSTARouteRegisterReqConfEvent_t(); routeCancel = new CSTARouteRegisterCancelConfEvent_t(); escapeService = new CSTAEscapeSvcConfEvent_t(); sysStatReq = new CSTASysStatReqConfEvent_t(); sysStatStart = new CSTASysStatStartConfEvent_t(); sysStatStop = new CSTASysStatStopConfEvent_t(); changeSysStatFilter = new CSTAChangeSysStatFilterConfEvent_t(); getAPICaps = new CSTAGetAPICapsConfEvent_t(); getDeviceList = new CSTAGetDeviceListConfEvent_t(); queryCallMonitor = new CSTAQueryCallMonitorConfEvent_t(); invokeID = (uint) Marshal.ReadInt32(point); point = IntPtr.Add(point, Marshal.SizeOf(invokeID)); switch (type) { case eventTypeCSTA.CSTA_ALTERNATE_CALL_CONF: alternateCall = (CSTAAlternateCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAAlternateCallConfEvent_t)); break; case eventTypeCSTA.CSTA_ANSWER_CALL_CONF: answerCall = (CSTAAnswerCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAAnswerCallConfEvent_t)); break; case eventTypeCSTA.CSTA_CALL_COMPLETION_CONF: callCompletion = (CSTACallCompletionConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTACallCompletionConfEvent_t)); break; case eventTypeCSTA.CSTA_CLEAR_CALL_CONF: clearCall = (CSTAClearCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAClearCallConfEvent_t)); break; case eventTypeCSTA.CSTA_CLEAR_CONNECTION_CONF: clearConnection = (CSTAClearConnectionConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAClearConnectionConfEvent_t)); break; case eventTypeCSTA.CSTA_CONFERENCE_CALL_CONF: conferenceCall = (CSTAConferenceCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAConferenceCallConfEvent_t)); break; case eventTypeCSTA.CSTA_CONSULTATION_CALL_CONF: consultationCall = (CSTAConsultationCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAConsultationCallConfEvent_t)); break; case eventTypeCSTA.CSTA_DEFLECT_CALL_CONF: deflectCall = (CSTADeflectCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTADeflectCallConfEvent_t)); break; case eventTypeCSTA.CSTA_PICKUP_CALL_CONF: pickupCall = (CSTAPickupCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAPickupCallConfEvent_t)); break; case eventTypeCSTA.CSTA_GROUP_PICKUP_CALL_CONF: groupPickupCall = (CSTAGroupPickupCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAGroupPickupCallConfEvent_t)); break; case eventTypeCSTA.CSTA_HOLD_CALL_CONF: holdCall = (CSTAHoldCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAHoldCallConfEvent_t)); break; case eventTypeCSTA.CSTA_MAKE_CALL_CONF: makeCall = (CSTAMakeCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAMakeCallConfEvent_t)); break; case eventTypeCSTA.CSTA_MAKE_PREDICTIVE_CALL_CONF: makePredictiveCall = (CSTAMakePredictiveCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAMakePredictiveCallConfEvent_t)); break; case eventTypeCSTA.CSTA_QUERY_MWI_CONF: queryMwi = (CSTAQueryMwiConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueryMwiConfEvent_t)); break; case eventTypeCSTA.CSTA_QUERY_DND_CONF: queryDnd = (CSTAQueryDndConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueryDndConfEvent_t)); break; case eventTypeCSTA.CSTA_QUERY_FWD_CONF: queryFwd = (CSTAQueryFwdConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueryFwdConfEvent_t)); break; case eventTypeCSTA.CSTA_QUERY_AGENT_STATE_CONF: queryAgentState = (CSTAQueryAgentStateConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueryAgentStateConfEvent_t)); break; case eventTypeCSTA.CSTA_QUERY_LAST_NUMBER_CONF: queryLastNumber = (CSTAQueryLastNumberConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueryLastNumberConfEvent_t)); break; case eventTypeCSTA.CSTA_QUERY_DEVICE_INFO_CONF: queryDeviceInfo = (CSTAQueryDeviceInfoConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueryDeviceInfoConfEvent_t)); break; case eventTypeCSTA.CSTA_RECONNECT_CALL_CONF: reconnectCall = (CSTAReconnectCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAReconnectCallConfEvent_t)); break; case eventTypeCSTA.CSTA_RETRIEVE_CALL_CONF: retrieveCall = (CSTARetrieveCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTARetrieveCallConfEvent_t)); break; case eventTypeCSTA.CSTA_SET_MWI_CONF: setMwi = (CSTASetMwiConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASetMwiConfEvent_t)); break; case eventTypeCSTA.CSTA_SET_DND_CONF: setDnd = (CSTASetDndConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASetDndConfEvent_t)); break; case eventTypeCSTA.CSTA_SET_FWD_CONF: setFwd = (CSTASetFwdConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASetFwdConfEvent_t)); break; case eventTypeCSTA.CSTA_SET_AGENT_STATE_CONF: setAgentState = (CSTASetAgentStateConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASetAgentStateConfEvent_t)); break; case eventTypeCSTA.CSTA_TRANSFER_CALL_CONF: transferCall = (CSTATransferCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTATransferCallConfEvent_t)); break; case eventTypeCSTA.CSTA_UNIVERSAL_FAILURE_CONF: universalFailure = (CSTAUniversalFailureConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAUniversalFailureConfEvent_t)); break; case eventTypeCSTA.CSTA_MONITOR_CONF: monitorStart = (CSTAMonitorConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAMonitorConfEvent_t)); break; case eventTypeCSTA.CSTA_CHANGE_MONITOR_FILTER_CONF: changeMonitorFilter = (CSTAChangeMonitorFilterConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAChangeMonitorFilterConfEvent_t)); break; case eventTypeCSTA.CSTA_MONITOR_STOP_CONF: monitorStop = (CSTAMonitorStopConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAMonitorStopConfEvent_t)); break; case eventTypeCSTA.CSTA_SNAPSHOT_DEVICE_CONF: snapshotDevice = (CSTASnapshotDeviceConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASnapshotDeviceConfEvent_t)); break; case eventTypeCSTA.CSTA_SNAPSHOT_CALL_CONF: snapshotCall = (CSTASnapshotCallConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASnapshotCallConfEvent_t)); break; case eventTypeCSTA.CSTA_ROUTE_REGISTER_REQ_CONF: routeRegister = (CSTARouteRegisterReqConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteRegisterReqConfEvent_t)); break; case eventTypeCSTA.CSTA_ROUTE_REGISTER_CANCEL_CONF: routeCancel = (CSTARouteRegisterCancelConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteRegisterCancelConfEvent_t)); break; case eventTypeCSTA.CSTA_ESCAPE_SVC_CONF: escapeService = (CSTAEscapeSvcConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAEscapeSvcConfEvent_t)); break; case eventTypeCSTA.CSTA_SYS_STAT_REQ_CONF: sysStatReq = (CSTASysStatReqConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASysStatReqConfEvent_t)); break; case eventTypeCSTA.CSTA_SYS_STAT_START_CONF: sysStatStart = (CSTASysStatStartConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASysStatStartConfEvent_t)); break; case eventTypeCSTA.CSTA_SYS_STAT_STOP_CONF: sysStatStop = (CSTASysStatStopConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTASysStatStopConfEvent_t)); break; case eventTypeCSTA.CSTA_CHANGE_SYS_STAT_FILTER_CONF: changeSysStatFilter = (CSTAChangeSysStatFilterConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAChangeSysStatFilterConfEvent_t)); break; case eventTypeCSTA.CSTA_GETAPI_CAPS_CONF: getAPICaps = (CSTAGetAPICapsConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAGetAPICapsConfEvent_t)); break; case eventTypeCSTA.CSTA_GET_DEVICE_LIST_CONF: getDeviceList =(CSTAGetDeviceListConfEvent_t)Marshal.PtrToStructure(point, typeof (CSTAGetDeviceListConfEvent_t)); break; case eventTypeCSTA.CSTA_QUERY_CALL_MONITOR_CONF: queryCallMonitor = (CSTAQueryCallMonitorConfEvent_t) Marshal.PtrToStructure(point, typeof (CSTAQueryCallMonitorConfEvent_t)); break; } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CstaEventReport { private readonly eventTypeCSTA _type; public CSTARouteRegisterAbortEvent_t registerAbort; public CSTARouteUsedEvent_t routeUsed; public CSTARouteUsedExtEvent_t routeUsedExt; public CSTARouteEndEvent_t routeEnd; public CSTAPrivateEvent_t privateEvent; public CSTASysStatEvent_t sysStat; public CSTASysStatEndedEvent_t sysStatEnded; public eventTypeCSTA GetTypeEvent() { return _type; } public CstaEventReport(IntPtr point, eventTypeCSTA type) { registerAbort = new CSTARouteRegisterAbortEvent_t(); routeUsed = new CSTARouteUsedEvent_t(); routeUsedExt = new CSTARouteUsedExtEvent_t(); routeEnd = new CSTARouteEndEvent_t(); privateEvent = new CSTAPrivateEvent_t(); sysStat = new CSTASysStatEvent_t(); sysStatEnded = new CSTASysStatEndedEvent_t(); _type = type; registerAbort = (CSTARouteRegisterAbortEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteRegisterAbortEvent_t)); routeUsed = (CSTARouteUsedEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteUsedEvent_t)); routeUsedExt = (CSTARouteUsedExtEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteUsedExtEvent_t)); routeEnd = (CSTARouteEndEvent_t) Marshal.PtrToStructure(point, typeof (CSTARouteEndEvent_t)); privateEvent = (CSTAPrivateEvent_t) Marshal.PtrToStructure(point, typeof (CSTAPrivateEvent_t)); sysStat = (CSTASysStatEvent_t) Marshal.PtrToStructure(point, typeof (CSTASysStatEvent_t)); sysStatEnded = (CSTASysStatEndedEvent_t) Marshal.PtrToStructure(point, typeof (CSTASysStatEndedEvent_t)); } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)] // ReSharper disable once InconsistentNaming public struct CSTAEvent_t { public ACSEventHeader_t eventHeader; public AcsUnsolicitedEvent acsUnsolicited; public ACSConfirmationEvent acsConfirmation; public CstaRequestEvent cstaRequest; public CstaUnsolicitedEvent cstaUnsolicited; public CstaConfirmationEvent cstaConfirmation; public CstaEventReport cstaEventReport; public CSTAEvent_t(IntPtr point) { acsUnsolicited = new AcsUnsolicitedEvent(); acsConfirmation = new ACSConfirmationEvent(); cstaRequest = new CstaRequestEvent(); cstaUnsolicited = new CstaUnsolicitedEvent(); cstaConfirmation = new CstaConfirmationEvent(); cstaEventReport = new CstaEventReport(); eventHeader = (ACSEventHeader_t) Marshal.PtrToStructure(point, typeof (ACSEventHeader_t)); point = IntPtr.Add(point, Marshal.SizeOf(eventHeader)); switch (eventHeader.eventClass) { case EventClass_t.ACSCONFIRMATION: acsConfirmation = new ACSConfirmationEvent(point, eventHeader.eventTypeACS); break; case EventClass_t.ACSUNSOLICITED: acsUnsolicited = new AcsUnsolicitedEvent(point, eventHeader.eventTypeACS); break; case EventClass_t.CSTACONFIRMATION: cstaConfirmation = new CstaConfirmationEvent(point, eventHeader.eventTypeCSTA); break; case EventClass_t.CSTAEVENTREPORT: cstaEventReport = new CstaEventReport(point, eventHeader.eventTypeCSTA); break; case EventClass_t.CSTAUNSOLICITED: cstaUnsolicited = new CstaUnsolicitedEvent(point, eventHeader.eventTypeCSTA); break; case EventClass_t.CSTAREQUEST: cstaRequest = new CstaRequestEvent(point, eventHeader.eventTypeCSTA); break; } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] // ReSharper disable once InconsistentNaming public struct ATTEvent_t { public TypeATTEvent eventType; public ATTSingleStepConferenceCallConfEvent_t ssconference; public ATTSelectiveListeningHoldConfEvent_t slhold; public ATTSelectiveListeningRetrieveConfEvent_t slretrieve; public ATTSendDTMFToneConfEvent_t sendDTMFTone; public ATTQueryAcdSplitConfEvent_t queryAcdSplit; public ATTQueryAgentLoginConfEvent_t queryAgentLogin; public ATTQueryAgentLoginResp_t queryAgentLoginResp; public ATTQueryAgentStateConfEvent_t queryAgentState; public ATTQueryCallClassifierConfEvent_t queryCallClassifier; public ATTQueryDeviceInfoConfEvent_t queryDeviceInfo; public ATTQueryDeviceNameConfEvent_t queryDeviceName; public ATTQueryMwiConfEvent_t queryMwi; public ATTQueryStationStatusConfEvent_t queryStationStatus; public ATTQueryTodConfEvent_t queryTod; public ATTQueryTgConfEvent_t queryTg; public ATTQueryAgentMeasurementsConfEvent_t queryAgentMeas; public ATTQuerySplitSkillMeasurementsConfEvent_t querySplitSkillMeas; public ATTQueryTrunkGroupMeasurementsConfEvent_t queryTrunkGroupMeas; public ATTQueryVdnMeasurementsConfEvent_t queryVdnMeas; public ATTSnapshotDeviceConfEvent_t snapshotDevice; public ATTMonitorConfEvent_t monitorStart; public ATTMonitorCallConfEvent_t monitorCallStart; public ATTMonitorStopOnCallConfEvent_t monitorStopOnCall; public ATTCallClearedEvent_t callClearedEvent; public ATTConferencedEvent_t conferencedEvent; public ATTConnectionClearedEvent_t connectionClearedEvent; public ATTDeliveredEvent_t deliveredEvent; public ATTEnteredDigitsEvent_t enteredDigitsEvent; public ATTEstablishedEvent_t establishedEvent; public ATTLoggedOnEvent_t loggedOnEvent; public ATTNetworkReachedEvent_t networkReachedEvent; public ATTOriginatedEvent_t originatedEvent; public ATTTransferredEvent_t transferredEvent; public ATTRouteRequestEvent_t routeRequest; public ATTRouteUsedEvent_t routeUsed; public ATTLinkStatusEvent_t linkStatus; public ATTGetAPICapsConfEvent_t getAPICaps; public ATTServiceInitiatedEvent_t serviceInitiated; public ATTChargeAdviceEvent_t chargeAdviceEvent; public ATTSetBillRateConfEvent_t setBillRate; public ATTQueryUcidConfEvent_t queryUCID; public ATTLoggedOffEvent_t loggedOffEvent; public ATTConsultationCallConfEvent_t consultationCall; public ATTConferenceCallConfEvent_t conferenceCall; public ATTMakeCallConfEvent_t makeCall; public ATTMakePredictiveCallConfEvent_t makePredictiveCall; public ATTTransferCallConfEvent_t transferCall; public ATTSetAdviceOfChargeConfEvent_t setAdviceOfCharge; public ATTSetAgentStateConfEvent_t setAgentState; public ATTQueuedEvent_t queuedEvent; public ATTDivertedEvent_t divertedEvent; public ATTFailedEvent_t failedEvent; public ATTSnapshotCallConfEvent_t snapshotCallConf; public ATTV3ConferencedEvent_t v3conferencedEvent; public ATTV3DeliveredEvent_t v3deliveredEvent; public ATTV3EstablishedEvent_t v3establishedEvent; public ATTV3TransferredEvent_t v3transferredEvent; public ATTV3LinkStatusEvent_t v3linkStatus; public ATTV4QueryDeviceInfoConfEvent_t v4queryDeviceInfo; public ATTV4GetAPICapsConfEvent_t v4getAPICaps; public ATTV4SnapshotDeviceConfEvent_t v4snapshotDevice; public ATTV4ConferencedEvent_t v4conferencedEvent; public ATTV4DeliveredEvent_t v4deliveredEvent; public ATTV4EstablishedEvent_t v4establishedEvent; public ATTV4TransferredEvent_t v4transferredEvent; public ATTV4LinkStatusEvent_t v4linkStatus; public ATTV4RouteRequestEvent_t v4routeRequest; public ATTV4QueryAgentStateConfEvent_t v4queryAgentState; public ATTV4QueryDeviceNameConfEvent_t v4queryDeviceName; public ATTV4MonitorConfEvent_t v4monitorStart; public ATTV4MonitorCallConfEvent_t v4monitorCallStart; public ATTV4NetworkReachedEvent_t v4networkReachedEvent; public ATTV5QueryAgentStateConfEvent_t v5queryAgentState; public ATTV5RouteRequestEvent_t v5routeRequest; public ATTV5TransferredEvent_t v5transferredEvent; public ATTV5ConferencedEvent_t v5conferencedEvent; public ATTV5ConnectionClearedEvent_t v5connectionClearedEvent; public ATTV5OriginatedEvent_t v5originatedEvent; public ATTV5EstablishedEvent_t v5establishedEvent; public ATTV5DeliveredEvent_t v5deliveredEvent; public ATTV6NetworkReachedEvent_t v6networkReachedEvent; public ATTV6ConferencedEvent_t v6conferencedEvent; public ATTV6DeliveredEvent_t v6deliveredEvent; public ATTV6EstablishedEvent_t v6establishedEvent; public ATTV6TransferredEvent_t v6transferredEvent; public ATTV6QueryDeviceNameConfEvent_t v6queryDeviceName; public ATTV6GetAPICapsConfEvent_t v6getAPICaps; public ATTV6ConnectionClearedEvent_t v6connectionClearedEvent; public ATTV6RouteRequestEvent_t v6routeRequest; public ATTClearConnection_t clearConnectionReq; public ATTConsultationCall_t consultationCallReq; public ATTMakeCall_t makeCallReq; public ATTDirectAgentCall_t directAgentCallReq; public ATTMakePredictiveCall_t makePredictiveCallReq; public ATTSupervisorAssistCall_t supervisorAssistCallReq; public ATTReconnectCall_t reconnectCallReq; public ATTSendDTMFTone_t sendDTMFToneReq; public ATTSingleStepConferenceCall_t ssconferenceReq; public ATTSelectiveListeningHold_t slholdReq; public ATTSelectiveListeningRetrieve_t slretrieveReq; public ATTSetAgentState_t setAgentStateReq; public ATTQueryAgentState_t queryAgentStateReq; public ATTQueryAcdSplit_t queryAcdSplitReq; public ATTQueryAgentLogin_t queryAgentLoginReq; public ATTQueryCallClassifier_t queryCallClassifierReq; public ATTQueryDeviceName_t queryDeviceNameReq; public ATTQueryStationStatus_t queryStationStatusReq; public ATTQueryTod_t queryTodReq; public ATTQueryTg_t queryTgReq; public ATTQueryAgentMeasurements_t queryAgentMeasReq; public ATTQuerySplitSkillMeasurements_t querySplitSkillMeasReq; public ATTQueryTrunkGroupMeasurements_t queryTrunkGroupMeasReq; public ATTQueryVdnMeasurements_t queryVdnMeasReq; public ATTMonitorFilter_t monitorFilterReq; public ATTMonitorStopOnCall_t monitorStopOnCallReq; public ATTRouteSelect_t routeSelectReq; public ATTSysStat_t sysStatReq; public ATTSetBillRate_t setBillRateReq; public ATTQueryUcid_t queryUCIDReq; public ATTSetAdviceOfCharge_t adviceOfChargeReq; public ATTV4SendDTMFTone_t v4sendDTMFToneReq; public ATTV4SetAgentState_t v4setAgentStateReq; public ATTV4MonitorFilter_t v4monitorFilterReq; public ATTV5SetAgentState_t v5setAgentStateReq; public ATTV5ClearConnection_t v5clearConnectionReq; public ATTV5ConsultationCall_t v5consultationCallReq; public ATTV5MakeCall_t v5makeCallReq; public ATTV5DirectAgentCall_t v5directAgentCallReq; public ATTV5MakePredictiveCall_t v5makePredictiveCallReq; public ATTV5SupervisorAssistCall_t v5supervisorAssistCallReq; public ATTV5ReconnectCall_t v5reconnectCallReq; public ATTV5RouteSelect_t v5routeSelectReq; public ATTV6RouteSelect_t v6routeSelectReq; public ATTEvent_t(IntPtr point) { ssconference = new ATTSingleStepConferenceCallConfEvent_t(); slhold = new ATTSelectiveListeningHoldConfEvent_t(); slretrieve = new ATTSelectiveListeningRetrieveConfEvent_t(); sendDTMFTone = new ATTSendDTMFToneConfEvent_t(); queryAcdSplit = new ATTQueryAcdSplitConfEvent_t(); queryAgentLogin = new ATTQueryAgentLoginConfEvent_t(); queryAgentLoginResp = new ATTQueryAgentLoginResp_t(); queryAgentState = new ATTQueryAgentStateConfEvent_t(); queryCallClassifier = new ATTQueryCallClassifierConfEvent_t(); queryDeviceInfo = new ATTQueryDeviceInfoConfEvent_t(); queryDeviceName = new ATTQueryDeviceNameConfEvent_t(); queryMwi = new ATTQueryMwiConfEvent_t(); queryStationStatus = new ATTQueryStationStatusConfEvent_t(); queryTod = new ATTQueryTodConfEvent_t(); queryTg = new ATTQueryTgConfEvent_t(); queryAgentMeas = new ATTQueryAgentMeasurementsConfEvent_t(); querySplitSkillMeas = new ATTQuerySplitSkillMeasurementsConfEvent_t(); queryTrunkGroupMeas = new ATTQueryTrunkGroupMeasurementsConfEvent_t(); queryVdnMeas = new ATTQueryVdnMeasurementsConfEvent_t(); snapshotDevice = new ATTSnapshotDeviceConfEvent_t(); monitorStart = new ATTMonitorConfEvent_t(); monitorCallStart = new ATTMonitorCallConfEvent_t(); monitorStopOnCall = new ATTMonitorStopOnCallConfEvent_t(); callClearedEvent = new ATTCallClearedEvent_t(); conferencedEvent = new ATTConferencedEvent_t(); connectionClearedEvent = new ATTConnectionClearedEvent_t(); deliveredEvent = new ATTDeliveredEvent_t(); enteredDigitsEvent = new ATTEnteredDigitsEvent_t(); establishedEvent = new ATTEstablishedEvent_t(); loggedOnEvent = new ATTLoggedOnEvent_t(); networkReachedEvent = new ATTNetworkReachedEvent_t(); originatedEvent = new ATTOriginatedEvent_t(); transferredEvent = new ATTTransferredEvent_t(); routeRequest = new ATTRouteRequestEvent_t(); routeUsed = new ATTRouteUsedEvent_t(); linkStatus = new ATTLinkStatusEvent_t(); getAPICaps = new ATTGetAPICapsConfEvent_t(); serviceInitiated = new ATTServiceInitiatedEvent_t(); chargeAdviceEvent = new ATTChargeAdviceEvent_t(); setBillRate = new ATTSetBillRateConfEvent_t(); queryUCID = new ATTQueryUcidConfEvent_t(); loggedOffEvent = new ATTLoggedOffEvent_t(); consultationCall = new ATTConsultationCallConfEvent_t(); conferenceCall = new ATTConferenceCallConfEvent_t(); makeCall = new ATTMakeCallConfEvent_t(); makePredictiveCall = new ATTMakePredictiveCallConfEvent_t(); transferCall = new ATTTransferCallConfEvent_t(); setAdviceOfCharge = new ATTSetAdviceOfChargeConfEvent_t(); setAgentState = new ATTSetAgentStateConfEvent_t(); queuedEvent = new ATTQueuedEvent_t(); divertedEvent = new ATTDivertedEvent_t(); failedEvent = new ATTFailedEvent_t(); snapshotCallConf = new ATTSnapshotCallConfEvent_t(); v3conferencedEvent = new ATTV3ConferencedEvent_t(); v3deliveredEvent = new ATTV3DeliveredEvent_t(); v3establishedEvent = new ATTV3EstablishedEvent_t(); v3transferredEvent = new ATTV3TransferredEvent_t(); v3linkStatus = new ATTV3LinkStatusEvent_t(); v4queryDeviceInfo = new ATTV4QueryDeviceInfoConfEvent_t(); v4getAPICaps = new ATTV4GetAPICapsConfEvent_t(); v4snapshotDevice = new ATTV4SnapshotDeviceConfEvent_t(); v4conferencedEvent = new ATTV4ConferencedEvent_t(); v4deliveredEvent = new ATTV4DeliveredEvent_t(); v4establishedEvent = new ATTV4EstablishedEvent_t(); v4transferredEvent = new ATTV4TransferredEvent_t(); v4linkStatus = new ATTV4LinkStatusEvent_t(); v4routeRequest = new ATTV4RouteRequestEvent_t(); v4queryAgentState = new ATTV4QueryAgentStateConfEvent_t(); v4queryDeviceName = new ATTV4QueryDeviceNameConfEvent_t(); v4monitorStart = new ATTV4MonitorConfEvent_t(); v4monitorCallStart = new ATTV4MonitorCallConfEvent_t(); v4networkReachedEvent = new ATTV4NetworkReachedEvent_t(); v5queryAgentState = new ATTV5QueryAgentStateConfEvent_t(); v5routeRequest = new ATTV5RouteRequestEvent_t(); v5transferredEvent = new ATTV5TransferredEvent_t(); v5conferencedEvent = new ATTV5ConferencedEvent_t(); v5connectionClearedEvent = new ATTV5ConnectionClearedEvent_t(); v5originatedEvent = new ATTV5OriginatedEvent_t(); v5establishedEvent = new ATTV5EstablishedEvent_t(); v5deliveredEvent = new ATTV5DeliveredEvent_t(); v6networkReachedEvent = new ATTV6NetworkReachedEvent_t(); v6conferencedEvent = new ATTV6ConferencedEvent_t(); v6deliveredEvent = new ATTV6DeliveredEvent_t(); v6establishedEvent = new ATTV6EstablishedEvent_t(); v6transferredEvent = new ATTV6TransferredEvent_t(); v6queryDeviceName = new ATTV6QueryDeviceNameConfEvent_t(); v6getAPICaps = new ATTV6GetAPICapsConfEvent_t(); v6connectionClearedEvent = new ATTV6ConnectionClearedEvent_t(); v6routeRequest = new ATTV6RouteRequestEvent_t(); clearConnectionReq = new ATTClearConnection_t(); consultationCallReq = new ATTConsultationCall_t(); makeCallReq = new ATTMakeCall_t(); directAgentCallReq = new ATTDirectAgentCall_t(); makePredictiveCallReq = new ATTMakePredictiveCall_t(); supervisorAssistCallReq = new ATTSupervisorAssistCall_t(); reconnectCallReq = new ATTReconnectCall_t(); sendDTMFToneReq = new ATTSendDTMFTone_t(); ssconferenceReq = new ATTSingleStepConferenceCall_t(); slholdReq = new ATTSelectiveListeningHold_t(); slretrieveReq = new ATTSelectiveListeningRetrieve_t(); setAgentStateReq = new ATTSetAgentState_t(); queryAgentStateReq = new ATTQueryAgentState_t(); queryAcdSplitReq = new ATTQueryAcdSplit_t(); queryAgentLoginReq = new ATTQueryAgentLogin_t(); queryCallClassifierReq = new ATTQueryCallClassifier_t(); queryDeviceNameReq = new ATTQueryDeviceName_t(); queryStationStatusReq = new ATTQueryStationStatus_t(); queryTodReq = new ATTQueryTod_t(); queryTgReq = new ATTQueryTg_t(); queryAgentMeasReq = new ATTQueryAgentMeasurements_t(); querySplitSkillMeasReq = new ATTQuerySplitSkillMeasurements_t(); queryTrunkGroupMeasReq = new ATTQueryTrunkGroupMeasurements_t(); queryVdnMeasReq = new ATTQueryVdnMeasurements_t(); monitorFilterReq = new ATTMonitorFilter_t(); monitorStopOnCallReq = new ATTMonitorStopOnCall_t(); routeSelectReq = new ATTRouteSelect_t(); sysStatReq = new ATTSysStat_t(); setBillRateReq = new ATTSetBillRate_t(); queryUCIDReq = new ATTQueryUcid_t(); adviceOfChargeReq = new ATTSetAdviceOfCharge_t(); v4sendDTMFToneReq = new ATTV4SendDTMFTone_t(); v4setAgentStateReq = new ATTV4SetAgentState_t(); v4monitorFilterReq = new ATTV4MonitorFilter_t(); v5setAgentStateReq = new ATTV5SetAgentState_t(); v5clearConnectionReq = new ATTV5ClearConnection_t(); v5consultationCallReq = new ATTV5ConsultationCall_t(); v5makeCallReq = new ATTV5MakeCall_t(); v5directAgentCallReq = new ATTV5DirectAgentCall_t(); v5makePredictiveCallReq = new ATTV5MakePredictiveCall_t(); v5supervisorAssistCallReq = new ATTV5SupervisorAssistCall_t(); v5reconnectCallReq = new ATTV5ReconnectCall_t(); v5routeSelectReq = new ATTV5RouteSelect_t(); v6routeSelectReq = new ATTV6RouteSelect_t(); eventType = (TypeATTEvent)Marshal.ReadInt16(point); point = IntPtr.Add(point, Marshal.SizeOf(typeof(Int32))); switch (eventType) { case TypeATTEvent.ATTSingleStepConferenceCallConfEvent_t_PDU: ssconference = (ATTSingleStepConferenceCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSingleStepConferenceCallConfEvent_t)); break; case TypeATTEvent.ATTSelectiveListeningHoldConfEvent_t_PDU: slhold = (ATTSelectiveListeningHoldConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSelectiveListeningHoldConfEvent_t)); break; case TypeATTEvent.ATTSelectiveListeningRetrieveConfEvent_t_PDU: slretrieve = (ATTSelectiveListeningRetrieveConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSelectiveListeningRetrieveConfEvent_t)); break; case TypeATTEvent.ATTSendDTMFToneConfEvent_t_PDU: sendDTMFTone = (ATTSendDTMFToneConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSendDTMFToneConfEvent_t)); break; case TypeATTEvent.ATTQueryAcdSplitConfEvent_t_PDU: queryAcdSplit = (ATTQueryAcdSplitConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryAcdSplitConfEvent_t)); break; case TypeATTEvent.ATTQueryAgentLoginConfEvent_t_PDU: queryAgentLogin = (ATTQueryAgentLoginConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryAgentLoginConfEvent_t)); break; case TypeATTEvent.ATTQueryAgentLoginResp_t_PDU: queryAgentLoginResp = (ATTQueryAgentLoginResp_t)Marshal.PtrToStructure(point, typeof(ATTQueryAgentLoginResp_t)); break; case TypeATTEvent.ATTQueryAgentStateConfEvent_t_PDU: queryAgentState = (ATTQueryAgentStateConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryAgentStateConfEvent_t)); break; case TypeATTEvent.ATTQueryCallClassifierConfEvent_t_PDU: queryCallClassifier = (ATTQueryCallClassifierConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryCallClassifierConfEvent_t)); break; case TypeATTEvent.ATTQueryDeviceInfoConfEvent_t_PDU: queryDeviceInfo = (ATTQueryDeviceInfoConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryDeviceInfoConfEvent_t)); break; case TypeATTEvent.ATTQueryDeviceNameConfEvent_t_PDU: queryDeviceName = (ATTQueryDeviceNameConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryDeviceNameConfEvent_t)); break; case TypeATTEvent.ATTQueryMwiConfEvent_t_PDU: queryMwi = (ATTQueryMwiConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryMwiConfEvent_t)); break; case TypeATTEvent.ATTQueryStationStatusConfEvent_t_PDU: queryStationStatus = (ATTQueryStationStatusConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryStationStatusConfEvent_t)); break; case TypeATTEvent.ATTQueryTodConfEvent_t_PDU: queryTod = (ATTQueryTodConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryTodConfEvent_t)); break; case TypeATTEvent.ATTQueryTgConfEvent_t_PDU: queryTg = (ATTQueryTgConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryTgConfEvent_t)); break; case TypeATTEvent.ATTQueryAgentMeasurementsConfEvent_t_PDU: queryAgentMeas = (ATTQueryAgentMeasurementsConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryAgentMeasurementsConfEvent_t)); break; case TypeATTEvent.ATTQuerySplitSkillMeasurementsConfEvent_t_PDU: querySplitSkillMeas = (ATTQuerySplitSkillMeasurementsConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQuerySplitSkillMeasurementsConfEvent_t)); break; case TypeATTEvent.ATTQueryTrunkGroupMeasurementsConfEvent_t_PDU: queryTrunkGroupMeas = (ATTQueryTrunkGroupMeasurementsConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryTrunkGroupMeasurementsConfEvent_t)); break; case TypeATTEvent.ATTQueryVdnMeasurementsConfEvent_t_PDU: queryVdnMeas = (ATTQueryVdnMeasurementsConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryVdnMeasurementsConfEvent_t)); break; case TypeATTEvent.ATTSnapshotDeviceConfEvent_t_PDU: snapshotDevice = (ATTSnapshotDeviceConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSnapshotDeviceConfEvent_t)); snapshotDevice.list = snapshotDevice.list.Take((int) snapshotDevice.count).ToArray(); //snapshotDevice.list = NativeMethods.GetArrayStruct<ATTSnapshotDevice_t>(point); break; case TypeATTEvent.ATTMonitorConfEvent_t_PDU: monitorStart = (ATTMonitorConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTMonitorConfEvent_t)); break; case TypeATTEvent.ATTMonitorCallConfEvent_t_PDU: monitorCallStart = (ATTMonitorCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTMonitorCallConfEvent_t)); break; case TypeATTEvent.ATTMonitorStopOnCallConfEvent_t_PDU: monitorStopOnCall = (ATTMonitorStopOnCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTMonitorStopOnCallConfEvent_t)); break; case TypeATTEvent.ATTCallClearedEvent_t_PDU: callClearedEvent = (ATTCallClearedEvent_t)Marshal.PtrToStructure(point, typeof(ATTCallClearedEvent_t)); break; case TypeATTEvent.ATTConferencedEvent_t_PDU: conferencedEvent = (ATTConferencedEvent_t)Marshal.PtrToStructure(point, typeof(ATTConferencedEvent_t)); break; case TypeATTEvent.ATTConnectionClearedEvent_t_PDU: connectionClearedEvent = (ATTConnectionClearedEvent_t)Marshal.PtrToStructure(point, typeof(ATTConnectionClearedEvent_t)); break; case TypeATTEvent.ATTDeliveredEvent_t_PDU: deliveredEvent = (ATTDeliveredEvent_t)Marshal.PtrToStructure(point, typeof(ATTDeliveredEvent_t)); break; case TypeATTEvent.ATTEnteredDigitsEvent_t_PDU: enteredDigitsEvent = (ATTEnteredDigitsEvent_t)Marshal.PtrToStructure(point, typeof(ATTEnteredDigitsEvent_t)); break; case TypeATTEvent.ATTEstablishedEvent_t_PDU: establishedEvent = (ATTEstablishedEvent_t)Marshal.PtrToStructure(point, typeof(ATTEstablishedEvent_t)); break; case TypeATTEvent.ATTLoggedOnEvent_t_PDU: loggedOnEvent = (ATTLoggedOnEvent_t)Marshal.PtrToStructure(point, typeof(ATTLoggedOnEvent_t)); break; case TypeATTEvent.ATTNetworkReachedEvent_t_PDU: networkReachedEvent = (ATTNetworkReachedEvent_t)Marshal.PtrToStructure(point, typeof(ATTNetworkReachedEvent_t)); break; case TypeATTEvent.ATTOriginatedEvent_t_PDU: originatedEvent = (ATTOriginatedEvent_t)Marshal.PtrToStructure(point, typeof(ATTOriginatedEvent_t)); break; case TypeATTEvent.ATTTransferredEvent_t_PDU: transferredEvent = (ATTTransferredEvent_t)Marshal.PtrToStructure(point, typeof(ATTTransferredEvent_t)); break; case TypeATTEvent.ATTRouteRequestEvent_t_PDU: routeRequest = (ATTRouteRequestEvent_t)Marshal.PtrToStructure(point, typeof(ATTRouteRequestEvent_t)); break; case TypeATTEvent.ATTRouteUsedEvent_t_PDU: routeUsed = (ATTRouteUsedEvent_t)Marshal.PtrToStructure(point, typeof(ATTRouteUsedEvent_t)); break; case TypeATTEvent.ATTLinkStatusEvent_t_PDU: linkStatus = (ATTLinkStatusEvent_t)Marshal.PtrToStructure(point, typeof(ATTLinkStatusEvent_t)); break; case TypeATTEvent.ATTGetAPICapsConfEvent_t_PDU: getAPICaps = (ATTGetAPICapsConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTGetAPICapsConfEvent_t)); break; case TypeATTEvent.ATTServiceInitiatedEvent_t_PDU: serviceInitiated = (ATTServiceInitiatedEvent_t)Marshal.PtrToStructure(point, typeof(ATTServiceInitiatedEvent_t)); break; case TypeATTEvent.ATTChargeAdviceEvent_t_PDU: chargeAdviceEvent = (ATTChargeAdviceEvent_t)Marshal.PtrToStructure(point, typeof(ATTChargeAdviceEvent_t)); break; case TypeATTEvent.ATTSetBillRateConfEvent_t_PDU: setBillRate = (ATTSetBillRateConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSetBillRateConfEvent_t)); break; case TypeATTEvent.ATTQueryUcidConfEvent_t_PDU: queryUCID = (ATTQueryUcidConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueryUcidConfEvent_t)); break; case TypeATTEvent.ATTLoggedOffEvent_t_PDU: loggedOffEvent = (ATTLoggedOffEvent_t)Marshal.PtrToStructure(point, typeof(ATTLoggedOffEvent_t)); break; case TypeATTEvent.ATTConsultationCallConfEvent_t_PDU: consultationCall = (ATTConsultationCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTConsultationCallConfEvent_t)); break; case TypeATTEvent.ATTConferenceCallConfEvent_t_PDU: conferenceCall = (ATTConferenceCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTConferenceCallConfEvent_t)); break; case TypeATTEvent.ATTMakeCallConfEvent_t_PDU: makeCall = (ATTMakeCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTMakeCallConfEvent_t)); break; case TypeATTEvent.ATTMakePredictiveCallConfEvent_t_PDU: makePredictiveCall = (ATTMakePredictiveCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTMakePredictiveCallConfEvent_t)); break; case TypeATTEvent.ATTTransferCallConfEvent_t_PDU: transferCall = (ATTTransferCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTTransferCallConfEvent_t)); break; case TypeATTEvent.ATTSetAdviceOfChargeConfEvent_t_PDU: setAdviceOfCharge = (ATTSetAdviceOfChargeConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSetAdviceOfChargeConfEvent_t)); break; case TypeATTEvent.ATTSetAgentStateConfEvent_t_PDU: setAgentState = (ATTSetAgentStateConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSetAgentStateConfEvent_t)); break; case TypeATTEvent.ATTQueuedEvent_t_PDU: queuedEvent = (ATTQueuedEvent_t)Marshal.PtrToStructure(point, typeof(ATTQueuedEvent_t)); break; case TypeATTEvent.ATTDivertedEvent_t_PDU: divertedEvent = (ATTDivertedEvent_t)Marshal.PtrToStructure(point, typeof(ATTDivertedEvent_t)); break; case TypeATTEvent.ATTFailedEvent_t_PDU: failedEvent = (ATTFailedEvent_t)Marshal.PtrToStructure(point, typeof(ATTFailedEvent_t)); break; case TypeATTEvent.ATTSnapshotCallConfEvent_t_PDU: snapshotCallConf = (ATTSnapshotCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTSnapshotCallConfEvent_t)); break; case TypeATTEvent.ATTV3ConferencedEvent_t_PDU: v3conferencedEvent = (ATTV3ConferencedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV3ConferencedEvent_t)); break; case TypeATTEvent.ATTV3DeliveredEvent_t_PDU: v3deliveredEvent = (ATTV3DeliveredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV3DeliveredEvent_t)); break; case TypeATTEvent.ATTV3EstablishedEvent_t_PDU: v3establishedEvent = (ATTV3EstablishedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV3EstablishedEvent_t)); break; case TypeATTEvent.ATTV3TransferredEvent_t_PDU: v3transferredEvent = (ATTV3TransferredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV3TransferredEvent_t)); break; case TypeATTEvent.ATTV3LinkStatusEvent_t_PDU: v3linkStatus = (ATTV3LinkStatusEvent_t)Marshal.PtrToStructure(point, typeof(ATTV3LinkStatusEvent_t)); break; case TypeATTEvent.ATTV4QueryDeviceInfoConfEvent_t_PDU: v4queryDeviceInfo = (ATTV4QueryDeviceInfoConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4QueryDeviceInfoConfEvent_t)); break; case TypeATTEvent.ATTV4GetAPICapsConfEvent_t_PDU: v4getAPICaps = (ATTV4GetAPICapsConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4GetAPICapsConfEvent_t)); break; case TypeATTEvent.ATTV4SnapshotDeviceConfEvent_t_PDU: v4snapshotDevice = (ATTV4SnapshotDeviceConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4SnapshotDeviceConfEvent_t)); break; case TypeATTEvent.ATTV4ConferencedEvent_t_PDU: v4conferencedEvent = (ATTV4ConferencedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4ConferencedEvent_t)); break; case TypeATTEvent.ATTV4DeliveredEvent_t_PDU: v4deliveredEvent = (ATTV4DeliveredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4DeliveredEvent_t)); break; case TypeATTEvent.ATTV4EstablishedEvent_t_PDU: v4establishedEvent = (ATTV4EstablishedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4EstablishedEvent_t)); break; case TypeATTEvent.ATTV4TransferredEvent_t_PDU: v4transferredEvent = (ATTV4TransferredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4TransferredEvent_t)); break; case TypeATTEvent.ATTV4LinkStatusEvent_t_PDU: v4linkStatus = (ATTV4LinkStatusEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4LinkStatusEvent_t)); break; case TypeATTEvent.ATTV4RouteRequestEvent_t_PDU: v4routeRequest = (ATTV4RouteRequestEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4RouteRequestEvent_t)); break; case TypeATTEvent.ATTV4QueryAgentStateConfEvent_t_PDU: v4queryAgentState = (ATTV4QueryAgentStateConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4QueryAgentStateConfEvent_t)); break; case TypeATTEvent.ATTV4QueryDeviceNameConfEvent_t_PDU: v4queryDeviceName = (ATTV4QueryDeviceNameConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4QueryDeviceNameConfEvent_t)); break; case TypeATTEvent.ATTV4MonitorConfEvent_t_PDU: v4monitorStart = (ATTV4MonitorConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4MonitorConfEvent_t)); break; case TypeATTEvent.ATTV4MonitorCallConfEvent_t_PDU: v4monitorCallStart = (ATTV4MonitorCallConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4MonitorCallConfEvent_t)); break; case TypeATTEvent.ATTV4NetworkReachedEvent_t_PDU: v4networkReachedEvent = (ATTV4NetworkReachedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV4NetworkReachedEvent_t)); break; case TypeATTEvent.ATTV5QueryAgentStateConfEvent_t_PDU: v5queryAgentState = (ATTV5QueryAgentStateConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5QueryAgentStateConfEvent_t)); break; case TypeATTEvent.ATTV5RouteRequestEvent_t_PDU: v5routeRequest = (ATTV5RouteRequestEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5RouteRequestEvent_t)); break; case TypeATTEvent.ATTV5TransferredEvent_t_PDU: v5transferredEvent = (ATTV5TransferredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5TransferredEvent_t)); break; case TypeATTEvent.ATTV5ConferencedEvent_t_PDU: v5conferencedEvent = (ATTV5ConferencedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5ConferencedEvent_t)); break; case TypeATTEvent.ATTV5ConnectionClearedEvent_t_PDU: v5connectionClearedEvent = (ATTV5ConnectionClearedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5ConnectionClearedEvent_t)); break; case TypeATTEvent.ATTV5OriginatedEvent_t_PDU: v5originatedEvent = (ATTV5OriginatedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5OriginatedEvent_t)); break; case TypeATTEvent.ATTV5EstablishedEvent_t_PDU: v5establishedEvent = (ATTV5EstablishedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5EstablishedEvent_t)); break; case TypeATTEvent.ATTV5DeliveredEvent_t_PDU: v5deliveredEvent = (ATTV5DeliveredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV5DeliveredEvent_t)); break; case TypeATTEvent.ATTV6NetworkReachedEvent_t_PDU: v6networkReachedEvent = (ATTV6NetworkReachedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6NetworkReachedEvent_t)); break; case TypeATTEvent.ATTV6ConferencedEvent_t_PDU: v6conferencedEvent = (ATTV6ConferencedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6ConferencedEvent_t)); break; case TypeATTEvent.ATTV6DeliveredEvent_t_PDU: v6deliveredEvent = (ATTV6DeliveredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6DeliveredEvent_t)); break; case TypeATTEvent.ATTV6EstablishedEvent_t_PDU: v6establishedEvent = (ATTV6EstablishedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6EstablishedEvent_t)); break; case TypeATTEvent.ATTV6TransferredEvent_t_PDU: v6transferredEvent = (ATTV6TransferredEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6TransferredEvent_t)); break; case TypeATTEvent.ATTV6QueryDeviceNameConfEvent_t_PDU: v6queryDeviceName = (ATTV6QueryDeviceNameConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6QueryDeviceNameConfEvent_t)); break; case TypeATTEvent.ATTV6GetAPICapsConfEvent_t_PDU: v6getAPICaps = (ATTV6GetAPICapsConfEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6GetAPICapsConfEvent_t)); break; case TypeATTEvent.ATTV6ConnectionClearedEvent_t_PDU: v6connectionClearedEvent = (ATTV6ConnectionClearedEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6ConnectionClearedEvent_t)); break; case TypeATTEvent.ATTV6RouteRequestEvent_t_PDU: v6routeRequest = (ATTV6RouteRequestEvent_t)Marshal.PtrToStructure(point, typeof(ATTV6RouteRequestEvent_t)); break; case TypeATTEvent.ATTClearConnection_t_PDU: clearConnectionReq = (ATTClearConnection_t)Marshal.PtrToStructure(point, typeof(ATTClearConnection_t)); break; case TypeATTEvent.ATTConsultationCall_t_PDU: consultationCallReq = (ATTConsultationCall_t)Marshal.PtrToStructure(point, typeof(ATTConsultationCall_t)); break; case TypeATTEvent.ATTMakeCall_t_PDU: makeCallReq = (ATTMakeCall_t)Marshal.PtrToStructure(point, typeof(ATTMakeCall_t)); break; case TypeATTEvent.ATTDirectAgentCall_t_PDU: directAgentCallReq = (ATTDirectAgentCall_t)Marshal.PtrToStructure(point, typeof(ATTDirectAgentCall_t)); break; case TypeATTEvent.ATTMakePredictiveCall_t_PDU: makePredictiveCallReq = (ATTMakePredictiveCall_t)Marshal.PtrToStructure(point, typeof(ATTMakePredictiveCall_t)); break; case TypeATTEvent.ATTSupervisorAssistCall_t_PDU: supervisorAssistCallReq = (ATTSupervisorAssistCall_t)Marshal.PtrToStructure(point, typeof(ATTSupervisorAssistCall_t)); break; case TypeATTEvent.ATTReconnectCall_t_PDU: reconnectCallReq = (ATTReconnectCall_t)Marshal.PtrToStructure(point, typeof(ATTReconnectCall_t)); break; case TypeATTEvent.ATTSendDTMFTone_t_PDU: sendDTMFToneReq = (ATTSendDTMFTone_t)Marshal.PtrToStructure(point, typeof(ATTSendDTMFTone_t)); break; case TypeATTEvent.ATTSingleStepConferenceCall_t_PDU: ssconferenceReq = (ATTSingleStepConferenceCall_t)Marshal.PtrToStructure(point, typeof(ATTSingleStepConferenceCall_t)); break; case TypeATTEvent.ATTSelectiveListeningHold_t_PDU: slholdReq = (ATTSelectiveListeningHold_t)Marshal.PtrToStructure(point, typeof(ATTSelectiveListeningHold_t)); break; case TypeATTEvent.ATTSelectiveListeningRetrieve_t_PDU: slretrieveReq = (ATTSelectiveListeningRetrieve_t)Marshal.PtrToStructure(point, typeof(ATTSelectiveListeningRetrieve_t)); break; case TypeATTEvent.ATTSetAgentState_t_PDU: setAgentStateReq = (ATTSetAgentState_t)Marshal.PtrToStructure(point, typeof(ATTSetAgentState_t)); break; case TypeATTEvent.ATTQueryAgentState_t_PDU: queryAgentStateReq = (ATTQueryAgentState_t)Marshal.PtrToStructure(point, typeof(ATTQueryAgentState_t)); break; case TypeATTEvent.ATTQueryAcdSplit_t_PDU: queryAcdSplitReq = (ATTQueryAcdSplit_t)Marshal.PtrToStructure(point, typeof(ATTQueryAcdSplit_t)); break; case TypeATTEvent.ATTQueryAgentLogin_t_PDU: queryAgentLoginReq = (ATTQueryAgentLogin_t)Marshal.PtrToStructure(point, typeof(ATTQueryAgentLogin_t)); break; case TypeATTEvent.ATTQueryCallClassifier_t_PDU: queryCallClassifierReq = (ATTQueryCallClassifier_t)Marshal.PtrToStructure(point, typeof(ATTQueryCallClassifier_t)); break; case TypeATTEvent.ATTQueryDeviceName_t_PDU: queryDeviceNameReq = (ATTQueryDeviceName_t)Marshal.PtrToStructure(point, typeof(ATTQueryDeviceName_t)); break; case TypeATTEvent.ATTQueryStationStatus_t_PDU: queryStationStatusReq = (ATTQueryStationStatus_t)Marshal.PtrToStructure(point, typeof(ATTQueryStationStatus_t)); break; case TypeATTEvent.ATTQueryTod_t_PDU: queryTodReq = (ATTQueryTod_t)Marshal.PtrToStructure(point, typeof(ATTQueryTod_t)); break; case TypeATTEvent.ATTQueryTg_t_PDU: queryTgReq = (ATTQueryTg_t)Marshal.PtrToStructure(point, typeof(ATTQueryTg_t)); break; case TypeATTEvent.ATTQueryAgentMeasurements_t_PDU: queryAgentMeasReq = (ATTQueryAgentMeasurements_t)Marshal.PtrToStructure(point, typeof(ATTQueryAgentMeasurements_t)); break; case TypeATTEvent.ATTQuerySplitSkillMeasurements_t_PDU: querySplitSkillMeasReq = (ATTQuerySplitSkillMeasurements_t)Marshal.PtrToStructure(point, typeof(ATTQuerySplitSkillMeasurements_t)); break; case TypeATTEvent.ATTQueryTrunkGroupMeasurements_t_PDU: queryTrunkGroupMeasReq = (ATTQueryTrunkGroupMeasurements_t)Marshal.PtrToStructure(point, typeof(ATTQueryTrunkGroupMeasurements_t)); break; case TypeATTEvent.ATTQueryVdnMeasurements_t_PDU: queryVdnMeasReq = (ATTQueryVdnMeasurements_t)Marshal.PtrToStructure(point, typeof(ATTQueryVdnMeasurements_t)); break; case TypeATTEvent.ATTMonitorFilter_t_PDU: monitorFilterReq = (ATTMonitorFilter_t)Marshal.PtrToStructure(point, typeof(ATTMonitorFilter_t)); break; case TypeATTEvent.ATTMonitorStopOnCall_t_PDU: monitorStopOnCallReq = (ATTMonitorStopOnCall_t)Marshal.PtrToStructure(point, typeof(ATTMonitorStopOnCall_t)); break; case TypeATTEvent.ATTRouteSelect_t_PDU: routeSelectReq = (ATTRouteSelect_t)Marshal.PtrToStructure(point, typeof(ATTRouteSelect_t)); break; case TypeATTEvent.ATTSysStat_t_PDU: sysStatReq = (ATTSysStat_t)Marshal.PtrToStructure(point, typeof(ATTSysStat_t)); break; case TypeATTEvent.ATTSetBillRate_t_PDU: setBillRateReq = (ATTSetBillRate_t)Marshal.PtrToStructure(point, typeof(ATTSetBillRate_t)); break; case TypeATTEvent.ATTQueryUcid_t_PDU: queryUCIDReq = (ATTQueryUcid_t)Marshal.PtrToStructure(point, typeof(ATTQueryUcid_t)); break; case TypeATTEvent.ATTSetAdviceOfCharge_t_PDU: adviceOfChargeReq = (ATTSetAdviceOfCharge_t)Marshal.PtrToStructure(point, typeof(ATTSetAdviceOfCharge_t)); break; case TypeATTEvent.ATTV4SendDTMFTone_t_PDU: v4sendDTMFToneReq = (ATTV4SendDTMFTone_t)Marshal.PtrToStructure(point, typeof(ATTV4SendDTMFTone_t)); break; case TypeATTEvent.ATTV4SetAgentState_t_PDU: v4setAgentStateReq = (ATTV4SetAgentState_t)Marshal.PtrToStructure(point, typeof(ATTV4SetAgentState_t)); break; case TypeATTEvent.ATTV4MonitorFilter_t_PDU: v4monitorFilterReq = (ATTV4MonitorFilter_t)Marshal.PtrToStructure(point, typeof(ATTV4MonitorFilter_t)); break; case TypeATTEvent.ATTV5SetAgentState_t_PDU: v5setAgentStateReq = (ATTV5SetAgentState_t)Marshal.PtrToStructure(point, typeof(ATTV5SetAgentState_t)); break; case TypeATTEvent.ATTV5ClearConnection_t_PDU: v5clearConnectionReq = (ATTV5ClearConnection_t)Marshal.PtrToStructure(point, typeof(ATTV5ClearConnection_t)); break; case TypeATTEvent.ATTV5ConsultationCall_t_PDU: v5consultationCallReq = (ATTV5ConsultationCall_t)Marshal.PtrToStructure(point, typeof(ATTV5ConsultationCall_t)); break; case TypeATTEvent.ATTV5MakeCall_t_PDU: v5makeCallReq = (ATTV5MakeCall_t)Marshal.PtrToStructure(point, typeof(ATTV5MakeCall_t)); break; case TypeATTEvent.ATTV5DirectAgentCall_t_PDU: v5directAgentCallReq = (ATTV5DirectAgentCall_t)Marshal.PtrToStructure(point, typeof(ATTV5DirectAgentCall_t)); break; case TypeATTEvent.ATTV5MakePredictiveCall_t_PDU: v5makePredictiveCallReq = (ATTV5MakePredictiveCall_t)Marshal.PtrToStructure(point, typeof(ATTV5MakePredictiveCall_t)); break; case TypeATTEvent.ATTV5SupervisorAssistCall_t_PDU: v5supervisorAssistCallReq = (ATTV5SupervisorAssistCall_t)Marshal.PtrToStructure(point, typeof(ATTV5SupervisorAssistCall_t)); break; case TypeATTEvent.ATTV5ReconnectCall_t_PDU: v5reconnectCallReq = (ATTV5ReconnectCall_t)Marshal.PtrToStructure(point, typeof(ATTV5ReconnectCall_t)); break; case TypeATTEvent.ATTV5RouteSelect_t_PDU: v5routeSelectReq = (ATTV5RouteSelect_t)Marshal.PtrToStructure(point, typeof(ATTV5RouteSelect_t)); break; case TypeATTEvent.ATTV6RouteSelect_t_PDU: v6routeSelectReq = (ATTV6RouteSelect_t)Marshal.PtrToStructure(point, typeof(ATTV6RouteSelect_t)); break; } } } } <file_sep>using System; namespace TSAPILIB2 { public class MonitorEventCollection : IDisposable { private readonly uint _monitorCrossRefId; private readonly ConnectionID_t _deviceId; private readonly bool _isCallMonitor; public bool IsCallMonitor { get { return _isCallMonitor; } } public MonitorEventCollection(uint monitorCrossRefId,String deviceId) { _monitorCrossRefId = monitorCrossRefId; _deviceId = new ConnectionID_t { deviceID = deviceId }; } public MonitorEventCollection(uint monitorCrossRefId, ConnectionID_t deviceId) { _monitorCrossRefId = monitorCrossRefId; _deviceId = deviceId; _isCallMonitor = true; } public ConnectionID_t GetTargertMonitror() { return _deviceId; } public uint GetTargertMonitrorId() { return _monitorCrossRefId; } public delegate void CallCleared(object sender, CstaAttEventArgs<CSTACallClearedEvent_t, ATTCallClearedEvent_t> e,uint monId); public delegate void Conferenced(object sender, CstaAttEventArgs<CSTAConferencedEvent_t, ATTConferencedEvent_t> e, uint monId); public delegate void ConnectionCleared(object sender, CstaEventArgs<CSTAConnectionClearedEvent_t> e, uint monId); public delegate void Delivered(object sender, CstaAttEventArgs<CSTADeliveredEvent_t, ATTDeliveredEvent_t> e, uint monId); public delegate void Diverted(object sender, CstaAttEventArgs<CSTADivertedEvent_t, ATTDivertedEvent_t> e, uint monId); public delegate void Established(object sender, CstaAttEventArgs<CSTAEstablishedEvent_t, ATTEstablishedEvent_t> e, uint monId); public delegate void Failed(object sender, CstaAttEventArgs<CSTAFailedEvent_t, ATTFailedEvent_t> e, uint monId); public delegate void Held(object sender, CstaEventArgs<CSTAHeldEvent_t> e, uint monId); public delegate void NetworkReached(object sender, CstaAttEventArgs<CSTANetworkReachedEvent_t, ATTNetworkReachedEvent_t> e, uint monId); public delegate void Originated(object sender, CstaAttEventArgs<CSTAOriginatedEvent_t, ATTOriginatedEvent_t> e, uint monId); public delegate void Queued(object sender, CstaAttEventArgs<CSTAQueuedEvent_t, ATTQueuedEvent_t> e, uint monId); public delegate void Retrieved(object sender, CstaEventArgs<CSTARetrievedEvent_t> e, uint monId); public delegate void ServiceInitiated(object sender, CstaAttEventArgs<CSTAServiceInitiatedEvent_t, ATTServiceInitiatedEvent_t> e, uint monId); public delegate void Transferred(object sender, CstaAttEventArgs<CSTATransferredEvent_t, ATTTransferredEvent_t> e, uint monId); public delegate void CallInformation(object sender, CstaEventArgs<CSTACallInformationEvent_t> e, uint monId); public delegate void DoNotDisturb(object sender, CstaEventArgs<CSTADoNotDisturbEvent_t> e, uint monId); public delegate void Forwarding(object sender, CstaEventArgs<CSTAForwardingEvent_t> e, uint monId); public delegate void MessageWaiting(object sender, CstaEventArgs<CSTAMessageWaitingEvent_t> e, uint monId); public delegate void BackInService(object sender, CstaEventArgs<CSTABackInServiceEvent_t> e, uint monId); public delegate void OutOfService(object sender, CstaEventArgs<CSTAOutOfServiceEvent_t> e, uint monId); public delegate void PrivateStatus(object sender, CstaEventArgs<CSTAPrivateStatusEvent_t> e, uint monId); public delegate void MonitorEnded(object sender, CstaEventArgs<CSTAMonitorEndedEvent_t> e, uint monId); public delegate void LogOn(object sender, CstaEventArgs<CSTALoggedOnEvent_t> e, uint monId); public delegate void LogOff(object sender, CstaEventArgs<CSTALoggedOffEvent_t> e, uint monId); public event CallCleared OnCallCleared; public event Conferenced OnConferenced; public event ConnectionCleared OnConnectionCleared; public event Delivered OnDelivered; public event Diverted OnDiverted; public event Established OnEstablished; public event Failed OnFailed; public event Held OnHeld; public event NetworkReached OnNetworkReached; public event Originated OnOriginated; public event Queued OnQueued; public event Retrieved OnRetrieved; public event ServiceInitiated OnServiceInitiated; public event Transferred OnTransferred; public event CallInformation OnCallInformation; public event DoNotDisturb OnDoNotDisturb; public event Forwarding OnForwarding; public event MessageWaiting OnMessageWaiting; public event BackInService OnBackInService; public event OutOfService OnOutOfService; public event PrivateStatus OnPrivateStatus; public event MonitorEnded OnMonitorEnded; public event LogOn OnLogOn; public event LogOff OnLogOff; public void Invoke(CstaUnsolicitedEvent data, eventTypeCSTA eventType, ATTEvent_t attData, uint monitorCrossRefId) { switch (eventType) { case eventTypeCSTA.CSTA_CALL_CLEARED: if (OnCallCleared != null) OnCallCleared(this, new CstaAttEventArgs<CSTACallClearedEvent_t, ATTCallClearedEvent_t>(data.callCleared, attData.callClearedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_CONFERENCED: if (OnConferenced != null) OnConferenced(this, new CstaAttEventArgs<CSTAConferencedEvent_t, ATTConferencedEvent_t>(data.conferenced, attData.conferencedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_CONNECTION_CLEARED: if (OnConnectionCleared != null) OnConnectionCleared(this, new CstaEventArgs<CSTAConnectionClearedEvent_t>(data.connectionCleared), monitorCrossRefId); break; case eventTypeCSTA.CSTA_DELIVERED: if (OnDelivered != null) OnDelivered(this, new CstaAttEventArgs<CSTADeliveredEvent_t, ATTDeliveredEvent_t>(data.delivered, attData.deliveredEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_DIVERTED: if (OnDiverted != null) OnDiverted(this, new CstaAttEventArgs<CSTADivertedEvent_t, ATTDivertedEvent_t>(data.diverted, attData.divertedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_ESTABLISHED: if (OnEstablished != null) OnEstablished(this, new CstaAttEventArgs<CSTAEstablishedEvent_t, ATTEstablishedEvent_t>(data.established, attData.establishedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_FAILED: if (OnFailed != null) OnFailed(this, new CstaAttEventArgs<CSTAFailedEvent_t, ATTFailedEvent_t>(data.failed, attData.failedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_HELD: if (OnHeld != null) OnHeld(this, new CstaEventArgs<CSTAHeldEvent_t>(data.held), monitorCrossRefId); break; case eventTypeCSTA.CSTA_NETWORK_REACHED: if (OnNetworkReached != null) OnNetworkReached(this, new CstaAttEventArgs<CSTANetworkReachedEvent_t, ATTNetworkReachedEvent_t>(data.networkReached, attData.networkReachedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_ORIGINATED: if (OnOriginated != null) OnOriginated(this, new CstaAttEventArgs<CSTAOriginatedEvent_t, ATTOriginatedEvent_t>(data.originated, attData.originatedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_QUEUED: if (OnQueued != null) OnQueued(this, new CstaAttEventArgs<CSTAQueuedEvent_t, ATTQueuedEvent_t>(data.queued, attData.queuedEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_RETRIEVED: if (OnRetrieved != null) OnRetrieved(this, new CstaEventArgs<CSTARetrievedEvent_t>(data.retrieved), monitorCrossRefId); break; case eventTypeCSTA.CSTA_SERVICE_INITIATED: if (OnServiceInitiated != null) OnServiceInitiated(this, new CstaAttEventArgs<CSTAServiceInitiatedEvent_t, ATTServiceInitiatedEvent_t>(data.serviceInitiated, attData.serviceInitiated), monitorCrossRefId); break; case eventTypeCSTA.CSTA_TRANSFERRED: if (OnTransferred != null) OnTransferred(this, new CstaAttEventArgs<CSTATransferredEvent_t, ATTTransferredEvent_t>(data.transferred, attData.transferredEvent), monitorCrossRefId); break; case eventTypeCSTA.CSTA_CALL_INFORMATION: if (OnCallInformation != null) OnCallInformation(this, new CstaEventArgs<CSTACallInformationEvent_t>(data.callInformation), monitorCrossRefId); break; case eventTypeCSTA.CSTA_DO_NOT_DISTURB: if (OnDoNotDisturb != null) OnDoNotDisturb(this, new CstaEventArgs<CSTADoNotDisturbEvent_t>(data.doNotDisturb), monitorCrossRefId); break; case eventTypeCSTA.CSTA_FORWARDING: if (OnForwarding != null) OnForwarding(this, new CstaEventArgs<CSTAForwardingEvent_t>(data.forwarding), monitorCrossRefId); break; case eventTypeCSTA.CSTA_MESSAGE_WAITING: if (OnMessageWaiting != null) OnMessageWaiting(this, new CstaEventArgs<CSTAMessageWaitingEvent_t>(data.messageWaiting), monitorCrossRefId); break; case eventTypeCSTA.CSTA_BACK_IN_SERVICE: if (OnBackInService != null) OnBackInService(this, new CstaEventArgs<CSTABackInServiceEvent_t>(data.backInService), monitorCrossRefId); break; case eventTypeCSTA.CSTA_OUT_OF_SERVICE: if (OnOutOfService != null) OnOutOfService(this, new CstaEventArgs<CSTAOutOfServiceEvent_t>(data.outOfService), monitorCrossRefId); break; case eventTypeCSTA.CSTA_PRIVATE_STATUS: if (OnPrivateStatus != null) OnPrivateStatus(this, new CstaEventArgs<CSTAPrivateStatusEvent_t>(data.privateStatus), monitorCrossRefId); break; case eventTypeCSTA.CSTA_MONITOR_ENDED: MonitorEndedInvoke(data.monitorEnded, monitorCrossRefId); break; case eventTypeCSTA.CSTA_LOGGED_ON: if (OnPrivateStatus != null) OnLogOn(this, new CstaEventArgs<CSTALoggedOnEvent_t>(data.loggedOn), monitorCrossRefId); break; case eventTypeCSTA.CSTA_LOGGED_OFF: if (OnPrivateStatus != null) OnLogOff(this, new CstaEventArgs<CSTALoggedOffEvent_t>(data.loggedOff), monitorCrossRefId); break; } } public void MonitorEndedInvoke(CSTAMonitorEndedEvent_t data, uint monId) { if (OnMonitorEnded != null) OnMonitorEnded(this, new CstaEventArgs<CSTAMonitorEndedEvent_t>(data), monId); } protected virtual void Dispose(bool disposing) { if (disposing ) { OnCallCleared = null; OnConferenced = null; OnConnectionCleared = null; OnDelivered = null; OnDiverted = null; OnEstablished = null; OnFailed = null; OnHeld = null; OnNetworkReached = null; OnOriginated = null; OnQueued = null; OnRetrieved = null; OnServiceInitiated = null; OnTransferred = null; OnCallInformation = null; OnDoNotDisturb = null; OnForwarding = null; OnMessageWaiting = null; OnLogOn = null; OnLogOff = null; } } public void Dispose() { Dispose(true); } } }<file_sep>using System; using System.Threading; namespace TSAPILIB2 { public class MonitorEventAgentCollection: IDisposable { private ATTQueryAgentStateConfEvent_t _mode; private AgentState_t _sate; private Timer _timer; private bool _start = true; public delegate void Login(object sender, AgentStateEventArgs e,uint monitorId); public delegate void Logout(object sender, AgentStateEventArgs e, uint monitorId); public delegate void Ready(object sender, AgentStateEventArgs e, uint monitorId); public delegate void NotRead(object sender, AgentStateEventArgs e, uint monitorId); public delegate void AftCall(object sender, AgentStateEventArgs e, uint monitorId); public event MonitorEventAgentCollection.Login OnLogin; public event Logout OnLogout; public event Ready OnReady; public event NotRead OnNotReady; public event AftCall OnAftCall; private readonly Tsapi _tsapi; private readonly string _agentId; private readonly uint _monitorId; private enum Timeouts { Login = 1000, Logout = 5000 } public string GetAgentName() { return _agentId; } public MonitorEventAgentCollection(Tsapi ts, string agentId, int count) { _tsapi = ts; _agentId = agentId; _monitorId = (uint)count + 1000000; // попытка уйти от пересечения с монитрингом девайсов _timer = new Timer(TimerCallBack, this, (long)Timeouts.Login,(long) Timeouts.Login); } ~MonitorEventAgentCollection() { Dispose(false); } private void TimerCallBack(object sender) { _tsapi.GetQueryAgentState(_agentId); } public void Invoke(CSTAQueryAgentStateConfEvent_t csta, ATTQueryAgentStateConfEvent_t att) { if (_start) { _mode = att; _sate = csta.agentState; if (csta.agentState == AgentState_t.agNull) { LogoutInvoke(); } else { LoginInvoke(); switch (_mode.workMode) { case ATTWorkMode_t.wmManualIn:ReadyInvoke(); break; case ATTWorkMode_t.wmAuxWork:NotReadyInvoke(); break; case ATTWorkMode_t.wmAftcalWk:AftCallInvoke(); break; } } _start = false; } else { if (_sate != csta.agentState ||_mode.workMode != att.workMode ||_mode.reasonCode != att.reasonCode ||_mode.talkState != att.talkState) { if (csta.agentState == AgentState_t.agNull &&_sate != AgentState_t.agNull) { LogoutInvoke(); } if (csta.agentState != AgentState_t.agNull &&_sate == AgentState_t.agNull) { LoginInvoke(); } _mode = att; _sate = csta.agentState; switch (_mode.workMode) { case ATTWorkMode_t.wmAutoIn: case ATTWorkMode_t.wmManualIn:ReadyInvoke(); break; case ATTWorkMode_t.wmAuxWork:NotReadyInvoke(); break; case ATTWorkMode_t.wmAftcalWk:AftCallInvoke(); break; } } } _timer.Change((long)Timeouts.Login, (long)Timeouts.Login); } void LoginInvoke() { _timer.Change((long)Timeouts.Login, (long)Timeouts.Login); OnLogin?.Invoke(this, new AgentStateEventArgs { Mode = _mode }, _monitorId); } void LogoutInvoke() { _timer.Change((long)Timeouts.Logout, (long)Timeouts.Logout); OnLogout?.Invoke(this, new AgentStateEventArgs { Mode = _mode }, _monitorId); } void ReadyInvoke() { OnReady?.Invoke(this, new AgentStateEventArgs { Mode = _mode }, _monitorId); } void NotReadyInvoke() { OnNotReady?.Invoke(this, new AgentStateEventArgs { Mode = _mode }, _monitorId); } void AftCallInvoke() { OnAftCall?.Invoke(this, new AgentStateEventArgs { Mode = _mode }, _monitorId); } public void Dispose() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (Disposed) return; if (disposing) { } if (_timer != null) { _timer.Dispose(); _timer = null; } OnAftCall = null; OnLogin = null; OnLogout = null; OnNotReady = null; OnReady = null; } public bool Disposed { get; set; } public uint MonitorId => _monitorId; } }<file_sep>using System; using System.Threading; using System.Threading.Tasks; namespace TSAPILIB2 { public class MyTask:IDisposable { private readonly string _command; private readonly int _timeoutMs; private Timer _time; private readonly object _locktask = new object(); private readonly TaskCompletionSource<object> _task = new TaskCompletionSource<object>(); public delegate void TimeoutEvent(MyTask t); public event TimeoutEvent OnTimeout; protected virtual void OnOnTimeout(MyTask t) { var handler = OnTimeout; handler?.Invoke(t); } public Task<object> Task { get { return _task.Task; } } public string Command { get { return _command; } } public Int32 CountElapsend = 0; private bool _disposed; public MyTask( Int32 timeoutMs, String command) { _command = command; _timeoutMs = timeoutMs*1000; _time = new Timer(SetTimeout, this, _timeoutMs, Timeout.Infinite); } private void SetTimeout(object state) { lock (_locktask) { if (!_task.Task.IsCompleted) { _task.SetException(new CstaExeption(CSTAUniversalFailure_t.operationTimeout)); OnOnTimeout(this); } } } public void UpdateTimeout() { lock (_locktask) { if (_time != null) { _time.Change(_timeoutMs, Timeout.Infinite); } } } protected virtual void Dispose(Boolean disposing) { if (_disposed)return; // Ресурсы уже освобождены if (disposing) { lock (_locktask) { _time.Dispose(); _time = null; } } _disposed = true; } public void Dispose() { Dispose(true); } public void Set(object ret) { lock (_locktask) { _task.TrySetResult(ret); } } public void SetError( CSTAUniversalFailure_t error) { lock (_locktask) { _task.TrySetException(new CstaExeption(error)); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace TSAPILIB2 { // ReSharper disable InconsistentNaming [Flags] [DataContract] public enum ACSFunctionRet_t { ACSPOSITIVE_ACK = 0, ACSERR_APIVERDENIED = -1, ACSERR_BADPARAMETER = -2, ACSERR_DUPSTREAM = -3, ACSERR_NODRIVER = -4, ACSERR_NOSERVER = -5, ACSERR_NORESOURCE = -6, ACSERR_UBUFSMALL = -7, ACSERR_NOMESSAGE = -8, ACSERR_UNKNOWN = -9, ACSERR_BADHDL = -10, ACSERR_STREAM_FAILED = -11, ACSERR_NOBUFFERS = -12, ACSERR_QUEUE_FULL = -13, ACSERR_ERROR_SEND_TO_QUEUR = -14, ACSERR_BAD_SESSION_ID = -15 } public enum StreamType_t { stCsta = 1, stOam = 2, stDirectory = 3, stNmsrv = 4 } public enum InvokeIDType_t { APP_GEN_ID, LIB_GEN_ID } public enum Level_t { acsLevel1 = 1, acsLevel2 = 2, acsLevel3 = 3, acsLevel4 = 4 } [Serializable,StructLayout(LayoutKind.Sequential)] public struct PrivateData_t { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string vendor; public ushort length; [MarshalAs(UnmanagedType.ByValArray, SizeConst= 1024 * 2)] public char[] data; public void Set(string ldata) { data = new char[1024*2]; ldata.ToCharArray().CopyTo(data, 1); length = (ushort)(ldata.Length+2); } } public enum TypeATTEvent { ATTV5ClearConnection_t_PDU = 1, ATTV5ConsultationCall_t_PDU = 2, ATTV5MakeCall_t_PDU = 3, ATTV5DirectAgentCall_t_PDU = 4, ATTV5MakePredictiveCall_t_PDU = 5, ATTV5SupervisorAssistCall_t_PDU = 6, ATTV5ReconnectCall_t_PDU = 7, ATTV4SendDTMFTone_t_PDU = 8, ATTSendDTMFToneConfEvent_t_PDU = 9, ATTV4SetAgentState_t_PDU = 10, ATTQueryAcdSplit_t_PDU = 11, ATTQueryAcdSplitConfEvent_t_PDU = 12, ATTQueryAgentLogin_t_PDU = 13, ATTQueryAgentLoginConfEvent_t_PDU = 14, ATTQueryAgentLoginResp_t_PDU = 15, ATTQueryAgentState_t_PDU = 16, ATTV4QueryAgentStateConfEvent_t_PDU = 17, ATTQueryCallClassifier_t_PDU = 18, ATTQueryCallClassifierConfEvent_t_PDU = 19, ATTV4QueryDeviceInfoConfEvent_t_PDU = 20, ATTQueryMwiConfEvent_t_PDU = 21, ATTQueryStationStatus_t_PDU = 22, ATTQueryStationStatusConfEvent_t_PDU = 23, ATTQueryTod_t_PDU = 24, ATTQueryTodConfEvent_t_PDU = 25, ATTQueryTg_t_PDU = 26, ATTQueryTgConfEvent_t_PDU = 27, ATTV4SnapshotDeviceConfEvent_t_PDU = 28, ATTV4MonitorFilter_t_PDU = 29, ATTV4MonitorConfEvent_t_PDU = 30, ATTMonitorStopOnCall_t_PDU = 31, ATTMonitorStopOnCallConfEvent_t_PDU = 32, ATTV4MonitorCallConfEvent_t_PDU = 33, ATTCallClearedEvent_t_PDU = 34, ATTV3ConferencedEvent_t_PDU = 35, ATTV5ConnectionClearedEvent_t_PDU = 36, ATTV3DeliveredEvent_t_PDU = 37, ATTEnteredDigitsEvent_t_PDU = 38, ATTV3EstablishedEvent_t_PDU = 39, ATTV4NetworkReachedEvent_t_PDU = 40, ATTV3TransferredEvent_t_PDU = 41, ATTV4RouteRequestEvent_t_PDU = 42, ATTV5RouteSelect_t_PDU = 43, ATTRouteUsedEvent_t_PDU = 44, ATTSysStat_t_PDU = 45, ATTV3LinkStatusEvent_t_PDU = 46, ATTV5OriginatedEvent_t_PDU = 47, ATTLoggedOnEvent_t_PDU = 48, ATTQueryDeviceName_t_PDU = 49, ATTV4QueryDeviceNameConfEvent_t_PDU = 50, ATTQueryAgentMeasurements_t_PDU = 51, ATTQueryAgentMeasurementsConfEvent_t_PDU = 52, ATTQuerySplitSkillMeasurements_t_PDU = 53, ATTQuerySplitSkillMeasurementsConfEvent_t_PDU = 54, ATTQueryTrunkGroupMeasurements_t_PDU = 55, ATTQueryTrunkGroupMeasurementsConfEvent_t_PDU = 56, ATTQueryVdnMeasurements_t_PDU = 57, ATTQueryVdnMeasurementsConfEvent_t_PDU = 58, ATTV4ConferencedEvent_t_PDU = 59, ATTV4DeliveredEvent_t_PDU = 60, ATTV4EstablishedEvent_t_PDU = 61, ATTV4TransferredEvent_t_PDU = 62, ATTV4LinkStatusEvent_t_PDU = 63, ATTV4GetAPICapsConfEvent_t_PDU = 64, ATTSingleStepConferenceCall_t_PDU = 65, ATTSingleStepConferenceCallConfEvent_t_PDU = 66, ATTSelectiveListeningHold_t_PDU = 67, ATTSelectiveListeningHoldConfEvent_t_PDU = 68, ATTSelectiveListeningRetrieve_t_PDU = 69, ATTSelectiveListeningRetrieveConfEvent_t_PDU = 70, ATTSendDTMFTone_t_PDU = 71, ATTSnapshotDeviceConfEvent_t_PDU = 72, ATTLinkStatusEvent_t_PDU = 73, ATTSetBillRate_t_PDU = 74, ATTSetBillRateConfEvent_t_PDU = 75, ATTQueryUcid_t_PDU = 76, ATTQueryUcidConfEvent_t_PDU = 77, ATTV5ConferencedEvent_t_PDU = 78, ATTLoggedOffEvent_t_PDU = 79, ATTV5DeliveredEvent_t_PDU = 80, ATTV5EstablishedEvent_t_PDU = 81, ATTV5TransferredEvent_t_PDU = 82, ATTV5RouteRequestEvent_t_PDU = 83, ATTConsultationCallConfEvent_t_PDU = 84, ATTMakeCallConfEvent_t_PDU = 85, ATTMakePredictiveCallConfEvent_t_PDU = 86, ATTV5SetAgentState_t_PDU = 87, ATTV5QueryAgentStateConfEvent_t_PDU = 88, ATTV6QueryDeviceNameConfEvent_t_PDU = 89, ATTConferenceCallConfEvent_t_PDU = 90, ATTTransferCallConfEvent_t_PDU = 91, ATTMonitorFilter_t_PDU = 92, ATTMonitorConfEvent_t_PDU = 93, ATTMonitorCallConfEvent_t_PDU = 94, ATTServiceInitiatedEvent_t_PDU = 95, ATTChargeAdviceEvent_t_PDU = 96, ATTV6GetAPICapsConfEvent_t_PDU = 97, ATTQueryDeviceInfoConfEvent_t_PDU = 98, ATTSetAdviceOfCharge_t_PDU = 99, ATTSetAdviceOfChargeConfEvent_t_PDU = 100, ATTV6NetworkReachedEvent_t_PDU = 101, ATTSetAgentState_t_PDU = 102, ATTSetAgentStateConfEvent_t_PDU = 103, ATTQueryAgentStateConfEvent_t_PDU = 104, ATTV6RouteRequestEvent_t_PDU = 105, ATTV6TransferredEvent_t_PDU = 106, ATTV6ConferencedEvent_t_PDU = 107, ATTClearConnection_t_PDU = 108, ATTConsultationCall_t_PDU = 109, ATTMakeCall_t_PDU = 110, ATTDirectAgentCall_t_PDU = 111, ATTMakePredictiveCall_t_PDU = 112, ATTSupervisorAssistCall_t_PDU = 113, ATTReconnectCall_t_PDU = 114, ATTV6ConnectionClearedEvent_t_PDU = 115, ATTV6RouteSelect_t_PDU = 116, ATTV6DeliveredEvent_t_PDU = 117, ATTV6EstablishedEvent_t_PDU = 118, ATTOriginatedEvent_t_PDU = 119, Reserved_t_PDU = 120, Reserved2_t_PDU = 121, Reserved3_t_PDU = 122, Reserved4_t_PDU = 123, Reserved5_t_PDU = 124, ATTQueryDeviceNameConfEvent_t_PDU = 125, ATTRouteSelect_t_PDU = 126, ATTGetAPICapsConfEvent_t_PDU = 127, ATTDeliveredEvent_t_PDU = 128, ATTEstablishedEvent_t_PDU = 129, ATTQueuedEvent_t_PDU = 130, ATTRouteRequestEvent_t_PDU = 131, ATTTransferredEvent_t_PDU = 132, ATTConferencedEvent_t_PDU = 133, ATTConnectionClearedEvent_t_PDU = 134, ATTDivertedEvent_t_PDU = 135, ATTNetworkReachedEvent_t_PDU = 136, ATTFailedEvent_t_PDU = 137, ATTSnapshotCallConfEvent_t_PDU = 138 }; public enum ACSUniversalFailure_t { tserverStreamFailed = 0, tserverNoThread = 1, tserverBadDriverId = 2, tserverDeadDriver = 3, tserverMessageHighWaterMark = 4, tserverFreeBufferFailed = 5, tserverSendToDriver = 6, tserverReceiveFromDriver = 7, tserverRegistrationFailed = 8, tserverSpxFailed = 9, tserverTrace = 10, tserverNoMemory = 11, tserverEncodeFailed = 12, tserverDecodeFailed = 13, tserverBadConnection = 14, tserverBadPdu = 15, tserverNoVersion = 16, tserverEcbMaxExceeded = 17, tserverNoEcbs = 18, tserverNoSdb = 19, tserverNoSdbCheckNeeded = 20, tserverSdbCheckNeeded = 21, tserverBadSdbLevel = 22, tserverBadServerid = 23, tserverBadStreamType = 24, tserverBadPasswordOrLogin = 25, tserverNoUserRecord = 26, tserverNoDeviceRecord = 27, tserverDeviceNotOnList = 28, tserverUsersRestrictedHome = 30, tserverNoAwaypermission = 31, tserverNoHomepermission = 32, tserverNoAwayWorktop = 33, tserverBadDeviceRecord = 34, tserverDeviceNotSupported = 35, tserverInsufficientPermission = 36, tserverNoResourceTag = 37, tserverInvalidMessage = 38, tserverExceptionList = 39, tserverNotOnOamList = 40, tserverPbxIdNotInSdb = 41, tserverUserLicensesExceeded = 42, tserverOamDropConnection = 43, tserverNoVersionRecord = 44, tserverOldVersionRecord = 45, tserverBadPacket = 46, tserverOpenFailed = 47, tserverOamInUse = 48, tserverDeviceNotOnHomeList = 49, tserverDeviceNotOnCallControlList = 50, tserverDeviceNotOnAwayList = 51, tserverDeviceNotOnRouteList = 52, tserverDeviceNotOnMonitorDeviceList = 53, tserverDeviceNotOnMonitorCallDeviceList = 54, tserverNoCallCallMonitorPermission = 55, tserverHomeDeviceListEmpty = 56, tserverCallControlListEmpty = 57, tserverAwayListEmpty = 58, tserverRouteListEmpty = 59, tserverMonitorDeviceListEmpty = 60, tserverMonitorCallDeviceListEmpty = 61, tserverUserAtHomeWorktop = 62, tserverDeviceListEmpty = 63, tserverBadGetDeviceLevel = 64, tserverDriverUnregistered = 65, tserverNoAcsStream = 66, tserverDropOam = 67, tserverEcbTimeout = 68, tserverBadEcb = 69, tserverAdvertiseFailed = 70, tserverNetwareFailure = 71, tserverTdiQueueFault = 72, tserverDriverCongestion = 73, tserverNoTdiBuffers = 74, tserverOldInvokeid = 75, tserverHwmarkToLarge = 76, tserverSetEcbToLow = 77, tserverNoRecordInFile = 78, tserverEcbOverdue = 79, tserverBadPwEncryption = 80, tserverBadTservProtocol = 81, tserverBadDriverProtocol = 82, tserverBadTransportType = 83, tserverPduVersionMismatch = 84, tserverVersionMismatch = 85, tserverLicenseMismatch = 86, tserverBadAttributeList = 87, tserverBadTlistType = 88, tserverBadProtocolFormat = 89, tserverOldTslib = 90, tserverBadLicenseFile = 91, tserverNoPatches = 92, tserverSystemError = 93, tserverOamListEmpty = 94, tserverTcpFailed = 95, tserverSpxDisabled = 96, tserverTcpDisabled = 97, tserverRequiredModulesNotLoaded = 98, tserverTransportInUseByOam = 99, tserverNoNdsOamPermission = 100, tserverOpenSdbLogFailed = 101, tserverInvalidLogSize = 102, tserverWriteSdbLogFailed = 103, tserverNtFailure = 104, tserverLoadLibFailed = 105, tserverInvalidDriver = 106, tserverRegistryError = 107, tserverDuplicateEntry = 108, tserverDriverLoaded = 109, tserverDriverNotLoaded = 110, tserverNoLogonPermission = 111, tserverAccountDisabled = 112, tserverNoNetlogon = 113, tserverAcctRestricted = 114, tserverInvalidLogonTime = 115, tserverInvalidWorkstation = 116, tserverAcctLockedOut = 117, tserverPasswordExpired = 118, driverDuplicateAcshandle = 1000, driverInvalidAcsRequest = 1001, driverAcsHandleRejection = 1002, driverInvalidClassRejection = 1003, driverGenericRejection = 1004, driverResourceLimitation = 1005, driverAcshandleTermination = 1006, driverLinkUnavailable = 1007, driverOamInUse = 1008 } public enum EventClass_t : ushort { ACSREQUEST = 0, ACSUNSOLICITED = 1, ACSCONFIRMATION = 2, CSTAREQUEST = 3, CSTAUNSOLICITED = 4, CSTACONFIRMATION = 5, CSTAEVENTREPORT = 6 } public enum DeviceIDType_t { deviceIdentifier = 0, explicitPublic = 20, explicitPublicUnknown = 30, explicitPublicInternational = 31, explicitPublicNational = 32, explicitPublicNetworkSpecific = 33, explicitPublicSubscriber = 34, explicitPublicAbbreviated = 35, explicitPrivate = 40, explicitPrivateUnknown = 50, explicitPrivateLevel3RegionalNumber = 51, explicitPrivateLevel2RegionalNumber = 52, explicitPrivateLevel1RegionalNumber = 53, explicitPrivatePtnSpecificNumber = 54, explicitPrivateLocalNumber = 55, explicitPrivateAbbreviated = 56, otherPlan = 60, trunkIdentifier = 70, trunkGroupIdentifier = 71 } public enum SelectValue_t { svNormal = 0, svLeastCost = 1, svEmergency = 2, svAcd = 3, svUserDefined = 4 } public enum eventTypeACS : ushort { ACS_OPEN_STREAM = 1, ACS_OPEN_STREAM_CONF = 2, ACS_CLOSE_STREAM = 3, ACS_CLOSE_STREAM_CONF = 4, ACS_ABORT_STREAM = 5, ACS_UNIVERSAL_FAILURE_CONF = 6, ACS_UNIVERSAL_FAILURE = 7, ACS_KEY_REQUEST = 8, ACS_KEY_REPLY = 9, ACS_NAME_SRV_REQUEST = 10, ACS_NAME_SRV_REPLY = 11, ACS_AUTH_REPLY = 12, ACS_AUTH_REPLY_TWO = 13 } public enum ConnectionID_Device_t { staticId = 0, dynamicId = 1, } [Serializable,StructLayout(LayoutKind.Sequential)] public struct ConnectionID_t { public int callID; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)] public string deviceID; public ConnectionID_Device_t devIDType; public ConnectionID_t(int call, String device) { callID = call; deviceID = device; devIDType = ConnectionID_Device_t.staticId; } public ConnectionID_t(int call, String device, ConnectionID_Device_t type) { callID = call; deviceID = device; devIDType = type; } public override string ToString() { return String.Format("ConnectionID_t{{'callID':'{0}','deviceID':'{1}','devIDType':'{2}',}}", callID, deviceID, devIDType); } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct SetUpValues_t { public uint length; [MarshalAsAttribute(UnmanagedType.LPStr)] public string value; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTARouteRequestEvent_t { public int routeRegisterReqID; public int routingCrossRefID; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string currentRoute; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string callingDevice; public ConnectionID_t routedCall; public SelectValue_t routedSelAlgorithm; [MarshalAs(UnmanagedType.I1)] public bool priority; public SetUpValues_t setupInformation; } public enum DeviceIDStatus_t { idProvided = 0, idNotKnown = 1, idNotRequired = 2, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ExtendedDeviceID_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string deviceID; public DeviceIDType_t deviceIDType; public DeviceIDStatus_t deviceIDStatus; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteRequestExtEvent_t { public int routeRegisterReqID; public int routingCrossRefID; public ExtendedDeviceID_t currentRoute; public ExtendedDeviceID_t callingDevice; public ConnectionID_t routedCall; public SelectValue_t routedSelAlgorithm; [MarshalAs(UnmanagedType.I1)] public bool priority; public SetUpValues_t setupInformation; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAReRouteRequest_t { public int routeRegisterReqID; public int routingCrossRefID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAEscapeSvcReqEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatReqEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } public enum CSTAEventCause_t { ecNone = -1, ecInitNone = 0, ecActiveMonitor = 1, ecAlternate = 2, ecBusy = 3, ecCallBack = 4, ecCallCancelled = 5, ecCallForwardAlways = 6, ecCallForwardBusy = 7, ecCallForwardNoAnswer = 8, ecCallForward = 9, ecCallNotAnswered = 10, ecCallPickup = 11, ecCampOn = 12, ecDestNotObtainable = 13, ecDoNotDisturb = 14, ecIncompatibleDestination = 15, ecInvalidAccountCode = 16, ecKeyConference = 17, ecLockout = 18, ecMaintenance = 19, ecNetworkCongestion = 20, ecNetworkNotObtainable = 21, ecNewCall = 22, ecNoAvailableAgents = 23, ecOverride = 24, ecPark = 25, ecOverflow = 26, ecRecall = 27, ecRedirected = 28, ecReorderTone = 29, ecResourcesNotAvailable = 30, ecSilentMonitor = 31, ecTransfer = 32, ecTrunksBusy = 33, ecVoiceUnitInitiator = 34, ecNetworkSignal = 46, ecAlertTimeExpired = 60, ecDestOutOfOrder = 65, ecNotSupportedBearerService = 80, ecUnassignedNumber = 81, ecIncompatibleBearerService = 87, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTACallClearedEvent_t { public ConnectionID_t clearedCall; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAConferencedEvent_t { public ConnectionID_t primaryOldCall; public ConnectionID_t secondaryOldCall; public ExtendedDeviceID_t confController; public ExtendedDeviceID_t addedParty; //public ConnectionList_t conferenceConnections; public List<Connection_t> conferenceConnections; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAConnectionClearedEvent_t { public ConnectionID_t droppedConnection; public ExtendedDeviceID_t releasingDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTADeliveredEvent_t { public ConnectionID_t connection; public ExtendedDeviceID_t alertingDevice; public ExtendedDeviceID_t callingDevice; public ExtendedDeviceID_t calledDevice; public ExtendedDeviceID_t lastRedirectionDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTADivertedEvent_t { public ConnectionID_t connection; public ExtendedDeviceID_t divertingDevice; public ExtendedDeviceID_t newDestination; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAEstablishedEvent_t { public ConnectionID_t establishedConnection; public ExtendedDeviceID_t answeringDevice; public ExtendedDeviceID_t callingDevice; public ExtendedDeviceID_t calledDevice; public ExtendedDeviceID_t lastRedirectionDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAFailedEvent_t { public ConnectionID_t failedConnection; public ExtendedDeviceID_t failingDevice; public ExtendedDeviceID_t calledDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAHeldEvent_t { public ConnectionID_t heldConnection; public ExtendedDeviceID_t holdingDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTANetworkReachedEvent_t { public ConnectionID_t connection; public ExtendedDeviceID_t trunkUsed; public ExtendedDeviceID_t calledDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAOriginatedEvent_t { public ConnectionID_t originatedConnection; public ExtendedDeviceID_t callingDevice; public ExtendedDeviceID_t calledDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAQueuedEvent_t { public ConnectionID_t queuedConnection; public ExtendedDeviceID_t queue; public ExtendedDeviceID_t callingDevice; public ExtendedDeviceID_t calledDevice; public ExtendedDeviceID_t lastRedirectionDevice; public short numberQueued; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARetrievedEvent_t { public ConnectionID_t retrievedConnection; public ExtendedDeviceID_t retrievingDevice; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAServiceInitiatedEvent_t { public ConnectionID_t initiatedConnection; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTATransferredEvent_t { public ConnectionID_t primaryOldCall; public ConnectionID_t secondaryOldCall; public ExtendedDeviceID_t transferringDevice; public ExtendedDeviceID_t transferredDevice; public ConnectionList_t transferredConnections; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTACallInformationEvent_t { public ConnectionID_t connection; public ExtendedDeviceID_t device; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string accountInfo; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string authorisationCode; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTADoNotDisturbEvent_t { public ExtendedDeviceID_t device; [MarshalAs(UnmanagedType.I1)] public bool doNotDisturbOn; } public enum ForwardingType_t { fwdImmediate = 0, fwdBusy = 1, fwdNoAns = 2, fwdBusyInt = 3, fwdBusyExt = 4, fwdNoAnsInt = 5, fwdNoAnsExt = 6, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ForwardingInfo_t { public ForwardingType_t forwardingType; [MarshalAs(UnmanagedType.I1)] public bool forwardingOn; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string forwardDN; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAForwardingEvent_t { public ExtendedDeviceID_t device; public ForwardingInfo_t forwardingInformation; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMessageWaitingEvent_t { public ExtendedDeviceID_t deviceForMessage; public ExtendedDeviceID_t invokingDevice; [MarshalAs(UnmanagedType.I1)] public bool messageWaitingOn; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTALoggedOnEvent_t { public ExtendedDeviceID_t agentDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string agentID; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string agentGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string password; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTALoggedOffEvent_t { public ExtendedDeviceID_t agentDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string agentID; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string agentGroup; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTANotReadyEvent_t { public ExtendedDeviceID_t agentDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string agentID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAReadyEvent_t { public ExtendedDeviceID_t agentDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string agentID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAWorkNotReadyEvent_t { public ExtendedDeviceID_t agentDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string agentID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAWorkReadyEvent_t { public ExtendedDeviceID_t agentDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string agentID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTARouteRegisterReq_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string routingDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteRegisterReqConfEvent_t { public int registerReqID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteRegisterCancel_t { public int routeRegisterReqID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteRegisterCancelConfEvent_t { public int routeRegisterReqID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteRegisterAbortEvent_t { public int routeRegisterReqID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTARouteSelectRequest_t { public int routeRegisterReqID; public int routingCrossRefID; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string routeSelected; public short remainRetry; public SetUpValues_t setupInformation; [MarshalAs(UnmanagedType.I1)] public bool routeUsedReq; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTARouteUsedEvent_t { public int routeRegisterReqID; public int routingCrossRefID; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string routeUsed; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string callingDevice; [MarshalAs(UnmanagedType.I1)] public bool domain; } public enum CSTAUniversalFailure_t { genericUnspecified = 0, genericOperation = 1, requestIncompatibleWithObject = 2, valueOutOfRange = 3, objectNotKnown = 4, invalidCallingDevice = 5, invalidCalledDevice = 6, invalidForwardingDestination = 7, privilegeViolationOnSpecifiedDevice = 8, privilegeViolationOnCalledDevice = 9, privilegeViolationOnCallingDevice = 10, invalidCstaCallIdentifier = 11, invalidCstaDeviceIdentifier = 12, invalidCstaConnectionIdentifier = 13, invalidDestination = 14, invalidFeature = 15, invalidAllocationState = 16, invalidCrossRefId = 17, invalidObjectType = 18, securityViolation = 19, genericStateIncompatibility = 21, invalidObjectState = 22, invalidConnectionIdForActiveCall = 23, noActiveCall = 24, noHeldCall = 25, noCallToClear = 26, noConnectionToClear = 27, noCallToAnswer = 28, noCallToComplete = 29, genericSystemResourceAvailability = 31, serviceBusy = 32, resourceBusy = 33, resourceOutOfService = 34, networkBusy = 35, networkOutOfService = 36, overallMonitorLimitExceeded = 37, conferenceMemberLimitExceeded = 38, genericSubscribedResourceAvailability = 41, objectMonitorLimitExceeded = 42, externalTrunkLimitExceeded = 43, outstandingRequestLimitExceeded = 44, genericPerformanceManagement = 51, performanceLimitExceeded = 52, unspecifiedSecurityError = 60, sequenceNumberViolated = 61, timeStampViolated = 62, pacViolated = 63, sealViolated = 64, genericUnspecifiedRejection = 70, genericOperationRejection = 71, duplicateInvocationRejection = 72, unrecognizedOperationRejection = 73, mistypedArgumentRejection = 74, resourceLimitationRejection = 75, acsHandleTerminationRejection = 76, serviceTerminationRejection = 77, requestTimeoutRejection = 78, requestsOnDeviceExceededRejection = 79, unrecognizedApduRejection = 80, mistypedApduRejection = 81, badlyStructuredApduRejection = 82, initiatorReleasingRejection = 83, unrecognizedLinkedidRejection = 84, linkedResponseUnexpectedRejection = 85, unexpectedChildOperationRejection = 86, mistypedResultRejection = 87, unrecognizedErrorRejection = 88, unexpectedErrorRejection = 89, mistypedParameterRejection = 90, nonStandard = 100, operationTimeout = 101, CBTaskIsFull = 102, allOK = 999 } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteEndEvent_t { public int routeRegisterReqID; public int routingCrossRefID; public CSTAUniversalFailure_t errorValue; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteEndRequest_t { public int routeRegisterReqID; public int routingCrossRefID; public CSTAUniversalFailure_t errorValue; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAEscapeSvc_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAEscapeSvcConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAEscapeSvcReqConf_t { public CSTAUniversalFailure_t errorValue; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAPrivateEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAPrivateStatusEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASendPrivateEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTABackInServiceEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAOutOfServiceEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; public CSTAEventCause_t cause; } public enum SystemStatus_t { ssInitializing = 0, ssEnabled = 1, ssNormal = 2, ssMessagesLost = 3, ssDisabled = 4, ssOverloadImminent = 5, ssOverloadReached = 6, ssOverloadRelieved = 7, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAReqSysStat_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatReqConfEvent_t { public SystemStatus_t systemStatus; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatStart_t { [MarshalAs(UnmanagedType.I1)] public bool statusFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatStartConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool statusFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatStop_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatStopConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAChangeSysStatFilter_t { [MarshalAs(UnmanagedType.I1)] public bool statusFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAChangeSysStatFilterConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool statusFilterSelected; [MarshalAs(UnmanagedType.I1)] public bool statusFilterActive; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatEvent_t { public SystemStatus_t systemStatus; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatEndedEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAReqSysStatConf_t { public SystemStatus_t systemStatus; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASysStatEventSend_t { public SystemStatus_t systemStatus; } public enum CSTACallFilter_t:ushort { cfCallCleared=0x8000, cfConferenced=0x4000, cfConnectionCleared=0x2000, cfDelivered=0x1000, cfDiverted=0x0800, cfEstablished=0x0400, cfFailed=0x0200, cfHeld=0x0100, cfNetworkReached=0x0080, cfOriginated=0x0040, cfQueued=0x0020, cfRetrieved=0x0010, cfServiceInitiated=0x0008, cfTransferred=0x0004 } public enum CSTAFeatureFilter_t:byte{ ffCallInformation=0x80, ffDoNotDisturb=0x40, ffForwarding=0x20, ffMessageWaiting=0x10 } public enum CSTAAgentFilter_t:byte{ afLoggedOn=0x80, afLoggedOff=0x40, afNotReady=0x20, afReady=0x10, afWorkNotReady=0x08, afWorkReady=0x04 } public enum CSTAMaintenanceFilter_t : byte { mfBackInService = 0x80, mfOutOfService = 0x40 } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMonitorFilter_t { public CSTACallFilter_t call; public CSTAFeatureFilter_t feature; public CSTAAgentFilter_t agent; public CSTAMaintenanceFilter_t maintenance; public int privateFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAMonitorDevice_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string deviceID; public CSTAMonitorFilter_t monitorFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMonitorCall_t { public ConnectionID_t call; public CSTAMonitorFilter_t monitorFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAMonitorCallsViaDevice_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string deviceID; public CSTAMonitorFilter_t monitorFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMonitorConfEvent_t { public uint monitorCrossRefID; public CSTAMonitorFilter_t monitorFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAChangeMonitorFilter_t { public int monitorCrossRefID; public CSTAMonitorFilter_t monitorFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAChangeMonitorFilterConfEvent_t { public CSTAMonitorFilter_t monitorFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMonitorStop_t { public int monitorCrossRefID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMonitorStopConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMonitorEndedEvent_t { public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASnapshotCall_t { public ConnectionID_t snapshotObject; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAAlternateCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAAnswerCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAAnswerCall_t { public ConnectionID_t alertingCall; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTACallCompletionConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAConsultationCall_t { public ConnectionID_t activeCall; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string calledDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAClearCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAClearConnectionConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAConferenceCallConfEvent_t { public ConnectionID_t newCall; public ConnectionList_t connList; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAConsultationCallConfEvent_t { public ConnectionID_t newCall; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTADeflectCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAPickupCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAGroupPickupCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAHoldCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMakeCallConfEvent_t { public ConnectionID_t newCall; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAMakePredictiveCallConfEvent_t { public ConnectionID_t newCall; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAQueryMwiConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool messages; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAQueryDndConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool doNotDisturb; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ListForwardParameters_t { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 7, ArraySubType = UnmanagedType.Struct)] public ForwardingInfo_t[] param; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAQueryFwdConfEvent_t { public ListForwardParameters_t forward; } public enum AgentState_t { agNotReady = 0, agNull = 1, agReady = 2, agWorkNotReady = 3, agWorkReady = 4, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAQueryAgentStateConfEvent_t { public AgentState_t agentState; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAQueryLastNumberConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string lastNumber; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAUniversalFailureConfEvent_t { public CSTAUniversalFailure_t error; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAGetAPICapsConfEvent_t { public short alternateCall; public short answerCall; public short callCompletion; public short clearCall; public short clearConnection; public short conferenceCall; public short consultationCall; public short deflectCall; public short pickupCall; public short groupPickupCall; public short holdCall; public short makeCall; public short makePredictiveCall; public short queryMwi; public short queryDnd; public short queryFwd; public short queryAgentState; public short queryLastNumber; public short queryDeviceInfo; public short reconnectCall; public short retrieveCall; public short setMwi; public short setDnd; public short setFwd; public short setAgentState; public short transferCall; public short eventReport; public short callClearedEvent; public short conferencedEvent; public short connectionClearedEvent; public short deliveredEvent; public short divertedEvent; public short establishedEvent; public short failedEvent; public short heldEvent; public short networkReachedEvent; public short originatedEvent; public short queuedEvent; public short retrievedEvent; public short serviceInitiatedEvent; public short transferredEvent; public short callInformationEvent; public short doNotDisturbEvent; public short forwardingEvent; public short messageWaitingEvent; public short loggedOnEvent; public short loggedOffEvent; public short notReadyEvent; public short readyEvent; public short workNotReadyEvent; public short workReadyEvent; public short backInServiceEvent; public short outOfServiceEvent; public short privateEvent; public short routeRequestEvent; public short reRoute; public short routeSelect; public short routeUsedEvent; public short routeEndEvent; public short monitorDevice; public short monitorCall; public short monitorCallsViaDevice; public short changeMonitorFilter; public short monitorStop; public short monitorEnded; public short snapshotDeviceReq; public short snapshotCallReq; public short escapeService; public short privateStatusEvent; public short escapeServiceEvent; public short escapeServiceConf; public short sendPrivateEvent; public short sysStatReq; public short sysStatStart; public short sysStatStop; public short changeSysStatFilter; public short sysStatReqEvent; public short sysStatReqConf; public short sysStatEvent; } public enum SDBLevel_t { noSdbChecking = -1, acsOnly = 1, acsAndCstaChecking = 0, } public enum CSTALevel_t { cstaHomeWorkTop = 1, cstaAwayWorkTop = 2, cstaDeviceDeviceMonitor = 3, cstaCallDeviceMonitor = 4, cstaCallControl = 5, cstaRouting = 6, cstaCallCallMonitor = 7, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct DeviceList_t { public ushort count; private IntPtr point; /*[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 20, ArraySubType = UnmanagedType.SysUInt)] public byte[][] device;*/ } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAGetDeviceListConfEvent_t { public SDBLevel_t driverSdbLevel; public CSTALevel_t level; public int index; public DeviceList_t devList; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAQueryCallMonitorConfEvent_t { public bool callMonitor; } public enum DeviceType_t { dtStation = 0, dtLine = 1, dtButton = 2, dtAcd = 3, dtTrunk = 4, dtOperator = 5, dtStationGroup = 16, dtLineGroup = 17, dtButtonGroup = 18, dtAcdGroup = 19, dtTrunkGroup = 20, dtOperatorGroup = 21, dtOther = 255, } public enum DeviceClass_t { DC_VOICE=0x80, DC_DATA=0x40, DC_IMAGE=0x20, DC_OTHER=0x10 } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct CSTAQueryDeviceInfoConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; public DeviceType_t deviceType; public DeviceClass_t deviceClass; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTAReconnectCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARetrieveCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASetMwiConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASetDndConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASetFwdConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASetAgentStateConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ConnectionList_t { public uint count; // public Connection_t[] list; private readonly IntPtr point; public Connection_t[] list { get { return NativeMethods.GetArrayStruct<Connection_t>(point,count).ToArray(); } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTATransferCallConfEvent_t { public ConnectionID_t newCall; public ConnectionList_t connList; } public enum LocalConnectionState_t { csNone = -1, csNull = 0, csInitiate = 1, csAlerting = 2, csConnect = 3, csHold = 4, csQueued = 5, csFail = 6, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTACallState_t { private readonly uint count; private readonly IntPtr point; public LocalConnectionState_t[] inf { get{ return NativeMethods.GetArrayEnum<LocalConnectionState_t>(point,count).ToArray(); } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASnapshotDeviceResponseInfo_t { public ConnectionID_t callIdentifier; public CSTACallState_t localCallState; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASnapshotDeviceData_t { private readonly uint count; private readonly IntPtr point; public CSTASnapshotDeviceResponseInfo_t[] info { get { return NativeMethods.GetArrayStruct<CSTASnapshotDeviceResponseInfo_t>(point,count).ToArray(); } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASnapshotDeviceConfEvent_t { public CSTASnapshotDeviceData_t snapshotData; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASnapshotCallConfEvent_t { public CSTASnapshotCallData_t snapshotData; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASnapshotCallData_t { private readonly uint count; private readonly IntPtr point; public CSTASnapshotCallResponseInfo_t[] info{get{return NativeMethods.GetArrayStruct<CSTASnapshotCallResponseInfo_t>(point,count).ToArray();}} } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTARouteUsedExtEvent_t { public int routeRegisterReqID; public int routingCrossRefID; public ExtendedDeviceID_t routeUsed; public ExtendedDeviceID_t callingDevice; [MarshalAs(UnmanagedType.I1)] public bool domain; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ACSEventHeader_t { public uint acsHandle; public EventClass_t eventClass; private readonly ushort eventType; public eventTypeACS eventTypeACS => (eventTypeACS)eventType; public eventTypeCSTA eventTypeCSTA => (eventTypeCSTA)eventType; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)] public struct ACSUniversalFailureEvent_t { public ACSUniversalFailure_t error; } [Serializable,StructLayout(LayoutKind.Sequential, Pack = 1)] public struct ACSOpenStreamConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 21)] public char[] _apiVer; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 21)] public char[] _libVer; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 21)] public char[] _tsrvVer; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 21)] public char[] _drvrVer; public string apiVer => _apiVer.Aggregate("", (s, c) => s + c); public string libVer => _libVer.Aggregate("", (s, c) => s + c); public string tsrvVer => _tsrvVer.Aggregate("", (s, c) => s + c); public string drvrVer => _drvrVer.Aggregate("", (s, c) => s + c); } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, Pack = 1)] public struct ACSUniversalFailureConfEvent_t { public ACSUniversalFailure_t error; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ACSCloseStreamConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } public enum Feature_t { ftCampOn = 0, ftCallBack = 1, ftIntrude = 2, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ACSAuthInfo_t { public ACSAuthType_t authType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 49)] public string authLoginID; } public enum ACSAuthType_t { requiresExternalAuth = -1, authLoginIdOnly = 0, authLoginIdIsDefault = 1, needLoginIdAndPasswd = 2, anyLoginId = 3, } public enum AllocationState_t { asCallDelivered = 0, asCallEstablished = 1, } public enum AgentMode_t { amLogIn = 0, amLogOut = 1, amNotReady = 2, amReady = 3, amWorkNotReady = 4, amWorkReady = 5, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTSingleStepConferenceCallConfEvent_t { public ConnectionID_t newCall; public ConnectionList_t connList; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSelectiveListeningHoldConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSelectiveListeningRetrieveConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct Connection_t { public ConnectionID_t party; public ExtendedDeviceID_t staticDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct CSTASnapshotCallResponseInfo_t { public ExtendedDeviceID_t deviceOnCall; public ConnectionID_t callIdentifier; public LocalConnectionState_t localConnectionState; } public enum ATTUUIProtocolType_t { uuiNone = -1, uuiUserSpecific = 0, uuiIa5Ascii = 4, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV5UserToUserInfo_t { public ATTUUIProtocolType_t type; public ushort length; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 33)] public string value; public override string ToString() { return String.Format("ATTV5UserToUserInfo_t{{'value':'{0}'}}", value); } } public enum ATTInterflow_t { laiNoInterflow = -1, laiAllInterflow = 0, laiThresholdInterflow = 1, laiVectoringInterflow = 2, } public enum ATTPriority_t { laiNotInQueue = 0, laiLow = 1, laiMedium = 2, laiHigh = 3, laiTop = 4, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4LookaheadInfo_t { public ATTInterflow_t type; public ATTPriority_t priority; public short hours; public short minutes; public short seconds; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string sourceVDN; } public enum ATTUserEnteredCodeType_t { ueNone = -1, ueAny = 0, ueLoginDigits = 2, ueCallPrompter = 5, ueDataBaseProvided = 17, ueToneDetector = 32, } public enum ATTUserEnteredCodeIndicator_t { ueCollect = 0, ueEntered = 1, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTUserEnteredCode_t { public ATTUserEnteredCodeType_t type; public ATTUserEnteredCodeIndicator_t indicator; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)] public string data; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string collectVDN; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4ConnIDList_t { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 5, ArraySubType = UnmanagedType.Struct)] public ConnectionID_t[] party; } public enum ATTProgressLocation_t { plNone = -1, plUser = 0, plPubLocal = 1, plPubRemote = 4, plPrivRemote = 5, } public enum ATTProgressDescription_t { pdNone = -1, pdCallOffIsdn = 1, pdDestNotIsdn = 2, pdOrigNotIsdn = 3, pdCallOnIsdn = 4, pdInband = 8, } public enum ATTWorkMode_t { wmNone = -1, wmAuxWork = 1, wmAftcalWk = 2, wmAutoIn = 3, wmManualIn = 4, } public enum ATTTalkState_t { tsOnCall = 0, tsIdle = 1, } public enum ATTExtensionClass_t { ecVdn = 0, ecAcdSplit = 1, ecAnnouncement = 2, ecData = 4, ecAnalog = 5, ecProprietary = 6, ecBri = 7, ecCti = 8, ecLogicalAgent = 9, ecOther = 10, } public enum ATTAnswerTreat_t { atNoTreatment = 0, atNone = 1, atDrop = 2, atConnect = 3, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4SnapshotCall_t { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.Struct)] public CSTASnapshotCallResponseInfo_t[] info; } public enum ATTLocalCallState_t { attNone = 0, attCsInitiated = 1, attCsAlerting = 2, attCsConnected = 3, attCsHeld = 4, attCsBridged = 5, attCsOther = 6, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSnapshotDevice_t { public ConnectionID_t call; public ATTLocalCallState_t state; } public enum ATTCollectCodeType_t { ucNone = 0, ucToneDetector = 32, } public enum ATTProvidedCodeType_t { upNone = 0, upDataBaseProvided = 17, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTUserProvidedCode_t { public ATTProvidedCodeType_t type; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)] public string data; } public enum ATTSpecificEvent_t { seAnswer = 11, seDisconnect = 4, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTUserCollectCode_t { public ATTCollectCodeType_t type; public short digitsToBeCollected; public short timeout; public ConnectionID_t collectParty; public ATTSpecificEvent_t specificEvent; } public enum ATTDropResource_t { drNone = -1, drCallClassifier = 0, drToneGenerator = 1, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV5ClearConnection_t { public ATTDropResource_t dropResource; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5ConsultationCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5MakeCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5DirectAgentCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5MakePredictiveCall_t { [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public short maxRings; public ATTAnswerTreat_t answerTreat; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5SupervisorAssistCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV5ReconnectCall_t { public ATTDropResource_t dropResource; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4SendDTMFTone_t { public ConnectionID_t sender; public ATTV4ConnIDList_t receivers; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 33)] public string tones; public short toneDuration; public short pauseDuration; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSendDTMFToneConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4SetAgentState_t { public ATTWorkMode_t workMode; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryAcdSplit_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryAcdSplitConfEvent_t { public short availableAgents; public short callsInQueue; public short agentsLoggedIn; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryAgentLogin_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryAgentLoginConfEvent_t { public int privEventCrossRefID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct DeviceString { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public String device; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryAgentLoginDeviceList { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 10, ArraySubType = UnmanagedType.LPTStr)] public DeviceString[] list; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryAgentLoginResp_t { public int privEventCrossRefID; public ATTQueryAgentLoginDeviceList list; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryAgentState_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4QueryAgentStateConfEvent_t { public ATTWorkMode_t workMode; public ATTTalkState_t talkState; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryCallClassifier_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryCallClassifierConfEvent_t { public short numAvailPorts; public short numInUsePorts; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4QueryDeviceInfoConfEvent_t { public ATTExtensionClass_t extensionClass; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryMwiConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool applicationType; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryStationStatus_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryStationStatusConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool stationStatus; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryTod_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryTodConfEvent_t { public short year; public short month; public short day; public short hour; public short minute; public short second; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryTg_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryTgConfEvent_t { public short idleTrunks; public short usedTrunks; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4SnapshotDeviceConfEvent_t { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.Struct)] public ATTSnapshotDevice_t[] snapshotDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4MonitorFilter_t { [MarshalAs(UnmanagedType.I1)] public bool privateFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4MonitorConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool usedFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTMonitorStopOnCall_t { public int monitorCrossRefID; public ConnectionID_t call; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTMonitorStopOnCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4MonitorCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool usedFilter; public ATTV4SnapshotCall_t snapshotCall; } public enum ATTReasonCode_t { arNone = 0, arAnswerNormal = 1, arAnswerTimed = 2, arAnswerVoiceEnergy = 3, arAnswerMachineDetected = 4, arSitReorder = 5, arSitNoCircuit = 6, arSitIntercept = 7, arSitVacantCode = 8, arSitIneffectiveOther = 9, arSitUnknown = 10, arInQueue = 11, arServiceObserver = 12, } public enum ATTReasonForCallInfo_t { orNone = 0, orConsultation = 1, orConferenced = 2, orTransferred = 3, orNewCall = 4, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4OriginalCallInfo_t { public ATTReasonForCallInfo_t reason; public ExtendedDeviceID_t callingDevice; public ExtendedDeviceID_t calledDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunk; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; public ATTV4LookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTCallClearedEvent_t { public ATTReasonCode_t reason; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV3ConferencedEvent_t { public ATTV4OriginalCallInfo_t originalCallInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV5ConnectionClearedEvent_t { public ATTV5UserToUserInfo_t userInfo; } public enum ATTDeliveredType_t { deliveredToAcd = 1, deliveredToStation = 2, deliveredOther = 3, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV3DeliveredEvent_t { public ATTDeliveredType_t deliveredType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunk; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTV4LookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV4OriginalCallInfo_t originalCallInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTEnteredDigitsEvent_t { public ConnectionID_t connection; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)] public string digits; public LocalConnectionState_t localConnectionInfo; public CSTAEventCause_t cause; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV3EstablishedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunk; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTV4LookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV4OriginalCallInfo_t originalCallInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4NetworkReachedEvent_t { public ATTProgressLocation_t progressLocation; public ATTProgressDescription_t progressDescription; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV3TransferredEvent_t { public ATTV4OriginalCallInfo_t originalCallInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4RouteRequestEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunk; public ATTV4LookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5RouteSelect_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string callingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string directAgentCallSplit; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; public ATTUserCollectCode_t collectCode; public ATTUserProvidedCode_t userProvidedCode; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTRouteUsedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSysStat_t { [MarshalAs(UnmanagedType.I1)] public bool linkStatusReq; } public enum ATTLinkState_t { lsLinkUnavail = 0, lsLinkUp = 1, lsLinkDown = 2, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTLinkStatus_t { public short linkID; public ATTLinkState_t linkState; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV3LinkStatusEvent_t { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 4, ArraySubType = UnmanagedType.Struct)] public ATTLinkStatus_t[] linkStatus; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5OriginatedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string logicalAgent; public ATTV5UserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTLoggedOnEvent_t { public ATTWorkMode_t workMode; } public enum ATTDeviceType_t { attDtAcdSplit = 1, attDtAnnouncement = 2, attDtData = 3, attDtLogicalAgent = 4, attDtStation = 5, attDtTrunkAccessCode = 6, attDtVdn = 7, attDtOther = 8, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryDeviceName_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4QueryDeviceNameConfEvent_t { public ATTDeviceType_t deviceType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string name; } public enum ATTAgentTypeID_t { extensionId = 0, logicalId = 1, } public enum ATTSplitSkill_t { splitSkillNone = -1, splitSkillAll = 0, splitSkill1 = 1, splitSkill2 = 2, splitSkill3 = 3, splitSkill4 = 4, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTAgentMeasurements_t { public int acdCalls; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 6)] public string extension; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string name; [MarshalAs(UnmanagedType.I1)] public bool state; public int avgACDTalkTime; public int avgExtensionTime; public int callRate; public short elapsedTime; public int extensionCalls; public int extensionIncomingCalls; public int extensionOutgoingCalls; public int shiftACDCalls; public int shiftAvgACDTalkTime; public short splitAcceptableSvcLevel; public int splitACDCalls; public int splitAfterCallSessions; public short splitAgentsAvailable; public short splitAgentsInAfterCall; public short splitAgentsInAux; public short splitAgentsInOther; public short splitAgentsOnACDCalls; public short splitAgentsOnExtCalls; public short splitAgentsStaffed; public int splitAvgACDTalkTime; public int splitAvgAfterCallTime; public short splitAvgSpeedOfAnswer; public short splitAvgTimeToAbandon; public int splitCallRate; public int splitCallsAbandoned; public int splitCallsFlowedIn; public int splitCallsFlowedOut; public short splitCallsWaiting; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string splitName; public short splitNumber; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 6)] public string splitExtension; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 6)] public string splitObjective; public short splitOldestCallWaiting; [MarshalAs(UnmanagedType.I1)] public bool splitPercentInSvcLevel; public int splitTotalACDTalkTime; public int splitTotalAfterCallTime; public int splitTotalAuxTime; public int timeAgentEnteredState; public int totalACDTalkTime; public int totalAfterCallTime; public int totalAuxTime; public int totalAvailableTime; public int totalHoldTime; public int totalStaffedTime; public int totalACDCallTime; public int avgACDCallTime; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTSplitSkillMeasurements_t { public short acceptableSvcLevel; public int acdCalls; public int afterCallSessions; public short agentsAvailable; public short agentsInAfterCall; public short agentsInAux; public short agentsInOther; public short onACDCalls; public short agentsOnExtensionCalls; public short agentsStaffed; public int avgACDTalkTime; public int afterCallTime; public short avgSpeedOfAnswer; public short avgTimeToAbandon; public int callRate; public int callsAbandoned; public int callsFlowedIn; public int callsFlowedOut; public short callsWaiting; public short oldestCallWaiting; [MarshalAs(UnmanagedType.I1)] public bool percentInSvcLevel; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string name; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 6)] public string extension; public short number; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 6)] public string objective; public int totalAfterCallTime; public int totalAuxTime; public int totalACDTalkTime; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTTrunkGroupMeasurements_t { public int avgIncomingCallTime; public int avgOutgoingCallTime; public int incomingAbandonedCalls; public int incomingCalls; public int incomingUsage; public short numberOfTrunks; public int outgoingCalls; public int outgoingCompletedCalls; public int outgoingUsage; [MarshalAs(UnmanagedType.I1)] public bool percentAllTrunksBusy; [MarshalAs(UnmanagedType.I1)] public bool percentTrunksMaintBusy; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string trunkGroupName; public short trunkGroupNumber; public short trunksInUse; public short trunksMaintBusy; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTVdnMeasurements_t { public short acceptableSvcLevel; public int acdCalls; public int avgACDTalkTime; public short avgSpeedOfAnswer; public short avgTimeToAbandon; public int callsAbandoned; public int callsFlowedOut; public int callsForcedBusyDisc; public int callsOffered; public short callsWaiting; public int callsNonACD; public short oldestCallWaiting; [MarshalAs(UnmanagedType.I1)] public bool percentInSvcLevel; public int totalACDTalkTime; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 6)] public string extension; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string name; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTAgentMeasurementsPresent_t { [MarshalAs(UnmanagedType.I1)] public bool allMeasurements; [MarshalAs(UnmanagedType.I1)] public bool acdCalls; [MarshalAs(UnmanagedType.I1)] public bool extension; [MarshalAs(UnmanagedType.I1)] public bool name; [MarshalAs(UnmanagedType.I1)] public bool state; [MarshalAs(UnmanagedType.I1)] public bool avgACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool avgExtensionTime; [MarshalAs(UnmanagedType.I1)] public bool callRate; [MarshalAs(UnmanagedType.I1)] public bool elapsedTime; [MarshalAs(UnmanagedType.I1)] public bool extensionCalls; [MarshalAs(UnmanagedType.I1)] public bool extensionIncomingCalls; [MarshalAs(UnmanagedType.I1)] public bool extensionOutgoingCalls; [MarshalAs(UnmanagedType.I1)] public bool shiftACDCalls; [MarshalAs(UnmanagedType.I1)] public bool shiftAvgACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool splitAcceptableSvcLevel; [MarshalAs(UnmanagedType.I1)] public bool splitACDCalls; [MarshalAs(UnmanagedType.I1)] public bool splitAfterCallSessions; [MarshalAs(UnmanagedType.I1)] public bool splitAgentsAvailable; [MarshalAs(UnmanagedType.I1)] public bool splitAgentsInAfterCall; [MarshalAs(UnmanagedType.I1)] public bool splitAgentsInAux; [MarshalAs(UnmanagedType.I1)] public bool splitAgentsInOther; [MarshalAs(UnmanagedType.I1)] public bool splitAgentsOnACDCalls; [MarshalAs(UnmanagedType.I1)] public bool splitAgentsOnExtCalls; [MarshalAs(UnmanagedType.I1)] public bool splitAgentsStaffed; [MarshalAs(UnmanagedType.I1)] public bool splitAvgACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool splitAvgAfterCallTime; [MarshalAs(UnmanagedType.I1)] public bool splitAvgSpeedOfAnswer; [MarshalAs(UnmanagedType.I1)] public bool splitAvgTimeToAbandon; [MarshalAs(UnmanagedType.I1)] public bool splitCallRate; [MarshalAs(UnmanagedType.I1)] public bool splitCallsAbandoned; [MarshalAs(UnmanagedType.I1)] public bool splitCallsFlowedIn; [MarshalAs(UnmanagedType.I1)] public bool splitCallsFlowedOut; [MarshalAs(UnmanagedType.I1)] public bool splitCallsWaiting; [MarshalAs(UnmanagedType.I1)] public bool splitName; [MarshalAs(UnmanagedType.I1)] public bool splitNumber; [MarshalAs(UnmanagedType.I1)] public bool splitExtension; [MarshalAs(UnmanagedType.I1)] public bool splitObjective; [MarshalAs(UnmanagedType.I1)] public bool splitOldestCallWaiting; [MarshalAs(UnmanagedType.I1)] public bool splitPercentInSvcLevel; [MarshalAs(UnmanagedType.I1)] public bool splitTotalACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool splitTotalAfterCallTime; [MarshalAs(UnmanagedType.I1)] public bool splitTotalAuxTime; [MarshalAs(UnmanagedType.I1)] public bool timeAgentEnteredState; [MarshalAs(UnmanagedType.I1)] public bool totalACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool totalAfterCallTime; [MarshalAs(UnmanagedType.I1)] public bool totalAuxTime; [MarshalAs(UnmanagedType.I1)] public bool totalAvailableTime; [MarshalAs(UnmanagedType.I1)] public bool totalHoldTime; [MarshalAs(UnmanagedType.I1)] public bool totalStaffedTime; [MarshalAs(UnmanagedType.I1)] public bool totalACDCallTime; [MarshalAs(UnmanagedType.I1)] public bool avgACDCallTime; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSplitSkillMeasurementsPresent_t { [MarshalAs(UnmanagedType.I1)] public bool allMeasurements; [MarshalAs(UnmanagedType.I1)] public bool acceptableSvcLevel; [MarshalAs(UnmanagedType.I1)] public bool acdCalls; [MarshalAs(UnmanagedType.I1)] public bool afterCallSessions; [MarshalAs(UnmanagedType.I1)] public bool agentsAvailable; [MarshalAs(UnmanagedType.I1)] public bool agentsInAfterCall; [MarshalAs(UnmanagedType.I1)] public bool agentsInAux; [MarshalAs(UnmanagedType.I1)] public bool agentsInOther; [MarshalAs(UnmanagedType.I1)] public bool onACDCalls; [MarshalAs(UnmanagedType.I1)] public bool agentsOnExtensionCalls; [MarshalAs(UnmanagedType.I1)] public bool agentsStaffed; [MarshalAs(UnmanagedType.I1)] public bool avgACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool afterCallTime; [MarshalAs(UnmanagedType.I1)] public bool avgSpeedOfAnswer; [MarshalAs(UnmanagedType.I1)] public bool avgTimeToAbandon; [MarshalAs(UnmanagedType.I1)] public bool callRate; [MarshalAs(UnmanagedType.I1)] public bool callsAbandoned; [MarshalAs(UnmanagedType.I1)] public bool callsFlowedIn; [MarshalAs(UnmanagedType.I1)] public bool callsFlowedOut; [MarshalAs(UnmanagedType.I1)] public bool callsWaiting; [MarshalAs(UnmanagedType.I1)] public bool oldestCallWaiting; [MarshalAs(UnmanagedType.I1)] public bool percentInSvcLevel; [MarshalAs(UnmanagedType.I1)] public bool name; [MarshalAs(UnmanagedType.I1)] public bool extension; [MarshalAs(UnmanagedType.I1)] public bool number; [MarshalAs(UnmanagedType.I1)] public bool objective; [MarshalAs(UnmanagedType.I1)] public bool totalAfterCallTime; [MarshalAs(UnmanagedType.I1)] public bool totalAuxTime; [MarshalAs(UnmanagedType.I1)] public bool totalACDTalkTime; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTTrunkGroupMeasurementsPresent_t { [MarshalAs(UnmanagedType.I1)] public bool allMeasurements; [MarshalAs(UnmanagedType.I1)] public bool avgIncomingCallTime; [MarshalAs(UnmanagedType.I1)] public bool avgOutgoingCallTime; [MarshalAs(UnmanagedType.I1)] public bool incomingAbandonedCalls; [MarshalAs(UnmanagedType.I1)] public bool incomingCalls; [MarshalAs(UnmanagedType.I1)] public bool incomingUsage; [MarshalAs(UnmanagedType.I1)] public bool numberOfTrunks; [MarshalAs(UnmanagedType.I1)] public bool outgoingCalls; [MarshalAs(UnmanagedType.I1)] public bool outgoingCompletedCalls; [MarshalAs(UnmanagedType.I1)] public bool outgoingUsage; [MarshalAs(UnmanagedType.I1)] public bool percentAllTrunksBusy; [MarshalAs(UnmanagedType.I1)] public bool percentTrunksMaintBusy; [MarshalAs(UnmanagedType.I1)] public bool trunkGroupName; [MarshalAs(UnmanagedType.I1)] public bool trunkGroupNumber; [MarshalAs(UnmanagedType.I1)] public bool trunksInUse; [MarshalAs(UnmanagedType.I1)] public bool trunksMaintBusy; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTVdnMeasurementsPresent_t { [MarshalAs(UnmanagedType.I1)] public bool allMeasurements; [MarshalAs(UnmanagedType.I1)] public bool acceptableSvcLevel; [MarshalAs(UnmanagedType.I1)] public bool acdCalls; [MarshalAs(UnmanagedType.I1)] public bool avgACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool avgSpeedOfAnswer; [MarshalAs(UnmanagedType.I1)] public bool avgTimeToAbandon; [MarshalAs(UnmanagedType.I1)] public bool callsAbandoned; [MarshalAs(UnmanagedType.I1)] public bool callsFlowedOut; [MarshalAs(UnmanagedType.I1)] public bool callsForcedBusyDisc; [MarshalAs(UnmanagedType.I1)] public bool callsOffered; [MarshalAs(UnmanagedType.I1)] public bool callsWaiting; [MarshalAs(UnmanagedType.I1)] public bool callsNonACD; [MarshalAs(UnmanagedType.I1)] public bool oldestCallWaiting; [MarshalAs(UnmanagedType.I1)] public bool percentInSvcLevel; [MarshalAs(UnmanagedType.I1)] public bool totalACDTalkTime; [MarshalAs(UnmanagedType.I1)] public bool extension; [MarshalAs(UnmanagedType.I1)] public bool name; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryAgentMeasurements_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string agentID; public ATTAgentTypeID_t typeID; public ATTSplitSkill_t splitSkill; public ATTAgentMeasurementsPresent_t requestItems; public short interval; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryAgentMeasurementsConfEvent_t { public ATTAgentMeasurementsPresent_t returnedItems; public ATTAgentMeasurements_t values; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQuerySplitSkillMeasurements_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; public ATTSplitSkillMeasurementsPresent_t requestItems; public short interval; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQuerySplitSkillMeasurementsConfEvent_t { public ATTSplitSkillMeasurementsPresent_t returnedItems; public ATTSplitSkillMeasurements_t values; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryTrunkGroupMeasurements_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; public ATTTrunkGroupMeasurementsPresent_t requestItems; public short interval; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryTrunkGroupMeasurementsConfEvent_t { public ATTTrunkGroupMeasurementsPresent_t returnedItems; public ATTTrunkGroupMeasurements_t values; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryVdnMeasurements_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; public ATTVdnMeasurementsPresent_t requestItems; public short interval; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryVdnMeasurementsConfEvent_t { public ATTVdnMeasurementsPresent_t returnedItems; public ATTVdnMeasurements_t values; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4ConferencedEvent_t { public ATTV4OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4DeliveredEvent_t { public ATTDeliveredType_t deliveredType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunk; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTV4LookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV4OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4EstablishedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunk; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTV4LookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV4OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4TransferredEvent_t { public ATTV4OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV4LinkStatusEvent_t { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 8, ArraySubType = UnmanagedType.Struct)] public ATTLinkStatus_t[] linkStatus; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV4GetAPICapsConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string switchVersion; [MarshalAs(UnmanagedType.I1)] public bool sendDTMFTone; [MarshalAs(UnmanagedType.I1)] public bool enteredDigitsEvent; [MarshalAs(UnmanagedType.I1)] public bool queryDeviceName; [MarshalAs(UnmanagedType.I1)] public bool queryAgentMeas; [MarshalAs(UnmanagedType.I1)] public bool querySplitSkillMeas; [MarshalAs(UnmanagedType.I1)] public bool queryTrunkGroupMeas; [MarshalAs(UnmanagedType.I1)] public bool queryVdnMeas; [MarshalAs(UnmanagedType.I1)] public bool reserved1; [MarshalAs(UnmanagedType.I1)] public bool reserved2; } public enum ATTParticipationType_t { ptActive = 1, ptSilent = 0, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTSingleStepConferenceCall_t { public ConnectionID_t activeCall; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string deviceToBeJoin; public ATTParticipationType_t participationType; [MarshalAs(UnmanagedType.I1)] public bool alertDestination; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSelectiveListeningHold_t { public ConnectionID_t subjectConnection; [MarshalAs(UnmanagedType.I1)] public bool allParties; public ConnectionID_t selectedParty; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSelectiveListeningRetrieve_t { public ConnectionID_t subjectConnection; [MarshalAs(UnmanagedType.I1)] public bool allParties; public ConnectionID_t selectedParty; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential,CharSet=CharSet.Ansi)] public struct ATTUnicodeDeviceID { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string value; /*[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 64, ArraySubType = UnmanagedType.I2)] public Int16[] value;*/ //[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 64, ArraySubType=UnmanagedType.I2)] /*[MarshalAsAttribute(UnmanagedType.LPTStr, SizeConst=64)] public string value;*/ /**/ /*[MarshalAsAttribute(UnmanagedType.SafeArray, SizeParamIndex = 0, ArraySubType = UnmanagedType.I2)] public short[] value;*/ /*[MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=64, ArraySubType = UnmanagedType.I2)] public short[] value;*/ } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTLookaheadInfo_t { public ATTInterflow_t type; public ATTPriority_t priority; public short hours; public short minutes; public short seconds; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string sourceVDN; public ATTUnicodeDeviceID uSourceVDN; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTCallOriginatorInfo_t { [MarshalAs(UnmanagedType.I1)] public bool hasInfo; public short callOriginatorType; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5OriginalCallInfo_t { public ATTReasonForCallInfo_t reason; public ExtendedDeviceID_t callingDevice; public ExtendedDeviceID_t calledDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; } [Serializable,StructLayout(LayoutKind.Sequential)] public struct ATTConnIDList_t { private readonly uint count; private readonly IntPtr point; public ConnectionID_t[] list { get { return NativeMethods.GetArrayStruct<ConnectionID_t>(point,count).ToArray(); } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTSendDTMFTone_t { public ConnectionID_t sender; public ATTConnIDList_t receivers; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 33)] public string tones; public short toneDuration; public short pauseDuration; } class SaferyArrayFromNativeMarchal : ICustomMarshaler { public object MarshalNativeToManaged(IntPtr pNativeData) { return NativeMethods.GetArrayStruct<ATTSnapshotDevice_t>(pNativeData).ToArray(); } public IntPtr MarshalManagedToNative(object ManagedObj) { return new IntPtr(); } public void CleanUpNativeData(IntPtr pNativeData) { } public void CleanUpManagedData(object ManagedObj) { } public int GetNativeDataSize() { return 0; } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential,Pack = 2)] public class ATTSnapshotDeviceConfEvent_t { /* private readonly uint count; private readonly IntPtr point; //public ATTSnapshotDevice_t[] list { get; set; } public ATTSnapshotDevice_t[] _list { get { return NativeMethods.GetArrayStruct<ATTSnapshotDevice_t>(point, count).ToArray(); } } */ public long count; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] public ATTSnapshotDevice_t[] list; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTLinkStatusEvent_t { private readonly uint count; private readonly IntPtr point; public ATTLinkStatus_t[] list { get { return NativeMethods.GetArrayStruct<ATTLinkStatus_t>(point,count).ToArray(); } } } public enum ATTBillType_t { btNewRate = 16, btFlatRate = 17, btPremiumCharge = 18, btPremiumCredit = 19, btFreeCall = 24, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSetBillRate_t { public ConnectionID_t call; public ATTBillType_t billType; public float billRate; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSetBillRateConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryUcid_t { public ConnectionID_t call; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryUcidConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5ConferencedEvent_t { public ATTV5OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTLoggedOffEvent_t { public int reasonCode; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5DeliveredEvent_t { public ATTDeliveredType_t deliveredType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV5OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5EstablishedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV5OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5TransferredEvent_t { public ATTV5OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV5RouteRequestEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTV5UserToUserInfo_t userInfo; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTConsultationCallConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTMakeCallConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTMakePredictiveCallConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV5SetAgentState_t { public ATTWorkMode_t workMode; public int reasonCode; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV5QueryAgentStateConfEvent_t { public ATTWorkMode_t workMode; public ATTTalkState_t talkState; public int reasonCode; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6QueryDeviceNameConfEvent_t { public ATTDeviceType_t deviceType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string name; public ATTUnicodeDeviceID uname; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTConferenceCallConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTTransferCallConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTMonitorFilter_t { [MarshalAs(UnmanagedType.I1)] public bool privateFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTMonitorConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool usedFilter; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSnapshotCall_t { private readonly uint count; private readonly IntPtr point; public CSTASnapshotCallResponseInfo_t[] list { get { return NativeMethods.GetArrayStruct<CSTASnapshotCallResponseInfo_t>(point,count).ToArray(); } } } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTMonitorCallConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool usedFilter; public ATTSnapshotCall_t snapshotCall; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTServiceInitiatedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; } public enum ATTChargeType_t { ctIntermediateCharge = 1, ctFinalCharge = 2, ctSplitCharge = 3, } public enum ATTChargeError_t { ceNone = 0, ceNoFinalCharge = 1, ceLessFinalCharge = 2, ceChargeTooLarge = 3, ceNetworkBusy = 4, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTChargeAdviceEvent_t { public ConnectionID_t connection; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string calledDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string chargingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; public ATTChargeType_t chargeType; public int charge; public ATTChargeError_t error; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6GetAPICapsConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 16)] public string switchVersion; [MarshalAs(UnmanagedType.I1)] public bool sendDTMFTone; [MarshalAs(UnmanagedType.I1)] public bool enteredDigitsEvent; [MarshalAs(UnmanagedType.I1)] public bool queryDeviceName; [MarshalAs(UnmanagedType.I1)] public bool queryAgentMeas; [MarshalAs(UnmanagedType.I1)] public bool querySplitSkillMeas; [MarshalAs(UnmanagedType.I1)] public bool queryTrunkGroupMeas; [MarshalAs(UnmanagedType.I1)] public bool queryVdnMeas; [MarshalAs(UnmanagedType.I1)] public bool singleStepConference; [MarshalAs(UnmanagedType.I1)] public bool selectiveListeningHold; [MarshalAs(UnmanagedType.I1)] public bool selectiveListeningRetrieve; [MarshalAs(UnmanagedType.I1)] public bool setBillingRate; [MarshalAs(UnmanagedType.I1)] public bool queryUCID; [MarshalAs(UnmanagedType.I1)] public bool chargeAdviceEvent; [MarshalAs(UnmanagedType.I1)] public bool reserved1; [MarshalAs(UnmanagedType.I1)] public bool reserved2; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryDeviceInfoConfEvent_t { public ATTExtensionClass_t extensionClass; public ATTExtensionClass_t associatedClass; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string associatedDevice; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSetAdviceOfCharge_t { [MarshalAs(UnmanagedType.I1)] public bool featureFlag; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSetAdviceOfChargeConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6NetworkReachedEvent_t { public ATTProgressLocation_t progressLocation; public ATTProgressDescription_t progressDescription; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSetAgentState_t { public ATTWorkMode_t workMode; public int reasonCode; [MarshalAs(UnmanagedType.I1)] public bool enablePending; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSetAgentStateConfEvent_t { [MarshalAs(UnmanagedType.I1)] public bool isPending; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueryAgentStateConfEvent_t { public ATTWorkMode_t workMode; public ATTTalkState_t talkState; public int reasonCode; public ATTWorkMode_t pendingWorkMode; public int pendingReasonCode; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTUserToUserInfo_Data { public ushort length; [MarshalAsAttribute(UnmanagedType.ByValTStr,SizeConst=129)] public string value; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTUserToUserInfo_t { public ATTUUIProtocolType_t type; public ATTUserToUserInfo_Data data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6RouteRequestEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTUserToUserInfo_t userInfo; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6OriginalCallInfo_t { public ATTReasonForCallInfo_t reason; public ExtendedDeviceID_t callingDevice; public ExtendedDeviceID_t calledDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTUserToUserInfo_t userInfo; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTTrunkInfo_t { public ConnectionID_t connection; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTTrunkList_t { public ushort count; [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst = 5, ArraySubType = UnmanagedType.Struct)] public ATTTrunkInfo_t[] trunks; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6TransferredEvent_t { public ATTV6OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTTrunkList_t trunkList; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6ConferencedEvent_t { public ATTV6OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTTrunkList_t trunkList; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTClearConnection_t { public ATTDropResource_t dropResource; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTConsultationCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTMakeCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTDirectAgentCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTMakePredictiveCall_t { [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; public short maxRings; public ATTAnswerTreat_t answerTreat; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTSupervisorAssistCall_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTReconnectCall_t { public ATTDropResource_t dropResource; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTV6ConnectionClearedEvent_t { public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6RouteSelect_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string callingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string directAgentCallSplit; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; public ATTUserCollectCode_t collectCode; public ATTUserProvidedCode_t userProvidedCode; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6DeliveredEvent_t { public ATTDeliveredType_t deliveredType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTUserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV6OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTV6EstablishedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTUserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTV6OriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTOriginatedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string logicalAgent; public ATTUserToUserInfo_t userInfo; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct Anonymous_61704943_801c_42d6_8135_28fae545d706 { public ushort length; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string value; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct Reserved_t { public Anonymous_61704943_801c_42d6_8135_28fae545d706 data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct Anonymous_48eed1af_da4c_48ac_8bde_7a38185256c8 { public ushort length; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string value; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct Reserved2_t { public Anonymous_48eed1af_da4c_48ac_8bde_7a38185256c8 data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct Anonymous_5d4dd665_21de_4058_8e0d_a08bbbf8f20a { public ushort length; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string value; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct Reserved3_t { public Anonymous_5d4dd665_21de_4058_8e0d_a08bbbf8f20a data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct Reserved4_t { [MarshalAs(UnmanagedType.I1)] public bool data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct Reserved5_t { public int data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct DeviceHistoryEntry_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string olddeviceID; public CSTAEventCause_t cause; public ConnectionID_t oldconnectionID; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)]//,Pack=2 public class DeviceHistory_t { public uint count; private readonly IntPtr point; public DeviceHistoryEntry_t[] list { get { return NativeMethods.GetArrayStruct<DeviceHistoryEntry_t>(point,count).ToArray(); } } /* public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("count", count, typeof(uint)); } public DeviceHistory_t(SerializationInfo info, StreamingContext context) { count = (uint)info.GetValue("count", typeof(uint)); // Reset the property value using the GetValue method. //myProperty_value = (string)info.GetValue("props", typeof(string)); }*/ } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTOriginalCallInfo_t { public ATTReasonForCallInfo_t reason; //4 public ExtendedDeviceID_t callingDevice; //72 public ExtendedDeviceID_t calledDevice; //72 [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] //64 public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] //64 public string trunkMember; public ATTLookaheadInfo_t lookaheadInfo; //208 public ATTUserEnteredCode_t userEnteredCode; //100 public ATTUserToUserInfo_t userInfo; //136 [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; //8 [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; //1 public DeviceHistory_t deviceHistory; //8 } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTQueryDeviceNameConfEvent_t { public ATTDeviceType_t deviceType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string device; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string name; public ATTUnicodeDeviceID uname; } public enum ATTRedirectType_t { vdn = 0, network = 1, } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTRouteSelect_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string callingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string directAgentCallSplit; [MarshalAs(UnmanagedType.I1)] public bool priorityCalling; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string destRoute; public ATTUserCollectCode_t collectCode; public ATTUserProvidedCode_t userProvidedCode; public ATTUserToUserInfo_t userInfo; public ATTRedirectType_t redirectType; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTGetAPICapsConfEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 65)] public string switchVersion; [MarshalAs(UnmanagedType.I1)] public bool sendDTMFTone; [MarshalAs(UnmanagedType.I1)] public bool enteredDigitsEvent; [MarshalAs(UnmanagedType.I1)] public bool queryDeviceName; [MarshalAs(UnmanagedType.I1)] public bool queryAgentMeas; [MarshalAs(UnmanagedType.I1)] public bool querySplitSkillMeas; [MarshalAs(UnmanagedType.I1)] public bool queryTrunkGroupMeas; [MarshalAs(UnmanagedType.I1)] public bool queryVdnMeas; [MarshalAs(UnmanagedType.I1)] public bool singleStepConference; [MarshalAs(UnmanagedType.I1)] public bool selectiveListeningHold; [MarshalAs(UnmanagedType.I1)] public bool selectiveListeningRetrieve; [MarshalAs(UnmanagedType.I1)] public bool setBillingRate; [MarshalAs(UnmanagedType.I1)] public bool queryUCID; [MarshalAs(UnmanagedType.I1)] public bool chargeAdviceEvent; [MarshalAs(UnmanagedType.I1)] public bool reserved1; [MarshalAs(UnmanagedType.I1)] public bool reserved2; [MarshalAs(UnmanagedType.I1)] public bool devicehistoryCount; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 256)] public string adminSoftwareVersion; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 256)] public string softwareVersion; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 256)] public string offerType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 256)] public string serverType; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTDeliveredEvent_t { public ATTDeliveredType_t deliveredType; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; //504 public ATTUserToUserInfo_t userInfo; //136 public ATTReasonCode_t reason; //4 public ATTOriginalCallInfo_t originalCallInfo; //804 //644 public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; public DeviceHistory_t deviceHistory; public ExtendedDeviceID_t distributingVDN; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTEstablishedEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string split; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTUserToUserInfo_t userInfo; public ATTReasonCode_t reason; public ATTOriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; public DeviceHistory_t deviceHistory; public ExtendedDeviceID_t distributingVDN; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTQueuedEvent_t { public DeviceHistory_t deviceHistory; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTRouteRequestEvent_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; public ATTLookaheadInfo_t lookaheadInfo; public ATTUserEnteredCode_t userEnteredCode; public ATTUserToUserInfo_t userInfo; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTCallOriginatorInfo_t callOriginatorInfo; [MarshalAs(UnmanagedType.I1)] public bool flexibleBilling; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; public DeviceHistory_t deviceHistory; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTTransferredEvent_t { public ATTOriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTTrunkList_t trunkList; public DeviceHistory_t deviceHistory; public ExtendedDeviceID_t distributingVDN; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTConferencedEvent_t { public ATTOriginalCallInfo_t originalCallInfo; public ExtendedDeviceID_t distributingDevice; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string ucid; public ATTTrunkList_t trunkList; public DeviceHistory_t deviceHistory; public ExtendedDeviceID_t distributingVDN; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTConnectionClearedEvent_t { public ATTUserToUserInfo_t userInfo; public DeviceHistory_t deviceHistory; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTDivertedEvent_t { public DeviceHistory_t deviceHistory; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTNetworkReachedEvent_t { public ATTProgressLocation_t progressLocation; public ATTProgressDescription_t progressDescription; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkGroup; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 64)] public string trunkMember; public DeviceHistory_t deviceHistory; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTFailedEvent_t { public DeviceHistory_t deviceHistory; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential)] public struct ATTSnapshotCallConfEvent_t { public DeviceHistory_t deviceHistory; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct ATTPrivateData_t { [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 32)] public string vendor; public ushort length; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 10240)] public string data; } [Serializable,StructLayoutAttribute(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct UserEnteredCode_t { public ushort size; [MarshalAs(UnmanagedType.I1)] public bool type; [MarshalAs(UnmanagedType.I1)] public bool timeout; [MarshalAs(UnmanagedType.I1)] public bool indicator; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 25)] public string data; [MarshalAsAttribute(UnmanagedType.ByValTStr, SizeConst = 10)] public string collectVDN; } public enum eventTypeCSTA : ushort { CSTA_ALTERNATE_CALL = 1, CSTA_ALTERNATE_CALL_CONF = 2, CSTA_ANSWER_CALL = 3, CSTA_ANSWER_CALL_CONF = 4, CSTA_CALL_COMPLETION = 5, CSTA_CALL_COMPLETION_CONF = 6, CSTA_CLEAR_CALL = 7, CSTA_CLEAR_CALL_CONF = 8, CSTA_CLEAR_CONNECTION = 9, CSTA_CLEAR_CONNECTION_CONF = 10, CSTA_CONFERENCE_CALL = 11, CSTA_CONFERENCE_CALL_CONF = 12, CSTA_CONSULTATION_CALL = 13, CSTA_CONSULTATION_CALL_CONF = 14, CSTA_DEFLECT_CALL = 15, CSTA_DEFLECT_CALL_CONF = 16, CSTA_PICKUP_CALL = 17, CSTA_PICKUP_CALL_CONF = 18, CSTA_GROUP_PICKUP_CALL = 19, CSTA_GROUP_PICKUP_CALL_CONF = 20, CSTA_HOLD_CALL = 21, CSTA_HOLD_CALL_CONF = 22, CSTA_MAKE_CALL = 23, CSTA_MAKE_CALL_CONF = 24, CSTA_MAKE_PREDICTIVE_CALL = 25, CSTA_MAKE_PREDICTIVE_CALL_CONF = 26, CSTA_QUERY_MWI = 27, CSTA_QUERY_MWI_CONF = 28, CSTA_QUERY_DND = 29, CSTA_QUERY_DND_CONF = 30, CSTA_QUERY_FWD = 31, CSTA_QUERY_FWD_CONF = 32, CSTA_QUERY_AGENT_STATE = 33, CSTA_QUERY_AGENT_STATE_CONF = 34, CSTA_QUERY_LAST_NUMBER = 35, CSTA_QUERY_LAST_NUMBER_CONF = 36, CSTA_QUERY_DEVICE_INFO = 37, CSTA_QUERY_DEVICE_INFO_CONF = 38, CSTA_RECONNECT_CALL = 39, CSTA_RECONNECT_CALL_CONF = 40, CSTA_RETRIEVE_CALL = 41, CSTA_RETRIEVE_CALL_CONF = 42, CSTA_SET_MWI = 43, CSTA_SET_MWI_CONF = 44, CSTA_SET_DND = 45, CSTA_SET_DND_CONF = 46, CSTA_SET_FWD = 47, CSTA_SET_FWD_CONF = 48, CSTA_SET_AGENT_STATE = 49, CSTA_SET_AGENT_STATE_CONF = 50, CSTA_TRANSFER_CALL = 51, CSTA_TRANSFER_CALL_CONF = 52, CSTA_UNIVERSAL_FAILURE_CONF = 53, CSTA_CALL_CLEARED = 54, CSTA_CONFERENCED = 55, CSTA_CONNECTION_CLEARED = 56, CSTA_DELIVERED = 57, CSTA_DIVERTED = 58, CSTA_ESTABLISHED = 59, CSTA_FAILED = 60, CSTA_HELD = 61, CSTA_NETWORK_REACHED = 62, CSTA_ORIGINATED = 63, CSTA_QUEUED = 64, CSTA_RETRIEVED = 65, CSTA_SERVICE_INITIATED = 66, CSTA_TRANSFERRED = 67, CSTA_CALL_INFORMATION = 68, CSTA_DO_NOT_DISTURB = 69, CSTA_FORWARDING = 70, CSTA_MESSAGE_WAITING = 71, CSTA_LOGGED_ON = 72, CSTA_LOGGED_OFF = 73, CSTA_NOT_READY = 74, CSTA_READY = 75, CSTA_WORK_NOT_READY = 76, CSTA_WORK_READY = 77, CSTA_ROUTE_REGISTER_REQ = 78, CSTA_ROUTE_REGISTER_REQ_CONF = 79, CSTA_ROUTE_REGISTER_CANCEL = 80, CSTA_ROUTE_REGISTER_CANCEL_CONF = 81, CSTA_ROUTE_REGISTER_ABORT = 82, CSTA_ROUTE_REQUEST = 83, CSTA_ROUTE_SELECT_REQUEST = 84, CSTA_RE_ROUTE_REQUEST = 85, CSTA_ROUTE_USED = 86, CSTA_ROUTE_END = 87, CSTA_ROUTE_END_REQUEST = 88, CSTA_ESCAPE_SVC = 89, CSTA_ESCAPE_SVC_CONF = 90, CSTA_ESCAPE_SVC_REQ = 91, CSTA_ESCAPE_SVC_REQ_CONF = 92, CSTA_PRIVATE = 93, CSTA_PRIVATE_STATUS = 94, CSTA_SEND_PRIVATE = 95, CSTA_BACK_IN_SERVICE = 96, CSTA_OUT_OF_SERVICE = 97, CSTA_REQ_SYS_STAT = 98, CSTA_SYS_STAT_REQ_CONF = 99, CSTA_SYS_STAT_START = 100, CSTA_SYS_STAT_START_CONF = 101, CSTA_SYS_STAT_STOP = 102, CSTA_SYS_STAT_STOP_CONF = 103, CSTA_CHANGE_SYS_STAT_FILTER = 104, CSTA_CHANGE_SYS_STAT_FILTER_CONF = 105, CSTA_SYS_STAT = 106, CSTA_SYS_STAT_ENDED = 107, CSTA_SYS_STAT_REQ = 108, CSTA_REQ_SYS_STAT_CONF = 109, CSTA_SYS_STAT_EVENT_SEND = 110, CSTA_MONITOR_DEVICE = 111, CSTA_MONITOR_CALL = 112, CSTA_MONITOR_CALLS_VIA_DEVICE = 113, CSTA_MONITOR_CONF = 114, CSTA_CHANGE_MONITOR_FILTER = 115, CSTA_CHANGE_MONITOR_FILTER_CONF = 116, CSTA_MONITOR_STOP = 117, CSTA_MONITOR_STOP_CONF = 118, CSTA_MONITOR_ENDED = 119, CSTA_SNAPSHOT_CALL = 120, CSTA_SNAPSHOT_CALL_CONF = 121, CSTA_SNAPSHOT_DEVICE = 122, CSTA_SNAPSHOT_DEVICE_CONF = 123, CSTA_GETAPI_CAPS = 124, CSTA_GETAPI_CAPS_CONF = 125, CSTA_GET_DEVICE_LIST = 126, CSTA_GET_DEVICE_LIST_CONF = 127, CSTA_QUERY_CALL_MONITOR = 128, CSTA_QUERY_CALL_MONITOR_CONF = 129, CSTA_ROUTE_REQUEST_EXT = 130, CSTA_ROUTE_USED_EXT = 131, CSTA_ROUTE_SELECT_INV_REQUEST = 132, CSTA_ROUTE_END_INV_REQUEST = 133, } // ReSharper enable InconsistentNaming } <file_sep>using System; namespace TSAPILIB2 { interface ITSAPI { APICapsEventReturn getAPICaps(); APICapsEventReturn getAPICapsComplite(IAsyncResult ar); GetDeviceListEventReturn getDeviceList(int index, CSTALevel_t level); GetDeviceListEventReturn getDeviceListComplite(IAsyncResult ar); QueryAcdSplitEventReturn getQueryAcdSplit(string deviceID); QueryAcdSplitEventReturn getQueryAcdSplitComplite(IAsyncResult ar); QueryAgentStateEventReturn getQueryAgentState(string deviceID); QueryAgentStateEventReturn getQueryAgentStateComplite(IAsyncResult ar); QueryDeviceInfoReturn getQueryDeviceInfo(string device); IAsyncResult getQueryDeviceInfoAsync(string deviceID, AsyncCallback cb = null); QueryDeviceInfoReturn getQueryDeviceInfoComplite(IAsyncResult ar); QueryLastNumberEventReturn getQueryLastNumber(string deviceID); QueryLastNumberEventReturn getQueryLastNumberComplite(IAsyncResult ar); QueryMsgWaitingEventReturn getQueryMsgWaitingInd(string deviceID); QueryMsgWaitingEventReturn getQueryMsgWaitingIndComplite(IAsyncResult ar); QueryStationStatusEventReturn getQueryStationStatus(string deviceID); QueryStationStatusEventReturn getQueryStationStatusComplite(IAsyncResult ar); QueryUCIDEventReturn getQueryUCID(ConnectionID_t call); QueryUCIDEventReturn getQueryUCIDComplite(IAsyncResult ar); event TSAPI.delegateClosed OnClosed; event TSAPI.delegateConnected OnConnnected; event TSAPI.delegateUniversalFailureSys OnUniversalFailureSys; void setAgentState(string deviceID, string agentID, string agentGroup, string password, AgentMode_t mode, ATTWorkMode_t wmode, int reasonCode); void setAgentStateComplite(IAsyncResult ar); void setAlternateCall(ConnectionID_t activeCall, ConnectionID_t otherCall); void setAlternateCallComplite(IAsyncResult ar); void setAnswerCall(ConnectionID_t allertingCall); void setAnswerCallComplite(IAsyncResult ar); void setCallCompletion(ConnectionID_t call, Feature_t feature); void setCallCompletionComplite(IAsyncResult ar); ChangeMonitorFilterEventReturn setChangeMonitorFilter(int monitorCrossId, CSTAMonitorFilter_t filter); ChangeMonitorFilterEventReturn setChangeMonitorFilterComplite(IAsyncResult ar); void setClearCall(ConnectionID_t call); void setClearCallComplite(IAsyncResult ar); void setClearConnection(ConnectionID_t call, ATTDropResource_t resourse, ATTV5UserToUserInfo_t info); void setClearConnectionComplite(IAsyncResult ar); ConferenceCallEventReturn setConferenceCall(ConnectionID_t activeCall, ConnectionID_t otherCall); ConferenceCallEventReturn setConferenceCallComplite(IAsyncResult ar); ConsultationCallEventReturn setConsultationCall(ConnectionID_t activeCall, string calledDevice, string destRoute, bool priorityCalling, ATTV5UserToUserInfo_t info); ConsultationCallEventReturn setConsultationCallComplite(IAsyncResult ar); void setDeflectCall(ConnectionID_t deflectCall, string calledDevice); void setDeflectCallComplite(IAsyncResult ar); void setGroupPickupCall(ConnectionID_t deflectCall, string pickupDevice); void setGroupPickupCallComplite(IAsyncResult ar); void setHoldCall(ConnectionID_t activeCall); void setHoldCallComplite(IAsyncResult ar); MakeCallEventReturn setMakeCall(string callingDevice, string calledDevice, string destroute, bool priorityCall, ATTV5UserToUserInfo_t info); MakeCallEventReturn setMakeCallComplite(IAsyncResult ar); MakePredictiveCallEventReturn setMakePredictiveCall(string callingDevice, string calledDevice, AllocationState_t allocationState, string destRoute, bool priorityCalling, short maxRing, ATTAnswerTreat_t answerTreat, ATTV5UserToUserInfo_t info); MakePredictiveCallEventReturn setMakePredictiveCallComplite(IAsyncResult ar); SetupMonitorEventReturn setMonitorCall(ConnectionID_t call, CSTAMonitorFilter_t filter, eventMonitor evnt); SetupMonitorEventReturn setMonitorCallComplite(IAsyncResult ar); SetupMonitorEventReturn setMonitorCallsViaDevice(string deviceID, CSTAMonitorFilter_t filter, eventMonitor evnt); SetupMonitorEventReturn setMonitorCallsViaDeviceComplite(IAsyncResult ar); SetupMonitorEventReturn setMonitorDevice(string deviceID, CSTAMonitorFilter_t filter, eventMonitor evnt); SetupMonitorEventReturn setMonitorDeviceComplite(IAsyncResult ar); StopMonitorEventReturn setMonitorStop(int monitorCrossId); StopMonitorEventReturn setMonitorStopComplite(IAsyncResult ar); void setPickupCall(ConnectionID_t deflectCall, string calledDevice); void setPickupCallComplite(IAsyncResult ar); QueryCallMonitorEventReturn setQueryCallMonitor(string deviceID); QueryCallMonitorEventReturn setQueryCallMonitorComplite(IAsyncResult ar); void setReconnectCall(ConnectionID_t activeCall, ConnectionID_t heldCall, ATTDropResource_t resource, ATTV5UserToUserInfo_t info); void setReconnectCallComplite(IAsyncResult ar); void setRetrieveCall(ConnectionID_t heldCall); void setRetrieveCallComplite(IAsyncResult ar); void setSendDTMFTone(ConnectionID_t call, ATTConnIDList_t list, string tone, short toneDuartion, short pauseDuartion); void setSendDTMFToneComplite(IAsyncResult ar); void setSetMsgWaitingInd(string deviceID, bool messages); void setSetMsgWaitingIndComplite(IAsyncResult ar); SnapshotCallEventReturn setSnapshotCallReq(ConnectionID_t call); SnapshotCallEventReturn setSnapshotCallReqComplite(IAsyncResult ar); SnapshotDeviceEventReturn setSnapshotDeviceReq(string deviceID); SnapshotDeviceEventReturn setSnapshotDeviceReqComplite(IAsyncResult ar); TransferCallEventReturn setTransferCall(ConnectionID_t activeCall, ConnectionID_t heldCall); TransferCallEventReturn setTransferCallComplite(IAsyncResult ar); } } <file_sep>using System.Collections.Generic; using System.Threading.Tasks; namespace TSAPILIB2 { public class Tsapi : Event { public Tsapi(string server, string login, string password, string appName, string apiVersion, string privateVersion) : base(server, login, password, appName, apiVersion, privateVersion) { } public Task<QueryAcdSplitEventReturn> GetQueryAcdSplit(string deviceId) { return CreateTask<QueryAcdSplitEventReturn>((u, t) => NativeMethods.attQueryAcdSplit(ref t, deviceId) | NativeMethods.cstaEscapeService(AcsHandle, u, ref t) , $"GetQueryAcdSplit('{deviceId}')"); } public Task<QueryDeviceInfoReturn> GetQueryDeviceInfo(string device) { return CreateTask<QueryDeviceInfoReturn>((invokeId, pd) =>NativeMethods.cstaQueryDeviceInfo(AcsHandle, invokeId, device, ref pd),$"GetQueryDeviceInfo('{device}')"); } public Task<GetDeviceListEventReturn> GetDeviceList(int index, CSTALevel_t level) { return CreateTask<GetDeviceListEventReturn>((invokeId, pd) =>NativeMethods.cstaGetDeviceList(AcsHandle, invokeId, index, level), $"GetDeviceList('{index}','{level}')"); } public Task<QueryStationStatusEventReturn> GetQueryStationStatus(string deviceId) { return CreateTask<QueryStationStatusEventReturn>((invokeId, pd) => NativeMethods.attQueryStationStatus(ref pd, deviceId) | NativeMethods.cstaEscapeService(AcsHandle, invokeId, ref pd) , $"GetQueryStationStatus('{deviceId}')" ); } public Task<QueryUcidEventReturn> GetQueryUcid(ConnectionID_t call) { return CreateTask<QueryUcidEventReturn>((invokeId, pd) => NativeMethods.attQueryUCID(ref pd, ref call) | NativeMethods.cstaEscapeService(AcsHandle, invokeId, ref pd), $"GetQueryUCID('{call}')" ); } public Task<NullTsapiReturn> SetSendDtmfTone(ConnectionID_t call, string tone, int pauseDuartion) { var list = new ATTV4ConnIDList_t(); return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.attSendDTMFTone(ref pd, ref call, ref list, tone, 0, 0) | NativeMethods.cstaEscapeService(AcsHandle, invokeId, ref pd), $"SetSendDTMFTone('{call}','{tone}','{pauseDuartion}')" ); } public Task<MakeCallEventReturn> SetMakeCall(string callingDevice, string calledDevice, string destroute, bool priorityCall, string info) { return CreateTask<MakeCallEventReturn>((invokeId, pd) => { var info2 = GetUuiFromString(info); var ret = NativeMethods.attV6MakeCall(ref pd, destroute, priorityCall, ref info2) | NativeMethods.cstaMakeCall(AcsHandle, invokeId, callingDevice, calledDevice, ref pd); return ret; },$"SetMakeCall('{callingDevice}','{calledDevice}','{destroute}','{priorityCall}','{info}')" ); } public Task<NullTsapiReturn> SetAlternateCall(ConnectionID_t activeCall, ConnectionID_t otherCall) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaAlternateCall(AcsHandle, invokeId, ref activeCall, ref otherCall, ref pd) , $"SetAlternateCall('{activeCall}','{otherCall}')" ); } public Task<NullTsapiReturn> SetAnswerCall(ConnectionID_t allertingCall) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaAnswerCall(AcsHandle, invokeId, ref allertingCall, ref pd) , $"SetAnswerCall('{allertingCall}')" ); } public Task<NullTsapiReturn> SetCallCompletion(ConnectionID_t call, Feature_t feature) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaCallCompletion(AcsHandle, invokeId, feature, ref call, ref pd), $"SetCallCompletion('{call}','{feature}')" ); } public Task<NullTsapiReturn> SetClearCall(ConnectionID_t call) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaClearCall(AcsHandle, invokeId, ref call, ref pd) , $"SetClearCall('{call}')" ); } public Task<NullTsapiReturn> SetClearConnection(ConnectionID_t call, ATTDropResource_t resourse, string info) { return CreateTask<NullTsapiReturn>((invokeId, pd) => { var info2 = GetUuiFromString(info); return NativeMethods.attV6ClearConnection(ref pd, resourse, ref info2) | NativeMethods.cstaClearConnection(AcsHandle, invokeId, ref call, ref pd); } , $"SetClearConnection('{call}','{resourse}','{info}')" ); } public Task<ConferenceCallEventReturn> SetConferenceCall(ConnectionID_t activeCall, ConnectionID_t otherCall) { return CreateTask<ConferenceCallEventReturn>((invokeId, pd) => NativeMethods.cstaConferenceCall(AcsHandle, invokeId, ref otherCall, ref activeCall, ref pd) , $"SetConferenceCall('{activeCall}','{otherCall}')" ); } public Task<ConsultationCallEventReturn> SetConsultationCall(ConnectionID_t activeCall, string calledDevice, string destRoute, bool priorityCalling, string info) { return CreateTask<ConsultationCallEventReturn>((invokeId, pd) => { var info2 = GetUuiFromString(info); var ret = NativeMethods.attV6ConsultationCall(ref pd, destRoute, priorityCalling, ref info2) | NativeMethods.cstaConsultationCall(AcsHandle, invokeId, ref activeCall, calledDevice, ref pd); return ret; },$"SetConsultationCall('{activeCall}','{calledDevice}','{destRoute}','{priorityCalling}','{info}')" ); } public Task<NullTsapiReturn> SetDeflectCall(ConnectionID_t deflectCall, string calledDevice) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaDeflectCall(AcsHandle, invokeId, ref deflectCall, calledDevice, ref pd) , $"SetDeflectCall('{deflectCall}','{calledDevice}')" ); } public Task<NullTsapiReturn> SetGroupPickupCall(ConnectionID_t deflectCall, string pickupDevice) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaGroupPickupCall(AcsHandle, invokeId, ref deflectCall, pickupDevice, ref pd) , $"SetGroupPickupCall('{deflectCall}','{pickupDevice}')" ); } public Task<NullTsapiReturn> SetHoldCall(ConnectionID_t activeCall) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaHoldCall(AcsHandle, invokeId, ref activeCall, false, ref pd) , $"SetHoldCall('{activeCall}')" ); } public Task<MakePredictiveCallEventReturn> SetMakePredictiveCall(string callingDevice, string calledDevice, AllocationState_t allocationState, string destRoute, bool priorityCalling, short maxRing, ATTAnswerTreat_t answerTreat, string info) { return CreateTask<MakePredictiveCallEventReturn>((invokeId, pd) => { var info2 = GetUuiFromString(info); return NativeMethods.attV6MakePredictiveCall(ref pd, priorityCalling, maxRing, answerTreat, destRoute, ref info2) | NativeMethods.cstaMakePredictiveCall(AcsHandle, invokeId, callingDevice, calledDevice, allocationState, ref pd); },$"SetMakePredictiveCall('{callingDevice}','{calledDevice}','{allocationState}','{destRoute}','{priorityCalling}','{maxRing}','{answerTreat}','{info}')"); } public Task<NullTsapiReturn> SetPickupCall(ConnectionID_t deflectCall, string calledDevice) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaPickupCall(AcsHandle, invokeId, ref deflectCall, calledDevice, ref pd), $"SetPickupCall('{deflectCall}','{calledDevice}')" ); } public Task<NullTsapiReturn> SetReconnectCall(ConnectionID_t activeCall, ConnectionID_t heldCall, ATTDropResource_t resource, string info) { return CreateTask<NullTsapiReturn>((invokeId, pd) => { var info2 = GetUuiFromString(info); return NativeMethods.attV6ReconnectCall(ref pd, resource, ref info2) | NativeMethods.cstaReconnectCall(AcsHandle, invokeId, ref activeCall, ref heldCall, ref pd); }, $"SetReconnectCall('{activeCall}','{heldCall}','{resource}','{info}')"); } public Task<NullTsapiReturn> SetRetrieveCall(ConnectionID_t heldCall) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaRetrieveCall(AcsHandle, invokeId, ref heldCall, ref pd), $"SetRetrieveCall('{heldCall}')"); } public Task<TransferCallEventReturn> SetTransferCall(ConnectionID_t activeCall, ConnectionID_t heldCall) { return CreateTask<TransferCallEventReturn>((invokeId, pd) => NativeMethods.cstaTransferCall(AcsHandle, invokeId, ref activeCall, ref heldCall, ref pd), $"SetTransferCall('{activeCall}','{heldCall}')" ); } public Task<NullTsapiReturn> SetSetMsgWaitingInd(string deviceId, bool messages) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.cstaSetMsgWaitingInd(AcsHandle, invokeId, deviceId, messages, ref pd) , $"SetSetMsgWaitingInd('{deviceId}','{messages}')" ); } public Task<NullTsapiReturn> SetAgentState(string deviceId, string agentId, string agentGroup, string lpassword, AgentMode_t mode, ATTWorkMode_t wmode, int reasonCode) { return CreateTask<NullTsapiReturn>((invokeId, pd) => NativeMethods.attSetAgentStateExt(ref pd, wmode, reasonCode) | NativeMethods.cstaSetAgentState(AcsHandle, invokeId, deviceId, mode, agentId, agentGroup, lpassword, ref pd) , $"SetAgentState('{deviceId}','{agentId}','{agentGroup}','{lpassword}','{mode}','{wmode}','{reasonCode}')" ); } public Task<QueryMsgWaitingEventReturn> GetQueryMsgWaitingInd(string deviceId) { return CreateTask<QueryMsgWaitingEventReturn>((invokeId, pd) => NativeMethods.cstaQueryMsgWaitingInd(AcsHandle, invokeId, deviceId, ref pd) , $"GetQueryMsgWaitingInd('{deviceId}')" ); } public Task<QueryAgentStateEventReturn> GetQueryAgentState(string deviceId) { return CreateTask<QueryAgentStateEventReturn>((invokeId, pd) => NativeMethods.cstaQueryAgentState(AcsHandle, invokeId, deviceId, ref pd) , $"GetQueryAgentState('{deviceId}')" ) /* MonitorEventAgentCollection evnt; if (Agents.TryGetValue(deviceId, out evnt)) { evnt.Invoke(task.Result.Csta, task.Result.Att); } return task.Result; })*/; } public Task<QueryLastNumberEventReturn> GetQueryLastNumber(string deviceId) { return CreateTask<QueryLastNumberEventReturn>((invokeId, pd) => NativeMethods.cstaQueryLastNumber(AcsHandle, invokeId, deviceId, ref pd) , $"GetQueryLastNumber('{deviceId}')" ); } public Task<NullTsapiReturn> SetMonitorStop(uint monitorCrossId) { //if (Monitors.ContainsKey((int) monitorCrossId)) return CreateTask<NullTsapiReturn>( (invokeId, pd) =>NativeMethods.cstaMonitorStop(AcsHandle, invokeId, monitorCrossId, ref pd), $"SetMonitorStop('{monitorCrossId}')") .ContinueWith(task => { MonitorEventCollection evnt; if (!Monitors.TryGetValue((int) monitorCrossId, out evnt)) return task.Result; evnt.MonitorEndedInvoke(new CSTAMonitorEndedEvent_t(), monitorCrossId); Monitors.TryRemove((int) monitorCrossId, out evnt); evnt.Dispose(); return task.Result; }); } public Task<ChangeMonitorFilterEventReturn> SetChangeMonitorFilter(uint monitorCrossId, CSTAMonitorFilter_t filter) { return CreateTask<ChangeMonitorFilterEventReturn>((invokeId, pd) => NativeMethods.cstaChangeMonitorFilter(AcsHandle, invokeId, monitorCrossId, ref filter, ref pd) , $"SetChangeMonitorFilter('{monitorCrossId}','{filter}')" ); } public Task<SnapshotCallEventReturn> SetSnapshotCallReq(ConnectionID_t call) { return CreateTask<SnapshotCallEventReturn>((invokeId, pd) => NativeMethods.cstaSnapshotCallReq(AcsHandle, invokeId, ref call, ref pd) , $"SetSnapshotCallReq('{call}')" ); } public Task<SnapshotDeviceEventReturn> SetSnapshotDeviceReq(string deviceId) { return CreateTask<SnapshotDeviceEventReturn>((invokeId, pd) => NativeMethods.cstaSnapshotDeviceReq(AcsHandle, invokeId, deviceId, ref pd) , $"SetSnapshotDeviceReq('{deviceId}')" ); } public Task<List<string>> GetQueryAgentLogin(string deviceId) { return CreateTask<List<string>>((invokeId, pd) => NativeMethods.attQueryAgentLogin(ref pd, deviceId) | NativeMethods.cstaEscapeService(AcsHandle, invokeId, ref pd) , $"GetQueryAgentLogin('{deviceId}')" ); } public Task<QueryCallMonitorEventReturn> SetQueryCallMonitor(string deviceId) { return CreateTask<QueryCallMonitorEventReturn>((invokeId, pd) => NativeMethods.cstaQueryCallMonitor(AcsHandle, invokeId) , $"SetQueryCallMonitor('{deviceId}')" ); } public Task<MonitorEventCollection> SetMonitorDevice(string deviceId, CSTAMonitorFilter_t filter) { return CreateTask<SetupMonitorEventReturn>((invokeId, pd) => NativeMethods.cstaMonitorDevice(AcsHandle, invokeId, deviceId, ref filter, ref pd) , $"SetMonitorDevice('{deviceId}','{filter}')" ).ContinueWith(task => { var monitoEvent = new MonitorEventCollection(task.Result.Csta.monitorCrossRefID, deviceId); Monitors.TryAdd((int) task.Result.Csta.monitorCrossRefID, monitoEvent); return monitoEvent; }); } public Task<MonitorEventCollection> SetMonitorCall(ConnectionID_t call, CSTAMonitorFilter_t filter) { return CreateTask<SetupMonitorEventReturn>((invokeId, pd) => NativeMethods.cstaMonitorCall(AcsHandle, invokeId, ref call, ref filter, ref pd) , $"SetMonitorCall('{call}','{filter}')" ).ContinueWith(task => { var monitoEvent = new MonitorEventCollection(task.Result.Csta.monitorCrossRefID, call); Monitors.TryAdd((int) task.Result.Csta.monitorCrossRefID, monitoEvent); return monitoEvent; }); } public Task<MonitorEventCollection> SetMonitorCallsViaDevice(string deviceId, CSTAMonitorFilter_t filter) { return CreateTask<SetupMonitorEventReturn>((invokeId, pd) => NativeMethods.cstaMonitorCallsViaDevice(AcsHandle, invokeId, deviceId, ref filter, ref pd) , $"SetMonitorCallsViaDevice('{deviceId}','{filter}')" ).ContinueWith(task => { var monitoEvent = new MonitorEventCollection(task.Result.Csta.monitorCrossRefID, deviceId); Monitors.TryAdd((int) task.Result.Csta.monitorCrossRefID, monitoEvent); return monitoEvent; }); } /* public MonitorEventAgentCollection SetMonitorAgent(string agentId) { if (StatusConnection != StatusConection.Open) return null; GetQueryAgentState(agentId); var mon = new MonitorEventAgentCollection(this, agentId, Agents.Count); if (!Agents.TryAdd(agentId, mon)) { mon.Dispose(); Agents.TryGetValue(agentId, out mon); } return mon; } public void SetMonitorAgentStop(string agentId) { if (StatusConnection != StatusConection.Open) return; MonitorEventAgentCollection mon; Agents.TryRemove(agentId, out mon); mon.Dispose(); } */ protected override void Dispose(bool disposing) { if (Disposed) return; if (disposing) { StatusConnection = StatusConection.Close; } base.Dispose(false); } } }<file_sep>using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Dynamic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Permissions; using System.Threading; using System.Threading.Tasks; using log4net; namespace TSAPILIB2 { public enum StatusConection { Close, Open } public class Event : IDisposable { public delegate void DelegateClosed(object sender, EventArgs e); public delegate void DelegateConnected(object sender, EventArgs e); public delegate void DelegateUniversalFailureSys(object sender, UniversalFailureSys e); public delegate void DelegateUniversalFailure(object sender, UniversalFailureEventArg e); protected const int Timeout = 5000; public static readonly ILog Log = LogManager.GetLogger(typeof (Event)); private static readonly object GlobalLock = new object(); private readonly CancellationTokenSource _closed = new CancellationTokenSource(); private readonly ReaderWriterLock _rw = new ReaderWriterLock(); // private readonly AutoResetEvent _waitClient = new AutoResetEvent(false); protected readonly CbTask<int> CbTaskForToPartNew = new CbTask<int>(); protected readonly CbTask<uint> CbTaskNew; protected readonly ConcurrentDictionary<object, object> ReportArray = new ConcurrentDictionary<object, object>(); private uint _acsHandle; private NativeMethods.ACSEventCallBack _callBackAnkor; private int _invokeId; private StatusConection _statusConnection = StatusConection.Close; /* protected ConcurrentDictionary<string, MonitorEventAgentCollection> Agents = new ConcurrentDictionary<string, MonitorEventAgentCollection>();*/ protected string ApiVersion; protected string AppName; protected bool Blocked; protected AcsEventCallBack CbEvent; protected bool Disposed; protected object InvokeIDlock = new object(); protected string Login; protected IAsyncResult MainLoopResult; protected ConcurrentDictionary<int, MonitorEventCollection> Monitors = new ConcurrentDictionary<int, MonitorEventCollection>(); protected string Password; protected string PrivateVersion; public ushort RecvExtraBufs = 0; public ushort RecvQSize = 400; public ushort SendExtraBufs = 0; public ushort SendQSize = 200; protected string Server; public Event() { CbTaskNew = new CbTask<uint>(SendQSize); Log.DebugFormat("{0} : Constructor", LinkName); } public Event(string server, string login, string password, string appName, string apiVersion, string privateVersion) : this() { Server = server; Login = login; Password = <PASSWORD>; AppName = appName; ApiVersion = apiVersion; PrivateVersion = privateVersion; } public uint AcsHandle { get { lock (this) { return _acsHandle; } } set { lock (this) { _acsHandle = value; } } } private Timer _timerWakUp; public uint InvokeId { get { lock (InvokeIDlock) { if (Blocked) { Thread.Sleep(100); Log.DebugFormat("Blocked {0} to 100 ms", LinkName); } var ret = (uint) Interlocked.Increment(ref _invokeId); if (ret > 32000) _invokeId = 0; _timerWakUp.Change(60*1000,60*1000*10); ; return ret; } } } public StatusConection StatusConnection { get { _rw.AcquireReaderLock(Timeout); var ret = _statusConnection; _rw.ReleaseReaderLock(); return ret; } set { _rw.AcquireWriterLock(Timeout); _statusConnection = value; _rw.ReleaseWriterLock(); } } public string LinkName => AppName; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected ATTUserToUserInfo_t GetUuiFromString(string info) { var info2 = new ATTUserToUserInfo_t(); if (!string.IsNullOrEmpty(info)) { info2.data = new ATTUserToUserInfo_Data { length = (ushort) info.Length, value = info }; info2.type = ATTUUIProtocolType_t.uuiIa5Ascii; } return info2; } public event DelegateConnected OnConnnectedEvent; public event DelegateClosed OnClosedEvent; public event DelegateUniversalFailure OnUniversalFailureEvent; public event DelegateUniversalFailureSys OnUniversalFailureSysEvent; ~Event() { Dispose(false); } static public T DeepCopy<T>(T obj) { BinaryFormatter s = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { s.Serialize(ms, obj); ms.Position = 0; T t = (T)s.Deserialize(ms); return t; } } // [SecurityPermission(SecurityAction.Demand, UnmanagedCode = true)] protected void EventCallBack(int lParam) { if (AcsHandle == 0) return; try { const int size = 1040*4; var pd = new PrivateData_t {length = size}; var ptrCsta = Marshal.AllocHGlobal(size); var ptrPd = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(pd, ptrPd, true); try { ushort count; do { var tt = NativeMethods.acsGetEventPoll(AcsHandle, ptrCsta, ref pd.length, ptrPd, out count); if (tt == ACSFunctionRet_t.ACSPOSITIVE_ACK) { var cstaEvent = new CSTAEvent_t(ptrCsta); var attEvent = new ATTEvent_t(); if ( NativeMethods.attPrivateData(ptrPd, ptrCsta) == ACSFunctionRet_t.ACSPOSITIVE_ACK) { attEvent = new ATTEvent_t(ptrCsta); } var csta = DeepCopy(cstaEvent); var att = DeepCopy(attEvent); switch (csta.eventHeader.eventClass) { case EventClass_t.ACSCONFIRMATION: Acsconfirmation(csta.acsConfirmation, csta.eventHeader.eventTypeACS); break; case EventClass_t.ACSUNSOLICITED: Acsunsolicited(csta.acsUnsolicited, csta.eventHeader.eventTypeACS); break; case EventClass_t.CSTACONFIRMATION: Cstaconfirmation(csta.cstaConfirmation, att, csta.eventHeader.eventTypeCSTA); break; case EventClass_t.CSTAEVENTREPORT: Cstaeventreport(csta.cstaEventReport, att, csta.eventHeader.eventTypeCSTA); break; case EventClass_t.CSTAREQUEST: Cstarequest(csta.cstaRequest, att, csta.eventHeader.eventTypeCSTA); break; case EventClass_t.CSTAUNSOLICITED: Cstaunsolicited(csta.cstaUnsolicited, att, csta.eventHeader.eventTypeCSTA); break; } } else { if (tt != ACSFunctionRet_t.ACSERR_NOMESSAGE && tt != ACSFunctionRet_t.ACSERR_BADHDL) { Log.Error(new Exeption("acsGetEventPoll", tt)); } return; } } while (count > 0); } catch (Exception ex) { Log.Error("EventCallBack", ex); } finally { Marshal.FreeHGlobal(ptrCsta); Marshal.FreeHGlobal(ptrPd); /* ptrCsta.Free(); ptrPd.Free(); */ } }catch(Exception ex) { Log.Error("EventCallBack", ex); } } protected Task<TRet> CreateTask<TRet>(Func<uint, PrivateData_t, ACSFunctionRet_t> functFunc, string commandDescription = "") { var invokeId = InvokeId; var pd = new PrivateData_t(); var t = CbTaskNew.Add(invokeId,command: commandDescription); // Thread.Sleep(5000); var ret = functFunc(invokeId, pd); if (ret != ACSFunctionRet_t.ACSPOSITIVE_ACK && StatusConnection == StatusConection.Open) { CbTaskNew.Set(invokeId, default(TRet)); switch (ret) { case ACSFunctionRet_t.ACSERR_APIVERDENIED: case ACSFunctionRet_t.ACSERR_UNKNOWN: break; case ACSFunctionRet_t.ACSERR_NOBUFFERS: case ACSFunctionRet_t.ACSERR_QUEUE_FULL: Blocked = true; break; default: AbortStream(); AlertClose(); break; } throw new Exeption(ret); } Blocked = false; /*t.ContinueWith(task => { var ex = task.Exception; if (ex == null) return; foreach (var exc in ex.Flatten().InnerExceptions) { Log.Error(commandDescription, exc); } }, TaskContinuationOptions.OnlyOnFaulted); return t.ContinueWith(task => (TRet) task.Result);*/ return t.ContinueWith(task => { if (task.IsFaulted) { var ex = task.Exception; if (ex != null) { foreach (var exc in ex.Flatten().InnerExceptions) { Log.Error(commandDescription, exc); } throw ex; } } return (TRet) task.Result; }); } public Task<ApiCapsEventReturn> GetApiCaps() { return CreateTask<ApiCapsEventReturn>((u, t) => NativeMethods.cstaGetAPICaps(AcsHandle, u), "GetAPICaps"); } private void Callback(object state) { GetApiCaps(); } public void OpenStream() { _timerWakUp = new Timer(Callback, this, 60 * 1000, 60 * 1000 * 10); Log.DebugFormat("{0} : Open stream ", LinkName); _acsHandle = 0; _invokeId = 0; if (MainLoopResult != null) { Log.DebugFormat("{0} : Wait last main_loop_result", LinkName); MainLoopResult.AsyncWaitHandle.WaitOne(10000); MainLoopResult = null; } _callBackAnkor = EventCallBack; ACSFunctionRet_t ret; lock (GlobalLock) { var pd = new PrivateData_t {vendor = "VERSION"}; pd.Set(PrivateVersion); ret = NativeMethods.acsOpenStream( out _acsHandle, InvokeIDType_t.APP_GEN_ID, 0, StreamType_t.stCsta, Server, Login, Password, AppName, 0, ApiVersion, SendQSize, SendExtraBufs, RecvQSize, RecvExtraBufs, ref pd ); } if (ret == ACSFunctionRet_t.ACSPOSITIVE_ACK) NativeMethods.acsSetESR(_acsHandle, _callBackAnkor, 0, true); _waitClient.WaitOne(); foreach (var monitorEventCollection in Monitors) { monitorEventCollection.Value.Dispose(); } Monitors.Clear(); } public void CloseStream() { Log.DebugFormat("{0} : Close stream ", LinkName); StatusConnection = StatusConection.Close; if (_acsHandle != 0) { CreateTask<object>((key, pd) => NativeMethods.acsCloseStream(AcsHandle, key, ref pd)); } } public void AbortStream() { Log.DebugFormat("{0} : Abort stream ", LinkName); StatusConnection = StatusConection.Close; if (_acsHandle != 0) { var pd = new PrivateData_t(); NativeMethods.acsAbortStream(AcsHandle, ref pd); /*if (ret != ACSFunctionRet_t.ACSPOSITIVE_ACK) { throw new Exeption("AbortStream", ret); }*/ } AlertClose(); } protected void AnalizeFailurs(ACSUniversalFailure_t error) { switch (error) { case ACSUniversalFailure_t.tserverStreamFailed: case ACSUniversalFailure_t.tserverNoThread: case ACSUniversalFailure_t.tserverDeadDriver: case ACSUniversalFailure_t.tserverBadStreamType: case ACSUniversalFailure_t.tserverNoNdsOamPermission: case ACSUniversalFailure_t.tserverOpenSdbLogFailed: case ACSUniversalFailure_t.tserverInvalidLogSize: case ACSUniversalFailure_t.tserverWriteSdbLogFailed: case ACSUniversalFailure_t.tserverNtFailure: case ACSUniversalFailure_t.tserverRegistrationFailed: case ACSUniversalFailure_t.tserverBadPwEncryption: case ACSUniversalFailure_t.tserverNoVersion: case ACSUniversalFailure_t.tserverBadPdu: case ACSUniversalFailure_t.tserverBadConnection: case ACSUniversalFailure_t.tserverDecodeFailed: case ACSUniversalFailure_t.tserverEncodeFailed: case ACSUniversalFailure_t.tserverNoMemory: case ACSUniversalFailure_t.tserverSpxFailed: case ACSUniversalFailure_t.tserverReceiveFromDriver: case ACSUniversalFailure_t.tserverSendToDriver: case ACSUniversalFailure_t.tserverFreeBufferFailed: case ACSUniversalFailure_t.tserverBadServerid: case ACSUniversalFailure_t.tserverRequiredModulesNotLoaded: case ACSUniversalFailure_t.tserverLoadLibFailed: case ACSUniversalFailure_t.tserverInvalidDriver: case ACSUniversalFailure_t.tserverDriverLoaded: case ACSUniversalFailure_t.tserverBadDriverProtocol: Log.ErrorFormat("{0} : Error ACSUniversalFailure_t : {1} ", LinkName, error); AbortStream(); break; } } protected void AlertClose() { StatusConnection = StatusConection.Close; _acsHandle = 0; _invokeId = 0; OnClosedEvent?.Invoke(this, null); } protected void Acsconfirmation(ACSConfirmationEvent data, eventTypeACS eventType) { switch (eventType) { case eventTypeACS.ACS_ABORT_STREAM: AlertClose(); break; case eventTypeACS.ACS_CLOSE_STREAM_CONF: AlertClose(); break; case eventTypeACS.ACS_OPEN_STREAM_CONF: OnConnnectedEvent?.Invoke(this, null); CbTaskNew.Set(data.invokeID, new NullTsapiReturn()); StatusConnection = StatusConection.Open; _waitClient.Set(); break; case eventTypeACS.ACS_UNIVERSAL_FAILURE_CONF: if (OnUniversalFailureEvent != null) { OnUniversalFailureSysEvent?.Invoke(this, new UniversalFailureSys {Error = data.failureEvent.error, EventType = eventType}); } CbTaskNew.Clear(); AnalizeFailurs(data.failureEvent.error); break; default: Log.Error($"{LinkName} : Error ACSCONFIRMATION ", new ProgrammingExeption($"Не обработан event '{eventType}' в ACSCONFIRMATION")); throw new ProgrammingExeption($"Не обработан event '{eventType}' в ACSCONFIRMATION"); } } protected void Acsunsolicited(AcsUnsolicitedEvent data, eventTypeACS eventType) { AnalizeFailurs(data.failureEvent.error); if (OnUniversalFailureEvent != null) { OnUniversalFailureSysEvent?.Invoke(this, new UniversalFailureSys {Error = data.failureEvent.error, EventType = eventType}); } } protected void Cstaconfirmation(CstaConfirmationEvent data, ATTEvent_t attPd, eventTypeCSTA eventType) { if (eventType == eventTypeCSTA.CSTA_UNIVERSAL_FAILURE_CONF) { CbTaskNew.SetError(data.invokeID, data.universalFailure.error); return; } object ret; switch (eventType) { case eventTypeCSTA.CSTA_QUERY_DEVICE_INFO_CONF: ret = new QueryDeviceInfoReturn(data, attPd); break; case eventTypeCSTA.CSTA_MAKE_CALL_CONF: ret = new MakeCallEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_CONSULTATION_CALL_CONF: ret = new ConsultationCallEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_MAKE_PREDICTIVE_CALL_CONF: ret = new MakePredictiveCallEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_TRANSFER_CALL_CONF: ret = new TransferCallEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_QUERY_AGENT_STATE_CONF: ret = new QueryAgentStateEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_QUERY_LAST_NUMBER_CONF: ret = new QueryLastNumberEventReturn(data); break; case eventTypeCSTA.CSTA_MONITOR_CONF: ret = new SetupMonitorEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_CHANGE_MONITOR_FILTER_CONF: ret = new ChangeMonitorFilterEventReturn(data); break; case eventTypeCSTA.CSTA_SNAPSHOT_DEVICE_CONF: ret = new SnapshotDeviceEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_SNAPSHOT_CALL_CONF: ret = new SnapshotCallEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_QUERY_CALL_MONITOR_CONF: ret = new QueryCallMonitorEventReturn(data); break; case eventTypeCSTA.CSTA_GET_DEVICE_LIST_CONF: ret = new GetDeviceListEventReturn(data); break; case eventTypeCSTA.CSTA_GETAPI_CAPS_CONF: ret = new ApiCapsEventReturn(data, attPd); break; case eventTypeCSTA.CSTA_ESCAPE_SVC_CONF: switch (attPd.eventType) { case TypeATTEvent.ATTQueryUcidConfEvent_t_PDU: ret = new QueryUcidEventReturn(attPd); break; case TypeATTEvent.ATTQueryAcdSplitConfEvent_t_PDU: ret = new QueryAcdSplitEventReturn(attPd); break; case TypeATTEvent.ATTQueryAgentLoginConfEvent_t_PDU: ret = new QueryAgentLoginEventReturn(attPd); var task = CbTaskNew.GeTask(data.invokeID); if (task != null) { CbTaskForToPartNew.Add(((QueryAgentLoginEventReturn) ret).Att.privEventCrossRefID, task); } break; default: ret = new NullTsapiReturn(); break; } break; default: ret = new NullTsapiReturn(); break; } CbTaskNew.Set(data.invokeID, ret); } protected void Cstaeventreport(CstaEventReport data, ATTEvent_t pd, eventTypeCSTA eventType) { switch (pd.eventType) { case TypeATTEvent.ATTQueryAgentLoginResp_t_PDU: var crid = pd.queryAgentLoginResp.privEventCrossRefID; if (pd.queryAgentLoginResp.list.count != 0) { var list = pd.queryAgentLoginResp.list.list.Take(pd.queryAgentLoginResp.list.count) .Select(_ => _.device) .ToList(); ReportArray.AddOrUpdate(crid, list, (u, o) => { var l = o as List<string>; if (l != null) l.AddRange(list); return (object) l; }); CbTaskForToPartNew.UpdateTimeout(crid); } else { object obj; var flag = ReportArray.TryRemove(crid, out obj); CbTaskForToPartNew.Set(crid, flag ? obj : new List<string>()); } break; } } protected void Cstarequest(CstaRequestEvent data, ATTEvent_t pd, eventTypeCSTA eventType) { } protected void Cstaunsolicited(CstaUnsolicitedEvent data, ATTEvent_t pd, eventTypeCSTA eventType) { MonitorEventCollection evnt; if (Monitors.TryGetValue((int) data.monitorCrossRefId, out evnt)) { if (eventType == eventTypeCSTA.CSTA_DELIVERED) { } evnt.Invoke(data, eventType, pd, data.monitorCrossRefId); if (eventType == eventTypeCSTA.CSTA_MONITOR_STOP || eventType == eventTypeCSTA.CSTA_MONITOR_ENDED) { Monitors.TryRemove((int) data.monitorCrossRefId, out evnt); evnt.Dispose(); } } } protected virtual void Dispose(bool disposing) { Log.DebugFormat("Wait command: {0}", CbTaskNew.CurrentCommand()); Log.DebugFormat("{0} : Destructor", LinkName); if (Disposed) return; if (disposing) { } _timerWakUp.Dispose(); _acsHandle = 0; try { _closed.Cancel(false); _closed.Dispose(); } catch (ObjectDisposedException) { //Deleted object } foreach (var variable in CbTaskNew) { variable.Value.Set(null); } CbTaskNew.Clear(); foreach (var variable in Monitors) { variable.Value.Dispose(); } Monitors.Clear(); /*foreach (var variable in Agents) { variable.Value.Dispose(); }*/ // Agents.Clear(); CbEvent = null; _callBackAnkor = null; } } }<file_sep>"# TSAPILIB" c# managed lib for Avaya TSAPI protocol<file_sep>using System; using System.Linq; using System.Runtime.Serialization; namespace TSAPILIB2 { public delegate void ResultDefault<T1, T2>(EventArg<T1, T2> arg); public delegate void ResultDefault<T1>(EventArg<T1> arg); public delegate void ResultDefault(NullTsapiReturn arg); public class ResultTsapi<T1,T2> { public T1 Csta; public T2 Att; public ResultTsapi(T1 a1,T2 a2) { Csta = a1; Att = a2; } } public class EventArg<T1,T2> { public T1 Csta ; public T2 Att; public EventArg() { } public EventArg(object a1, object a2) { Csta = (T1)a1; Att = (T2)a2; } public EventArg(T1 a1, T2 a2) { Csta = a1; Att = a2; } public void Set(T1 data,T2 attData) { Csta = data; Att = attData; } } public class NullTsapiReturn { public int Case = 0; } public struct SnapshotDeviceEventReturn { public CSTASnapshotDeviceConfEvent_t Csta; public ATTSnapshotDeviceConfEvent_t Att; public SnapshotDeviceEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.snapshotDevice; Att = a2.snapshotDevice; } } [DataContract] public struct QueryDeviceInfoReturn { [DataMember] public CSTAQueryDeviceInfoConfEvent_t Csta; [DataMember] public ATTQueryDeviceInfoConfEvent_t Att; public QueryDeviceInfoReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.queryDeviceInfo; Att = a2.queryDeviceInfo; } } public struct ConferenceCallEventReturn { [DataMember] public CSTAConferenceCallConfEvent_t Csta; [DataMember] public ATTConferenceCallConfEvent_t Att; public ConferenceCallEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.conferenceCall; Att = a2.conferenceCall; } } public struct MakeCallEventReturn { [DataMember] public CSTAMakeCallConfEvent_t Csta; [DataMember] public ATTMakeCallConfEvent_t Att; public MakeCallEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.makeCall; Att = a2.makeCall; } } public struct ConsultationCallEventReturn { [DataMember] public CSTAConsultationCallConfEvent_t Csta; [DataMember] public ATTConsultationCallConfEvent_t Att; public ConsultationCallEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.consultationCall; Att = a2.consultationCall; } } public struct MakePredictiveCallEventReturn { [DataMember] public CSTAMakePredictiveCallConfEvent_t Csta; [DataMember] public ATTMakePredictiveCallConfEvent_t Att; public MakePredictiveCallEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.makePredictiveCall; Att = a2.makePredictiveCall; } } public struct TransferCallEventReturn { /* [DataMember] public CSTATransferCallConfEvent_t Csta; [DataMember] public ATTTransferCallConfEvent_t Att;*/ public TransferCallEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { // Csta = a1.transferCall; //Att = a2.transferCall; } } public struct QueryMsgWaitingEventReturn { [DataMember] public CSTAQueryMwiConfEvent_t Csta; [DataMember] public ATTQueryMwiConfEvent_t Att; public QueryMsgWaitingEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.queryMwi; Att = a2.queryMwi; } } public struct QueryAgentStateEventReturn { [DataMember] public CSTAQueryAgentStateConfEvent_t Csta; [DataMember] public ATTQueryAgentStateConfEvent_t Att; public QueryAgentStateEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.queryAgentState; Att = a2.queryAgentState; } } public struct QueryLastNumberEventReturn { [DataMember] public CSTAQueryLastNumberConfEvent_t Csta; public QueryLastNumberEventReturn(CstaConfirmationEvent a1) { Csta = a1.queryLastNumber; } } public struct ChangeMonitorFilterEventReturn { [DataMember] public CSTAChangeMonitorFilterConfEvent_t Csta; public ChangeMonitorFilterEventReturn(CstaConfirmationEvent a1) { Csta = a1.changeMonitorFilter; } } public struct SnapshotCallEventReturn { [DataMember] public CSTASnapshotCallConfEvent_t Csta; [DataMember] public ATTSnapshotCallConfEvent_t Att; public SnapshotCallEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.snapshotCall; Att = a2.snapshotCallConf; } } public struct QueryCallMonitorEventReturn { [DataMember] public CSTAQueryCallMonitorConfEvent_t Csta; public QueryCallMonitorEventReturn(CstaConfirmationEvent a1) { Csta = a1.queryCallMonitor; } } public struct GetDeviceListEventReturn { [DataMember] public CSTAGetDeviceListConfEvent_t Csta; public GetDeviceListEventReturn(CstaConfirmationEvent a1) { Csta = a1.getDeviceList; } } public struct ApiCapsEventReturn { [DataMember] public CSTAGetAPICapsConfEvent_t Csta; [DataMember] public ATTGetAPICapsConfEvent_t Att; public ApiCapsEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.getAPICaps; Att = a2.getAPICaps; } } public struct QueryAcdSplitEventReturn { [DataMember] public ATTQueryAcdSplitConfEvent_t Att; public QueryAcdSplitEventReturn( ATTEvent_t a1) { Att = a1.queryAcdSplit; } public override string ToString() { return Att.agentsLoggedIn + ":" + Att.availableAgents; } } public struct QueryAgentLoginEventReturn { [DataMember] public ATTQueryAgentLoginConfEvent_t Att; public QueryAgentLoginEventReturn(ATTEvent_t a1) { Att = a1.queryAgentLogin; } } public struct QueryStationStatusEventReturn { [DataMember] public ATTQueryStationStatusConfEvent_t Att; public QueryStationStatusEventReturn(ATTEvent_t a1) { Att = a1.queryStationStatus; } } public struct QueryUcidEventReturn { [DataMember] public ATTQueryUcidConfEvent_t Att; public QueryUcidEventReturn( ATTEvent_t a1) { Att = a1.queryUCID; } } public struct SetupMonitorEventReturn { [DataMember] public CSTAMonitorConfEvent_t Csta; [DataMember] public ATTMonitorConfEvent_t Att; public SetupMonitorEventReturn(CstaConfirmationEvent a1, ATTEvent_t a2) { Csta = a1.monitorStart; Att = a2.monitorStart; } } public class CstaEventArgs<TCsta> : EventArgs { public CstaEventArgs(TCsta csta) { Csta = csta; } public TCsta Csta { get; private set; } } public class CstaAttEventArgs<TCsta, TAtt> : CstaEventArgs<TCsta> { public CstaAttEventArgs(TCsta csta, TAtt att):base(csta) { Att = att; } public TAtt Att { get; private set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TSAPILIB2 { public class AgentExeption : Exception { public String device; public String agent; public AgentExeption(String device,String agent, String error) :base (String.Format("Agent {0}. Device {1}. Error: '{2}'" ,agent,device,error)) { this.device = device; this.agent = agent; } } public class AgentDeviceNoSation : AgentExeption { public AgentDeviceNoSation(String device, String agent) : base(device, agent, "Device is not station.") { } } public class AgentDeviceinUse : AgentExeption { public ATTExtensionClass_t obj_used_class; public String obj_used; public AgentDeviceinUse(String device, String agent, ATTExtensionClass_t obj_used_class, String obj_used) : base(device, agent, String.Format("Device in use for '{0}:{1}'.", obj_used_class,obj_used)) { this.obj_used_class = obj_used_class; this.obj_used = obj_used; } } public class Agent { public struct StatusAgent { public StausAgentItem cstate; public StausAgentItem lstate; public DateTime update; public StatusAgent(bool init) { this.cstate = new StausAgentItem() { status = ATTWorkMode_t.wmNone, code = 0 }; this.lstate = new StausAgentItem() { status = ATTWorkMode_t.wmNone, code = 0 }; this.update = DateTime.Now; } public void Set(ATTWorkMode_t mode, int code) { this.update = DateTime.Now; this.lstate = this.cstate; this.cstate = new StausAgentItem() { status = mode, code = code }; } public struct StausAgentItem { public ATTWorkMode_t status; public int code; } } protected TSAPI tsapi; protected String agent; protected String password; protected Device device; protected StatusAgent status = new StatusAgent(true); public Agent(TSAPI tsapi,String agent, String password,Device device) { this.tsapi = tsapi; this.device = device; this.agent = agent; this.password = <PASSWORD>; this.checkDevice(); } protected void setExpetion(String function, String error) { throw new AgentExeption(this.agent, this.device.getDeviceId(), function + ":" + error); } public void checkDevice() { if (this.device.type != DeviceType_t.dtStation) { throw new AgentDeviceNoSation(this.agent, this.device.getDeviceId()); } if ( !( this.device.associatedClass == ATTExtensionClass_t.ecOther || ( this.device.associatedClass == ATTExtensionClass_t.ecLogicalAgent && this.device.associatedDevice == this.agent ) ) ) { throw new AgentDeviceinUse(this.agent, this.device.getDeviceId(), this.device.associatedClass, this.device.associatedDevice); } } public Device getDevice() { return this.device; } protected void setStatus(ATTWorkMode_t mode, int code) { this.status.Set(mode, code); } protected void changeStatusAgent(AgentMode_t type,ATTWorkMode_t mode,int code) { this.tsapi.setAgentStateAsync(this.device.getDeviceId(), this.agent, "", this.password, type, mode, code, new resultDefault(delegate(eventArg arg) { if (arg.error == CSTAUniversalFailure_t.allOK) { this.setStatus(mode, code); } })); } public String getAgentId() { return this.agent; } public void Login() { if (this.status.cstate.status == ATTWorkMode_t.wmNone) { this.changeStatusAgent(AgentMode_t.amLogIn, ATTWorkMode_t.wmAuxWork, 0); } } public void Logout() { if (this.status.cstate.status != ATTWorkMode_t.wmNone) { this.changeStatusAgent(AgentMode_t.amLogOut, ATTWorkMode_t.wmNone, 0); } } public void Manual() { if (this.status.cstate.status == ATTWorkMode_t.wmManualIn && this.status.cstate.status != ATTWorkMode_t.wmNone) { this.changeStatusAgent(AgentMode_t.amReady, ATTWorkMode_t.wmManualIn, 0); } } public void AuxWrok(int code) { if (this.status.cstate.status == ATTWorkMode_t.wmAuxWork && this.status.cstate.status != ATTWorkMode_t.wmNone) { this.changeStatusAgent(AgentMode_t.amNotReady, ATTWorkMode_t.wmAuxWork, code); } } public void AftrCall(int code) { if (this.status.cstate.status == ATTWorkMode_t.wmAftcalWk && this.status.cstate.status != ATTWorkMode_t.wmNone) { this.changeStatusAgent(AgentMode_t.amWorkNotReady, ATTWorkMode_t.wmAftcalWk, 0); } } } } <file_sep>using System; using System.Collections.Generic; using System.Runtime.InteropServices; using log4net; namespace TSAPILIB2 { class NativeMethods { public static readonly ILog Log = LogManager.GetLogger(typeof(NativeMethods)); public static T GetStruct<T>(byte[] body) { if (body == null || body.Length == 0) { return default(T); } var adr = Marshal.UnsafeAddrOfPinnedArrayElement(body, 0); try { return (T)Marshal.PtrToStructure(adr, typeof(T)); } catch (Exception ex) { Log.Error(ex); } return default (T); } public struct SafeArrasyPoint { public uint count; public IntPtr point; } public static List<T> GetArrayStruct<T>(IntPtr point) { var t = Marshal.PtrToStructure<SafeArrasyPoint>(point); if (t.count > 0) return GetArrayStruct<T>(t.point, t.count); return new List<T>(); } public static List<T> GetArrayStruct<T>(IntPtr point, uint count) { var ret = new List<T>(); if (point != IntPtr.Zero) for (var x = 0; x < count; x++) { try { ret.Add( (T) Marshal.PtrToStructure( IntPtr.Add(point, x*Marshal.SizeOf(typeof (T))), typeof (T)) ); } catch (Exception ex) { Log.Error(ex); } } return ret; } public static List<int> GetArrayInt(IntPtr point, uint count) { var ret = new List<int>(); for (var x = 0; x < count; x++) { ret.Add( Marshal.ReadInt32(IntPtr.Add(point, x * sizeof(int))) ); } return ret; } public static List<T> GetArrayEnum<T>(IntPtr point, uint count) { var ret = new List<T>(); for (var x = 0; x < count; x++) { ret.Add( (T)Enum.ToObject(typeof(T), Marshal.ReadInt32(IntPtr.Add(point, x * sizeof(int))) ) ); } return ret; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void ACSEventCallBack(int lParam); [DllImport("Csta32.DLL", ExactSpelling = true)] public static extern ACSFunctionRet_t acsGetEventBlock(uint acsHandle, IntPtr eventBuf, ref ushort eventBufSize, ref PrivateData_t privData, out ushort numEvents); [DllImport("Csta32.DLL", ExactSpelling = true)] public static extern ACSFunctionRet_t acsGetEventPoll(uint acsHandle, IntPtr point, ref ushort eventBufSize, IntPtr privData, out ushort numEvents); [DllImport("Csta32.DLL",CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern ACSFunctionRet_t cstaQueryDeviceInfo(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t acsEnumServerNames(StreamType_t streamType, EnumServerNamesCb callback, uint lParam); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi, ExactSpelling = true)] public static extern ACSFunctionRet_t acsOpenStream(out uint acsHandle, InvokeIDType_t invokeIdType, uint invokeId, StreamType_t streamType, [ MarshalAs ( UnmanagedType . LPStr )]string serverId, [ MarshalAs ( UnmanagedType . LPStr )]string loginId, [ MarshalAs ( UnmanagedType . LPStr )]string passwd, [ MarshalAs ( UnmanagedType . LPStr )]string applicationName, Level_t acsLevelReq, [ MarshalAs ( UnmanagedType . LPStr )]string apiVer, ushort sendQSize, ushort sendExtraBufs, ushort recvQSize, ushort recvExtraBufs, ref PrivateData_t priv); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t acsCloseStream(uint acsHandle, UInt32 invokeId, ref PrivateData_t pd); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t acsAbortStream(uint acsHandle, ref PrivateData_t pd); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t acsFlushEventQueue(uint acsHandle); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t acsEventNotify(uint acsHandle, int hwnd, uint msg, bool notifyAll); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t acsSetESR(uint acsHandle, ACSEventCallBack cb, uint mesrParamsg, bool notifyAll); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t acsQueryAuthInfo([ MarshalAs ( UnmanagedType . LPStr )]string serverId, ref ACSAuthInfo_t authInfo); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaAlternateCall(uint acsHandle, uint invokeId, ref ConnectionID_t activeCall, ref ConnectionID_t otherCall, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaAnswerCall(uint acsHandle, uint invokeId, ref ConnectionID_t alertingCall, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaCallCompletion(uint acsHandle, uint invokeId, Feature_t feature, ref ConnectionID_t call, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaClearCall(uint acsHandle, uint invokeId, ref ConnectionID_t call, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaClearConnection(uint acsHandle, uint invokeId, ref ConnectionID_t call, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaConferenceCall(uint acsHandle, uint invokeId, ref ConnectionID_t heldCall, ref ConnectionID_t activeCall, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaConsultationCall(uint acsHandle, uint invokeId, ref ConnectionID_t activeCall, [ MarshalAs ( UnmanagedType . LPStr )]string calledDevice, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaDeflectCall(uint acsHandle, uint invokeId, ref ConnectionID_t deflectCall, [ MarshalAs ( UnmanagedType . LPStr )]string calledDevice, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaGroupPickupCall(uint acsHandle, uint invokeId, ref ConnectionID_t deflectCall, [ MarshalAs ( UnmanagedType . LPStr )]string pickupDevice, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaHoldCall(uint acsHandle, uint invokeId, ref ConnectionID_t activeCall, bool reservation, ref PrivateData_t privateData); [DllImport("Csta32.DLL",CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaMakeCall(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string callingDevice, [ MarshalAs ( UnmanagedType . LPStr )]string calledDevice, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaMakePredictiveCall(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string callingDevice, [ MarshalAs ( UnmanagedType . LPStr )]string calledDevice, AllocationState_t allocationState, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaPickupCall(uint acsHandle, uint invokeId, ref ConnectionID_t deflectCall, [ MarshalAs ( UnmanagedType . LPStr )]string calledDevice, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaReconnectCall(uint acsHandle, uint invokeId, ref ConnectionID_t activeCall, ref ConnectionID_t heldCall, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaRetrieveCall(uint acsHandle, uint invokeId, ref ConnectionID_t heldCall, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaTransferCall(uint acsHandle, uint invokeId, ref ConnectionID_t heldCall, ref ConnectionID_t activeCall, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaSetMsgWaitingInd(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, bool messages, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaSetDoNotDisturb(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, byte doNotDisturb, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaSetForwarding(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, ForwardingType_t forwardingType, byte forwardingOn, [ MarshalAs ( UnmanagedType . LPStr )]string forwardingDestination, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaSetAgentState(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, AgentMode_t agentMode, [ MarshalAs ( UnmanagedType . LPStr )]string agentId, [ MarshalAs ( UnmanagedType . LPStr )]string agentGroup, [ MarshalAs ( UnmanagedType . LPStr )]string agentPassword, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaQueryMsgWaitingInd(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaQueryDoNotDisturb(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaQueryForwarding(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaQueryAgentState(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaQueryLastNumber(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaMonitorDevice(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string deviceId, ref CSTAMonitorFilter_t monitorFilter, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaMonitorCall(uint acsHandle, uint invokeId, ref ConnectionID_t call, ref CSTAMonitorFilter_t monitorFilter, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaMonitorCallsViaDevice(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string deviceId, ref CSTAMonitorFilter_t monitorFilter, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaChangeMonitorFilter(uint acsHandle, uint invokeId, uint monitorCrossRefId, ref CSTAMonitorFilter_t filterlist, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaMonitorStop(uint acsHandle, uint invokeId, uint monitorCrossRefId, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaSnapshotCallReq(uint acsHandle, uint invokeId, ref ConnectionID_t snapshotObj, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaSnapshotDeviceReq(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string snapshotObj, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaRouteRegisterReq(uint acsHandle, uint invokeId, [ MarshalAs ( UnmanagedType . LPStr )]string routingDevice, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaRouteRegisterCancel(uint acsHandle, uint invokeId, int routeRegisterReqId, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaRouteSelect(uint acsHandle, int routeRegisterReqId, int routingCrossRefId, [ MarshalAs ( UnmanagedType . LPStr )]string routeSelected, short remainRetry, ref SetUpValues_t setupInformation, byte routeUsedReq, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaRouteEnd(uint acsHandle, int routeRegisterReqId, int routingCrossRefId, CSTAUniversalFailure_t errorValue, ref PrivateData_t privateData); [DllImport("Csta32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t cstaRouteSelectInv(uint acsHandle, uint invokeId, int routeRegisterReqId, int routingCrossRefId, [ MarshalAs ( UnmanagedType . LPStr )]string routeSelected, short remainRetry, ref SetUpValues_t setupInformation, byte routeUsedReq, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaRouteEndInv(uint acsHandle, uint invokeId, int routeRegisterReqId, int routingCrossRefId, CSTAUniversalFailure_t errorValue, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaEscapeService(uint acsHandle, uint invokeId, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaEscapeServiceConf(uint acsHandle, uint invokeId, CSTAUniversalFailure_t error, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaSendPrivateEvent(uint acsHandle, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaSysStatReq(uint acsHandle, uint invokeId, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaSysStatStart(uint acsHandle, uint invokeId, byte statusFilter, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaSysStatStop(uint acsHandle, uint invokeId, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaChangeSysStatFilter(uint acsHandle, uint invokeId, byte statusFilter, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaSysStatReqConf(uint acsHandle, uint invokeId, SystemStatus_t systemStatus, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaSysStatEvent(uint acsHandle, SystemStatus_t systemStatus, ref PrivateData_t privateData); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaGetAPICaps(uint acsHandle, uint invokeId); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaGetDeviceList(uint acsHandle, uint invokeId, int index, CSTALevel_t level); [DllImport("Csta32.DLL")] public static extern ACSFunctionRet_t cstaQueryCallMonitor(uint acsHandle, uint invokeId); [DllImport("ATTPRV32.DLL")] //public static extern ACSFunctionRet_t attPrivateData(ref PrivateData_t privateData, IntPtr eventBuffer); public static extern ACSFunctionRet_t attPrivateData(IntPtr privateData, IntPtr eventBuffer); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attMakeVersionstring([ MarshalAs ( UnmanagedType . LPStr )]string requestedVersion, [ MarshalAs ( UnmanagedType . LPStr )]string supportedVersion); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t encodePrivate(int pdunum, [ MarshalAs ( UnmanagedType . LPStr )]string pdu, ref PrivateData_t priv); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attClearConnection(ref PrivateData_t privateData, ATTDropResource_t dropResource, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attConsultationCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, bool priorityCalling, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attMakeCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, bool priorityCalling, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attDirectAgentCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string split, bool priorityCalling, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attMakePredictiveCall(ref PrivateData_t privateData, bool priorityCalling, short maxRings, ATTAnswerTreat_t answerTreat, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attSupervisorAssistCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string split, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attReconnectCall(ref PrivateData_t privateData, ATTDropResource_t dropResource, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attSendDTMFTone(ref PrivateData_t privateData, ref ConnectionID_t sender, ref ATTV4ConnIDList_t receivers, [ MarshalAs ( UnmanagedType . LPStr )]string tones, short toneDuration, short pauseDuration); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attSetAgentState(ref PrivateData_t privateData, ATTWorkMode_t workMode); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryAcdSplit(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryAgentLogin(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryAgentState(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attQueryCallClassifier(ref PrivateData_t privateData); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryDeviceName(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryStationStatus(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attQueryTimeOfDay(ref PrivateData_t privateData); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryTrunkGroup(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryAgentMeasurements(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string agentId, ATTAgentTypeID_t typeId, ATTSplitSkill_t splitSkill, ref ATTAgentMeasurementsPresent_t requestItems, short interval); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQuerySplitSkillMeasurements(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref ATTSplitSkillMeasurementsPresent_t requestItems, short interval); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryTrunkGroupMeasurements(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref ATTTrunkGroupMeasurementsPresent_t requestItems, short interval); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attQueryVdnMeasurements(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string device, ref ATTVdnMeasurementsPresent_t requestItems, short interval); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attMonitorFilter(ref PrivateData_t privateData, byte privateFilter); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attMonitorStopOnCall(ref PrivateData_t privateData, int monitorCrossRefId, ref ConnectionID_t call); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attRouteSelect(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string callingDevice, [ MarshalAs ( UnmanagedType . LPStr )]string directAgentCallSplit, byte priorityCalling, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, ref ATTUserCollectCode_t collectCode, ref ATTUserProvidedCode_t userProvidedCode, ref ATTV5UserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attSysStat(ref PrivateData_t privateData, byte linkStatusReq); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attSingleStepConferenceCall(ref PrivateData_t privateData, ref ConnectionID_t activeCall, [ MarshalAs ( UnmanagedType . LPStr )]string deviceToBeJoin, ATTParticipationType_t participationType, byte alertDestination); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attSelectiveListeningHold(ref PrivateData_t privateData, ref ConnectionID_t subjectConnection, byte allParties, ref ConnectionID_t selectedParty); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attSelectiveListeningRetrieve(ref PrivateData_t privateData, ref ConnectionID_t subjectConnection, byte allParties, ref ConnectionID_t selectedParty); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attSetAgentStateExt(ref PrivateData_t privateData, ATTWorkMode_t workMode, int reasonCode); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attSetBillRate(ref PrivateData_t privateData, ref ConnectionID_t call, ATTBillType_t billType, float billRate); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attQueryUCID(ref PrivateData_t privateData, ref ConnectionID_t call); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attSetAdviceOfCharge(ref PrivateData_t privateData, byte flag); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attSendDTMFToneExt(ref PrivateData_t privateData, ref ConnectionID_t sender, ref ATTConnIDList_t receivers, [ MarshalAs ( UnmanagedType . LPStr )]string tones, short toneDuration, short pauseDuration); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attMonitorFilterExt(ref PrivateData_t privateData, byte privateFilter); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attV6SetAgentState(ref PrivateData_t privateData, ATTWorkMode_t workMode, int reasonCode, byte enablePending); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attV6MakeCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, bool priorityCalling, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attV6ClearConnection(ref PrivateData_t privateData, ATTDropResource_t dropResource, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attV6ConsultationCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, bool priorityCalling, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attV6DirectAgentCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string split, byte priorityCalling, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attV6MakePredictiveCall(ref PrivateData_t privateData, bool priorityCalling, short maxRings, ATTAnswerTreat_t answerTreat, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attV6SupervisorAssistCall(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string split, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL")] public static extern ACSFunctionRet_t attV6ReconnectCall(ref PrivateData_t privateData, ATTDropResource_t dropResource, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attV6RouteSelect(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string callingDevice, [ MarshalAs ( UnmanagedType . LPStr )]string directAgentCallSplit, byte priorityCalling, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, ref ATTUserCollectCode_t collectCode, ref ATTUserProvidedCode_t userProvidedCode, ref ATTUserToUserInfo_t userInfo); [DllImport("ATTPRV32.DLL", CharSet = CharSet.Ansi)] public static extern ACSFunctionRet_t attV7RouteSelect(ref PrivateData_t privateData, [ MarshalAs ( UnmanagedType . LPStr )]string callingDevice, [ MarshalAs ( UnmanagedType . LPStr )]string directAgentCallSplit, byte priorityCalling, [ MarshalAs ( UnmanagedType . LPStr )]string destRoute, ref ATTUserCollectCode_t collectCode, ref ATTUserProvidedCode_t userProvidedCode, ref ATTUserToUserInfo_t userInfo, ATTRedirectType_t networkredirect); } /********************************/ public delegate void EnumServerNamesCb([ MarshalAs ( UnmanagedType . LPStr )]string serverName, ulong lParam); public delegate void AcsEventCallBack(ulong esrParam); public delegate void AcsSetEsrCallBack(ulong esrParam); } <file_sep>using System; using System.Runtime.Serialization; namespace TSAPILIB2 { [Serializable] public class Exeption : Exception { public ACSFunctionRet_t Code; public Exeption(ACSFunctionRet_t type) : base(String.Format("{0}", type)) { } public Exeption(String text, ACSFunctionRet_t type) : base(String.Format("{0}:{1}",text,type)) { Code = type; } // ReSharper disable once RedundantOverridenMember public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } [Serializable] public class CstaExeption : Exception { public CSTAUniversalFailure_t Code; public CstaExeption(CSTAUniversalFailure_t type) : base(String.Format("{0}", type)) { Code = type; } public CstaExeption(String text, CSTAUniversalFailure_t type) : base(String.Format("{0}:{1}", text, type)) { Code = type; } // ReSharper disable once RedundantOverridenMember public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); } } [Serializable] public class TsapiSystemExeption : Exception { public TsapiSystemExeption(ACSUniversalFailure_t error) : base(error.ToString()) { } } [Serializable] public class ProgrammingExeption : Exception { public ProgrammingExeption(String text) : base(text) { } } }
d265fb9a7f94bd7f9c34286abc9e0835760d2ac7
[ "Markdown", "C#", "INI" ]
18
C#
cws2097/TSAPILIB
c4fc33959c5e98b077b68c7ed08deff77e436f08
9ac0cc9563f6767eedc2485afc2caa9fd4a0177c
refs/heads/master
<repo_name>orse0002/web-app<file_sep>/page-2.php <?php /** *Small Description of File: *The wicked wonderful awesome magic ball! * *@author <NAME> <<EMAIL>> *@copyright 2012 A Group of Moving Pictures 8@license BSD-3-Clause <http://spdx.org/licenses/BSD-3-Clausess> *@version 1.0.0 *@package Wicked Wonderful Awesome Magic Ball */ require_once 'includes/validate.php'; require_once 'includes/db.php'; $sql=$db->query(' SELECT id, choices FROM 8ball ORDER BY RAND() LIMIT 1 '); $results=$sql->fetch(); ?><!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Wicked Awesome Magic Eight Ball</title> <link rel="stylesheet" href="css/general.css"> </head> <body> <h1>The Wonderful Wicked Awesome</h1> <h1 class="title">Magic Ball!!!!</h1> <?php if ($complete) : ?> <?php else :?> <div class="center"> <figure> <img src="images/ball-2.png" > <figcaption><?php echo $results ['choices'] ?></figcaption> </figure> <form method="post" action="page-2.php"> <div class="quest"> <label for="wish">Make Another Wish?<?php if (isset($errors['wish'])) : ?> <strong>is required</strong><?php endif; ?></label> <textarea id="wish" name="wish" required></textarea> </div> <button id="add" type="submit">Submit</button> </form> <?php endif;?> </div> <footer><img src="images/cp.png"> 2012 GMP</footer> </body> </html> <file_sep>/schema/8ball.sql -- phpMyAdmin SQL Dump -- version 3.3.9 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Jul 26, 2012 at 05:30 PM -- Server version: 5.5.8 -- PHP Version: 5.3.5 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `orse0002` -- -- -------------------------------------------------------- -- -- Table structure for table `8ball` -- CREATE TABLE IF NOT EXISTS `8ball` ( `id` int(11) NOT NULL AUTO_INCREMENT, `choices` varchar(256) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=6 ; -- -- Dumping data for table `8ball` -- INSERT INTO `8ball` (`id`, `choices`) VALUES (1, 'Better Luck Next Time'), (2, 'I would say yes, but No'), (3, 'No Means No... Too bad your mom didn''t know that'), (4, 'Stupid question... Are you retard strong too?'), (5, 'Are you a Jerk Face? Yes'); <file_sep>/css/input.php <?php /** *Small Description of File: *The wicked wonderful awesome magic ball! * *@author <NAME> <<EMAIL>> *@copyright 2012 A Group of Moving Pictures 8@license BSD-3-Clause <http://spdx.org/licenses/BSD-3-Clausess> *@version 1.0.0 *@package Wicked Wonderful Awesome Magic Ball */ ?> <file_sep>/includes/validate.php <?php /** *Small Description of File: *The wicked wonderful awesome magic ball! * *@author <NAME> <<EMAIL>> *@copyright 2012 A Group of Moving Pictures 8@license BSD-3-Clause <http://spdx.org/licenses/BSD-3-Clausess> *@version 1.0.0 *@package Wicked Wonderful Awesome Magic Ball */ $errors = array(); $complete = false; $wish = filter_input(INPUT_POST, 'wish', FILTER_SANITIZE_STRING); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Check to see if the form has been submitted before validating if (empty($wish)) { $errors['wish'] = true; } if (empty($errors)){ $complete = true; header('Location: page-2.php'); } } //test ?><file_sep>/CHANGELOG.md CHANGELOG ========= ver 1.0.0.0<file_sep>/includes/db.php <?php /** *Small Description of File: *The wicked wonderful awesome magic ball! * *@author <NAME> <<EMAIL>> *@copyright 2012 A Group of Moving Pictures 8@license BSD-3-Clause <http://spdx.org/licenses/BSD-3-Clausess> *@version 1.0.0 *@package Wicked Wonderful Awesome Magic Ball */ $user = getenv('MYSQL_USERNAME'); $pass = getenv('MYSQL_PASSWORD'); $host = getenv('MYSQL_DB_HOST'); $name = getenv('MYSQL_DB_NAME'); $data_source = sprintf('mysql:host=%s;dbname=%s', $host, $name); $db = new PDO($data_source, $user, $pass); $db->exec('SET NAMES utf8');<file_sep>/index.php <?php /** *Small Description of File: *The wicked wonderful awesome magic ball! * *@author <NAME> <<EMAIL>> *@copyright 2012 A Group of Moving Pictures 8@license BSD-3-Clause <http://spdx.org/licenses/BSD-3-Clause> *@version 1.0.0 *@package Wicked Wonderful Awesome Magic Ball */ require_once 'includes/validate.php'; ?><!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Wicked Wonderful Awesome Magic Ball!</title> <link rel="stylesheet" href="css/general.css"> </head> <body> <h1>The Wonderful Wicked Awesome</h1> <h1 class="title">Magic Ball!!!!</h1> <div class="center"> <img src="images/ball.png" width="500px" height="500px"> </div> <?php if ($complete) : ?> <?php else :?> <form method="post" action="index.php"> <div class="quest"> <label for="wish">Put In Your Wish and See What The Future Holds!<?php if (isset($errors['wish'])) : ?> <strong>is required</strong><?php endif; ?></label> <textarea id="wish" name="wish" required></textarea> </div> <button id="add" type="submit">Submit</button> </form> <?php endif;?> <footer><img src="images/cp.png"> 2012 GMP</footer> </body> </html> <file_sep>/README.md web-app ======= Magic eight ball http://magic8ball.phpfogapp.com/ <NAME> <EMAIL> INSTALL ======= Install table Download github directory Run Local Host
128a3240fa88e5abfc215fd4aa57d2ff49076662
[ "Markdown", "SQL", "PHP" ]
8
PHP
orse0002/web-app
66cf8d24711e7394fe351390960586c809a0c394
56232ba3f208feacb377770797099224c99a5def
refs/heads/master
<repo_name>pmahida1/Cash_Register_App<file_sep>/Cash_Register_App/Cash_Register_App/Restoke.xaml.cs using Cash_Register_App.Model; using SQLite; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Cash_Register_App { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Restoke : ContentPage { public SQLiteConnection conn; public ProductsTable pTable; public int productId; private int productPrice; public string productName; public Restoke() { InitializeComponent(); conn = DependencyService.Get<ProductSqlite>().GetConnection(); conn.CreateTable<ProductsTable>(); DisplayDetails(); } public void DisplayDetails() { var data = (from x in conn.Table<ProductsTable>() select x); itemsList.ItemsSource = data; } private void Restock(object sender, EventArgs e) { if(product_Qty.Text == null || productName == null) { DisplayAlert("Error", "You have to select an Item and provide new Quantity", "Ok"); } else { var newQTy = pTable.Quantity + int.Parse(product_Qty.Text); pTable = new ProductsTable(); pTable.ID = productId; pTable.Name = productName; pTable.Price = productPrice; pTable.Quantity = newQTy; try { conn.Update(pTable); product_Qty.Text = ""; } catch (Exception ex) { throw ex; } } DisplayDetails(); } private async void cancel(object sender, EventArgs e) { await Navigation.PushAsync(new ManagerPage()); } private void select(object sender, SelectedItemChangedEventArgs e) { pTable = itemsList.SelectedItem as ProductsTable; productName = pTable.Name; productId = pTable.ID; productPrice = pTable.Price; } } }<file_sep>/README.md # Cash_Register_App <NAME> ( 140 172 180) This is my Cash Register App. <file_sep>/Cash_Register_App/Cash_Register_App/MainPage.xaml.cs using Cash_Register_App.Model; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace Cash_Register_App { public partial class MainPage : ContentPage { public SQLiteConnection conn; public ProductsTable pTable; public int productId; private int productPrice; int currentState = 1; string mathOperator; double firstNumber, secondNumber; public MainPage() { InitializeComponent(); conn = DependencyService.Get<ProductSqlite>().GetConnection(); conn.CreateTable<ProductsTable>(); DisplayDetails(); } public void DisplayDetails() { var data = (from x in conn.Table<ProductsTable>() select x); itemsList.ItemsSource = data; } private void Number_Button_Clicked(object sender, EventArgs e) { if (Type.Text == "Type") { DisplayAlert("Alert!", "Please Select an Item from Below List!", "Ok"); } else { Button button = (Button)sender; string pressed = button.Text; if (this.Quantity.Text == "0" || currentState < 0) { this.Quantity.Text = ""; if (currentState < 0) currentState *= -1; } this.Quantity.Text += pressed; if(int.Parse(Quantity.Text) > pTable.Quantity) { DisplayAlert("Error", "quantity exceed from the stock", "Ok"); Quantity.Text = "0"; totalPrice.Text = "0"; } else { double number; if (double.TryParse(this.Quantity.Text, out number)) { this.Quantity.Text = number.ToString("N0"); if (currentState == 1) { firstNumber = number; } else { secondNumber = number; } } int quantity = int.Parse(Quantity.Text); var productsTable = itemsList.SelectedItem as ProductsTable; totalPrice.Text = (productsTable.Price * quantity).ToString(); Type.Text = productsTable.Name; } } } private async void managerButton_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new ManagerPage()); Navigation.RemovePage(this); } private void select(object sender, SelectedItemChangedEventArgs e) { int quantity = int.Parse(Quantity.Text); pTable = itemsList.SelectedItem as ProductsTable; totalPrice.Text = (pTable.Price * quantity).ToString(); Type.Text = pTable.Name ; productId = pTable.ID; productPrice = pTable.Price; } private void buy_Product(object sender, EventArgs e) { if(Quantity.Text != "0") { int quantity = int.Parse(Quantity.Text); var newQTy = pTable.Quantity - quantity; pTable = new ProductsTable(); pTable.ID = productId; pTable.Name = Type.Text; pTable.Price = productPrice; pTable.Quantity = newQTy; try { conn.Update(pTable); Type.Text = "Type"; Quantity.Text = "0"; totalPrice.Text = "0"; } catch (Exception ex) { throw ex; } DisplayDetails(); } else { DisplayAlert("Not Selected", "Please Select the Product", "Ok"); } } } } <file_sep>/Cash_Register_App/Cash_Register_App.Android/ProductSQlite_Droid.cs using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Cash_Register_App.Droid; using SQLite; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Xamarin.Forms; [assembly:Dependency(typeof(ProductSQlite_Droid))] namespace Cash_Register_App.Droid { public class ProductSQlite_Droid : ProductSqlite { public SQLiteConnection GetConnection() { var dbName = "product_Db"; var dbPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData); var path = Path.Combine(dbPath, dbName); var conn = new SQLiteConnection(path); return conn; } } }<file_sep>/Cash_Register_App/Cash_Register_App/ManagerPage.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Cash_Register_App { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class ManagerPage : ContentPage { public ManagerPage() { InitializeComponent(); } private async void historyButton_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new HistoryPage()); } private async void restokeButton_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new Restoke()); } private async void newProductbutton_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new New_Product()); } //private async void backHome_Clicked(object sender, EventArgs e) //{ // await Navigation.PushAsync(new MainPage()); // Navigation.RemovePage(this); //} private async void homeIcon_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new MainPage()); Navigation.RemovePage(this); } } }<file_sep>/Cash_Register_App/Cash_Register_App/New_Product.xaml.cs using Cash_Register_App.Model; using SQLite; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Cash_Register_App { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class New_Product : ContentPage { private SQLiteConnection conn; public ProductsTable pTable; public New_Product() { InitializeComponent(); conn = DependencyService.Get<ProductSqlite>().GetConnection(); conn.CreateTable<ProductsTable>(); } //private void save_ToolbarItem_Clicked(object sender, EventArgs e) //{ //} //private void cancel_ToolbarItem_Clicked(object sender, EventArgs e) //{ //} private void Save_Button_Clicked(object sender, EventArgs e) { pTable = new ProductsTable(); pTable.Name = productName.Text; pTable.Price = int.Parse(productPrice.Text); pTable.Quantity = int.Parse(productQuantity.Text); int x = 0; try { if(productName.Text != " " && productPrice.Text!= " " && productQuantity.Text != " ") { x = conn.Insert(pTable); productName.Text = ""; productPrice.Text = ""; productQuantity.Text = ""; } } catch (Exception ex) { throw ex; } if (x == 1) { DisplayAlert("Done!", "New Product Added Successfully!", "Ok"); } else { DisplayAlert("Failed!", "New Product is not Added Successfully!", "Ok"); } } private async void Cancel_Button_Clicked(object sender, EventArgs e) { await Navigation.PushAsync(new ManagerPage()); } } }<file_sep>/Cash_Register_App/Cash_Register_App/HistoryPage.xaml.cs using Cash_Register_App.Model; using SQLite; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Cash_Register_App { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class HistoryPage : ContentPage { public SQLiteConnection conn; public HistoryPage() { InitializeComponent(); conn = DependencyService.Get<ProductSqlite>().GetConnection(); conn.CreateTable<ProductsTable>(); DisplayDetails(); } public void DisplayDetails() { var data = (from x in conn.Table<ProductsTable>() select x); itemsList.ItemsSource = data; } private void select(object sender, SelectedItemChangedEventArgs e) { } } }
ef7a025ffb408069e6165fc47158361a6d362547
[ "Markdown", "C#" ]
7
C#
pmahida1/Cash_Register_App
2ec840321885afd0006a3f913f8922f489a7ded9
15618cc43c9bc7f3a0b4fc495e257ed25d4ae6ff
refs/heads/master
<repo_name>TangoJP/datafeeder<file_sep>/datafeeder/datasource.py from abc import ABC, abstractclassmethod import numpy as np import pandas as pd import time class ABCDataSource(ABC): @abstractclassmethod def retrieve_data(self): pass class SingleSource(ABC): """ Class to hold source data and allows access to the data by a retrieval method. """ @staticmethod def read_source2df(source, **pandas_kwargs): """ Function to read in or assigne 'source' into a DataFrame object. """ if type(source) == str: # Read file as CSV df = pd.read_csv(source, **pandas_kwargs).reset_index(drop=True) elif type(source) == pd.core.frame.DataFrame: # Directly assign DF df = source else: raise TypeError('\'source\' must be DataFrame or String.') return df def __init__(self, source, name='', cols=[], **pandas_kwargs): """ INPUTS: ======= source : str or DataFrame if str, read in the file in the path, if DataFrame, directly assigns it as an attribute name : str name of the source cols : list list of columns to slice in the DataFrame pandas_kwargs: dict **kwargs for pd.read_csv() method ATTRIBUTES: =========== column_names : tuple tuple of the included columns """ self.source = self.read_source2df(source, **pandas_kwargs) self.name = name self.size = len(self.source) if isinstance(cols, list) and cols != []: self.source = self.source[cols] if cols == []: self.column_names = tuple(self.source.columns) else: self.column_names = tuple(cols) def _retrieve_single_row(self, ind, type='iloc'): """ INPUT: ====== ind : int index to retrieve type : 'iloc' or 'loc' typf of index retrieval to use. use iloc by default OUTPUT: ======= returns DataFrame.iloc[ind] as tuple """ if type == 'loc': return tuple(self.source.loc[ind]) else: return tuple(self.source.iloc[ind]) def _retrieve_rows(self, ind, num_rows): if (ind + num_rows) > self.size: raise IndexError('index max passed. \ (\'ind + \' num_rows\') must be smaller than data size') data = [self._retrieve_single_row(i) for i in range(ind, ind + num_rows)] return data def retrieve_data(self, ind, num_rows=1, type='iloc'): if num_rows > 1: return self._retrieve_rows(ind, num_rows) else: return self._retrieve_single_row(ind, type=type) class MultiSource(ABC): """ Multi-version of Sources class """ def __init__(self, sources, cols=[], **pandas_kwargs): """ Input: ====== sources : {name1:path1, name2:path2, ...} or {name1:df1, name2:df2, ...} dictionary whose key is the name of the data and the value the path to the file or DataFrame Object cols : list columns to include ATTRIBUTE: ========== sources : list list containig Source objects for sources input sizes : dictionary dict whose key is data name and the value the size of the data *in the future: cols = {name1:[col1, col2], name2:[col3, col4], ....} ** This assumes indices are aligned among different data. Also uses iloc[] """ # Check elements of sources if not isinstance(sources, dict): raise TypeError('sources must be a dictionary object') self.sources = [ SingleSource(src, name=name, cols=cols)\ for name, src in sources.items()] self.names = [src.name for src in self.sources] self.sizes = {src.name:src.size for src in self.sources} def retrieve_data(self, ind, num_rows=1): data = { src.name:src.retrieve_data(ind, num_rows=num_rows, type='iloc') \ for src in self.sources } return data # Use below for quick testing if __name__ == '__main__': pass ### END<file_sep>/datafeeder/feeder.py from abc import ABC, abstractclassmethod import numpy as np import pandas as pd import time from datafeeder.datasource import SingleSource, MultiSource class ABCFeeder(ABC): @abstractclassmethod def __init__(self): pass @abstractclassmethod def __iter__(self): pass @abstractclassmethod def __next__(self): pass class SingleRowFeeder(ABCFeeder): def __init__(self, source, cols=[], num_feeds=10, retrieve_type='iloc', print_col_names=False, **pandas_kwargs): """ INPUT: ====== source : str or DataFrame file path for data or DataFrame object cols : list columns to include num_feeds : positive int number of times to feed retrieve_type : str by default, it uses iloc[] for slicing, but if this parameter is set to 'loc', use loc[] print_col_names : Boolean if True, print the included column names pandas_kwargs : dict **kwargs for pd.read_csv() ATTRIBUTES: =========== index : int index for the iterator source : Source() object Source object read from source input. """ self.index = 0 self.source = SingleSource(source, cols=cols, **pandas_kwargs) self.retrieve_type = retrieve_type if num_feeds > self.source.size: raise ValueError('num_feeds must not be bigger than the source size') self.num_feeds = num_feeds if print_col_names: print(self.source.column_names) def __iter__(self): return self def __next__(self): # Stop iteration once max reached if self.index >= self.num_feeds: raise StopIteration() # Retrieve data from source and feed data = self.source.retrieve_data(self.index, type=self.retrieve_type) self.index += 1 return data class MultiRowFeeder(SingleRowFeeder): def __init__(self, source, cols=[], num_rows=5, num_feeds=10, print_col_names=False, **pandas_kwargs): super().__init__(source, cols=cols, num_feeds=num_feeds, print_col_names=False, **pandas_kwargs) self.num_rows = num_rows def __iter__(self): super().__iter__() def __next__(self): # Stop iteration once max reached if self.index >= (self.source.size - self.num_feeds): raise StopIteration() # Retrieve data from source and feed data = self.source.retrieve_data(self.index, num_rows=self.num_rows) self.index += 1 return data class MultiSourceFeeder(ABCFeeder): """ Multi-version of Feeder """ def __init__(self, sources, cols=[], num_feeds=10, print_col_names=False, **pandas_kwargs): """ INPUT: ====== sources : dict sources input for MultiSources object cols : list list of columns to include num_feeds : int number of feeds print_col_names : Boolean print included column names or not pandas_kwargs : dict kwargs for pd.read_csv() function ATTRIBUTES: =========== index : int index for the Feeder """ self.index = 0 self.sources = MultiSource(sources, cols=cols, **pandas_kwargs) if any(num_feeds > size for size in self.sources.sizes.values()): raise ValueError('num_feeds must not be bigger than the source size') self.num_feeds = num_feeds if print_col_names: print(cols) def __iter__(self): return self def __next__(self): """ next() method. Identical to Feeder class except what's returned is dictionary instead of tuple. """ if self.index >= self.num_feeds: raise StopIteration() data = self.sources.retrieve_data(self.index) self.index += 1 return data # Use below for quick testing if __name__ == '__main__': pass ### END<file_sep>/datafeeder/holder.py import pandas as pd import numpy as np class DataHolder: def __init__(self): pass def _pop_first(self): pass def _insert_last(self): pass def replace(self): pass<file_sep>/tests/test_pulser.py # The second import fails unless run from the datafeeder (project root) directory import time from datafeeder.to_be_deprecated.pulser import Pulser # Simple test func def myprint1(message): return ('{}'.format(str(message) + '\n')) def myprint2(message, wait): if type(wait) not in (int, float): raise TypeError('\'wait\' must be a number (int or float)') elif wait < 0: raise ValueError('num_pulses must be a positive number') time.sleep(wait) return myprint1(message) def collect_pulse(pulse): print('{:d}-th: {}'.format(pulse[0], str(pulse[1]))) message = 'testing pulser' pulser1 = Pulser(5, myprint1, wait=1) pulser2 = Pulser(3, myprint2) for pulse in pulser1.pulse(message): collect_pulse(pulse)<file_sep>/tests/test_plotter.py from datafeeder.plotter import Plotter, FeedPlotter from datafeeder.feeder import SingleRowFeeder import pandas as pd import numpy as np import matplotlib.pyplot as plt import unittest class PlotterTest(unittest.TestCase): def test_basic_scatter(self): plotter = Plotter(pause=0.5) self.assertIsInstance(plotter, Plotter) num_points = 10 scatter_kwargs = {'color':'skyblue', 'marker':'^'} for i in range(num_points): #print(i) y = np.random.random() plotter.scatter(i, y, **scatter_kwargs) plt.show() def test_scatter_with_formatted_axis(self): plotter = Plotter(pause=0.5) self.assertIsInstance(plotter, Plotter) plotter.format_axis( xlim=[-1, 11], ylim=[-0.1, 1.1], xlabel='Iteration', ylabel='Random #', title='Basic Plotter Class Test with axis formatting' ) num_points = 10 scatter_kwargs = {'color':'skyblue', 'marker':'^'} for i in range(num_points): #print(i) y = np.random.random() plotter.scatter(i, y, **scatter_kwargs) plt.show() class TestFeedPlotter(unittest.TestCase): def test_basic_scatter(self): # Set up plotter source = './data/EURJPY/EURJPY_2002-201802_day.csv' # set up feeder num_feeds = 50 feeder = SingleRowFeeder( source, cols=['time', 'close'], num_feeds=num_feeds, print_col_names=False, parse_dates=['time'], dtype={'close':np.float64} ) # Set up plotter plotter = Plotter(pause=1e-12) plotter.format_axis( title='test scatter @ FeedPlotter', xlabel='time', ylabel='EUR/JPY', grid=True, ) # scatter plot feedplotter = FeedPlotter(feeder, plotter) scatter_kargs = {'color':'skyblue', 's':10, 'marker':'s'} self.assertEqual(feedplotter.feeder.index, 0) feedplotter.scatter(**scatter_kargs) self.assertEqual(feedplotter.feeder.index, num_feeds) if __name__ == '__main__': unittest.main() ### END<file_sep>/tests/test_feeder.py # To be run from the directory with __main__() from datafeeder.feeder import ( SingleRowFeeder, MultiRowFeeder, MultiSourceFeeder) from datafeeder.datasource import SingleSource, MultiSource import pandas as pd import numpy as np import unittest source1 = [ {'time': 0, 'open':100, 'close': 101}, {'time': 1, 'open':101, 'close': 105}, {'time': 2, 'open':104, 'close': 102}, {'time': 3, 'open':103, 'close': 101}, {'time': 4, 'open':102, 'close': 107} ] source2 = [ {'time': 0, 'open':120, 'close': 121}, {'time': 1, 'open':121, 'close': 125}, {'time': 2, 'open':124, 'close': 122}, {'time': 3, 'open':123, 'close': 121}, {'time': 4, 'open':122, 'close': 127} ] source1 = pd.DataFrame(source1) source2 = pd.DataFrame(source2) sources = {'src1':source1, 'src2':source2} class TestSingleRowFeeder(unittest.TestCase): def test_attributes(self): feeder = SingleRowFeeder(source1, cols=['time', 'close'], num_feeds=5, print_col_names=True) self.assertTrue(isinstance(feeder, SingleRowFeeder)) self.assertEqual(feeder.index, 0) self.assertEqual(feeder.retrieve_type, 'iloc') self.assertEqual(feeder.num_feeds, 5) def test_iteration(self): print('\n') print('Testing Feeder') feeder = SingleRowFeeder(source1, cols=['time', 'close'], num_feeds=5, print_col_names=True) self.assertEqual(feeder.index, 0) for feed in feeder: print(feed) self.assertEqual(feeder.index, 5) class TestMultiMultiSourceFeeder(unittest.TestCase): def test_attributes(self): feeder = MultiSourceFeeder(sources, cols=['time', 'close'], num_feeds=5, print_col_names=True) self.assertTrue(isinstance(feeder, MultiSourceFeeder)) self.assertTrue(isinstance(feeder.sources, MultiSource)) self.assertEqual(feeder.index, 0) self.assertEqual(feeder.num_feeds, 5) def test_iteration(self): print('\n') print('Testing MultiFeeder') feeder = MultiSourceFeeder(sources, cols=['time', 'close'], num_feeds=5, print_col_names=True) self.assertEqual(feeder.index, 0) for feed in feeder: print(feed) self.assertEqual(feeder.index, 5) if __name__ == '__main__': unittest.main()<file_sep>/datafeeder/to_be_deprecated/pulser.py import numpy as np import pandas as pd import time class Pulser: """ It executes a function for a fixed number of times and yields its result along with an index. It is basically an enumerator of a sort. """ def __init__(self, num_pulses, func, wait=0): """ INPUTS: ======= num_pulses : int number of pulses to be emitted func : callable function to execute at each pulse ATTRIBUTES: self.num_pulses : int number of pulses self.func : callable function to execute self.counter : int total number of pulses emmitted by the Pulser object """ # Raise TypeError if num_pulses are not an integer if type(num_pulses) != int: raise TypeError('num_pulses must be an \'int\' type') elif num_pulses < 0: raise ValueError('num_pulses must be a positive number') self.num_pulses = num_pulses self.func = func # Raise Error if wait not correctly specified if type(wait) not in (int, float): raise TypeError('\'wait\' must be a number (int or float)') elif wait < 0: raise ValueError('num_pulses must be a positive number') self.wait = wait self.counter = 0 def pulse(self, *func_args, **func_kwargs): """ This creates a iteractor object that yields i-th iteration index as well as whatever the input function returns INPUTS: *func_args & **func_kwargs: *args, **kwargs *args, **kwargs for self.func """ for i in range(self.num_pulses): time.sleep(self.wait) yield i, self.func(*func_args, **func_kwargs) self.counter += 1 # counter for initial run would equal to i def reset_counter(self): """ Resets the counter attribute to zero """ self.counter = 0 ### END<file_sep>/datafeeder/to_be_deprecated/timer.py import numpy as np import pandas as pd import time from datafeeder.timer.pulser import Pulser class ABCTimer: pass class Timer(ABCTimer): def __init__(self, period, interval=1, unit='min'): self.period = period self.interval = interval self.unit = unit def execute(self): pass # For testing if __name__ == "__main__": pass <file_sep>/datafeeder/plotter.py import numpy as np import pandas as pd import matplotlib.pyplot as plt from datafeeder.feeder import ( ABCFeeder, SingleRowFeeder, MultiRowFeeder, MultiSourceFeeder) class Plotter: """ Class to create a plotter, that plots a point whose data are to be fed by a feeder. """ @staticmethod def create_figure(figsize=(10, 6)): """ Just creates a plain fig and ax objects using plt.subplots() INPUT: ====== figsize : tuple figsize parameter for plt.subplots() OUTPUT: fig : matplotlib figure object ax : matplotlib axis object associated with fig """ fig, ax = plt.subplots(1, 1, figsize=figsize) return fig, ax def __init__(self, ax=None, pause=1e-12, title='',xlabel='', ylabel='', grid=True, xlim=None, ylim=None, **axis_kwargs): """ Instantiation sets 'pause' parameter that sets the time interval between plots. It also creates an axes.Axes object if not specified. """ self.pause = pause if ax is None: self.fig, self.ax = self.create_figure() else: self.ax = ax def format_axis(self, title='',xlabel='', ylabel='', grid=True, xlim=None, ylim=None, **axis_kwargs): """ This function takes in a matplotlib axes.Axes object and formats it. """ self.ax.set_title(title) self.ax.set_xlabel(xlabel) self.ax.set_ylabel(ylabel) if xlim: self.ax.set_xlim(xlim) if ylim: self.ax.set_ylim(ylim) if grid and type(grid) == dict: self.ax.grid(grid) elif grid: self.ax.grid(color='0.7', ls=':') def scatter(self, x, y, **scatter_kwargs): """ scatter plot a single point with a pause """ plt.pause(self.pause) self.ax.scatter(x, y, **scatter_kwargs) class FeedPlotter: def __init__(self, feeder, plotter): """ INPUTS: feeder : iterable Feeder object Feeder object plotter : Plotter object Plotter object """ if not isinstance(feeder, ABCFeeder): raise TypeError('feeder input must be a Feeder object') # Set up a Feeder self.feeder = feeder self.plotter = plotter def scatter(self, **scatter_kwargs): """ Use Feeder object as an iterator and Plotter object as the plotter to plot each time point in the data. """ for feed in self.feeder: self.plotter.scatter(feed[0], feed[1], **scatter_kwargs) plt.show() ### END<file_sep>/tests/test_datasource.py # To be run from the directory with __main__() from datafeeder.datasource import SingleSource, MultiSource import pandas as pd import numpy as np import unittest source1 = [ {'time': 0, 'open':100, 'close': 101}, {'time': 1, 'open':101, 'close': 105}, {'time': 2, 'open':104, 'close': 102}, {'time': 3, 'open':103, 'close': 101}, {'time': 4, 'open':102, 'close': 107} ] source2 = [ {'time': 0, 'open':120, 'close': 121}, {'time': 1, 'open':121, 'close': 125}, {'time': 2, 'open':124, 'close': 122}, {'time': 3, 'open':123, 'close': 121}, {'time': 4, 'open':122, 'close': 127} ] source1 = pd.DataFrame(source1) source2 = pd.DataFrame(source2) sources = {'src1':source1, 'src2':source2} class TestSingleSource(unittest.TestCase): def test_attributes(self): src = SingleSource(source1, name='test1', cols=['time', 'close']) self.assertTrue(isinstance(src, SingleSource)) self.assertEqual(src.name, 'test1') self.assertSequenceEqual(src.column_names, ['time', 'close']) self.assertEqual(src.size, 5) def test_retrieve_row(self): src = SingleSource(source1, name='test1', cols=['time', 'close']) data_0 = src.retrieve_data(0) self.assertSequenceEqual(data_0, (0, 101)) def test_retrieve_rows(self): src = SingleSource(source1, name='test1', cols=['time', 'close']) ind = 0 num_rows = 3 data_03 = src.retrieve_data(ind, num_rows) self.assertTrue(isinstance(data_03, list)) self.assertEqual(len(data_03), num_rows) self.assertSequenceEqual(data_03[0], (0, 101)) self.assertSequenceEqual(data_03[1], (1, 105)) self.assertSequenceEqual(data_03[2], (2, 102)) class TestMultiSource(unittest.TestCase): def test_attributes(self): src = MultiSource(sources, cols=['time', 'close']) self.assertTrue(isinstance(src, MultiSource)) self.assertTrue(isinstance(src.sources, list)) self.assertTrue(all(isinstance(s, SingleSource) for s in src.sources)) self.assertSequenceEqual(src.names, ['src1', 'src2']) def test_retrieve_row(self): src = MultiSource(sources, cols=['time', 'close']) data_0 = src.retrieve_data(0) self.assertSequenceEqual(data_0['src1'], (0, 101)) self.assertSequenceEqual(data_0['src2'], (0, 121)) def test_retrieve_rows(self): src = MultiSource(sources, cols=['time', 'close']) ind = 0 num_rows = 3 data_03 = src.retrieve_data(ind, num_rows) self.assertTrue(isinstance(data_03, dict)) self.assertEqual(len(data_03), 2) self.assertEqual(len(data_03['src1']), num_rows) self.assertEqual(len(data_03['src2']), num_rows) self.assertSequenceEqual(data_03['src1'][0], (0, 101)) self.assertSequenceEqual(data_03['src1'][1], (1, 105)) self.assertSequenceEqual(data_03['src1'][2], (2, 102)) self.assertSequenceEqual(data_03['src2'][0], (0, 121)) self.assertSequenceEqual(data_03['src2'][1], (1, 125)) self.assertSequenceEqual(data_03['src2'][2], (2, 122)) if __name__ == '__main__': unittest.main()
4c08df2dbded884c692a76b4c852f24589204217
[ "Python" ]
10
Python
TangoJP/datafeeder
80d89e8366ac73fd4b2ed08c61fe1a15b29e2ed8
004505be5db5c9a2b3fb0f9317436b6bc1ab9b44
refs/heads/main
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task01 { class Program { static void Main(string[] args) //1. Из пяти целых положительных чисел найти два наибольших. { { int max = 0; int max2 = 0; Console.WriteLine("Введите первое число: "); int C1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите второе число: "); int C2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите третье число: "); int C3 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите четвертое число: "); int C4 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Введите пятое число: "); int C5 = Convert.ToInt32(Console.ReadLine()); if (max < C1) { max = C1; } if (max < C2) { max = C2; } if (max < C3) { max = C3; } if (max < C4) { max = C4; } if (max < C5) { max = C5; } if (max != C1 && max2 < C1) { max2 = C1; } if (max != C2 && max2 < C2) { max2 = C2; } if (max != C3 && max2 < C3) { max2 = C3; } if (max != C4 && max2 < C4) { max2 = C4; } if (max != C5 && max2 < C5) { max2 = C5; } Console.WriteLine("Первое максимальное число: {0} \n Второе максимальное число: {1} ", max, max2); Console.ReadKey(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task02 { class Program { static void Main(string[] args) { int c1 = 0; int c2 = 0; int c3 = 0; int c4 = 0; Console.WriteLine("Введите четырехзначное число (>0):"); int chis = Convert.ToInt32(Console.ReadLine()); c1 = chis / 1000; chis = chis - c1 * 100; c2 = chis / 100; chis = chis - c2 * 10; c3 = chis / 10; chis = chis - c3 * 10; c4 = chis; if (c1 != c2 && c2 != c3 && c3 != c1 && c1 != c4 && c2 != c4 && c3 != c4) { Console.WriteLine("Высказывание верное!"); } else { Console.WriteLine("Высказывание неверное!"); } } } }
ad873eda7b282d7f599ae4633eb4a9fad3044be3
[ "C#" ]
2
C#
MidLut16/PR11
ce4b0537fcbb57bb400ee9447d86dc5a787210be
3fafe87575eec0b370ebbb902356e11c0c9a5c16
refs/heads/master
<file_sep>import React from 'react'; export default class UserPage extends React.Component { render() { return ( <div> <h2>User Page View</h2> </div> ); } }
889a5afb14f25776070e3bcd6651d205f1c744c9
[ "JavaScript" ]
1
JavaScript
pshvedov/webr
73ffa1f21a4d8769c5f080c3493bd0434a07d486
9f1b53631b1c5892b75887e9fdcdbf5b0c3c48ce
refs/heads/master
<file_sep>import React from 'react'; import Video from './Video'; const VideoList = ({ videos, onVideoSelect }) => { const renderVideoList = videos.map(video => { return <Video onVideoSelect={onVideoSelect} video={video} />; }); return <div className="collection">{renderVideoList}</div>; }; export default VideoList; <file_sep>import React from 'react'; import './Style.css'; class SearchBar extends React.Component { state = { term: '' }; onInputChange = e => { this.setState({ term: e.target.value }); }; onFormSubmit = e => { e.preventDefault(); this.props.onFormSubmit(this.state.term); }; render() { return ( <section className="section section-search red darken-4 white-text center"> <div className="container"> <div className="row"> <div className="col s12"> <h4 className="left-align">YouTuber</h4> <div className="nav-wrapper"> <form onSubmit={this.onFormSubmit}> <div className="input-field"> <input className="white grey-text autocomplete" placeholder=" Watch Something Now!" type="search" id="search" value={this.state.term} onChange={this.onInputChange} /> <label className="label-icon red-text"> <i className="material-icons">search</i> </label> </div> </form> </div> </div> </div> </div> </section> ); } } export default SearchBar;
d123076a2b4f978ba0b176e1863aa43a3ef57643
[ "JavaScript" ]
2
JavaScript
Harvey783/YouTuber
e8dabc5d448334b4bd25264107888a4a6e20b651
8342fcce677fbb1f3ecbd63362530e2bd86fb50c
refs/heads/main
<file_sep><?php include_once(__DIR__ . "./Item.php"); include_once(__DIR__ . "./User.php"); class Box{ private $items; private $users; private $location; private $id; public function loadUsers($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from user where box_id = :box_id"); $statement->bindValue(":box_id", $id); $statement->execute(); $result = $statement->fetchAll(PDO::FETCH_ASSOC); return $result; } public function loadAll(){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from box"); $statement->execute(); $result = $statement->fetchAll(PDO::FETCH_ASSOC); return $result; } public function getInfo($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from box where id = :id"); $statement->bindValue(":id", $id); $statement->execute(); $result = $statement->fetch(); return $result; } public function isSet($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select box_id from user where id = :id"); $statement->bindValue(':id', $id); $statement->execute(); $result = $statement->fetch(); return $result; } }<file_sep><?php include_once(__DIR__ . "/classes/Item.php"); session_start(); $id = $_SESSION['id']; if(!empty($_POST)){ try { $i = new Item(); $i->setDescription($_POST['description']); $i->setName($_POST['name']); $i->setQuality($_POST['quality']); $i->addItem(); }catch(\throwable $th){ $error = $th->getMessage(); } } ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>add an item</title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>add an item</h1> </section> <?php if(isset($error)): ?> <div class="error"> <?php echo $error ?> </div> <?php endif; ?> <section class="upload"> <form action="" method="post"> <label for="">item name</label> <input type="text" name="name"> <label for="">item description</label> <input type="text" name="description"> <label for="state">state of the item</label> <select name="quality" id="state"> <option value="damaged">damaged</option> <option value="surface damage">surface damage</option> <option value="almost new">almost new</option> <option value="new">new</option> </select> <label for="">available till</label> <input type="date"> <input type="submit" value="add item to borrow box"> </form> </section> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.9.5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Apr 29, 2021 at 09:24 AM -- Server version: 5.7.24 -- PHP Version: 7.4.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `borrowbox_db` -- -- -------------------------------------------------------- -- -- Table structure for table `box` -- CREATE TABLE `box` ( `id` int(11) NOT NULL, `items` int(11) NOT NULL, `users` int(11) NOT NULL, `location` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `item` -- CREATE TABLE `item` ( `id` int(11) NOT NULL, `name` varchar(255) NOT NULL, `description` text NOT NULL, `posted_by` int(11) NOT NULL, `quality` varchar(255) NOT NULL, `available` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `id` int(11) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `street` varchar(255) NOT NULL, `housenumber` int(11) NOT NULL, `postalcode` int(11) NOT NULL, `city` varchar(255) NOT NULL, `picture` varchar(300) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Indexes for dumped tables -- -- -- Indexes for table `box` -- ALTER TABLE `box` ADD PRIMARY KEY (`id`); -- -- Indexes for table `item` -- ALTER TABLE `item` ADD PRIMARY KEY (`id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `box` -- ALTER TABLE `box` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `item` -- ALTER TABLE `item` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php include_once(__DIR__ . "/classes/User.php"); $id = $_GET['id']; $u = new User(); $info = $u->getInfo($id); $items = $u->getItems($id); ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>profile</title> </head> <body> <header> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>inventory</h1> </section> <h1>profile</h1> </header> <section class="info"> <img src="#" alt="profile picture"> <h3>name</h3> <p><span class="bold">adress: </span><?php echo $info['street']; ?> - <?php echo $info['city'] ?></p> <p><span class="bold">email: </span><?php echo $info["email"] ?></p> <p><span class="bold">telephone number: </span><?php echo $info["phone_number"] ?></p> <p><span class="bold">age: </span>20 years</p> </section> <section class="itemsUsed"> <?php foreach($items as $item): ?> <div class="item"> <h3><?php echo $item["name"]; ?></h3> <p><?php echo $item["description"]; ?></p> </div> <?php endforeach; ?> </section> <script src="navigation.js"></script> </body> </html><file_sep><?php include_once(__DIR__ . '/classes/Item.php'); include_once(__DIR__ . '/classes/Use_item.php'); session_start(); $id = $_SESSION['id']; $item = new Item(); $u = new Use_item(); $uses = $u->getUsesFromUser($id); if(!empty($_POST)){ $u->removeUse($id, $_POST['item']); $item->setItemAvailable($_POST['item']); } ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>return item</title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>return item</h1> </section> <section> <form action="" method="post"> <label for="item">select the item you want to return</label> <select name="item" id="item"> <?php foreach($uses as $u): ?> <option value="<?php $info = $item->getInfo($u["item_id"]); echo $u["item_id"]; ?>"><?php echo $info["name"]; ?></option> <?php endforeach; ?> </select> <label for="check">I return in this item in the state I got it</label> <input type="checkbox" name="state" id="check"> <label for="description">If not, what is wrong with it?</label> <input type="text" name="description" id="description"> <img src="#" alt="qr code"> <input type="submit" value="return this item to the box" name="submit"> </form> </section> </body> </html><file_sep><?php include_once(__DIR__ . '/classes/Box.php'); session_start(); $box = new Box(); $id = $_SESSION['id']; $boxId = $_SESSION['box_id']; $boxInfo = $box->getInfo($boxId); $boxAdress = $boxInfo["location"]; ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>box info</title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>box info</h1> </section> <a href="boxUsers.php">users of this box</a> <a href="returnItem.php">return item</a> <a href="addItem.php">add item</a> <a href="#">location of the box</a> <a href="switchBox.php">switch from box</a> <script src="navigation.js"></script> </body> </html><file_sep><?php session_start(); include_once(__DIR__ . "/classes/Box.php"); include_once(__DIR__ . "/classes/User.php"); $u = new User(); $b = new Box(); $userId = $u->getId(); $boxId = $_GET["id"]; $info = $b->getInfo($boxId); if(!empty($_POST)){ $u->linkBox($boxId, $userId); header("location: index.php"); } ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>box detail</title> </head> <body> <form action="" method="post"> <h1><?php echo $info['name'] ?></h1> <h2><?php echo $info['location'] ?></h2> <label for="useBox">Are you sure you want to use this box?</label> <input type="submit" value="use this box!" id="useBox" name="submit"> </form> </body> </html><file_sep><?php include_once(__DIR__ . "/classes/Box.php"); include_once(__DIR__ . "/classes/User.php"); session_start(); $b = new Box(); $u = new User(); $boxId = $_SESSION["box_id"]; $id = $_SESSION ["id"]; $users = $b->loadUsers($boxId); ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>box users</title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>users of this box</h1> </section> <section class="users"> <?php foreach($users as $user): ?> <a href="profile.php?id=<?php echo $user['id']?>"> <div class="user"> <img src="#" alt="profile pic"> <h3><?php echo $user["first_name"] ?></h3> <p><?php echo $user["last_name"] ?></p> <p><?php echo $user["email"] ?></p> </div> </a> <?php endforeach; ?> </section> <script src="navigation.js"></script> </body> </html><file_sep><?php include_once(__DIR__ . "/Item.php"); include_once(__DIR__ . "/User.php"); class Use_item{ private $user_id; private $item_id; /** * @return mixed */ public function getItemId() { return $this->item_id; } /** * @param mixed $item_id */ public function setIteId($item_id): void { $this->item_id = $item_id; } /** * @return mixed */ public function getUserId() { return $this->user_id; } /** * @param mixed $user_id */ public function setUserId($user_id): void { $this->user_id = $user_id; } public function useItem($id, $itemId){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("insert into use_item (user_id, item_id) values (:id, :item_id)"); $statement->bindValue(":id", $id); $statement->bindValue(":item_id", $itemId); $result = $statement->execute(); return $result; } public function removeUse($id, $itemId){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("delete from use_item where (user_id, item_id) = (:id, :item_id)"); $statement->bindValue(":id", $id); $statement->bindValue(":item_id", $itemId); $result = $statement->execute(); return $result; } public function getUsesFromUser($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from use_item where user_id = :id"); $statement->bindValue(":id", $id); $statement->execute(); $result = $statement->fetchAll(PDO::FETCH_ASSOC); return $result; } }<file_sep><?php include_once(__DIR__ . "/classes/Item.php"); include_once(__DIR__ . "/classes/User.php"); session_start(); $id = $_SESSION['id']; $item = new Item(); $boxId = $_SESSION['box_id']; $availableItems = $item->getAllAvailable($boxId); $notAvailableItems = $item->getAllNotAvailable($boxId); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>inventory</title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>inventory</h1> </section> <div class="search__item"> <form action="" method="post"> <input type="text" name="search" placeholder="look for an item in this box"> <input type="submit" value="search"> </form> </div> <section class="available"> <?php foreach($availableItems as $i): ?> <div class="item"> <a href="details.php?id=<?php echo $i['id']?>"> <img src="#" alt="profilepicture"> <div class="info"> <h3><?php echo $i["name"]; ?></h3> <p><?php echo $i["description"] ?></p> </div> </a> </div> <?php endforeach; ?> </section> <section class="notAvailable"> <?php foreach($notAvailableItems as $ni): ?> <div class="item"> <img src="#" alt="profilepicture"> <div class="info"> <h3><?php echo $ni["name"]; ?></h3> <p><?php echo $ni["description"]; ?></p> </div> </div> <?php endforeach; ?> </section> <div class="plus"> add button </div> <script src="navigation.js"></script> </body> </html><file_sep><?php include_once(__DIR__ . "/classes/Item.php"); include_once(__DIR__ . "/classes/Use_item.php"); session_start(); $i = new Item(); $u = new Use_item(); $itemId = $_GET['id']; $info = $i->getInfo($itemId); $id = $_SESSION['id']; if (!empty($_POST)){ $i->setUnavailable($itemId); $u->UseItem($id, $itemId); } ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>use item</title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>Select a box</h1> </section> <section> <p><span class="bold">item I want to use: </span><?php echo $info['name']; ?></p> <p><span class="bold">use till: </span>hier nog iets invullen!!!!</p> <img src="#" alt="QR-code"> <form action="" method="post"> <input type="submit" value="confirm" name="submit"> </form> </section> </body> </html><file_sep><?php include_once(__DIR__ . "/classes/Item.php"); session_start(); $id = $_SESSION['id']; $i = new Item(); $info = $i->getInfo($_GET['id']); $owner = $i->getUser($info["posted_by"]); ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title><?php echo $info['name']; ?></title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1><?php echo $info["name"]; ?></h1> </section> <section class="info"> <p><span class="bold">specifications: </span><?php echo $info['name']?></p> <p><span class="bold">added by: </span><?php echo $owner ?></p> <p><span class="bold">description: </span><?php echo $info["description"]?></p> <p><span class="bold">available till: </span></p> <a href="useItem.php?id=<?php echo $_GET['id']; ?>">I want to use this item</a> <a href="report.php?id=<?php echo $_GET['id'] ?>">report this item</a> </section> </body> </html><file_sep><?php include_once(__DIR__ . "/classes/User.php"); include_once(__DIR__ . "/classes/Box.php"); if(!empty($_POST)){ $user = new User(); $box = new Box(); $user->setEmail($_POST['email']); $user->setPassword($_POST['password']); try{ if($user->canLogin()){ session_start(); $_SESSION['email'] = $_POST['email']; $_SESSION['id'] = $user->getId(); var_dump($_SESSION["id"]); $_SESSION["box_id"] = $user->getBoxId($_POST["email"]); $boxSet = $box->isSet($user->getId()); if($boxSet["box_id"] === null){ header("location: selectBox.php"); }else{ header("location: index.php"); } } }catch(\Throwable $th){ $error = $th->getMessage(); } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>login page</title> </head> <body> <div class="logo">hier komt logo in</div> <form action="" method="post"> <input type="email" placeholder="email" name="email"> <input type="<PASSWORD>" placeholder="<PASSWORD>" name="<PASSWORD>"> <input type="submit" name="login" value="login"> </form> <?php if(!empty($error)): ?> <div class="error"> <?php echo $error?> </div> <?php endif; ?> </body> </html><file_sep><?php include_once(__DIR__ . "/classes/Item.php"); session_start(); $id = $_SESSION['id']; $i = new Item(); $info = $i->getInfo($_GET['id']); if(!empty($_POST)){ $i->reportItem($_GET['id']); } ?><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>report item</title> </head> <body> <section class="header"> <div> <a href="#" id="navbar"> <img src="./Hamburger_icon.svg%20(1).png" alt="hamburger icon"> </a> </div> <section class="navItems"> <a href="index.php">inventory</a> <a href="profile.php?id=<?php echo $id ?>">profile</a> <a href="boxInfo.php">box info</a> <a href="logout.php">logout</a> </section> <h1>report item</h1> </section> <section> <h2><?php echo $info["name"]; ?></h2> <form action="" method="post"> <label for="">what is wrong with the item?</label> <input type="text" name="description"> <input type="submit" value="report item" name="submit"> </form> </section> </body> </html><file_sep><?php include_once(__DIR__ . "/classes/User.php"); if(!empty($_POST)){ $user = new User(); $user ->setPassword($_POST["<PASSWORD>"]); $user->setEmail($_POST["email"]); $user->setFirstname($_POST['firstname']); $user->setLastname($_POST['lastname']); $user->setStreetname($_POST['streetname']); $user->setCity($_POST['city']); $user->register(); $_SESSION['email'] = $_POST['email']; var_dump($_SESSION); header("location: selectBox.php"); } ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div class="logo">hier komt logo in</div> <a href="login.php">log in with existing account</a> <h3>or make a new account</h3> <form action="" method="post"> <input type="text" name="firstname" placeholder="firstname"> <input type="text" name="lastname" placeholder="lastname"> <input type="text" name="email" placeholder="email"> <input type="number" name="phonenumber" placeholder="phone number"> <input type="text" name="streetname" placeholder="streetname"> <input type="text" name="city" placeholder="city"> <input type="password" name="password" placeholder="<PASSWORD>">µ <input type="submit" value="next step"> </form> </body> </html><file_sep><?php include_once(__DIR__ . "/User.php"); class Item{ private $name; private $description; private $owner; private $available; private $quality; private $box; /** * @return mixed */ public function getBox() { return $this->box; } /** * @param mixed $box */ public function setBox($box): void { $this->box = $box; } /** * @return mixed */ public function getAvailable() { return $this->available; } /** * @param mixed $available */ public function setAvailable($available): void { $this->available = $available; } /** * @return mixed */ public function getOwner() { return $this->owner; } /** * @param mixed $owner */ public function setOwner($owner): void { $this->owner = $owner; } /** * @return mixed */ public function getQuality() { return $this->quality; } /** * @param mixed $quality */ public function setQuality($quality): void { $this->quality = $quality; } /** * @return mixed */ public function getDescription() { return $this->description; } /** * @param mixed $description */ public function setDescription($description): void { $this->description = $description; } /** * @return mixed */ public function getName() { return $this->name; } /** * @param mixed $name */ public function setName($name): void { $this->name = $name; } public function getAllAvailable($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from item where (available) = true and box_id = (:id) and report = 0"); $statement->bindValue(":id", $id); $statement->execute(); $result = $statement->fetchAll(PDO::FETCH_ASSOC); return $result; } public function getAllNotAvailable($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from items where (available) = 0 and box_id = (:id) and report = 0"); $statement->bindValue(":id", $id); $statement->execute(); $result = $statement->fetchAll(PDO::FETCH_ASSOC); return $result; } public function addItem(){ session_start(); $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("insert into item (name, description, posted_by, quality, available, box_id) values (:name, :description, :posted_by, :quality, true, :box_id)"); $statement->bindValue("name", $this->getName()); $statement->bindValue(":description", $this->getDescription()); $statement->bindValue(':posted_by', $_SESSION['id']); $statement->bindValue(":quality", $this->getQuality()); $statement->bindValue(":box_id", "1"); $result = $statement->execute(); if ($result){ return $result; }else{ throw new Exception("something went wrong while adding your item"); } } public function getInfo($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from item where id = :id and report = 0"); $statement->bindValue(":id", $id); $statement->execute(); $result = $statement->fetch(); return $result; } public function getUser($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select first_name from user where id = :id"); $statement->bindValue(":id", $id); $statement->execute(); $result = $statement->fetch(); return $result["first_name"]; } public function setUnavailable($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("update item set available = 0 where id = :id"); $statement->bindValue(":id", $id); $result = $statement->execute(); return $result; } public function setItemAvailable($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("update item set available = 1 where id = :id"); $statement->bindValue(":id", $id); $result = $statement->execute(); return $result; } public function reportItem($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("update item set report = 1 where id = :id"); $statement->bindValue(":id", $id); $result = $statement->execute(); return $result; } } ?><file_sep><?php class User{ private $firstname; private $lastname; private $email; private $password; private $streetname; private $housenumber; private $postalcode; private $city; private $picture; private $id; private $box; private $phoneNumber; /** * @return mixed */ public function getPhoneNumber() { return $this->phoneNumber; } /** * @param mixed $phoneNumber */ public function setPhoneNumber($phoneNumber): void { $this->phoneNumber = $phoneNumber; } /** * @return mixed */ public function getPicture() { return $this->picture; } /** * @param mixed $picture */ public function setPicture($picture): void { $this->picture = $picture; } /** * @return mixed */ public function getCity() { return $this->city; } /** * @param mixed $city */ public function setCity($city): void { $this->city = $city; } /** * @return mixed */ public function getPostalcode() { return $this->postalcode; } /** * @param mixed $postalcode */ public function setPostalcode($postalcode): void { $this->postalcode = $postalcode; } /** * @return mixed */ public function getHousenumber() { return $this->housenumber; } /** * @param mixed $housenumber */ public function setHousenumber($housenumber): void { $this->housenumber = $housenumber; } /** * @return mixed */ public function getStreetname() { return $this->streetname; } /** * @param mixed $streetname */ public function setStreetname($streetname): void { $this->streetname = $streetname; } /** * @return mixed */ public function getLastname() { return $this->lastname; } /** * @param mixed $lastname */ public function setLastname($lastname): void { $this->lastname = $lastname; } /** * @return mixed */ public function getBox() { return $this->box; } /** * @param mixed $box */ public function setBox($box): void { $this->box = $box; } /** * @return mixed */ public function getId() { session_start(); $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select id from user where email = :email"); $statement->bindValue(':email', $_SESSION['email']); $statement->execute(); $result = $statement->fetch(); return $result['id']; } /** * @param mixed $id */ public function setId($id): void { $this->id = $id; } /** * @return mixed */ public function getFirstname() { return $this->firstname; } /** * @param mixed $firstname */ public function setFirstname($firstname): void { $this->firstname = $firstname; } /** * @return mixed */ public function getEmail() { return $this->email; } /** * @param mixed $email */ public function setEmail($email): void { $this->email = $email; } /** * @return mixed */ public function getPassword() { return $this->password; } /** * @param mixed $password */ public function setPassword($password): void { $this->password = $password; } public function canLogin(){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from user where (email) = (:email)"); $statement->bindValue(":email", $this->getEmail()); $statement->execute(); $result = $statement->fetch(); $password = $this->getPassword(); $hash = $result["password"]; if(password_verify($password, $hash)){ return true; }else{ return false; throw new Exception("password is not correct"); } } public function register(){ $options = [ "cost" => 14 ]; $password = password_hash($this->getPassword(), PASSWORD_DEFAULT, $options); $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("insert into user (email, password, firstname, lastname, city, street phone_number) values (:email, :password, :firstname, :lastname, :city, :streetname, :phonenumber)"); echo "test het werkt denk ik"; $statement->bindValue(":email", $this->getEmail()); $statement->bindValue(":firstname", $this->getFirstname()); $statement->bindValue(":lastname", $this->getLastname()); $statement->bindValue(":city", $this->getCity()); $statement->bindValue(":streetname", $this->getStreetname()); $statement->bindValue(":phonenumber", $this->getPhoneNumber()); $statement->bindValue(":password", $password); return $statement->execute(); } public function getBoxId($email){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select box_id from user where email = :email"); $statement->bindValue(":email", $email); $statement->execute(); $result = $statement->fetch(); return $result["box_id"]; } public function getInfo($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from user where id = :id"); $statement->bindValue(":id",$id); $statement->execute(); $result = $statement->fetch(); return $result; } public function getItems($id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("select * from item where posted_by = :id and report = 0"); $statement->bindValue(":id", $id); $statement->execute(); $result = $statement->fetchAll(PDO::FETCH_ASSOC); return $result; } public function linkBox($box_id, $user_id){ $conn = new PDO('mysql:host=localhost;dbname=borrowbox_db', "root", "root"); $statement = $conn->prepare("UPDATE user SET box_id = (:box_id) WHERE user.id = (:user_id)"); $statement->bindValue(":box_id", $box_id); $statement->bindValue(":user_id", $user_id); $result = $statement->execute(); var_dump($result); return $result; } }<file_sep>let clicked = 0; document.querySelector("#navbar").addEventListener("click", (e)=>{ let navigation = document.querySelector(".navItems"); e.preventDefault(); switch(clicked){ case 0: navigation.style = "display: block;" console.log(clicked + "display block") clicked = 1; break; case 1: navigation.style = "display: none;" console.log(clicked) clicked = 0; break } });
38f5c8869cbe7cde96c1de91efade9bd6fcfa91e
[ "JavaScript", "SQL", "PHP" ]
18
PHP
BramCooper/borrow-box
e11a96aed84c41a51d09b61cdc69c24d8041c6ed
06ed9f1bbbc7616d7265db7545bda6746267a566
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Base classes standardizing some Qt signals. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtCore # NOTE: http://stackoverflow.com/questions/9957195/updating-gui-elements-in-multithreaded-pyqt class SignalingThread(QtCore.QThread): """ Mixin that serves to standardize how we use signals to pass information around """ # Signal to indicate success done = QtCore.pyqtSignal(object) def __del__(self): self.wait() class SignalingObject(QtCore.QObject): """ Mixin for other objects that manage threaded work, and need to signal completion """ # Signal to indicate success done = QtCore.pyqtSignal(object) <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyweed/gui/uic/SpinnerWidget.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_SpinnerWidget(object): def setupUi(self, SpinnerWidget): SpinnerWidget.setObjectName(_fromUtf8("SpinnerWidget")) SpinnerWidget.resize(306, 207) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Ignored, QtGui.QSizePolicy.Ignored) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(SpinnerWidget.sizePolicy().hasHeightForWidth()) SpinnerWidget.setSizePolicy(sizePolicy) SpinnerWidget.setStyleSheet(_fromUtf8("QFrame { background-color: rgba(224,224,224,192)} \n" "QLabel { background-color: transparent }")) self.verticalLayout = QtGui.QVBoxLayout(SpinnerWidget) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.icon = QtGui.QLabel(SpinnerWidget) self.icon.setText(_fromUtf8("")) self.icon.setAlignment(QtCore.Qt.AlignBottom|QtCore.Qt.AlignHCenter) self.icon.setObjectName(_fromUtf8("icon")) self.verticalLayout.addWidget(self.icon) self.label = QtGui.QLabel(SpinnerWidget) self.label.setText(_fromUtf8("")) self.label.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop) self.label.setObjectName(_fromUtf8("label")) self.verticalLayout.addWidget(self.label) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.cancelButton = QtGui.QPushButton(SpinnerWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.cancelButton.sizePolicy().hasHeightForWidth()) self.cancelButton.setSizePolicy(sizePolicy) self.cancelButton.setObjectName(_fromUtf8("cancelButton")) self.horizontalLayout.addWidget(self.cancelButton) self.verticalLayout.addLayout(self.horizontalLayout) self.verticalLayout.setStretch(0, 1) self.verticalLayout.setStretch(1, 1) self.retranslateUi(SpinnerWidget) QtCore.QMetaObject.connectSlotsByName(SpinnerWidget) def retranslateUi(self, SpinnerWidget): SpinnerWidget.setWindowTitle(_translate("SpinnerWidget", "Form", None)) self.cancelButton.setText(_translate("SpinnerWidget", "Cancel", None)) <file_sep># Custom FigureCanvas for displaying Matplotlib output # # https://github.com/krischer/instaseis/blob/master/instaseis/gui/qt4mplcanvas.py from matplotlib import rc as matplotlibrc import matplotlib as mpl from matplotlib.figure import Figure from matplotlib.backends.backend_qt4agg import \ FigureCanvasQTAgg as FigureCanvas mpl.rcParams['font.size'] = 10 matplotlibrc('figure.subplot', left=0.0, right=1.0, bottom=0.0, top=1.0) class MyQt4MplCanvas(FigureCanvas): """ Class to represent the FigureCanvas widget. """ def __init__(self, parent=None): # Standard Matplotlib code to generate the plot self.fig = Figure() # initialize the canvas where the Figure renders into super(MyQt4MplCanvas, self).__init__(self.fig) self.setParent(parent) <file_sep># -*- coding: utf-8 -*- """ Dialog showing logging information. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from pyweed.gui.BaseDialog import BaseDialog from pyweed.gui.uic import LoggingDialog from pyweed.gui.MyTextEditLoggingHandler import MyTextEditLoggingHandler import logging from PyQt4 import QtCore class LoggingDialog(BaseDialog, LoggingDialog.Ui_LoggingDialog): """ Dialog window displaying all logs. """ append = QtCore.pyqtSignal(str) def __init__(self, parent=None): super(LoggingDialog, self).__init__(parent=parent) self.setupUi(self) self.setWindowTitle('Logs') # Initialize loggingPlainTextEdit self.loggingPlainTextEdit.setReadOnly(True) # Add a widget logging handler to the logger loggingHandler = MyTextEditLoggingHandler(signal=self.append) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') loggingHandler.setFormatter(formatter) logging.getLogger().addHandler(loggingHandler) self.append.connect(self.appendMessage) def appendMessage(self, msg): self.loggingPlainTextEdit.appendPlainText(msg) <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyweed/gui/uic/MainWindow.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(1037, 594) MainWindow.setStyleSheet(_fromUtf8("QTableView { gridline-color: gray }")) self.centralwidget = QtGui.QWidget(MainWindow) self.centralwidget.setObjectName(_fromUtf8("centralwidget")) self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget) self.verticalLayout.setContentsMargins(-1, -1, -1, 0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.splitter = QtGui.QSplitter(self.centralwidget) self.splitter.setOrientation(QtCore.Qt.Vertical) self.splitter.setChildrenCollapsible(False) self.splitter.setObjectName(_fromUtf8("splitter")) self.mapFrame = QtGui.QFrame(self.splitter) self.mapFrame.setFrameShape(QtGui.QFrame.StyledPanel) self.mapFrame.setFrameShadow(QtGui.QFrame.Raised) self.mapFrame.setObjectName(_fromUtf8("mapFrame")) self.verticalLayout_4 = QtGui.QVBoxLayout(self.mapFrame) self.verticalLayout_4.setMargin(0) self.verticalLayout_4.setSpacing(0) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.mapCanvas = MyQt4MplCanvas(self.mapFrame) self.mapCanvas.setObjectName(_fromUtf8("mapCanvas")) self.verticalLayout_4.addWidget(self.mapCanvas) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setSpacing(2) self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) spacerItem = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem) self.mapZoomInButton = QtGui.QToolButton(self.mapFrame) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mapZoomInButton.sizePolicy().hasHeightForWidth()) self.mapZoomInButton.setSizePolicy(sizePolicy) self.mapZoomInButton.setObjectName(_fromUtf8("mapZoomInButton")) self.horizontalLayout_3.addWidget(self.mapZoomInButton) self.mapZoomOutButton = QtGui.QToolButton(self.mapFrame) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mapZoomOutButton.sizePolicy().hasHeightForWidth()) self.mapZoomOutButton.setSizePolicy(sizePolicy) self.mapZoomOutButton.setObjectName(_fromUtf8("mapZoomOutButton")) self.horizontalLayout_3.addWidget(self.mapZoomOutButton) self.mapResetButton = QtGui.QToolButton(self.mapFrame) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.mapResetButton.sizePolicy().hasHeightForWidth()) self.mapResetButton.setSizePolicy(sizePolicy) self.mapResetButton.setObjectName(_fromUtf8("mapResetButton")) self.horizontalLayout_3.addWidget(self.mapResetButton) spacerItem1 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_3.addItem(spacerItem1) self.verticalLayout_4.addLayout(self.horizontalLayout_3) self.eventAndStationWidget = QtGui.QWidget(self.splitter) self.eventAndStationWidget.setObjectName(_fromUtf8("eventAndStationWidget")) self.verticalLayout_3 = QtGui.QVBoxLayout(self.eventAndStationWidget) self.verticalLayout_3.setMargin(0) self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.splitter_2 = QtGui.QSplitter(self.eventAndStationWidget) self.splitter_2.setFrameShape(QtGui.QFrame.NoFrame) self.splitter_2.setOrientation(QtCore.Qt.Horizontal) self.splitter_2.setChildrenCollapsible(False) self.splitter_2.setObjectName(_fromUtf8("splitter_2")) self.eventsWidget = QtGui.QWidget(self.splitter_2) self.eventsWidget.setObjectName(_fromUtf8("eventsWidget")) self.eventsLayout = QtGui.QVBoxLayout(self.eventsWidget) self.eventsLayout.setMargin(0) self.eventsLayout.setSpacing(0) self.eventsLayout.setObjectName(_fromUtf8("eventsLayout")) self.eventsButtonLayout = QtGui.QHBoxLayout() self.eventsButtonLayout.setSpacing(12) self.eventsButtonLayout.setObjectName(_fromUtf8("eventsButtonLayout")) self.toggleEventOptions = QtGui.QToolButton(self.eventsWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.toggleEventOptions.sizePolicy().hasHeightForWidth()) self.toggleEventOptions.setSizePolicy(sizePolicy) self.toggleEventOptions.setCheckable(True) self.toggleEventOptions.setChecked(True) self.toggleEventOptions.setObjectName(_fromUtf8("toggleEventOptions")) self.eventsButtonLayout.addWidget(self.toggleEventOptions) self.getEventsButton = QtGui.QPushButton(self.eventsWidget) self.getEventsButton.setDefault(True) self.getEventsButton.setObjectName(_fromUtf8("getEventsButton")) self.eventsButtonLayout.addWidget(self.getEventsButton) self.eventsLayout.addLayout(self.eventsButtonLayout) self.eventsTable = QtGui.QTableWidget(self.eventsWidget) self.eventsTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.eventsTable.setAlternatingRowColors(True) self.eventsTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) self.eventsTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.eventsTable.setShowGrid(False) self.eventsTable.setWordWrap(False) self.eventsTable.setObjectName(_fromUtf8("eventsTable")) self.eventsTable.setColumnCount(0) self.eventsTable.setRowCount(0) self.eventsTable.verticalHeader().setVisible(False) self.eventsLayout.addWidget(self.eventsTable) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.eventSelectionLabel = QtGui.QLabel(self.eventsWidget) self.eventSelectionLabel.setText(_fromUtf8("")) self.eventSelectionLabel.setObjectName(_fromUtf8("eventSelectionLabel")) self.horizontalLayout.addWidget(self.eventSelectionLabel) self.clearEventSelectionButton = QtGui.QToolButton(self.eventsWidget) self.clearEventSelectionButton.setObjectName(_fromUtf8("clearEventSelectionButton")) self.horizontalLayout.addWidget(self.clearEventSelectionButton) self.eventsLayout.addLayout(self.horizontalLayout) self.stationsWidget = QtGui.QWidget(self.splitter_2) self.stationsWidget.setObjectName(_fromUtf8("stationsWidget")) self.stationsLayout = QtGui.QVBoxLayout(self.stationsWidget) self.stationsLayout.setMargin(0) self.stationsLayout.setSpacing(0) self.stationsLayout.setObjectName(_fromUtf8("stationsLayout")) self.stationsButtonLayout = QtGui.QHBoxLayout() self.stationsButtonLayout.setSpacing(12) self.stationsButtonLayout.setObjectName(_fromUtf8("stationsButtonLayout")) self.getStationsButton = QtGui.QPushButton(self.stationsWidget) self.getStationsButton.setDefault(True) self.getStationsButton.setObjectName(_fromUtf8("getStationsButton")) self.stationsButtonLayout.addWidget(self.getStationsButton) self.toggleStationOptions = QtGui.QToolButton(self.stationsWidget) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.toggleStationOptions.sizePolicy().hasHeightForWidth()) self.toggleStationOptions.setSizePolicy(sizePolicy) self.toggleStationOptions.setCheckable(True) self.toggleStationOptions.setChecked(True) self.toggleStationOptions.setObjectName(_fromUtf8("toggleStationOptions")) self.stationsButtonLayout.addWidget(self.toggleStationOptions) self.stationsLayout.addLayout(self.stationsButtonLayout) self.stationsTable = QtGui.QTableWidget(self.stationsWidget) self.stationsTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.stationsTable.setAlternatingRowColors(True) self.stationsTable.setSelectionMode(QtGui.QAbstractItemView.MultiSelection) self.stationsTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.stationsTable.setShowGrid(False) self.stationsTable.setWordWrap(False) self.stationsTable.setObjectName(_fromUtf8("stationsTable")) self.stationsTable.setColumnCount(0) self.stationsTable.setRowCount(0) self.stationsTable.verticalHeader().setVisible(False) self.stationsLayout.addWidget(self.stationsTable) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.stationSelectionLabel = QtGui.QLabel(self.stationsWidget) self.stationSelectionLabel.setText(_fromUtf8("")) self.stationSelectionLabel.setObjectName(_fromUtf8("stationSelectionLabel")) self.horizontalLayout_2.addWidget(self.stationSelectionLabel) self.clearStationSelectionButton = QtGui.QToolButton(self.stationsWidget) self.clearStationSelectionButton.setObjectName(_fromUtf8("clearStationSelectionButton")) self.horizontalLayout_2.addWidget(self.clearStationSelectionButton) self.stationsLayout.addLayout(self.horizontalLayout_2) self.verticalLayout_3.addWidget(self.splitter_2) self.waveformButtonLayout = QtGui.QHBoxLayout() self.waveformButtonLayout.setObjectName(_fromUtf8("waveformButtonLayout")) self.getWaveformsButton = QtGui.QPushButton(self.eventAndStationWidget) self.getWaveformsButton.setDefault(True) self.getWaveformsButton.setObjectName(_fromUtf8("getWaveformsButton")) self.waveformButtonLayout.addWidget(self.getWaveformsButton) self.verticalLayout_3.addLayout(self.waveformButtonLayout) self.verticalLayout_3.setStretch(0, 1) self.verticalLayout.addWidget(self.splitter) MainWindow.setCentralWidget(self.centralwidget) self.eventOptionsDockWidget = QtGui.QDockWidget(MainWindow) self.eventOptionsDockWidget.setFloating(False) self.eventOptionsDockWidget.setFeatures(QtGui.QDockWidget.AllDockWidgetFeatures) self.eventOptionsDockWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea|QtCore.Qt.RightDockWidgetArea) self.eventOptionsDockWidget.setObjectName(_fromUtf8("eventOptionsDockWidget")) self.dockWidgetContents = QtGui.QWidget() self.dockWidgetContents.setObjectName(_fromUtf8("dockWidgetContents")) self.eventOptionsDockWidget.setWidget(self.dockWidgetContents) MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(1), self.eventOptionsDockWidget) self.stationOptionsDockWidget = QtGui.QDockWidget(MainWindow) self.stationOptionsDockWidget.setFloating(False) self.stationOptionsDockWidget.setFeatures(QtGui.QDockWidget.AllDockWidgetFeatures) self.stationOptionsDockWidget.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea|QtCore.Qt.RightDockWidgetArea) self.stationOptionsDockWidget.setObjectName(_fromUtf8("stationOptionsDockWidget")) self.dockWidgetContents_2 = QtGui.QWidget() self.dockWidgetContents_2.setObjectName(_fromUtf8("dockWidgetContents_2")) self.stationOptionsDockWidget.setWidget(self.dockWidgetContents_2) MainWindow.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.stationOptionsDockWidget) self.statusBar = QtGui.QStatusBar(MainWindow) self.statusBar.setObjectName(_fromUtf8("statusBar")) MainWindow.setStatusBar(self.statusBar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) MainWindow.setTabOrder(self.getEventsButton, self.getStationsButton) MainWindow.setTabOrder(self.getStationsButton, self.eventsTable) MainWindow.setTabOrder(self.eventsTable, self.stationsTable) MainWindow.setTabOrder(self.stationsTable, self.getWaveformsButton) MainWindow.setTabOrder(self.getWaveformsButton, self.clearEventSelectionButton) MainWindow.setTabOrder(self.clearEventSelectionButton, self.clearStationSelectionButton) MainWindow.setTabOrder(self.clearStationSelectionButton, self.toggleEventOptions) MainWindow.setTabOrder(self.toggleEventOptions, self.toggleStationOptions) MainWindow.setTabOrder(self.toggleStationOptions, self.mapZoomInButton) MainWindow.setTabOrder(self.mapZoomInButton, self.mapZoomOutButton) MainWindow.setTabOrder(self.mapZoomOutButton, self.mapResetButton) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None)) self.mapZoomInButton.setText(_translate("MainWindow", "Zoom In", None)) self.mapZoomOutButton.setText(_translate("MainWindow", "Zoom Out", None)) self.mapResetButton.setText(_translate("MainWindow", "Reset", None)) self.toggleEventOptions.setText(_translate("MainWindow", "< Options", None)) self.getEventsButton.setText(_translate("MainWindow", "Get Events", None)) self.eventsTable.setSortingEnabled(True) self.clearEventSelectionButton.setText(_translate("MainWindow", "Clear Selection", None)) self.getStationsButton.setText(_translate("MainWindow", "Get Stations", None)) self.toggleStationOptions.setText(_translate("MainWindow", "Options >", None)) self.stationsTable.setSortingEnabled(True) self.clearStationSelectionButton.setText(_translate("MainWindow", "Clear Selection", None)) self.getWaveformsButton.setText(_translate("MainWindow", "Get Waveforms", None)) self.eventOptionsDockWidget.setWindowTitle(_translate("MainWindow", "Event Options", None)) self.stationOptionsDockWidget.setWindowTitle(_translate("MainWindow", "Station Options", None)) from pyweed.gui.uic.MyQt4MplCanvas import MyQt4MplCanvas <file_sep># -*- coding: utf-8 -*- """ Preferences dialog :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui from pyweed.gui.uic import PreferencesDialog from logging import getLogger from obspy.clients.fdsn.header import URL_MAPPINGS from obspy.clients.fdsn.client import Client LOGGER = getLogger(__name__) class PreferencesDialog(QtGui.QDialog, PreferencesDialog.Ui_PreferencesDialog): """ Dialog window for editing preferences. """ def __init__(self, pyweed, parent=None): super(PreferencesDialog, self).__init__(parent=parent) self.setupUi(self) self.pyweed = pyweed # Ordered list of all available data centers self.data_centers = sorted(URL_MAPPINGS.keys()) # Put these in the comboboxes for data_center in self.data_centers: label = "%s: %s" % (data_center, URL_MAPPINGS[data_center]) self.eventDataCenterComboBox.addItem(label, data_center) self.stationDataCenterComboBox.addItem(label, data_center) self.okButton.pressed.connect(self.accept) self.cancelButton.pressed.connect(self.reject) def showEvent(self, *args, **kwargs): """ Perform any necessary initialization each time the dialog is opened """ super(PreferencesDialog, self).showEvent(*args, **kwargs) # Indicate the currently selected data centers self.eventDataCenterComboBox.setCurrentIndex(self.data_centers.index(self.pyweed.event_data_center)) self.stationDataCenterComboBox.setCurrentIndex(self.data_centers.index(self.pyweed.station_data_center)) self.cacheSizeSpinBox.setValue(int(self.pyweed.preferences.Waveforms.cacheSize)) def accept(self): """ Validate and update the client """ try: self.pyweed.set_event_data_center( self.data_centers[self.eventDataCenterComboBox.currentIndex()]) self.pyweed.set_station_data_center( self.data_centers[self.stationDataCenterComboBox.currentIndex()]) except Exception as e: # Error usually means that the user selected a data center that doesn't provide the given service QtGui.QMessageBox.critical( self, "Unable to update data center", str(e) ) # Don't call super() which would close the preferences dialog return self.pyweed.preferences.Waveforms.cacheSize = self.cacheSizeSpinBox.value() return super(PreferencesDialog, self).accept() <file_sep># -*- coding: utf-8 -*- """ Dialog for selecting and downloading waveform data :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore from pyweed.gui.uic import WaveformDialog from pyweed.waveforms_handler import WaveformsHandler from logging import getLogger from pyweed.gui.TableItems import TableItems, Column from pyweed.pyweed_utils import get_event_name, TimeWindow, OUTPUT_FORMATS, PHASES from pyweed.preferences import safe_int from PyQt4.QtGui import QTableWidgetItem from pyweed.gui.Adapters import ComboBoxAdapter from pyweed.gui.BaseDialog import BaseDialog from pyweed.gui.SpinnerWidget import SpinnerWidget from pyweed.gui.TableWidget import CustomTableWidgetItemMixin LOGGER = getLogger(__name__) # Download/save status values STATUS_READY = "ready" # Waiting for user to initiate STATUS_WORKING = "working" # Working STATUS_DONE = "done" # Finished STATUS_ERROR = "error" # Something went wrong class KeepIndicatorTableWidgetItem(CustomTableWidgetItemMixin, QTableWidgetItem): """ Custom QTableWidgetItem that indicates whether the row is included in the request Note that this uses Unicode characters for the checkboxes, this appears to be the easiest way to control the size, and we don't need an actual toggle widget here since that is done at the row level. """ checkedText = '☑' checkedIcon = QtGui.QPixmap(':qrc/check-on.png') uncheckedText = '☐' uncheckedIcon = QtGui.QPixmap(':qrc/check-off.png') fontSize = 36 checkedBackground = QtGui.QBrush(QtGui.QColor(220, 239, 223)) uncheckedBackground = QtGui.QBrush(QtCore.Qt.NoBrush) def __init__(self, value): super(KeepIndicatorTableWidgetItem, self).__init__() self.setKeep(value) # Use a large font size for the checkboxes font = QtGui.QFont() font.setPointSize(self.fontSize) self.setFont(font) def keep(self): return self.data(QtCore.Qt.UserRole) def setKeep(self, value): self.setData(QtCore.Qt.UserRole, value) # Update as needed to indicate the value to the user if value: self.setBackground(self.checkedBackground) self.setData(QtCore.Qt.DecorationRole, self.checkedIcon) else: self.setBackground(self.uncheckedBackground) self.setData(QtCore.Qt.DecorationRole, self.uncheckedIcon) class WaveformTableWidgetItem(CustomTableWidgetItemMixin, QtGui.QTableWidgetItem): """ Custom QTableWidgetItem that shows a waveform image (or a status message) """ imagePath = None errorForeground = QtGui.QBrush(QtGui.QColor(255, 0, 0)) defaultForeground = None def __init__(self, waveform): super(WaveformTableWidgetItem, self).__init__() self.defaultForeground = self.foreground() self.setWaveform(waveform) def setWaveform(self, waveform): if waveform and waveform.error: self.setForeground(self.errorForeground) else: self.setForeground(self.defaultForeground) if waveform: if waveform.loading or waveform.error or not waveform.image_exists: self.imagePath = None self.setData(QtCore.Qt.DecorationRole, None) if waveform.loading: self.setText('Loading waveform data...') elif waveform.error: self.setText(waveform.error) else: self.setText('') else: if waveform.image_path != self.imagePath: self.imagePath = waveform.image_path pic = QtGui.QPixmap(waveform.image_path) self.setData(QtCore.Qt.DecorationRole, pic) self.setText('') else: self.imagePath = None self.setText('') class WaveformTableItems(TableItems): #: Fixed row height based on the height of the waveform image rowHeight = 110 columns = [ Column('Id'), Column('Keep'), Column('Event Time', width=100), Column('Location', width=100), Column('Magnitude'), Column('SNCL'), Column('Distance'), Column('Waveform', width=600), ] def keepWidget(self, keep, **props): return self.applyProps(KeepIndicatorTableWidgetItem(keep), **props) def waveformWidget(self, waveform, **props): return self.applyProps(WaveformTableWidgetItem(waveform), **props) def rows(self, data): """ Turn the data into rows (an iterable of lists) of QTableWidgetItems """ for waveform in data: # Make the time and location wrap yield [ self.stringWidget(waveform.waveform_id), self.keepWidget(waveform.keep, textAlignment=QtCore.Qt.AlignCenter), self.stringWidget(waveform.event_time_str), self.stringWidget(waveform.event_description), self.numericWidget(waveform.event_mag_value, waveform.event_mag, textAlignment=QtCore.Qt.AlignCenter), self.stringWidget(waveform.sncl, textAlignment=QtCore.Qt.AlignCenter), self.numericWidget(waveform.distance, '%.02f°', textAlignment=QtCore.Qt.AlignCenter), self.waveformWidget(waveform), ] # Convenience values for some commonly used table column values _COLUMN_NAMES = [c.label for c in WaveformTableItems.columns] WAVEFORM_ID_COLUMN = _COLUMN_NAMES.index('Id') WAVEFORM_KEEP_COLUMN = _COLUMN_NAMES.index('Keep') WAVEFORM_IMAGE_COLUMN = _COLUMN_NAMES.index('Waveform') class TimeWindowAdapter(QtCore.QObject): """ Adapter tying a set of inputs to a TimeWindow """ # Signal indicating that the time window has changed changed = QtCore.pyqtSignal() def __init__(self, secondsBeforeSpinBox, secondsAfterSpinBox, secondsBeforePhaseComboBox, secondsAfterPhaseComboBox): super(TimeWindowAdapter, self).__init__() self.timeWindow = TimeWindow() # Phase options phaseOptions = [(phase.name, phase.label) for phase in PHASES] self.secondsBeforeSpinBox = secondsBeforeSpinBox self.secondsAfterSpinBox = secondsAfterSpinBox self.secondsBeforePhaseAdapter = ComboBoxAdapter( secondsBeforePhaseComboBox, phaseOptions) self.secondsAfterPhaseAdapter = ComboBoxAdapter( secondsAfterPhaseComboBox, phaseOptions) # Connect input signals self.secondsBeforeSpinBox.valueChanged.connect(self.onTimeWindowChanged) self.secondsAfterSpinBox.valueChanged.connect(self.onTimeWindowChanged) self.secondsBeforePhaseAdapter.changed.connect(self.onTimeWindowChanged) self.secondsAfterPhaseAdapter.changed.connect(self.onTimeWindowChanged) def onTimeWindowChanged(self): """ When an input changes, update the time window and emit a notification """ self.timeWindow.update( self.secondsBeforeSpinBox.value(), self.secondsAfterSpinBox.value(), self.secondsBeforePhaseAdapter.getValue(), self.secondsAfterPhaseAdapter.getValue() ) self.changed.emit() def setValues(self, start_offset, end_offset, start_phase, end_phase): """ This should be called on startup to set the initial values """ self.timeWindow.update( start_offset, end_offset, start_phase, end_phase ) self.updateInputs() def updateInputs(self): """ Update the inputs to reflect the current state """ self.secondsBeforeSpinBox.setValue(self.timeWindow.start_offset) self.secondsAfterSpinBox.setValue(self.timeWindow.end_offset) self.secondsBeforePhaseAdapter.setValue(self.timeWindow.start_phase) self.secondsAfterPhaseAdapter.setValue(self.timeWindow.end_phase) class WaveformDialog(BaseDialog, WaveformDialog.Ui_WaveformDialog): tableItems = None """ Dialog window for selection and display of waveforms. """ def __init__(self, pyweed, parent=None): super(WaveformDialog, self).__init__(parent=parent) LOGGER.debug('Initializing waveform dialog...') self.setupUi(self) self.setWindowTitle('Waveforms') # Keep a reference to globally shared components self.pyweed = pyweed # Time window for waveform selection self.timeWindowAdapter = TimeWindowAdapter( self.secondsBeforeSpinBox, self.secondsAfterSpinBox, self.secondsBeforePhaseComboBox, self.secondsAfterPhaseComboBox ) self.saveFormatAdapter = ComboBoxAdapter( self.saveFormatComboBox, [(f.value, f.label) for f in OUTPUT_FORMATS] ) # Initialize any preference-based settings self.loadPreferences() # Modify default GUI settings self.saveDirectoryPushButton.setText(self.waveformDirectory) self.saveDirectoryPushButton.setFocusPolicy(QtCore.Qt.NoFocus) # Waveforms self.waveforms_handler = WaveformsHandler(LOGGER, pyweed.preferences, pyweed.station_client) # The callbacks here are expensive, so use QueuedConnection to run them asynchronously self.waveforms_handler.progress.connect(self.onWaveformDownloaded, QtCore.Qt.QueuedConnection) self.waveforms_handler.done.connect(self.onAllDownloaded, QtCore.Qt.QueuedConnection) # Spinner overlays for downloading and saving self.downloadSpinner = SpinnerWidget("Downloading...", parent=self.downloadGroupBox) self.downloadSpinner.cancelled.connect(self.onDownloadCancel) self.saveSpinner = SpinnerWidget("Saving...", cancellable=False, parent=self.saveGroupBox) # Connect signals associated with the main table # self.selectionTable.horizontalHeader().sortIndicatorChanged.connect(self.selectionTable.resizeRowsToContents) self.selectionTable.itemClicked.connect(self.handleTableItemClicked) # Connect the Download and Save GUI elements self.downloadPushButton.clicked.connect(self.onDownloadPushButton) self.savePushButton.clicked.connect(self.onSavePushButton) self.saveDirectoryPushButton.clicked.connect(self.getWaveformDirectory) self.saveDirectoryBrowseToolButton.clicked.connect(self.browseWaveformDirectory) self.saveFormatAdapter.changed.connect(self.resetSave) # Connect signals associated with comboBoxes # NOTE: http://www.tutorialspoint.com/pyqt/pyqt_qcombobox_widget.htm # NOTE: currentIndexChanged() responds to both user and programmatic changes. # Use activated() for user initiated changes self.eventComboBox.activated.connect(self.onFilterChanged) self.networkComboBox.activated.connect(self.onFilterChanged) self.stationComboBox.activated.connect(self.onFilterChanged) # Connect the timewindow signals self.timeWindowAdapter.changed.connect(self.resetDownload) # Dictionary of filter values self.filters = {} # Information about download progress self.downloadCount = 0 self.downloadCompleted = 0 LOGGER.debug('Finished initializing waveform dialog') # NOTE: http://stackoverflow.com/questions/12366521/pyqt-checkbox-in-qtablewidget # NOTE: http://stackoverflow.com/questions/30462078/using-a-checkbox-in-pyqt @QtCore.pyqtSlot(QTableWidgetItem) def handleTableItemClicked(self, item): """ Triggered whenever an item in the waveforms table is clicked. """ row = item.row() LOGGER.debug("Clicked on table row") # Toggle the Keep state waveformID = str(self.selectionTable.item(row, WAVEFORM_ID_COLUMN).text()) waveform = self.waveforms_handler.get_waveform(waveformID) waveform.keep = not waveform.keep keepItem = self.selectionTable.item(row, WAVEFORM_KEEP_COLUMN) keepItem.setKeep(waveform.keep) @QtCore.pyqtSlot() def loadWaveformChoices(self): """ Fill the selectionTable with all SNCL-Event combinations selected in the MainWindow. This function is triggered whenever the "Get Waveforms" button in the MainWindow is clicked. """ LOGGER.debug('Loading waveform choices...') self.resetDownload() self.waveforms_handler.create_waveforms(self.pyweed) # Add events to the eventComboBox ------------------------------- self.eventComboBox.clear() self.eventComboBox.addItem('All events') for event in self.pyweed.iter_selected_events(): self.eventComboBox.addItem(get_event_name(event)) # Add networks/stations to the networkComboBox and stationsComboBox --------------------------- self.networkComboBox.clear() self.networkComboBox.addItem('All networks') self.stationComboBox.clear() self.stationComboBox.addItem('All stations') foundNetworks = set() foundStations = set() for (network, station, _channel) in self.pyweed.iter_selected_stations(): if network.code not in foundNetworks: foundNetworks.add(network.code) self.networkComboBox.addItem(network.code) netstaCode = '.'.join((network.code, station.code)) if netstaCode not in foundStations: foundStations.add(netstaCode) self.stationComboBox.addItem(netstaCode) self.loadSelectionTable() # Start downloading data self.downloadWaveformData() LOGGER.debug('Finished loading waveform choices') @QtCore.pyqtSlot() def loadSelectionTable(self): """ Add event-SNCL combinations to the selection table """ LOGGER.debug('Loading waveform selection table...') # Use WaveformTableItems to put the data into the table if not self.tableItems: self.tableItems = WaveformTableItems( self.selectionTable ) self.tableItems.fill(self.iterWaveforms()) self.filterSelectionTable() LOGGER.debug('Finished loading waveform selection table') @QtCore.pyqtSlot(int) def onFilterChanged(self): self.filters = {} self.filterSelectionTable() def filterSelectionTable(self): """ Filter the selection table based on the currently defined filters """ if self.tableItems: if not self.filters: self.filters = { 'event': self.eventComboBox.currentText(), 'network': self.networkComboBox.currentText(), 'station': self.stationComboBox.currentText(), } filterResults = dict( (waveform.waveform_id, self.applyFilter(waveform)) for waveform in self.iterWaveforms() ) def filterFn(row): waveformID = str(self.selectionTable.item(row, WAVEFORM_ID_COLUMN).text()) return filterResults.get(waveformID) self.tableItems.filter(filterFn) def iterWaveforms(self, saveable_only=False): """ Iterate through the waveforms, optionally yielding only the saveable ones """ for waveform in self.waveforms_handler.waveforms: if saveable_only and not (waveform.keep and waveform.mseed_exists): continue yield waveform def applyFilter(self, waveform): """ Apply self.filters to the given waveform @return True iff the waveform should be included """ # Get the values from the waveform to match against the filter value sncl_parts = waveform.sncl.split('.') net_code = sncl_parts[0] netsta_code = '.'.join(sncl_parts[:2]) filter_values = { 'event': get_event_name(waveform.event_ref()), 'network': net_code, 'station': netsta_code } for (fname, fval) in self.filters.items(): if not fval.startswith('All') and fval != filter_values[fname]: return False return True @QtCore.pyqtSlot() def onDownloadPushButton(self): """ Triggered when downloadPushButton is clicked. """ if self.waveformsDownloadStatus == STATUS_READY: # Start the download self.downloadWaveformData() @QtCore.pyqtSlot() def onDownloadCancel(self): if self.waveformsDownloadStatus == STATUS_WORKING: # Cancel running download self.waveforms_handler.cancel_download() def updateToolbars(self): """ Update the UI elements to reflect the current status """ self.downloadPushButton.setEnabled(self.waveformsDownloadStatus == STATUS_READY) @QtCore.pyqtSlot() def onSavePushButton(self): """ Triggered after savePushButton is toggled. """ if self.waveformsSaveStatus != STATUS_WORKING: self.waveformsSaveStatus = STATUS_WORKING self.saveSpinner.show() if self.waveformsDownloadStatus == STATUS_DONE: # If any downloads are complete, we can trigger the save now self.saveWaveformData() else: # Otherwise we have to wait until the download is done, indicate this to the user self.saveSpinner.setLabel("Waiting for downloads to finish") # If not already downloading, try to start if self.waveformsDownloadStatus != STATUS_WORKING: self.downloadWaveformData() @QtCore.pyqtSlot() def resetDownload(self): """ This function is triggered whenever the values in secondsBeforeSpinBox or secondsAfterSpinBox are changed. Any change means that we need to wipe out all the downloads that have occurred and start over. """ LOGGER.debug("Download button reset") self.waveformsDownloadStatus = STATUS_READY self.resetSave() @QtCore.pyqtSlot() def resetSave(self): """ This function is triggered whenever the values in saveDirectory or saveFormat elements are changed. Any change means that we need to start saving from the beginning. """ LOGGER.debug("Save button reset") self.waveformsSaveStatus = STATUS_READY self.updateToolbars() def downloadWaveformData(self): """ This function is triggered after the selectionTable is initially loaded by loadWaveformChoices() and, after that, by handleWaveformResponse() after it has finished handling a waveform. This function looks at the current selectionTable view for any waveforms that have not yet been downloaded. After that table is exhausted, it goes through all not-yet-downloaded data in waveformHandler.currentDF. """ LOGGER.info("Starting download of waveform data") self.waveformsDownloadStatus = STATUS_WORKING self.downloadCount = len(self.waveforms_handler.waveforms) self.downloadCompleted = 0 self.downloadSpinner.show() self.updateToolbars() # Priority is given to waveforms shown on the screen priority_ids = [waveform.waveform_id for waveform in self.waveforms_handler.waveforms] other_ids = [] self.waveforms_handler.download_waveforms( priority_ids, other_ids, self.timeWindowAdapter.timeWindow) # Update the table rows for row in range(self.selectionTable.rowCount()): waveform_id = self.selectionTable.item(row, WAVEFORM_ID_COLUMN).text() waveform = self.waveforms_handler.waveforms_by_id.get(waveform_id) self.selectionTable.item(row, WAVEFORM_IMAGE_COLUMN).setWaveform(waveform) def getTableRow(self, waveform_id): """ Get the table row for a given waveform """ for row in range(self.selectionTable.rowCount()): if self.selectionTable.item(row, WAVEFORM_ID_COLUMN).text() == waveform_id: return row return None @QtCore.pyqtSlot(object) def onWaveformDownloaded(self, result): """ Called each time a waveform request has completed """ waveform_id = result.waveform_id LOGGER.debug("Ready to display waveform %s (%s)", waveform_id, QtCore.QThread.currentThreadId()) self.downloadCompleted += 1 msg = "Downloaded %d of %d" % (self.downloadCompleted, self.downloadCount) # self.downloadStatusLabel.setText(msg) self.downloadSpinner.setLabel(msg) row = self.getTableRow(waveform_id) if row is None: LOGGER.error("Couldn't find a row for waveform %s", waveform_id) return waveform = self.waveforms_handler.waveforms_by_id.get(waveform_id) self.selectionTable.item(row, WAVEFORM_IMAGE_COLUMN).setWaveform(waveform) LOGGER.debug("Displayed waveform %s", waveform_id) @QtCore.pyqtSlot(object) def onAllDownloaded(self, result): """ Called after all waveforms have been downloaded """ LOGGER.debug('COMPLETED all downloads') if self.waveformsDownloadStatus == STATUS_WORKING: self.downloadSpinner.hide() # If normal result, mark as done. If an error, mark as ready (ie. user can download again) if isinstance(result, Exception): self.waveformsDownloadStatus = STATUS_READY else: self.waveformsDownloadStatus = STATUS_DONE self.downloadStatusLabel.setText("Downloaded %d waveforms" % len(self.waveforms_handler.waveforms)) # Initiate save if that was queued if self.waveformsSaveStatus == STATUS_WORKING: self.saveWaveformData() self.updateToolbars() @QtCore.pyqtSlot() def saveWaveformData(self): """ Save waveforms after all downloads are complete. """ # Update status self.waveformsSaveStatus = STATUS_WORKING self.updateToolbars() # Update GUI in case we came from an internal call QtGui.QApplication.processEvents() errors = [] savedCount = 0 skippedCount = 0 try: waveforms = self.iterWaveforms(saveable_only=True) outputDir = self.waveformDirectory outputFormat = self.saveFormatAdapter.getValue() for result in self.waveforms_handler.save_waveforms_iter(outputDir, outputFormat, waveforms): if isinstance(result.result, Exception): LOGGER.error("Failed to save waveform %s: %s", result.waveform_id, result.result) errors.append("%s: %s" % (result.waveform_id, result.result)) elif result.result: savedCount += 1 self.saveSpinner.setLabel("Saved %d waveforms" % savedCount) QtGui.QApplication.processEvents() # update GUI else: skippedCount += 1 self.saveStatusLabel.setText("Saved %d waveforms" % savedCount) self.saveStatusLabel.repaint() LOGGER.info("Save complete: %d saved, %d already existed, %d errors", savedCount, skippedCount, len(errors)) if errors: # Truncate the list of errors if it's very long errorCount = len(errors) if errorCount > 20: errors = errors[:20] errors.append("(see log for full list)") raise Exception("%d waveforms couldn't be saved:\n%s" % (errorCount, "\n".join(errors))) self.waveformsSaveStatus = STATUS_DONE except Exception as e: LOGGER.error(e) self.waveformsSaveStatus = STATUS_ERROR QtGui.QMessageBox.critical( self, "Error", str(e) ) finally: self.updateToolbars() self.saveSpinner.hide() LOGGER.debug('COMPLETED saving all waveforms') @QtCore.pyqtSlot() def getWaveformDirectory(self): """ This function is triggered whenever the user presses the "to <directory>" button. """ # If the user quits or cancels this dialog, '' is returned newDirectory = str(QtGui.QFileDialog.getExistingDirectory( self, "Waveform Directory", self.waveformDirectory, QtGui.QFileDialog.ShowDirsOnly)) if newDirectory != '': self.waveformDirectory = newDirectory self.saveDirectoryPushButton.setText(self.waveformDirectory) self.resetSave() @QtCore.pyqtSlot() def browseWaveformDirectory(self): """ This function is triggered whenever the user presses the "browse" button. """ url = QtCore.QUrl.fromLocalFile(self.waveformDirectory) QtGui.QDesktopServices.openUrl(url) def loadPreferences(self): """ Load preferences relevant to this widget """ prefs = self.pyweed.preferences self.waveformDirectory = prefs.Waveforms.saveDir self.timeWindowAdapter.setValues( safe_int(prefs.Waveforms.timeWindowBefore, 60), safe_int(prefs.Waveforms.timeWindowAfter, 600), prefs.Waveforms.timeWindowBeforePhase, prefs.Waveforms.timeWindowAfterPhase ) self.saveFormatAdapter.setValue(prefs.Waveforms.saveFormat) def savePreferences(self): """ Save preferences related to the controls on this widget """ prefs = self.pyweed.preferences prefs.Waveforms.saveDir = self.waveformDirectory timeWindow = self.timeWindowAdapter.timeWindow prefs.Waveforms.timeWindowBefore = timeWindow.start_offset prefs.Waveforms.timeWindowAfter = timeWindow.end_offset prefs.Waveforms.timeWindowBeforePhase = timeWindow.start_phase prefs.Waveforms.timeWindowAfterPhase = timeWindow.end_phase prefs.Waveforms.saveFormat = self.saveFormatAdapter.getValue() <file_sep>## 上述文件说明: * depend_soft : 运行Python 文件时所依赖的软件; * ven:此文件是运行Python 文件的Python 虚拟环境; * Example_web_scraping_website : 里面含有一个破解 (http://example.webscraping.com/places/default/user/register)网站验证码的python 文件; * SIPO_login : 里面含有一个登录且破解(http://www.pss-system.gov.cn/sipopublicsearch/portal/uilogin-forwardLogin.shtml)验证码的Python 文件; * slider_cnblogs_login : 里面含有一个登录且破解(https://passport.cnblogs.com/user/signin)博客园验证码的 Python 文件; * sliderJigsaw_captcha : 里面含有一个登录且破解(https://open.captcha.qq.com/cap_web/experience-slideJigsaw.html)腾讯验证码的 Python 文件; * sliderjigsaw_dun_163 : 里面含有一个登录且破解(http://dun.163.com/trial/jigsaw)验证码的 Python 文件。 ## 使用方法: * 1、使用ven 文件下的python3 运行; * 2、使用pycharm 直接将全部文件导入,然后分别运行您想要的python 文件。<file_sep># -*- coding: utf-8 -*- """ Spinner overlay to indicate that an operation is in progress. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore from logging import getLogger from pyweed.gui.uic import SpinnerWidget LOGGER = getLogger(__name__) class SpinnerWidget(QtGui.QFrame, SpinnerWidget.Ui_SpinnerWidget): """ Spinner overlay widget. When shown, this covers the parent window and plays an animated spinner graphic along with a text message. """ cancelled = QtCore.pyqtSignal() def __init__(self, labelText, cancellable=True, parent=None): super(SpinnerWidget, self).__init__(parent=parent) self.setupUi(self) self.movie = QtGui.QMovie(":qrc/rotator-32.gif") self.icon.setMovie(self.movie) self.originalLabelText = labelText self.label.setText(labelText) if cancellable: self.cancelButton.clicked.connect(self.cancelled.emit) else: self.cancelButton.hide() self.hide() def setLabel(self, labelText): self.label.setText(labelText) def showEvent(self, *args, **kwargs): """ Widget is being shown """ self.setGeometry(self.parent().contentsRect()) self.movie.start() self.label.setText(self.originalLabelText) return super(SpinnerWidget, self).showEvent(*args, **kwargs) def hideEvent(self, *args, **kwargs): """ Widget is being hidden """ self.movie.stop() return super(SpinnerWidget, self).hideEvent(*args, **kwargs) <file_sep># -*- coding: utf-8 -*- """ Pyweed utility functions. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) # Basic packages import os import logging import re from pyproj import Geod from obspy.taup.tau import TauPyModel from future.moves.urllib.parse import urlencode LOGGER = logging.getLogger(__name__) GEOD = Geod(ellps='WGS84') TAUP = TauPyModel() # Rough meters/degree calculation M_PER_DEG = (GEOD.inv(0, 0, 0, 1)[2] + GEOD.inv(0, 0, 1, 0)[2]) / 2 class OutputFormat(object): """ Simple output format definition. """ def __init__(self, value, label=None, extension=None): #: This is the name used by ObsPy, which we treat as the "real" value self.value = value #: This is the label used in the UI, it defaults to value self.label = label or value #: This is the file extension, it defaults to lowercased value self.extension = extension or value.lower() # List of the output formats we support OUTPUT_FORMATS = [ OutputFormat('MSEED', 'MiniSEED'), OutputFormat('SAC'), OutputFormat('SACXY', 'SAC ASCII', 'sac.txt'), OutputFormat('SLIST', 'ASCII (1 column)', 'ascii1.txt'), OutputFormat('TSPAIR', 'ASCII (2 column)', 'ascii2.txt'), ] # Map of a format to the file extension to use OUTPUT_FORMAT_EXTENSIONS = dict(((f.value, f.extension) for f in OUTPUT_FORMATS)) class Phase(object): """ Simple phase definition """ def __init__(self, name, label): self.name = name self.label = label # List of phases we can use for time windows EVENT_TIME_PHASE = 'Event' PHASES = [ Phase('P', 'P wave arrival'), Phase('S', 'S wave arrival'), Phase(EVENT_TIME_PHASE, 'Event time') ] # Actual phase values retrieved from TauP, this should give us a good P and S value for any input (I hope!) TAUP_PHASES = ['P', 'PKIKP', 'Pdiff', 'S', 'SKIKS', 'SKS', 'p', 's'] def manage_cache(download_dir, cache_size): """ Maintain a cache directory at a certain size (MB) by removing the oldest files. """ try: # Compile statistics on all files in the output directory and subdirectories stats = [] total_size = 0 for root, dirs, files in os.walk(download_dir): for file in files: path = os.path.join(root, file) stat_list = os.stat(path) # path, size, atime new_stat_list = [path, stat_list.st_size, stat_list.st_atime] total_size = total_size + stat_list.st_size # don't want hidden files like .htaccess so don't add stuff that starts with . if not file.startswith('.'): stats.append(new_stat_list) # Sort file stats by last access time stats = sorted(stats, key=lambda file: file[2]) # Delete old files until we get under cache_size (configured in megabytes) deletion_count = 0 while total_size > cache_size * 1000000: # front of stats list is the file with the smallest (=oldest) access time last_accessed_file = stats[0] # index 1 is where size is total_size = total_size - last_accessed_file[1] # index 0 is where path is os.remove(last_accessed_file[0]) # remove the file from the stats list stats.pop(0) deletion_count = deletion_count + 1 LOGGER.debug('Removed %d files to keep %s below %.0f megabytes' % (deletion_count, download_dir, cache_size)) except Exception as e: LOGGER.error(str(e)) def iter_channels(inventory, dedupe=True): """ Iterate over every channel in an inventory. For each channel, yields (network, station, channel) If dedupe=True, repeated channels are filtered out -- this can occur if the inventory includes multiple epochs for a given channel. Only the first channel will be included in this case. """ last_sncl = None if inventory: for network in inventory.networks: for station in network.stations: for channel in station.channels: if dedupe: sncl = get_sncl(network, station, channel) if sncl == last_sncl: continue last_sncl = sncl yield (network, station, channel) def get_sncl(network, station, channel): """ Generate the SNCL for the given network/station/channel """ return '.'.join((network.code, station.code, channel.location_code, channel.code)) def get_event_id(event): """ Get a unique ID for a given event Event IDs are given differently by different data centers. Examples compiled by <EMAIL>: IRIS <event publicID="smi:service.iris.edu/fdsnws/event/1/query?eventid=3337497"> NCEDC <event publicID="quakeml:nc.anss.org/Event/NC/71377596" catalog:datasource="nc" catalog:dataid="nc71377596" catalog:eventsource="nc" catalog:eventid="71377596"> SCEDC <event publicID="quakeml:service.scedc.caltech.edu/fdsnws/event/1/query?eventid=37300872" catalog:datasource="ci" catalog:dataid="ci37300872" catalog:eventsource="ci" catalog:eventid="37300872"> USGS <event catalog:datasource="us" catalog:eventsource="us" catalog:eventid="c000lvb5" publicID="quakeml:earthquake.usgs.gov/fdsnws/event/1/query?eventid=usc000lvb5&format=quakeml"> ETHZ <event publicID="smi:ch.ethz.sed/sc3a/2017eemfch"> INGV <event publicID="smi:webservices.ingv.it/fdsnws/event/1/query?eventId=863301"> ISC <event publicID="smi:ISC/evid=600516598"> """ # Look for "eventid=" as a URL query parameter m = re.search(r'eventid=([^\&]+)', event.resource_id.id, re.IGNORECASE) if m: return m.group(1) # Otherwise, return the trailing segment of alphanumerics return re.sub(r'^.*?(\w+)\W*$', r'\1', event.resource_id.id) def get_event_name(event): time_str = get_event_time_str(event) mag_str = get_event_mag_str(event) description = get_event_description(event) return "%s | %s | %s" % (time_str, mag_str, description) def format_time_str(time): return time.isoformat(sep=' ').split('.')[0] def get_event_time_str(event): origin = get_preferred_origin(event) return format_time_str(origin.time) def get_event_mag_str(event): mag = get_preferred_magnitude(event) return "%s%s" % (mag.mag, mag.magnitude_type) def get_event_description(event): return str(event.event_descriptions[0].text).title() def get_preferred_origin(event): """ Get the preferred origin for the event, or None if not defined """ origin = event.preferred_origin() if not origin: LOGGER.error("No preferred origin found for event %s", event.resource_id) if len(event.origins): origin = event.origins[0] return origin def get_preferred_magnitude(event): """ Get the preferred magnitude for the event, or None if not defined """ magnitude = event.preferred_magnitude() if not magnitude: LOGGER.error("No preferred magnitude found for event %s", event.resource_id) if len(event.magnitudes): magnitude = event.magnitudes[0] return magnitude class TimeWindow(object): """ Represents a time window for data based on phase arrivals at a particular location """ start_offset = 0 end_offset = 0 start_phase = None end_phase = None def __init__(self, start_offset=0, end_offset=0, start_phase=PHASES[0].name, end_phase=PHASES[0].name): self.update(start_offset, end_offset, start_phase, end_phase) def update(self, start_offset, end_offset, start_phase, end_phase): """ Set all values. Phases can be specified by name or label. """ self.start_offset = start_offset self.end_offset = end_offset self.start_phase = start_phase self.end_phase = end_phase def calculate_window(self, event_time, arrivals): """ Given an event time and a dictionary of arrival times (see Distances below) calculate the full time window """ return ( # Start time event_time + arrivals.get(self.start_phase, 0) - self.start_offset, # End time event_time + arrivals.get(self.end_phase, 0) + self.end_offset, ) def __eq__(self, other): """ Compare two TimeWindows """ if not isinstance(other, TimeWindow): return False return (other.start_offset == self.start_offset and other.end_offset == self.end_offset and other.start_phase == self.start_phase and other.end_phase == self.end_phase) def get_distance(lat1, lon1, lat2, lon2): """ Get the distance between two points in degrees """ # NOTE that GEOD takes longitude first! _az, _baz, meters = GEOD.inv(lon1, lat1, lon2, lat2) return meters / M_PER_DEG def get_arrivals(distance, event_depth): """ Calculate phase arrival times :param distance: distance in degrees :param event_depth: event depth in km """ arrivals = TAUP.get_travel_times( event_depth, distance, TAUP_PHASES ) # From the travel time and origin, calculate the actual first arrival time for each basic phase type first_arrivals = {} for arrival in arrivals: # The basic phase name is the uppercase first letter of the full phase name # We assume this matches a Phase.name defined in PHASES phase_name = arrival.name[0].upper() if phase_name not in first_arrivals: first_arrivals[phase_name] = arrival.time return first_arrivals def get_bounding_circle(lat, lon, radius, num_points=36): """ Returns groups of lat/lon pairs representing a circle on the map """ radius_meters = radius * M_PER_DEG # NOTE that GEOD takes longitude first! trans = GEOD.fwd( [lon] * num_points, [lat] * num_points, list(((i * 360) / num_points) for i in range(num_points)), [radius_meters] * num_points ) points = list(zip(trans[1], trans[0])) # We need to complete the circle by adding the first point again as the last point points.append(points[0]) return points def get_service_url(client, service, parameters): """ Figure out the URL for the given service call. This isn't publicly available from the ObsPy client, we need to use internal APIs, so those messy details are encapsulated here. """ try: return client._create_url_from_parameters(service, {}, parameters) except: return "%s %s %s" % ( client.base_url, service, urlencode(parameters) ) class CancelledException(Exception): """ An exception to return in an event notification indicating that an operation was cancelled. See `StationsHandler` for an example. """ def __str__(self, *args, **kwargs): s = super(CancelledException, self).__str__(*args, **kwargs) if s == '': return 'Cancelled' else: return s class DataRequest(object): """ Wrapper object for a data request, which may or may not be more than a single web service query. """ # The client to use client = None # List of option dictionaries, one for each sub-request required sub_requests = None def __init__(self, client, *requests): self.client = client self.sub_requests = requests def process_result(self, result): """ Subclasses can define behavior here to do post-processing on the resulting data """ return result <file_sep># -*- coding: utf-8 -*- """ Custom QTableWidgetItem that forces numerical sorting http://stackoverflow.com/questions/25533140/sorting-qtablewidget-items-numerically :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtCore from PyQt4 import QtGui from pyweed.gui.TableWidget import CustomTableWidgetItemMixin class MyNumericTableWidgetItem (CustomTableWidgetItemMixin, QtGui.QTableWidgetItem): """ Custom QTableWidgetItem that forces numerical sorting http://stackoverflow.com/questions/25533140/sorting-qtablewidget-items-numerically """ def __init__(self, value, text): super(MyNumericTableWidgetItem, self).__init__(text) self.setData(QtCore.Qt.UserRole, value) def __lt__(self, other): if (isinstance(other, MyNumericTableWidgetItem)): selfDataValue = float(self.data(QtCore.Qt.UserRole)) otherDataValue = float(other.data(QtCore.Qt.UserRole)) return selfDataValue < otherDataValue else: return QtGui.QTableWidgetItem.__lt__(self, other) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Main PyWEED application :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) # Basic packages import os import logging # Pyweed UI components from pyweed.preferences import Preferences, user_config_path from pyweed.pyweed_utils import manage_cache, iter_channels, get_sncl, get_preferred_origin, DataRequest, get_distance from obspy.clients.fdsn import Client from pyweed.event_options import EventOptions from pyweed.station_options import StationOptions from pyweed.events_handler import EventsHandler from pyweed.stations_handler import StationsHandler, StationsDataRequest from PyQt4.QtCore import QObject LOGGER = logging.getLogger(__name__) class NoConsoleLoggingFilter(logging.Filter): """ Logging filter that excludes the (very noisy) output from the attached Python console """ exclude = ('ipykernel', 'traitlets',) def filter(self, record): for exclude in self.exclude: if record.name.startswith(exclude): return False return True class PyWeedCore(QObject): """ This is intended to be the core PyWEED functionality, without any reference to the GUI layer. The original intent was to allow this to run independently, eg. from a script or interactive shell. """ preferences = None event_client = None event_data_center = None event_options = None events_handler = None events = None selected_event_ids = None station_client = None station_data_center = None station_options = None stations_handler = None stations = None selected_station_ids = None def __init__(self): super(PyWeedCore, self).__init__() self.configure_logging() self.event_options = EventOptions() self.station_options = StationOptions() self.load_preferences() self.manage_cache() self.events_handler = EventsHandler(self) self.events_handler.done.connect(self.on_events_loaded) self.stations_handler = StationsHandler(self) self.stations_handler.done.connect(self.on_stations_loaded) def set_event_data_center(self, data_center): """ Set the data center used for events """ if data_center != self.event_data_center or not self.event_client: # Use the station client if they're the same, otherwise create a client if data_center == self.station_data_center and self.station_client: client = self.station_client else: LOGGER.info("Creating ObsPy client for %s", data_center) client = Client(data_center) # Verify that this client supports events if 'event' not in client.services: LOGGER.error("The %s data center does not provide an event service" % data_center) return # Update settings self.event_data_center = data_center self.event_client = client def set_station_data_center(self, data_center): """ Set the data center used for stations """ if data_center != self.station_data_center or not self.station_client: # Use the event client if they're the same, otherwise create a client if data_center == self.event_data_center and self.event_client: client = self.event_client else: LOGGER.info("Creating ObsPy client for %s", data_center) client = Client(data_center) # Verify that this client supports station and dataselect for service in ('station', 'dataselect',): if service not in client.services: LOGGER.error("The %s data center does not provide a %s service" % (data_center, service)) return # Update settings self.station_data_center = data_center self.station_client = client def load_preferences(self): """ Load configurable preferences from ~/.pyweed/config.ini """ LOGGER.info("Loading preferences") self.preferences = Preferences() try: self.preferences.load() except Exception as e: LOGGER.error("Unable to load configuration preferences -- using defaults.\n%s", e) self.set_event_options(self.preferences.EventOptions) self.set_event_data_center(self.preferences.Data.eventDataCenter) self.set_station_options(self.preferences.StationOptions) self.set_station_data_center(self.preferences.Data.stationDataCenter) def save_preferences(self): """ Save preferences to ~/.pyweed/config.ini """ LOGGER.info("Saving preferences") try: self.preferences.EventOptions.update(self.event_options.get_options(stringify=True)) self.preferences.Data.eventDataCenter = self.event_data_center self.preferences.StationOptions.update(self.station_options.get_options(stringify=True)) self.preferences.Data.stationDataCenter = self.station_data_center self.preferences.save() except Exception as e: LOGGER.error("Unable to save configuration preferences: %s", e) def configure_logging(self): """ Configure the root logger """ logger = logging.getLogger() try: log_level = getattr(logging, self.preferences.Logging.level) logger.setLevel(log_level) except Exception: logger.setLevel(logging.DEBUG) # Log to the terminal if available, otherwise log to a file if False: # Log to stderr handler = logging.StreamHandler() else: log_file = os.path.join(user_config_path(), 'pyweed.log') handler = logging.FileHandler(log_file, mode='w') formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S' ) handler.setFormatter(formatter) handler.addFilter(NoConsoleLoggingFilter()) logger.addHandler(handler) LOGGER.info("Logging configured") def manage_cache(self, init=True): """ Make sure the waveform download directory exists and isn't full """ download_path = self.preferences.Waveforms.downloadDir cache_size = int(self.preferences.Waveforms.cacheSize) LOGGER.info('Checking on download directory...') if os.path.exists(download_path): manage_cache(download_path, cache_size) elif init: try: os.makedirs(download_path, 0o700) except Exception as e: LOGGER.error("Creation of download directory failed with" + " error: \"%s\'""" % e) raise ############### # Events ############### def set_event_options(self, options): """ Update the event options """ LOGGER.debug("Set event options: %s", repr(options)) self.event_options.set_options(options) def get_event_obspy_options(self): """ Get the options for making an event request from Obspy """ return self.event_options.get_obspy_options() def fetch_events(self, options=None): """ Launch a fetch operation for events """ if options: # Simple request request = DataRequest(self.event_client, options) else: # Potentially complex request request = DataRequest( self.event_client, self.event_options.get_obspy_options() ) self.events_handler.load_catalog(request) def on_events_loaded(self, events): """ Handler triggered when the EventsHandler finishes loading events """ if not isinstance(events, Exception): self.set_events(events) def set_events(self, events): """ Set the current event list @param events: a Catalog """ LOGGER.info("Set events") self.events = events def set_selected_event_ids(self, event_ids): self.selected_event_ids = event_ids def iter_selected_events(self): """ Iterate over the selected events """ if self.events: for event in self.events: event_id = event.resource_id.id if event_id in self.selected_event_ids: yield event def iter_selected_event_locations(self): """ Return an iterator of (id, (lat, lon)) for each event. """ for event in self.iter_selected_events(): origin = get_preferred_origin(event) if origin: yield (event.resource_id.id, (origin.latitude, origin.longitude),) ############### # Stations ############### def set_station_options(self, options): LOGGER.debug("Set station options: %s", repr(options)) self.station_options.set_options(options) def fetch_stations(self, options=None): """ Load stations """ if options: # Simple request request = DataRequest(self.station_client, options) else: # Potentially complex request request = StationsDataRequest( self.station_client, self.station_options.get_obspy_options(), self.station_options.get_event_distances(), self.iter_selected_event_locations() ) self.stations_handler.load_inventory(request) def on_stations_loaded(self, stations): if not isinstance(stations, Exception): self.set_stations(stations) def set_stations(self, stations): """ Set the current station list @param stations: an Inventory """ LOGGER.info("Set stations") self.stations = stations def set_selected_station_ids(self, station_ids): self.selected_station_ids = station_ids def iter_selected_stations(self): """ Iterate over the selected stations (channels) Yields (network, station, channel) for each selected channel """ if self.stations: for (network, station, channel) in iter_channels(self.stations): sncl = get_sncl(network, station, channel) if sncl in self.selected_station_ids: yield (network, station, channel) ############### # Waveforms ############### def iter_selected_events_stations(self): """ Iterate through the selected event/station combinations. The main use case this method is meant to handle is where the user loaded stations based on selected events. For example, if the user selected multiple events and searched for stations within 20 degrees of any event, there may be stations that are within 20 degrees of one event but farther away from others -- we want to ensure that we only include the event/station combinations that are within 20 degrees of each other. """ events = list(self.iter_selected_events()) # Look for any event-based distance filter distance_range = self.station_options.get_event_distances() if distance_range: # Event locations by id event_locations = dict(self.iter_selected_event_locations()) else: event_locations = {} # Iterate through the stations for (network, station, channel) in self.iter_selected_stations(): for event in events: if distance_range: event_location = event_locations.get(event.resource_id.id) if event_location: distance = get_distance( event_location[0], event_location[1], station.latitude, station.longitude) LOGGER.debug( "Distance from (%s, %s) to (%s, %s): %s", event_location[0], event_location[1], station.latitude, station.longitude, distance ) if distance < distance_range['mindistance'] or distance > distance_range['maxdistance']: continue # If we reach here, include this event/station pair yield (event, network, station, channel) def close(self): self.manage_cache(init=False) self.save_preferences() if __name__ == "__main__": pyweed = PyWeedCore() # Do something? <file_sep># -*- coding: utf-8 -*- """ Helper class for web services. Options represents a set of key/value pairs (ie. query parameters), internally these are typed values but they can be read/written as strings. >>> class Test(Options): ... option1 = Option() ... option2 = DateOption() >>> t = Test() >>> t.option1 = 'test' >>> t.option1 'test' >>> t.option2 = '2012-01-01' >>> t.option2 UTCDateTime(2012, 1, 1, 0, 0) >>> t.get_options(stringify=True) {'option1': 'test', 'option2': '2012-01-01'} :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from obspy.core.utcdatetime import UTCDateTime from distutils.util import strtobool from logging import getLogger from numbers import Number from datetime import timedelta from future.utils import with_metaclass """ """ LOGGER = getLogger(__name__) class Option(object): """ Defines a web service query parameter. This allows the service API to take parameter values as Python objects, and convert them to the proper string form for the service. """ def __init__(self, option_name=None, default=None, hidden=False): """ :param options_name: The name of the option (eg. "starttime") :param default: The default to use if no value is set :param hidden: Indicate that this option shouldn't be included in the actual query """ self.option_name = option_name self.default = default self.hidden = hidden def to_option(self, value): """ Turn the value into a "native" option type """ return value def to_string(self, value): return str(value) class DateOption(Option): """ A date parameter. """ def to_option(self, value): # Value can be a number indicating number of days relative to today if isinstance(value, Number): return UTCDateTime() + timedelta(days=value) else: return UTCDateTime(value) def to_string(self, value): if hasattr(value, 'isoformat'): return value.isoformat() elif isinstance(value, str): return value else: raise ValueError("%s is not a date" % (value,)) class BinaryOption(Option): """ A binary parameter that is passed in a query as "yes" or "no". """ def to_option(self, value): return strtobool(value) def to_string(self, value): return "yes" if value else "no" class IntOption(Option): """ An integer value """ def to_option(self, value): return int(value) class FloatOption(Option): """ A floating point value """ def to_option(self, value): return float(value) class OptionsMeta(type): """ Metaclass for the Options type, this converts the Options defined in the class attributes into type-aware attributes. """ def __new__(cls, name, bases, attrs): options = {} for attr, option in attrs.items(): if isinstance(option, Option): # Keep the definition options[attr] = option # Set the actual instance attribute to the default value or None if option.default is not None: attrs[attr] = option.to_option(option.default) else: attrs[attr] = None # Store the option definitions in a private attribute attrs['_options'] = options return type.__new__(cls, name, bases, attrs) class Options(with_metaclass(OptionsMeta, object)): """ Base class for a web service request. """ def set_options(self, options): """ Set all the options in the given dictionary """ for k, v in options.items(): if k in self._options: setattr(self, k, v) def get_options(self, keys=None, hidden=True, stringify=False): """ Return the options as a dictionary, with a few options @param keys: only include the options named @param hidden: if True, include options where Option.hidden is set @param stringify: convert the option value to a string """ options = {} if not keys: keys = self.keys(hidden=hidden) for attr in keys: option = self._options.get(attr) if option: value = getattr(self, attr, None) if value is not None: if stringify: options[attr] = option.to_string(value) else: options[attr] = value return options def keys(self, hidden=True): """ Return a list of keys @param hidden: if True, include options where Option.hidden is set """ return [key for key, option in self._options.items() if hidden or not option.hidden] def __setattr__(self, k, v): if k in self._options: v = self._options[k].to_option(v) self.__dict__[k] = v def __repr__(self): return repr(self.get_options()) <file_sep>#!/usr/bin/env python # _*_coding:utf-8 _*_ import requests from bs4 import BeautifulSoup __title__ = '' __author__ = "wenyali" __mtime__ = "2018/5/11" def get_http_proproxy(url): headers = {"User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"} response = requests.get(url,headers=headers) soup = BeautifulSoup(response.text,"html.parser") tbody = soup.select("#ip_list > tr") proxy_list = [] for item in tbody: try : proxy_list.append(item.select("td").__getitem__(1).string+":"+item.select("td").__getitem__(2).string) except IndexError: pass return proxy_list if __name__ == "__main__": http_url = 'http://www.xicidaili.com/wt/' https_url = 'http://www.xicidaili.com/wn/' # http://31f.cn/http-proxy/ 网站的 http 代理 proxy_http_list = get_http_proproxy(http_url) proxy_https_list = get_http_proproxy(https_url) print(proxy_http_list,"\n",proxy_https_list) print(len(proxy_http_list),len(proxy_https_list)) headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'} #测试当前使用的代理IP 是否有用 for i in range(len(proxy_http_list)-1): try : response = requests.get("http://www.whatismyip.com.tw/",headers=headers,proxies={'http':proxy_http_list[i],"https":proxy_https_list[i]}) except: pass continue if response.status_code == 200: soup = BeautifulSoup(response.content.decode("utf-8"),"html.parser") ip = soup.select("body > span > b")[0].string print("当前的ip :",ip) break <file_sep>ObsPy is an open-source project dedicated to provide a Python framework for processing seismological data. It provides parsers for common file formats, clients to access data centers and seismological signal processing routines which allow the manipulation of seismological time series (see Beyreuther et al. 2010, Megies et al. 2011). The goal of the ObsPy project is to facilitate rapid application development for seismology. For more information visit https://www.obspy.org. :copyright: The ObsPy Development Team (<EMAIL>) :license: GNU Lesser General Public License, Version 3 (https://www.gnu.org/copyleft/lesser.html) <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyweed/gui/uic/StationOptionsWidget.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_StationOptionsWidget(object): def setupUi(self, StationOptionsWidget): StationOptionsWidget.setObjectName(_fromUtf8("StationOptionsWidget")) StationOptionsWidget.resize(302, 682) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(StationOptionsWidget.sizePolicy().hasHeightForWidth()) StationOptionsWidget.setSizePolicy(sizePolicy) self.verticalLayout = QtGui.QVBoxLayout(StationOptionsWidget) self.verticalLayout.setSpacing(4) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.SNCLGroupBox = QtGui.QGroupBox(StationOptionsWidget) self.SNCLGroupBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.SNCLGroupBox.setObjectName(_fromUtf8("SNCLGroupBox")) self.verticalLayout_5 = QtGui.QVBoxLayout(self.SNCLGroupBox) self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) self.formLayout = QtGui.QFormLayout() self.formLayout.setFieldGrowthPolicy(QtGui.QFormLayout.FieldsStayAtSizeHint) self.formLayout.setFormAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.formLayout.setHorizontalSpacing(4) self.formLayout.setVerticalSpacing(1) self.formLayout.setObjectName(_fromUtf8("formLayout")) self.networkLabel = QtGui.QLabel(self.SNCLGroupBox) self.networkLabel.setObjectName(_fromUtf8("networkLabel")) self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.networkLabel) self.networkLineEdit = QtGui.QLineEdit(self.SNCLGroupBox) self.networkLineEdit.setObjectName(_fromUtf8("networkLineEdit")) self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.networkLineEdit) self.stationLineEdit = QtGui.QLineEdit(self.SNCLGroupBox) self.stationLineEdit.setObjectName(_fromUtf8("stationLineEdit")) self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.stationLineEdit) self.locationLabel = QtGui.QLabel(self.SNCLGroupBox) self.locationLabel.setObjectName(_fromUtf8("locationLabel")) self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.locationLabel) self.locationLineEdit = QtGui.QLineEdit(self.SNCLGroupBox) self.locationLineEdit.setObjectName(_fromUtf8("locationLineEdit")) self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.locationLineEdit) self.channelLabel = QtGui.QLabel(self.SNCLGroupBox) self.channelLabel.setObjectName(_fromUtf8("channelLabel")) self.formLayout.setWidget(3, QtGui.QFormLayout.LabelRole, self.channelLabel) self.channelLineEdit = QtGui.QLineEdit(self.SNCLGroupBox) self.channelLineEdit.setObjectName(_fromUtf8("channelLineEdit")) self.formLayout.setWidget(3, QtGui.QFormLayout.FieldRole, self.channelLineEdit) self.stationLabel = QtGui.QLabel(self.SNCLGroupBox) self.stationLabel.setObjectName(_fromUtf8("stationLabel")) self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.stationLabel) self.verticalLayout_5.addLayout(self.formLayout) self.verticalLayout.addWidget(self.SNCLGroupBox) self.timeGroupBox = QtGui.QGroupBox(StationOptionsWidget) self.timeGroupBox.setObjectName(_fromUtf8("timeGroupBox")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.timeGroupBox) self.verticalLayout_2.setContentsMargins(-1, -1, -1, 4) self.verticalLayout_2.setSpacing(4) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.verticalLayout_6 = QtGui.QVBoxLayout() self.verticalLayout_6.setSpacing(0) self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6")) self.formLayout_2 = QtGui.QFormLayout() self.formLayout_2.setFieldGrowthPolicy(QtGui.QFormLayout.FieldsStayAtSizeHint) self.formLayout_2.setFormAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.formLayout_2.setHorizontalSpacing(4) self.formLayout_2.setVerticalSpacing(1) self.formLayout_2.setObjectName(_fromUtf8("formLayout_2")) self.starttimeLabel = QtGui.QLabel(self.timeGroupBox) self.starttimeLabel.setObjectName(_fromUtf8("starttimeLabel")) self.formLayout_2.setWidget(0, QtGui.QFormLayout.LabelRole, self.starttimeLabel) self.starttimeDateTimeEdit = QtGui.QDateTimeEdit(self.timeGroupBox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.starttimeDateTimeEdit.sizePolicy().hasHeightForWidth()) self.starttimeDateTimeEdit.setSizePolicy(sizePolicy) self.starttimeDateTimeEdit.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.starttimeDateTimeEdit.setCalendarPopup(True) self.starttimeDateTimeEdit.setTimeSpec(QtCore.Qt.UTC) self.starttimeDateTimeEdit.setObjectName(_fromUtf8("starttimeDateTimeEdit")) self.formLayout_2.setWidget(0, QtGui.QFormLayout.FieldRole, self.starttimeDateTimeEdit) self.endtimeLabel = QtGui.QLabel(self.timeGroupBox) self.endtimeLabel.setObjectName(_fromUtf8("endtimeLabel")) self.formLayout_2.setWidget(1, QtGui.QFormLayout.LabelRole, self.endtimeLabel) self.endtimeDateTimeEdit = QtGui.QDateTimeEdit(self.timeGroupBox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.endtimeDateTimeEdit.sizePolicy().hasHeightForWidth()) self.endtimeDateTimeEdit.setSizePolicy(sizePolicy) self.endtimeDateTimeEdit.setProperty("showGroupSeparator", False) self.endtimeDateTimeEdit.setCalendarPopup(True) self.endtimeDateTimeEdit.setTimeSpec(QtCore.Qt.UTC) self.endtimeDateTimeEdit.setObjectName(_fromUtf8("endtimeDateTimeEdit")) self.formLayout_2.setWidget(1, QtGui.QFormLayout.FieldRole, self.endtimeDateTimeEdit) self.verticalLayout_6.addLayout(self.formLayout_2) self.horizontalLayout_7 = QtGui.QHBoxLayout() self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) self.time30DaysPushButton = QtGui.QPushButton(self.timeGroupBox) self.time30DaysPushButton.setObjectName(_fromUtf8("time30DaysPushButton")) self.horizontalLayout_7.addWidget(self.time30DaysPushButton) self.time1YearPushButton = QtGui.QPushButton(self.timeGroupBox) self.time1YearPushButton.setObjectName(_fromUtf8("time1YearPushButton")) self.horizontalLayout_7.addWidget(self.time1YearPushButton) self.verticalLayout_6.addLayout(self.horizontalLayout_7) self.verticalLayout_2.addLayout(self.verticalLayout_6) self.line_3 = QtGui.QFrame(self.timeGroupBox) self.line_3.setFrameShape(QtGui.QFrame.HLine) self.line_3.setFrameShadow(QtGui.QFrame.Sunken) self.line_3.setObjectName(_fromUtf8("line_3")) self.verticalLayout_2.addWidget(self.line_3) self.timeFromEventsToolButton = QtGui.QToolButton(self.timeGroupBox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.timeFromEventsToolButton.sizePolicy().hasHeightForWidth()) self.timeFromEventsToolButton.setSizePolicy(sizePolicy) self.timeFromEventsToolButton.setObjectName(_fromUtf8("timeFromEventsToolButton")) self.verticalLayout_2.addWidget(self.timeFromEventsToolButton) self.verticalLayout.addWidget(self.timeGroupBox) self.locationGroupBox = QtGui.QGroupBox(StationOptionsWidget) self.locationGroupBox.setObjectName(_fromUtf8("locationGroupBox")) self.verticalLayout_4 = QtGui.QVBoxLayout(self.locationGroupBox) self.verticalLayout_4.setContentsMargins(-1, -1, -1, 4) self.verticalLayout_4.setSpacing(4) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.horizontalLayout_3 = QtGui.QHBoxLayout() self.horizontalLayout_3.setSpacing(0) self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3")) self.locationGlobalRadioButton = QtGui.QRadioButton(self.locationGroupBox) self.locationGlobalRadioButton.setChecked(False) self.locationGlobalRadioButton.setObjectName(_fromUtf8("locationGlobalRadioButton")) self.horizontalLayout_3.addWidget(self.locationGlobalRadioButton) self.verticalLayout_4.addLayout(self.horizontalLayout_3) self.line_4 = QtGui.QFrame(self.locationGroupBox) self.line_4.setFrameShape(QtGui.QFrame.HLine) self.line_4.setFrameShadow(QtGui.QFrame.Sunken) self.line_4.setObjectName(_fromUtf8("line_4")) self.verticalLayout_4.addWidget(self.line_4) self.verticalLayout_8 = QtGui.QVBoxLayout() self.verticalLayout_8.setSpacing(0) self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8")) self.horizontalLayout_8 = QtGui.QHBoxLayout() self.horizontalLayout_8.setSpacing(0) self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8")) self.locationRangeRadioButton = QtGui.QRadioButton(self.locationGroupBox) self.locationRangeRadioButton.setChecked(False) self.locationRangeRadioButton.setObjectName(_fromUtf8("locationRangeRadioButton")) self.horizontalLayout_8.addWidget(self.locationRangeRadioButton) spacerItem = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_8.addItem(spacerItem) self.drawLocationRangeToolButton = QtGui.QToolButton(self.locationGroupBox) self.drawLocationRangeToolButton.setCheckable(True) self.drawLocationRangeToolButton.setObjectName(_fromUtf8("drawLocationRangeToolButton")) self.horizontalLayout_8.addWidget(self.drawLocationRangeToolButton) self.verticalLayout_8.addLayout(self.horizontalLayout_8) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setContentsMargins(24, -1, -1, -1) self.horizontalLayout_2.setSpacing(0) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.verticalLayout_7 = QtGui.QVBoxLayout() self.verticalLayout_7.setSpacing(0) self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7")) self.horizontalLayout_4 = QtGui.QHBoxLayout() self.horizontalLayout_4.setSpacing(0) self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) spacerItem1 = QtGui.QSpacerItem(1, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem1) self.locationRangeNorthDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeNorthDoubleSpinBox.setMinimum(-90.0) self.locationRangeNorthDoubleSpinBox.setMaximum(90.0) self.locationRangeNorthDoubleSpinBox.setObjectName(_fromUtf8("locationRangeNorthDoubleSpinBox")) self.horizontalLayout_4.addWidget(self.locationRangeNorthDoubleSpinBox) spacerItem2 = QtGui.QSpacerItem(1, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem2) self.verticalLayout_7.addLayout(self.horizontalLayout_4) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setSpacing(2) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.locationRangeWestDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeWestDoubleSpinBox.setMinimum(-180.0) self.locationRangeWestDoubleSpinBox.setMaximum(180.0) self.locationRangeWestDoubleSpinBox.setObjectName(_fromUtf8("locationRangeWestDoubleSpinBox")) self.horizontalLayout.addWidget(self.locationRangeWestDoubleSpinBox) self.locationRangeEastDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeEastDoubleSpinBox.setMinimum(-180.0) self.locationRangeEastDoubleSpinBox.setMaximum(180.0) self.locationRangeEastDoubleSpinBox.setObjectName(_fromUtf8("locationRangeEastDoubleSpinBox")) self.horizontalLayout.addWidget(self.locationRangeEastDoubleSpinBox) self.verticalLayout_7.addLayout(self.horizontalLayout) self.horizontalLayout_5 = QtGui.QHBoxLayout() self.horizontalLayout_5.setSpacing(0) self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) spacerItem3 = QtGui.QSpacerItem(1, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_5.addItem(spacerItem3) self.locationRangeSouthDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeSouthDoubleSpinBox.setMinimum(-90.0) self.locationRangeSouthDoubleSpinBox.setMaximum(90.0) self.locationRangeSouthDoubleSpinBox.setObjectName(_fromUtf8("locationRangeSouthDoubleSpinBox")) self.horizontalLayout_5.addWidget(self.locationRangeSouthDoubleSpinBox) spacerItem4 = QtGui.QSpacerItem(1, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_5.addItem(spacerItem4) self.verticalLayout_7.addLayout(self.horizontalLayout_5) self.horizontalLayout_2.addLayout(self.verticalLayout_7) spacerItem5 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_2.addItem(spacerItem5) self.horizontalLayout_2.setStretch(1, 1) self.verticalLayout_8.addLayout(self.horizontalLayout_2) self.verticalLayout_4.addLayout(self.verticalLayout_8) self.line_2 = QtGui.QFrame(self.locationGroupBox) self.line_2.setFrameShape(QtGui.QFrame.HLine) self.line_2.setFrameShadow(QtGui.QFrame.Sunken) self.line_2.setObjectName(_fromUtf8("line_2")) self.verticalLayout_4.addWidget(self.line_2) self.verticalLayout_9 = QtGui.QVBoxLayout() self.verticalLayout_9.setSpacing(0) self.verticalLayout_9.setObjectName(_fromUtf8("verticalLayout_9")) self.horizontalLayout_9 = QtGui.QHBoxLayout() self.horizontalLayout_9.setSpacing(0) self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9")) self.locationDistanceFromPointRadioButton = QtGui.QRadioButton(self.locationGroupBox) self.locationDistanceFromPointRadioButton.setEnabled(True) self.locationDistanceFromPointRadioButton.setObjectName(_fromUtf8("locationDistanceFromPointRadioButton")) self.horizontalLayout_9.addWidget(self.locationDistanceFromPointRadioButton) spacerItem6 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_9.addItem(spacerItem6) self.drawDistanceFromPointToolButton = QtGui.QToolButton(self.locationGroupBox) self.drawDistanceFromPointToolButton.setCheckable(True) self.drawDistanceFromPointToolButton.setObjectName(_fromUtf8("drawDistanceFromPointToolButton")) self.horizontalLayout_9.addWidget(self.drawDistanceFromPointToolButton) self.verticalLayout_9.addLayout(self.horizontalLayout_9) self.horizontalLayout_6 = QtGui.QHBoxLayout() self.horizontalLayout_6.setContentsMargins(24, -1, -1, -1) self.horizontalLayout_6.setSpacing(0) self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) self.verticalLayout_3 = QtGui.QVBoxLayout() self.verticalLayout_3.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.verticalLayout_3.setSpacing(1) self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.horizontalLayout_14 = QtGui.QHBoxLayout() self.horizontalLayout_14.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.horizontalLayout_14.setSpacing(4) self.horizontalLayout_14.setObjectName(_fromUtf8("horizontalLayout_14")) self.distanceFromPointMinRadiusDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointMinRadiusDoubleSpinBox.setMinimum(0.0) self.distanceFromPointMinRadiusDoubleSpinBox.setMaximum(180.0) self.distanceFromPointMinRadiusDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointMinRadiusDoubleSpinBox")) self.horizontalLayout_14.addWidget(self.distanceFromPointMinRadiusDoubleSpinBox) self.label_2 = QtGui.QLabel(self.locationGroupBox) self.label_2.setObjectName(_fromUtf8("label_2")) self.horizontalLayout_14.addWidget(self.label_2) self.distanceFromPointMaxRadiusDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointMaxRadiusDoubleSpinBox.setMinimum(0.0) self.distanceFromPointMaxRadiusDoubleSpinBox.setMaximum(180.0) self.distanceFromPointMaxRadiusDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointMaxRadiusDoubleSpinBox")) self.horizontalLayout_14.addWidget(self.distanceFromPointMaxRadiusDoubleSpinBox) self.label_8 = QtGui.QLabel(self.locationGroupBox) self.label_8.setEnabled(True) self.label_8.setAlignment(QtCore.Qt.AlignCenter) self.label_8.setObjectName(_fromUtf8("label_8")) self.horizontalLayout_14.addWidget(self.label_8) self.verticalLayout_3.addLayout(self.horizontalLayout_14) self.horizontalLayout_15 = QtGui.QHBoxLayout() self.horizontalLayout_15.setSpacing(4) self.horizontalLayout_15.setObjectName(_fromUtf8("horizontalLayout_15")) self.label_6 = QtGui.QLabel(self.locationGroupBox) self.label_6.setObjectName(_fromUtf8("label_6")) self.horizontalLayout_15.addWidget(self.label_6) self.distanceFromPointEastDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointEastDoubleSpinBox.setMinimum(-180.0) self.distanceFromPointEastDoubleSpinBox.setMaximum(180.0) self.distanceFromPointEastDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointEastDoubleSpinBox")) self.horizontalLayout_15.addWidget(self.distanceFromPointEastDoubleSpinBox) self.label_14 = QtGui.QLabel(self.locationGroupBox) self.label_14.setEnabled(True) self.label_14.setObjectName(_fromUtf8("label_14")) self.horizontalLayout_15.addWidget(self.label_14) self.distanceFromPointNorthDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointNorthDoubleSpinBox.setMinimum(-90.0) self.distanceFromPointNorthDoubleSpinBox.setMaximum(90.0) self.distanceFromPointNorthDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointNorthDoubleSpinBox")) self.horizontalLayout_15.addWidget(self.distanceFromPointNorthDoubleSpinBox) self.label_7 = QtGui.QLabel(self.locationGroupBox) self.label_7.setObjectName(_fromUtf8("label_7")) self.horizontalLayout_15.addWidget(self.label_7) self.verticalLayout_3.addLayout(self.horizontalLayout_15) self.horizontalLayout_6.addLayout(self.verticalLayout_3) spacerItem7 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_6.addItem(spacerItem7) self.horizontalLayout_6.setStretch(1, 1) self.verticalLayout_9.addLayout(self.horizontalLayout_6) self.verticalLayout_4.addLayout(self.verticalLayout_9) self.line = QtGui.QFrame(self.locationGroupBox) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName(_fromUtf8("line")) self.verticalLayout_4.addWidget(self.line) self.verticalLayout_10 = QtGui.QVBoxLayout() self.verticalLayout_10.setSpacing(0) self.verticalLayout_10.setObjectName(_fromUtf8("verticalLayout_10")) self.horizontalLayout_10 = QtGui.QHBoxLayout() self.horizontalLayout_10.setSpacing(0) self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10")) self.locationDistanceFromEventsRadioButton = QtGui.QRadioButton(self.locationGroupBox) self.locationDistanceFromEventsRadioButton.setEnabled(True) self.locationDistanceFromEventsRadioButton.setObjectName(_fromUtf8("locationDistanceFromEventsRadioButton")) self.horizontalLayout_10.addWidget(self.locationDistanceFromEventsRadioButton) self.verticalLayout_10.addLayout(self.horizontalLayout_10) self.horizontalLayout_11 = QtGui.QHBoxLayout() self.horizontalLayout_11.setContentsMargins(24, -1, -1, -1) self.horizontalLayout_11.setSpacing(0) self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11")) self.verticalLayout_11 = QtGui.QVBoxLayout() self.verticalLayout_11.setSpacing(1) self.verticalLayout_11.setObjectName(_fromUtf8("verticalLayout_11")) self.horizontalLayout_16 = QtGui.QHBoxLayout() self.horizontalLayout_16.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.horizontalLayout_16.setSpacing(4) self.horizontalLayout_16.setObjectName(_fromUtf8("horizontalLayout_16")) self.distanceFromEventsMinDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromEventsMinDoubleSpinBox.setMinimum(0.0) self.distanceFromEventsMinDoubleSpinBox.setMaximum(180.0) self.distanceFromEventsMinDoubleSpinBox.setObjectName(_fromUtf8("distanceFromEventsMinDoubleSpinBox")) self.horizontalLayout_16.addWidget(self.distanceFromEventsMinDoubleSpinBox) self.label_3 = QtGui.QLabel(self.locationGroupBox) self.label_3.setObjectName(_fromUtf8("label_3")) self.horizontalLayout_16.addWidget(self.label_3) self.distanceFromEventsMaxDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromEventsMaxDoubleSpinBox.setMinimum(0.0) self.distanceFromEventsMaxDoubleSpinBox.setMaximum(180.0) self.distanceFromEventsMaxDoubleSpinBox.setObjectName(_fromUtf8("distanceFromEventsMaxDoubleSpinBox")) self.horizontalLayout_16.addWidget(self.distanceFromEventsMaxDoubleSpinBox) self.label_9 = QtGui.QLabel(self.locationGroupBox) self.label_9.setEnabled(True) self.label_9.setAlignment(QtCore.Qt.AlignCenter) self.label_9.setObjectName(_fromUtf8("label_9")) self.horizontalLayout_16.addWidget(self.label_9) self.verticalLayout_11.addLayout(self.horizontalLayout_16) self.horizontalLayout_11.addLayout(self.verticalLayout_11) spacerItem8 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_11.addItem(spacerItem8) self.horizontalLayout_11.setStretch(1, 1) self.verticalLayout_10.addLayout(self.horizontalLayout_11) self.verticalLayout_4.addLayout(self.verticalLayout_10) self.line_5 = QtGui.QFrame(self.locationGroupBox) self.line_5.setFrameShape(QtGui.QFrame.HLine) self.line_5.setFrameShadow(QtGui.QFrame.Sunken) self.line_5.setObjectName(_fromUtf8("line_5")) self.verticalLayout_4.addWidget(self.line_5) self.locationFromEventsToolButton = QtGui.QToolButton(self.locationGroupBox) self.locationFromEventsToolButton.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.locationFromEventsToolButton.sizePolicy().hasHeightForWidth()) self.locationFromEventsToolButton.setSizePolicy(sizePolicy) self.locationFromEventsToolButton.setObjectName(_fromUtf8("locationFromEventsToolButton")) self.verticalLayout_4.addWidget(self.locationFromEventsToolButton) self.verticalLayout.addWidget(self.locationGroupBox) spacerItem9 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem9) self.retranslateUi(StationOptionsWidget) QtCore.QMetaObject.connectSlotsByName(StationOptionsWidget) StationOptionsWidget.setTabOrder(self.networkLineEdit, self.stationLineEdit) StationOptionsWidget.setTabOrder(self.stationLineEdit, self.locationLineEdit) StationOptionsWidget.setTabOrder(self.locationLineEdit, self.channelLineEdit) StationOptionsWidget.setTabOrder(self.channelLineEdit, self.starttimeDateTimeEdit) StationOptionsWidget.setTabOrder(self.starttimeDateTimeEdit, self.endtimeDateTimeEdit) StationOptionsWidget.setTabOrder(self.endtimeDateTimeEdit, self.timeFromEventsToolButton) StationOptionsWidget.setTabOrder(self.timeFromEventsToolButton, self.locationFromEventsToolButton) def retranslateUi(self, StationOptionsWidget): self.SNCLGroupBox.setTitle(_translate("StationOptionsWidget", "SNCL", None)) self.networkLabel.setText(_translate("StationOptionsWidget", "Networks", None)) self.networkLineEdit.setText(_translate("StationOptionsWidget", "_GSN", None)) self.stationLineEdit.setText(_translate("StationOptionsWidget", "*", None)) self.locationLabel.setText(_translate("StationOptionsWidget", "Locations", None)) self.locationLineEdit.setText(_translate("StationOptionsWidget", "*", None)) self.channelLabel.setText(_translate("StationOptionsWidget", "Channels", None)) self.channelLineEdit.setText(_translate("StationOptionsWidget", "?HZ", None)) self.stationLabel.setText(_translate("StationOptionsWidget", "Stations", None)) self.timeGroupBox.setTitle(_translate("StationOptionsWidget", "Time", None)) self.starttimeLabel.setText(_translate("StationOptionsWidget", "Start", None)) self.starttimeDateTimeEdit.setDisplayFormat(_translate("StationOptionsWidget", "yyyy-MM-dd hh:mm:ss", None)) self.endtimeLabel.setText(_translate("StationOptionsWidget", "End", None)) self.endtimeDateTimeEdit.setDisplayFormat(_translate("StationOptionsWidget", "yyyy-MM-dd hh:mm:ss", None)) self.time30DaysPushButton.setText(_translate("StationOptionsWidget", "Last 30 days", None)) self.time1YearPushButton.setText(_translate("StationOptionsWidget", "Last year", None)) self.timeFromEventsToolButton.setText(_translate("StationOptionsWidget", ">> Copy Time Range from Event Options", None)) self.locationGroupBox.setTitle(_translate("StationOptionsWidget", "Location", None)) self.locationGlobalRadioButton.setText(_translate("StationOptionsWidget", "Global", None)) self.locationRangeRadioButton.setText(_translate("StationOptionsWidget", "Within lat/lon box", None)) self.drawLocationRangeToolButton.setText(_translate("StationOptionsWidget", "Draw on map", None)) self.locationDistanceFromPointRadioButton.setText(_translate("StationOptionsWidget", "Distance from point", None)) self.drawDistanceFromPointToolButton.setText(_translate("StationOptionsWidget", "Draw on map", None)) self.label_2.setText(_translate("StationOptionsWidget", "-", None)) self.label_8.setText(_translate("StationOptionsWidget", "degrees", None)) self.label_6.setText(_translate("StationOptionsWidget", "from", None)) self.label_14.setText(_translate("StationOptionsWidget", "E", None)) self.label_7.setText(_translate("StationOptionsWidget", "N", None)) self.locationDistanceFromEventsRadioButton.setText(_translate("StationOptionsWidget", "Distance from selected events", None)) self.label_3.setText(_translate("StationOptionsWidget", "-", None)) self.label_9.setText(_translate("StationOptionsWidget", "degrees", None)) self.locationFromEventsToolButton.setText(_translate("StationOptionsWidget", ">> Copy Location from Event Options", None)) <file_sep>#!/usr/bin/env python # _*_coding:utf-8 _*_ import time import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.webdriver.support import expected_conditions __title__ = '' __author__ = "wenyali" __mtime__ = "2018/5/13" def get_filml_list_url(url:str)->list: response = requests.get(url) soup = BeautifulSoup(response.text,"html.parser") divs = soup.select("body > div.container > div > div") div = divs[2:14] film_list_url = [] for item in div : film_list_url.append(url+item.a.get("href")) return film_list_url def get_film_watch_url(url:str)->str: response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") watch_url = soup.select("body > div.container > div.container-fluid > div > div.col-md-9 > div > div.col-md-4 > div.online-button > a") return watch_url[0].get("href") def get_origin_url(url:str)->str: chromeOptions = Options() prefs = { "profile.managed_default_content_settings.images":1, "profile.content_settings.plugin_whitelist.adobe-flash-player":1, "profile.content_settings.exceptions.plugins.*,*.per_resource.adobe-flash-player":1, } chromeOptions.add_experimental_option("prefs",prefs) # 为了让 chromedriver 支持 falsh,picture 的加载,添加属性 chrome_options driver = webdriver.Chrome(executable_path=r"..\depend_soft\chromedriver",chrome_options=chromeOptions) if "http://www.m4yy.com" in url: driver.get(url) else: driver.get("http://www.m4yy.com" + url) # 获取 cciframe 这个 iframe 框架,并让 driver 使用 switch_to.frame() 方法进入到 cciframe 中, # 这样才能获取到 cciframe 所有的元素 # 备注: 如果是 framerest 框架,则不需要进入 cciframe = driver.find_element_by_css_selector(".container-fluid #player #cciframe") driver.switch_to.frame(cciframe) # 设置一个等待时间,知道某个 element 课件 其中 By.(ID/TAG_NAME/CSS_SELECTOR/...) 是通过某种选择器来设置 wait = WebDriverWait(driver,30) wait.until(expected_conditions.visibility_of_element_located((By.ID, "player"))) # 获取视频播放的最终路径的 iframe 的src 属性获取 player_iframe = driver.find_element_by_css_selector("#player > iframe") origin_url = player_iframe.get_attribute("src") return origin_url if __name__ == "__main__": # 电影主页地址 url = "http://www.m4yy.com" #获取主页所有电影 URL film_list_url = get_filml_list_url(url) # 获取某个电影的播放 URL watch_url = get_film_watch_url(film_list_url[0]) # 获取某个电影最原始的播放 URL origin_url = get_origin_url(watch_url) print(origin_url) <file_sep># -*- coding: utf-8 -*- """ Application preferences Adapted from: https://github.com/claysmith/oldArcD/blob/master/tools/arctographer/arcmap/preferences.py :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) import os import platform from future.moves.configparser import SafeConfigParser def safe_bool(s, default=False): try: return s.startswith('y') except: return default def bool_to_str(b): if b: return "y" else: return "n" def safe_int(s, default=0): try: return int(s) except: return default class Section(object): def __init__(self, **initial): self.__dict__.update(initial) def read_from_config(self, config): name = self.__name__ if config.has_section(name): fix_case = dict((k.lower(), k) for k in self.__dict__.keys()) for k, v in config.items(name): if k in fix_case: k = fix_case[k] self.__dict__[k] = v def write_to_config(self, config): name = self.__name__ config.add_section(name) for key, value in self.items(): config.set(name, key, str(value)) @property def __name__(self): return self.__class__.__name__ def items(self): return self.__dict__.items() def update(self, values): self.__dict__.update(values) def __repr__(self): return self.__dict__.__repr__() @classmethod def create(cls, section_name, **initial): return type(section_name, (cls,), {})(**initial) class Preferences(object): """ Container for application preferences. """ def __init__(self): """ Initialization with default settings. """ # for (section, prefs) in DEFAULTS.items(): # setattr(self, section, Section.create(section, **prefs)) self.Data = Section.create("Data") self.Data.eventDataCenter = "IRIS" self.Data.stationDataCenter = "IRIS" self.Waveforms = Section.create("Waveforms") self.Waveforms.downloadDir = user_download_path() self.Waveforms.cacheSize = "50" # megabytes self.Waveforms.saveDir = user_save_path() self.Waveforms.timeWindowBefore = "60" # seconds self.Waveforms.timeWindowBeforePhase = "P" # P|S|Event self.Waveforms.timeWindowAfter = "600" # seconds self.Waveforms.timeWindowAfterPhase = "P" # P|S|Event self.Waveforms.saveFormat = "MSEED" self.Logging = Section.create("Logging") self.Logging.level = "INFO" self.Map = Section.create("Map") self.MainWindow = Section.create("MainWindow") self.MainWindow.width = "1000" self.MainWindow.height = "800" self.MainWindow.eventOptionsFloat = "n" self.MainWindow.stationOptionsFloat = "n" self.EventOptions = Section.create("EventOptions") self.StationOptions = Section.create("StationOptions") def save(self): """ Saves the user's preferences to config file """ config = SafeConfigParser() sections = [ self.Data, self.Waveforms, self.Logging, self.Map, self.MainWindow, self.EventOptions, self.StationOptions, ] for section in sections: section.write_to_config(config) if not os.path.exists(user_config_path()): try: os.makedirs(user_config_path(), 0o700) except Exception as e: print("Creation of user configuration directory failed with" + " error: \"%s\'""" % e) return f = open(os.path.join(user_config_path(), "pyweed.ini"), "w") config.write(f) def load(self): """ Loads the user's preferences from saved config file '""" path = os.path.join(user_config_path(), "pyweed.ini") if not os.path.exists(path): # Save the default configuration info self.save() else: # Override defaults with anything found in config.ini f = open(path, "r") config = SafeConfigParser() config.readfp(f) sections = [ self.Data, self.Waveforms, self.Logging, self.Map, self.MainWindow, self.EventOptions, self.StationOptions, ] for section in sections: section.read_from_config(config) # ------------------------------------------------------------------------------ # Helper functions # ------------------------------------------------------------------------------ def user_config_path(safe=True): """ @param safe: If set, auto-create the path if it doesn't exist @rtype: str @return: the directory for storing user configuration files """ p = os.path.join(os.path.expanduser("~"), ".pyweed") if safe: os.makedirs(p, exist_ok=True) return p # if platform.system() == "Darwin": # return os.path.join(os.path.expanduser("~"), "Library", "Preferences") # elif platform.system() == "Windows": # return os.path.join(os.path.expanduser("~"), "AppData", "Local") # else: # # Assume a Linux-like system # return os.path.join(os.path.expanduser("~"), ".config") def user_download_path(safe=True): """ @param safe: If set, auto-create the path if it doesn't exist @rtype: str @return: the default directory for saving downloaded (previewed) waveform data """ p = os.path.join(os.path.expanduser("~"), ".pyweed", "data") if safe: os.makedirs(p, exist_ok=True) return p # if platform.system() == "Darwin": # return os.path.join(os.path.expanduser("~"), "Library", "Application Support", "pyweed_data") # elif platform.system() == "Windows": # return os.path.join(os.path.expanduser("~"), "AppData", "Local", "pyweed_data") # else: # # Assume a Linux-like system # return os.path.join(os.path.expanduser("~"), ".config", "pyweed_data") def user_save_path(safe=False): """ @param safe: If set, auto-create the path if it doesn't exist @rtype: str @return: the default directory for saving waveform files """ p = os.path.join(os.path.expanduser("~"), "Downloads", "pyweed") if safe: os.makedirs(p, exist_ok=True) return p # if platform.system() == "Darwin": # return os.path.join(os.path.expanduser("~"), "Downloads", "pyweed") # elif platform.system() == "Windows": # return os.path.join(os.path.expanduser("~"), "Documents", "pyweed") # else: # # Assume a Linux-like system # return os.path.join(os.path.expanduser("~"), "Downloads", "pyweed") # ------------------------------------------------------------------------------ # Main # ------------------------------------------------------------------------------ if __name__ == '__main__': import doctest doctest.testmod(exclude_empty=True) <file_sep># -*- coding: utf-8 -*- """ Container for events. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) from pyweed.signals import SignalingThread, SignalingObject import logging from obspy.core.event.catalog import Catalog from pyweed.pyweed_utils import get_service_url, CancelledException from PyQt4 import QtCore import concurrent.futures LOGGER = logging.getLogger(__name__) def load_events(client, parameters): """ Execute one query for event data. This is a standalone function so we can run it in a separate thread. """ try: LOGGER.info('Loading events: %s', get_service_url(client, 'event', parameters)) return client.get_events(**parameters) except Exception as e: # If no results found, the client will raise an exception, we need to trap this # TODO: this should be much cleaner with a fix to https://github.com/obspy/obspy/issues/1656 if str(e).startswith("No data"): LOGGER.warning("No events found! Your query may be too narrow.") return Catalog() else: raise class EventsLoader(SignalingThread): """ Thread to handle event requests """ progress = QtCore.pyqtSignal() def __init__(self, request): """ Initialization. """ # Keep a reference to globally shared components self.request = request self.futures = {} super(EventsLoader, self).__init__() def run(self): """ Make a webservice request for events using the passed in options. """ self.setPriority(QtCore.QThread.LowestPriority) self.clearFutures() self.futures = {} catalog = None LOGGER.info("Making %d event requests", len(self.request.sub_requests)) with concurrent.futures.ThreadPoolExecutor(5) as executor: for sub_request in self.request.sub_requests: # Dictionary lets us look up argument by result later self.futures[executor.submit(load_events, self.request.client, sub_request)] = sub_request # Iterate through Futures as they complete for result in concurrent.futures.as_completed(self.futures): LOGGER.debug("Events loaded") try: if not catalog: catalog = result.result() else: catalog += result.result() self.progress.emit() except Exception: self.progress.emit() self.futures = {} if not catalog: catalog = Catalog() LOGGER.info("Loader processing") catalog = self.request.process_result(catalog) LOGGER.info("Loader done") self.done.emit(catalog) def clearFutures(self): """ Cancel any outstanding tasks """ if self.futures: for future in self.futures: if not future.done(): LOGGER.debug("Cancelling unexecuted future") future.cancel() def cancel(self): """ User-requested cancel """ self.done.disconnect() self.progress.disconnect() self.clearFutures() class EventsHandler(SignalingObject): """ Container for events. """ def __init__(self, pyweed): """ Initialization. """ super(EventsHandler, self).__init__() self.pyweed = pyweed self.catalog_loader = None def load_catalog(self, request): self.catalog_loader = EventsLoader(request) self.catalog_loader.done.connect(self.on_catalog_loaded) self.catalog_loader.start() def on_catalog_loaded(self, event_catalog): self.done.emit(event_catalog) def cancel(self): if self.catalog_loader: self.catalog_loader.done.disconnect() self.done.emit(CancelledException()) # ------------------------------------------------------------------------------ # Main # ------------------------------------------------------------------------------ if __name__ == '__main__': import doctest doctest.testmod(exclude_empty=True) <file_sep># -*- coding: utf-8 -*- """ Common library for adding data to a QTableWidget. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from pyweed.gui.MyNumericTableWidgetItem import MyNumericTableWidgetItem from PyQt4 import QtGui, QtCore from logging import getLogger LOGGER = getLogger(__name__) class Column(object): """ Defines a column for `TableItems` """ def __init__(self, label, description=None, width=None): """ :param label: The label to display in the column header :param description: If set, text will appear when the user hovers over the header :param width: Hardcode the column width, this is useful for fields that may have long values that would otherwise blow out the table width """ self.label = label self.description = description self.width = width class TableItems(object): """ Base helper class for adding a bunch of records to a QTableWidget. Subclasses just need to define the columns and how to turn a list of records into table cells. :example: >>> class ExampleTableItems(TableItems): >>> columns = [ >>> Column('Id'), >>> Column('Name', width=200), >>> Column('Email'), >>> Column('Age'), >>> ] >>> def rows(self, data): >>> for person in data: >>> yield [ >>> self.stringWidget(person.id), >>> self.stringWidget(person.name), >>> self.stringWidget(person.email), >>> self.numericWidget(person.age), >>> ] >>> items = ExampleTableItems(q_table_widget) >>> items.fill(list_of_people) """ #: Subclass should define the columns columns = None #: Table that the items are tied to table = None #: Subclass can set this to enforce a fixed row height (otherwise it will be sized to fit when it gets filled) rowHeight = None def __init__(self, table, *args): self.table = table def rows(self, data): """ Turn the data into rows (an iterable of lists) of QTableWidgetItems Subclasses should implement this """ pass def applyProps(self, widget, **props): """ Apply props to a newly created widget. This is used by the various widget methods to handle arbitrary keyword arguments by translating them into Qt setter calls. For example, passing `textAlignment=QtCore.Qt.AlignCenter` as a keyword argument will result in `widget.setTextAlignment(QtCore.Qt.AlignCenter)` """ # Look for Qt setter for any given prop name for prop, value in props.items(): setter = 'set%s%s' % (prop[:1].capitalize(), prop[1:]) if hasattr(widget, setter): try: getattr(widget, setter)(value) except Exception as e: LOGGER.error("Tried and failed to set %s: %s", prop, e) return widget def stringWidget(self, s, **props): """ Create a new item displaying the given string """ return self.applyProps(QtGui.QTableWidgetItem(s), **props) def numericWidget(self, i, text=None, **props): """ Create a new item displaying the given numeric value. Pass a string or a string format as `text` to customize how the number is actually displayed. The numeric value will still be used for sorting. """ if text is None: text = "%s" if '%' in text: text = text % i return self.applyProps(MyNumericTableWidgetItem(i, text), **props) def checkboxWidget(self, b, **props): """ Create a new checkbox widget showing the given boolean state """ checkboxItem = self.applyProps(QtGui.QTableWidgetItem(), **props) checkboxItem.setFlags(QtCore.Qt.ItemIsEnabled) if b: checkboxItem.setCheckState(QtCore.Qt.Checked) else: checkboxItem.setCheckState(QtCore.Qt.Unchecked) return checkboxItem def initColumns(self): # Only run this if the table columns aren't already set up if self.table.columnCount() != len(self.columns): self.table.setColumnCount(len(self.columns)) columnLabels = [c.label for c in self.columns] self.table.setHorizontalHeaderLabels(columnLabels) # Use the first column for identification self.table.setColumnHidden(0, True) # Set the tooltips for i, column in enumerate(self.columns): if column.description: self.table.horizontalHeaderItem(i).setToolTip(column.description) def fill(self, data): """ Fill the table """ # Clear existing contents self.table.setRowCount(0) # Initialize the table columns if needed self.initColumns() # Need to turn off sorting before inserting items self.table.setSortingEnabled(False) # Add new contents for rowidx, row in enumerate(self.rows(data)): self.table.insertRow(rowidx) if len(row) != len(self.columns): LOGGER.error("Row length doesn't match column count: %s / %s", str(row), str([c.label for c in self.columns])) for cellidx, cell in enumerate(row): self.table.setItem(rowidx, cellidx, cell) # Turn sorting back on self.table.setSortingEnabled(True) # Adjust the row heights if self.rowHeight: for i in range(self.table.rowCount()): self.table.setRowHeight(i, self.rowHeight) else: self.table.resizeRowsToContents() # Adjust the column widths for i, column in enumerate(self.columns): if column.width: self.table.setColumnWidth(i, column.width) else: self.table.resizeColumnToContents(i) def filter(self, filterFn): for row in range(self.table.rowCount()): if not filterFn or filterFn(row): self.table.showRow(row) else: self.table.hideRow(row) <file_sep># -*- coding: utf-8 -*- """ Container for stations. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) import logging from pyweed.signals import SignalingThread, SignalingObject from obspy.core.inventory.inventory import Inventory from pyweed.pyweed_utils import get_service_url, CancelledException, DataRequest, get_distance from PyQt4 import QtCore import concurrent.futures from pyweed.dist_from_events import get_combined_locations, CrossBorderException LOGGER = logging.getLogger(__name__) def load_stations(client, parameters): """ Execute one query for station metadata. This is a standalone function so we can run it in a separate thread. """ try: LOGGER.info('Loading stations: %s', get_service_url(client, 'station', parameters)) return client.get_stations(**parameters) except Exception as e: # If no results found, the client will raise an exception, we need to trap this # TODO: this should be much cleaner with a fix to https://github.com/obspy/obspy/issues/1656 if str(e).startswith("No data"): LOGGER.warning("No stations found! Your query may be too narrow.") return Inventory([], 'INTERNAL') else: raise class StationsLoader(SignalingThread): """ Thread to handle station requests """ progress = QtCore.pyqtSignal() def __init__(self, request): """ Initialization. """ # Keep a reference to globally shared components self.request = request self.futures = {} super(StationsLoader, self).__init__() def run(self): """ Make a webservice request for events using the passed in options. """ self.setPriority(QtCore.QThread.LowestPriority) self.clearFutures() self.futures = {} inventory = None LOGGER.info("Making %d station requests" % len(self.request.sub_requests)) with concurrent.futures.ThreadPoolExecutor(5) as executor: for sub_request in self.request.sub_requests: # Dictionary lets us look up argument by result later self.futures[executor.submit(load_stations, self.request.client, sub_request)] = sub_request # Iterate through Futures as they complete for result in concurrent.futures.as_completed(self.futures): LOGGER.debug("Stations loaded") try: if not inventory: inventory = result.result() else: inventory += result.result() self.progress.emit() except Exception: self.progress.emit() self.futures = {} # If no inventory object (ie. no sub-requests were run) create a dummy one if not inventory: inventory = Inventory([], 'INTERNAL') inventory = self.request.process_result(inventory) self.done.emit(inventory) def clearFutures(self): """ Cancel any outstanding tasks """ if self.futures: for future in self.futures: if not future.done(): LOGGER.debug("Cancelling unexecuted future") future.cancel() def cancel(self): """ User-requested cancel """ self.done.disconnect() self.progress.disconnect() self.clearFutures() class StationsDataRequest(DataRequest): event_locations = None distance_range = None def __init__(self, client, base_options, distance_range, event_locations): """ :param client: an ObsPy FDSN client :param base_options: the basic query options (ie. from StationOptions) :param distance_range: a tuple of (min, max) if querying by distance from events :param event_locations: a list of selected event locations if querying by distance from events """ super(StationsDataRequest, self).__init__(client) if distance_range and event_locations: # Get a list of just the (lat, lon) for each event self.event_locations = list((loc[1] for loc in event_locations)) self.distance_range = distance_range try: combined_locations = get_combined_locations(self.event_locations, self.distance_range['maxdistance']) self.sub_requests = [ dict( base_options, minlatitude=box.lat1, maxlatitude=box.lat2, minlongitude=box.lon1, maxlongitude=box.lon2 ) for box in combined_locations ] except CrossBorderException: # Can't break into subqueries, return the base (global, we assume) query LOGGER.warning("Couldn't calculate a bounding box for events, using global") self.sub_requests = [base_options] else: self.sub_requests = [base_options] def filter_one_station(self, station): """ Filter one station from the results """ for lat, lon in self.event_locations: dist = get_distance(lat, lon, station.latitude, station.longitude) if self.distance_range['mindistance'] <= dist <= self.distance_range['maxdistance']: return True return False def process_result(self, result): """ If the request is based on distance from a set of events, we need to perform a filter after the request, since the low-level request probably overselected. """ result = super(StationsDataRequest, self).process_result(result) if isinstance(result, Inventory) and self.event_locations and self.distance_range: filtered_networks = [] for network in result: filtered_stations = [station for station in network if self.filter_one_station(station)] if filtered_stations: network.stations = filtered_stations filtered_networks.append(network) result.networks = filtered_networks return result class StationsHandler(SignalingObject): """ Container for stations. """ def __init__(self, pyweed): """ Initialization. """ super(StationsHandler, self).__init__() self.pyweed = pyweed self.inventory_loader = None def load_inventory(self, request): try: self.inventory_loader = StationsLoader(request) self.inventory_loader.done.connect(self.on_inventory_loaded) self.inventory_loader.start() except Exception as e: self.done.emit(e) def on_inventory_loaded(self, inventory): self.done.emit(inventory) def cancel(self): if self.inventory_loader: self.inventory_loader.done.disconnect() self.done.emit(CancelledException()) # ------------------------------------------------------------------------------ # Main # ------------------------------------------------------------------------------ if __name__ == '__main__': import doctest doctest.testmod(exclude_empty=True) <file_sep>#!/usr/bin/env python # _*_coding:utf-8 _*_ from PIL import Image import pytesseract import requests from io import BytesIO __title__ = '' __author__ = "wenyali" __mtime__ = "2018/5/11" # image = Image.open("1.png") # image = image.convert("L") # image = image.point(lambda x: 0 if x < 125 else 255) # 返回图像的大小。返回一个元素。元组中含有两个元素,第1个元素:宽度,第2个元素:高度。 # print(image.size) # scale = 3 # 重新设置图片的大小。 # 参数是一个元组,元组含有两个元素。第1个元素:图像的宽度。第2个元素:图像的高度 # image = image.resize((round(image.size[0] * scale), round(image.size[1] * scale))) # image.show() # text = pytesseract.image_to_string(image, config="--psm 7") # print(text) # 过程 # 1 获取并解析验证码 # 2 获取表单所需要的参数,提交表单,进行登录。 headers = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"} # 创建Session会话,用来维护Cookie信息。 session = requests.session() def get_captcha(): """ 获取并返回验证码 """ captcha_url = "http://www.pss-system.gov.cn/sipopublicsearch/portal/login-showPic.shtml" response = session.get(captcha_url, headers=headers) image = Image.open(BytesIO(response.content)) image = image.convert("L") image = image.point(lambda x: 0 if x < 125 else 255) scale = 3 image = image.resize((round(image.size[0] * scale), round(image.size[1] * scale))) image.save("binaryzation.jpg") pytesseract.pytesseract.tesseract_cmd = r'D:\soft\tesseract\Tesseract-OCR\tesseract' text = pytesseract.image_to_string(image, config="--psm 7") print("验证码上获取的运算为:",text) text = text[:text.index("=")] try: result = eval(text) print("计算的结果为:{}".format(result)) return result except: return None def log_in(captcha): """ 进行登录。 """ log_in_url = "http://www.pss-system.gov.cn/sipopublicsearch/wee/platform/wee_security_check" data = {"j_loginsuccess_url":"", "j_validation_code": captcha, "j_username": "d2VueWFsaV8xMjM=", "j_password":"<PASSWORD>"} response = session.post(log_in_url, headers=headers, data=data) return response def main(): captcha = get_captcha() if captcha: response = log_in(captcha) if "wenyali_123,欢迎访问!" in response.text: print("登录成功") else: print("登录失败") if __name__ == "__main__": main()<file_sep># -*- coding: utf-8 -*- """ Base class for the *Dialog widgets. This is necessary because there are some significant differences among platforms, which we want to normalize for all of our secondary windows. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore import platform # Identify the platform IS_DARWIN = (platform.system() == 'Darwin') IS_LINUX = (platform.system() == 'Linux') class BaseDialog(QtGui.QDialog): def __init__(self, parent=None, *args, **kwargs): # On non-Mac platforms, a dialog with a parent will always float above the parent. We want these # windows to be independent, so in that case remove the parent. # (We need the parent on Mac because it allows all windows to share a menu.) if not IS_DARWIN: parent = None super(BaseDialog, self).__init__(parent=parent, *args, **kwargs) # On Linux, dialogs don't have window controls, this can be fixed by turning off that window flag if IS_LINUX: self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.Dialog) <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ PyWEED GUI :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) # Basic packages import sys import logging import os.path import platform from PyQt4 import QtCore from PyQt4 import QtGui from obspy.core.event.catalog import read_events from obspy.core.inventory.inventory import read_inventory from pyweed import __version__, __app_name__ from pyweed.gui.MainWindow import MainWindow from pyweed.gui.LoggingDialog import LoggingDialog from pyweed.events_handler import EventsHandler from pyweed.stations_handler import StationsHandler from pyweed.gui.WaveformDialog import WaveformDialog from pyweed.gui.ConsoleDialog import ConsoleDialog from pyweed.gui.PreferencesDialog import PreferencesDialog from pyweed.pyweed_core import PyWeedCore from pyweed.summary import get_filtered_catalog, get_filtered_inventory LOGGER = logging.getLogger(__name__) class PyWeedGUI(PyWeedCore, QtCore.QObject): # We need to define mainWindow since we may check it before we are fully initialized mainWindow = None def __init__(self): super(PyWeedGUI, self).__init__() LOGGER.info('Setting up main window...') self.mainWindow = MainWindow(self) # Logging # see: http://stackoverflow.com/questions/28655198/best-way-to-display-logs-in-pyqt # see: http://stackoverflow.com/questions/24469662/how-to-redirect-logger-output-into-pyqt-text-widget self.loggingDialog = LoggingDialog(self.mainWindow) # Waveforms # NOTE: The WaveformsHandler is created inside waveformsDialog. It is only relevant to that Dialog. LOGGER.info('Setting up waveforms dialog...') self.waveformsDialog = WaveformDialog(self, self.mainWindow) # Preferences self.preferencesDialog = PreferencesDialog(self, self.mainWindow) # Python console self.console = ConsoleDialog(self, self.mainWindow) self.configureMenu() # Display MainWindow LOGGER.info('Showing main window...') self.mainWindow.initialize() self.mainWindow.show() ############### # Events ############### def set_event_options(self, options): super(PyWeedGUI, self).set_event_options(options) if self.mainWindow: self.mainWindow.eventOptionsWidget.setOptions() def on_events_loaded(self, events): super(PyWeedGUI, self).on_events_loaded(events) if self.mainWindow: self.mainWindow.onEventsLoaded(events) ############### # Stations ############### def set_station_options(self, options): super(PyWeedGUI, self).set_station_options(options) if self.mainWindow: self.mainWindow.stationOptionsWidget.setOptions() def on_stations_loaded(self, stations): super(PyWeedGUI, self).on_stations_loaded(stations) if self.mainWindow: self.mainWindow.onStationsLoaded(stations) ############### # Waveforms ############### def openWaveformsDialog(self): self.waveformsDialog.show() self.waveformsDialog.loadWaveformChoices() ############### # Summary ############### def saveSummary(self): """ Save the selected events/stations """ # If the user quits or cancels this dialog, '' is returned savePath = str(QtGui.QFileDialog.getExistingDirectory( parent=self.mainWindow, caption="Save Summary to")) if savePath != '': try: catalog = get_filtered_catalog(self.events, self.iter_selected_events()) catalog.write(os.path.join(savePath, 'events.xml'), format="QUAKEML") except Exception as e: LOGGER.error("Unable to save event selection! %s", e) try: inventory = get_filtered_inventory(self.stations, self.iter_selected_stations()) inventory.write(os.path.join(savePath, 'stations.xml'), format="STATIONXML") except Exception as e: LOGGER.error("Unable to save station selection! %s", e) def loadSummary(self): # If the user quits or cancels this dialog, '' is returned loadPath = str(QtGui.QFileDialog.getExistingDirectory( parent=self.mainWindow, caption="Load Summary from")) if loadPath != '': try: catalog = read_events(os.path.join(loadPath, 'events.xml')) self.on_events_loaded(catalog) self.mainWindow.selectAllEvents() except Exception as e: LOGGER.error("Unable to load events! %s", e) try: inventory = read_inventory(os.path.join(loadPath, 'stations.xml')) self.on_stations_loaded(inventory) self.mainWindow.selectAllStations() except Exception as e: LOGGER.error("Unable to load stations! %s", e) ############### # Other UI elements ############### def configureMenu(self): # Create menuBar # see: http://doc.qt.io/qt-4.8/qmenubar.html # see: http://zetcode.com/gui/pyqt4/menusandtoolbars/ # see: https://pythonprogramming.net/menubar-pyqt-tutorial/ # see: http://www.dreamincode.net/forums/topic/261282-a-basic-pyqt-tutorial-notepad/ mainMenu = QtGui.QMenuBar() # mainMenu.setNativeMenuBar(False) fileMenu = mainMenu.addMenu('&File') saveSummaryAction = QtGui.QAction("Save Summary", self.mainWindow) saveSummaryAction.triggered.connect(self.saveSummary) fileMenu.addAction(saveSummaryAction) loadSummaryAction = QtGui.QAction("Load Summary", self.mainWindow) loadSummaryAction.triggered.connect(self.loadSummary) fileMenu.addAction(loadSummaryAction) quitAction = QtGui.QAction("&Quit", self.mainWindow) quitAction.setShortcut("Ctrl+Q") quitAction.triggered.connect(self.closeApplication) fileMenu.addAction(quitAction) viewMenu = mainMenu.addMenu('View') showConsoleAction = QtGui.QAction("Show Python Console", self) showConsoleAction.triggered.connect(self.console.show) viewMenu.addAction(showConsoleAction) showLogsAction = QtGui.QAction("Show Logs", self) showLogsAction.triggered.connect(self.loggingDialog.show) viewMenu.addAction(showLogsAction) optionsMenu = mainMenu.addMenu('Options') showPreferencesAction = QtGui.QAction("Preferences", self) showPreferencesAction.triggered.connect(self.preferencesDialog.exec_) optionsMenu.addAction(showPreferencesAction) helpMenu = mainMenu.addMenu('Help') aboutPyweedAction = QtGui.QAction("&About PYWEED", self) aboutPyweedAction.triggered.connect(self.showAboutDialog) helpMenu.addAction(aboutPyweedAction) helpMenu.addSeparator() self.mainWindow.setMenuBar(mainMenu) # self.waveformsDialog.setMenuBar(mainMenu) def showAboutDialog(self): """Display About message box.""" # see: http://www.programcreek.com/python/example/62361/PyQt4.QtGui.QMessageBox website = "https://github.com/iris-edu/pyweed" # email = "<EMAIL>" license_link = "https://github.com/iris-edu/pyweed/blob/master/LICENSE" license_name = "LGPLv3" mazama_link = "http://mazamascience.com" mazama_name = "Mazama Science" iris_link = "http://ds.iris.edu/ds/nodes/dmc/" iris_name = "IRIS" msgBox = QtGui.QMessageBox() msgBox.setWindowTitle("About %s" % __app_name__) msgBox.setTextFormat(QtCore.Qt.RichText) # msgBox.setIconPixmap(QtGui.QPixmap(ComicTaggerSettings.getGraphic('about.png'))) msgBox.setText("<br><br><br>" + __app_name__ + " v" + __version__ + "<br><br>" + "Pyweed is a cross-platform GUI application for retrieving event-based seismic data." + "<br><br>" + "<a href='{0}'>{0}</a><br><br>".format(website) + # "<a href='mailto:{0}'>{0}</a><br><br>".format(email) + "License: <a href='{0}'>{1}</a>".format(license_link, license_name) + "<br><br>" + "Developed by <a href='{0}'>{1}</a>".format(mazama_link, mazama_name) + " for <a href='{0}'>{1}</a>".format(iris_link, iris_name) + ".") msgBox.setStandardButtons(QtGui.QMessageBox.Ok) msgBox.exec_() # NOTE: For info on " modalSession has been exited prematurely" error on OS X see: # NOTE: https://forum.qt.io/topic/43618/modal-sessions-with-pyqt4-and-os-x/2 def closeApplication(self): LOGGER.info('Closing application...') # Update preferences self.mainWindow.savePreferences() self.waveformsDialog.savePreferences() self.close() QtGui.QApplication.quit() if __name__ == "__main__": print("Run pyweed_launcher.py instead!") <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- """ PyWEED GUI Launcher This exists mainly to show the splash screen as quickly as possible, by deferring lots of the expensive library imports required for the application itself. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) import sys import os from future.utils import PY2 import matplotlib # If running under windows, redirect stdout/stderr, since writing to them will crash Python if there's # not a console. See https://bugs.python.org/issue706263 if sys.executable.endswith('pythonw.exe'): nul = open(os.devnull, 'w') sys.stderr = nul sys.stdout = nul # Configure matplotlib backend matplotlib.use('AGG') # For debugging, raise an exception on attempted chained assignment # See http://pandas.pydata.org/pandas-docs/version/0.19.1/indexing.html#returning-a-view-versus-a-copy # import pandas as pd # pd.set_option('mode.chained_assignment', 'raise') if PY2: # Configure PyQt4 -- in order for the Python console to work in Python 2, we need to load a particular # version of some internal libraries. This must be done before the first import of the PyQt4 libraries. # See http://stackoverflow.com/questions/11513132/embedding-ipython-qt-console-in-a-pyqt-application/20610786#20610786 os.environ['QT_API'] = 'pyqt' import sip sip.setapi("QString", 2) sip.setapi("QVariant", 2) def get_pyweed(): """ Load the PyWEED GUI code, this is where most of the expensive stuff happens """ from pyweed.gui.PyWeedGUI import PyWeedGUI return PyWeedGUI() def launch(): """ Basic startup process. """ from PyQt4 import QtGui, QtCore from pyweed.gui.SplashScreenHandler import SplashScreenHandler import pyweed.gui.qrc # NOQA # See https://stackoverflow.com/questions/31952711/ QtCore.QCoreApplication.setAttribute(QtCore.Qt.AA_X11InitThreads) app = QtGui.QApplication(sys.argv) splashScreenHandler = SplashScreenHandler() app.processEvents() pyweed = get_pyweed() splashScreenHandler.finish(pyweed.mainWindow) sys.exit(app.exec_()) if __name__ == "__main__": launch() <file_sep># -*- coding: utf-8 -*- """ Main window :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) from pyweed import __version__, __app_name__ from PyQt4 import QtGui from pyweed.gui.uic import MainWindow from pyweed.preferences import safe_int, safe_bool, bool_to_str import logging from pyweed.pyweed_utils import iter_channels, get_preferred_origin, get_preferred_magnitude from pyweed.gui.Seismap import Seismap from pyweed.gui.EventOptionsWidget import EventOptionsWidget from pyweed.gui.StationOptionsWidget import StationOptionsWidget from pyweed.gui.TableItems import TableItems, Column from pyweed.event_options import EventOptions from PyQt4.QtCore import pyqtSlot from pyweed.gui.SpinnerWidget import SpinnerWidget from pyweed.station_options import StationOptions LOGGER = logging.getLogger(__name__) def make_exclusive(widget1, widget2): """ Make two widgets exclusive, so that if one is toggled the other is disabled and vice versa """ widget1.toggled.connect( lambda b: widget2.setEnabled(not b)) widget2.toggled.connect( lambda b: widget1.setEnabled(not b)) widget2.setEnabled(not widget1.isChecked()) widget1.setEnabled(not widget2.isChecked()) class EventTableItems(TableItems): """ Defines the table for displaying events """ columns = [ Column('Id'), Column('Date/Time'), Column('Magnitude'), Column('Longitude'), Column('Latitude'), Column('Depth'), Column('Location'), ] def rows(self, data): """ Turn the data into rows (an iterable of lists) of QTableWidgetItems """ for i, event in enumerate(data): origin = get_preferred_origin(event) if not origin: continue magnitude = get_preferred_magnitude(event) if not magnitude: continue time = origin.time.strftime("%Y-%m-%d %H:%M:%S") # use strftime to remove milliseconds event_description = "no description" if len(event.event_descriptions) > 0: event_description = event.event_descriptions[0].text yield [ self.numericWidget(i), self.stringWidget(time), self.numericWidget(magnitude.mag, "%s %s" % (magnitude.mag, magnitude.magnitude_type)), self.numericWidget(origin.longitude, "%.03f°"), self.numericWidget(origin.latitude, "%.03f°"), self.numericWidget(origin.depth / 1000, "%.02f km"), # we wish to report in km self.stringWidget(event_description.title()), ] class StationTableItems(TableItems): """ Defines the table for displaying stations """ columns = [ Column('SNCL'), Column('Network'), Column('Station'), Column('Location'), Column('Channel'), Column('Longitude'), Column('Latitude'), Column('Description'), ] def rows(self, data): """ Turn the data into rows (an iterable of lists) of QTableWidgetItems """ sncls = set() for (network, station, channel) in iter_channels(data): sncl = '.'.join((network.code, station.code, channel.location_code, channel.code)) if sncl in sncls: LOGGER.debug("Found duplicate SNCL: %s", sncl) else: sncls.add(sncl) yield [ self.stringWidget(sncl), self.stringWidget(network.code), self.stringWidget(station.code), self.stringWidget(channel.location_code), self.stringWidget(channel.code), self.numericWidget(channel.longitude, "%.03f°"), self.numericWidget(channel.latitude, "%.03f°"), self.stringWidget(station.site.name), ] class MainWindow(QtGui.QMainWindow, MainWindow.Ui_MainWindow): eventTableItems = None stationTableItems = None eventsSpinner = None stationsSpinner = None def __init__(self, pyweed): super(MainWindow, self).__init__() self.setupUi(self) # Note that at this point, pyweed is only minimally initialized! self.pyweed = pyweed def initialize(self): """ Most of the initialization should happen here. PyWEED has to create the MainWindow first, before it's fully configured everything (mainly because it needs to attach various other widgets and things to MainWindow). So __init__() above needs to be very minimal. Once everything is ready, the application will call initialize() and we can safely do all the "real" initialization. """ prefs = self.pyweed.preferences # Set MainWindow properties self.setWindowTitle('%s version %s' % (__app_name__, __version__)) # Options widgets self.eventOptionsWidget = EventOptionsWidget( self, self.pyweed.event_options, self.pyweed.station_options, self.eventOptionsDockWidget, self.toggleEventOptions) self.stationOptionsWidget = StationOptionsWidget( self, self.pyweed.station_options, self.pyweed.event_options, self.stationOptionsDockWidget, self.toggleStationOptions) # When any options change, enable the relevant download button self.eventOptionsWidget.changed.connect(lambda: self.getEventsButton.setEnabled(True)) self.stationOptionsWidget.changed.connect(lambda: self.getStationsButton.setEnabled(True)) # Map self.initializeMap() # When the options coordinates change, we want to update the map self.eventOptionsWidget.changedCoords.connect( lambda: self.updateSeismap(events=True) ) self.stationOptionsWidget.changedCoords.connect( lambda: self.updateSeismap(stations=True) ) # Table selection self.eventsTable.itemSelectionChanged.connect(self.onEventSelectionChanged) self.stationsTable.itemSelectionChanged.connect(self.onStationSelectionChanged) self.clearEventSelectionButton.clicked.connect(self.eventsTable.clearSelection) self.clearStationSelectionButton.clicked.connect(self.stationsTable.clearSelection) # Main window buttons self.getEventsButton.clicked.connect(self.getEvents) self.getStationsButton.clicked.connect(self.getStations) self.getWaveformsButton.clicked.connect(self.getWaveforms) # Size and placement according to preferences self.resize( safe_int(prefs.MainWindow.width, 1000), safe_int(prefs.MainWindow.height, 800)) self.eventOptionsDockWidget.setFloating(safe_bool(prefs.MainWindow.eventOptionsFloat, False)) self.stationOptionsDockWidget.setFloating(safe_bool(prefs.MainWindow.stationOptionsFloat, False)) # Add spinner overlays to the event/station widgets self.eventsSpinner = SpinnerWidget("Loading events...", parent=self.eventsWidget) self.eventsSpinner.cancelled.connect(self.pyweed.events_handler.cancel) self.stationsSpinner = SpinnerWidget("Loading stations...", parent=self.stationsWidget) self.stationsSpinner.cancelled.connect(self.pyweed.stations_handler.cancel) # Do an initial update self.updateSeismap(events=True) self.updateSeismap(stations=True) self.manageGetWaveformsButton() def initializeMap(self): LOGGER.info('Setting up main map...') self.seismap = Seismap(self.mapCanvas) # Map of buttons to the relevant draw modes self.drawButtons = { 'events.box': self.eventOptionsWidget.drawLocationRangeToolButton, 'events.toroid': self.eventOptionsWidget.drawDistanceFromPointToolButton, 'stations.box': self.stationOptionsWidget.drawLocationRangeToolButton, 'stations.toroid': self.stationOptionsWidget.drawDistanceFromPointToolButton, } # Generate a handler to toggle a given drawing mode def drawModeFn(mode): return lambda checked: self.seismap.toggleDrawMode(mode, checked) # Register draw mode toggle handlers for mode, button in self.drawButtons.items(): button.clicked.connect(drawModeFn(mode)) self.mapZoomInButton.clicked.connect(self.seismap.zoomIn) self.mapZoomOutButton.clicked.connect(self.seismap.zoomOut) self.mapResetButton.clicked.connect(self.seismap.zoomReset) self.seismap.drawEnd.connect(self.onMapDrawFinished) def showMessage(self, message): """ Display the given message in the status bar """ self.statusBar.showMessage(message, 4000) @pyqtSlot(object) def onMapDrawFinished(self, event): """ Called when Seismap emits a DrawEvent upon completion """ # If the user finished an operation associated with a button, uncheck it button = self.drawButtons.get(event.mode) if button: button.setChecked(False) # For box/toroid bounds drawing, handle the returned geo data options = {} if event.points: if 'box' in event.mode: (n, e, s, w) = event.points options = { 'location_choice': EventOptions.LOCATION_BOX, # Assumes StationOptions.LOCATION_BOX is the same 'maxlatitude': n, 'maxlongitude': e, 'minlatitude': s, 'minlongitude': w, } elif 'toroid' in event.mode: (lat, lon, dist) = event.points options = { 'location_choice': EventOptions.LOCATION_POINT, # Assumes StationOptions.LOCATION_POINT is the same 'latitude': lat, 'longitude': lon, 'maxradius': dist } # Set event or station options if 'events' in event.mode: self.pyweed.set_event_options(options) elif 'stations' in event.mode: self.pyweed.set_station_options(options) def getEvents(self): """ Trigger the event retrieval from web services """ LOGGER.info('Loading events...') self.eventsSpinner.show() self.getEventsButton.setEnabled(False) self.pyweed.fetch_events() def updateSeismap(self, events=False, stations=False): """ Update seismap when [event|station]OptionsWidget coordinates change """ LOGGER.debug("Updating map from widget: %s" % ((events and "events") or "stations")) if events: options = self.eventOptionsWidget.getOptions() markers = self.seismap.eventMarkers else: options = self.stationOptionsWidget.getOptions() markers = self.seismap.stationMarkers try: self.seismap.clearBoundingMarkers(markers) if options["location_choice"] == EventOptions.LOCATION_BOX: self.seismap.addMarkerBox( markers, float(options["maxlatitude"]), float(options["maxlongitude"]), float(options["minlatitude"]), float(options["minlongitude"]) ) elif options["location_choice"] == EventOptions.LOCATION_POINT: self.seismap.addMarkerToroid( markers, float(options["latitude"]), float(options["longitude"]), float(options["minradius"]), float(options["maxradius"]) ) elif options["location_choice"] == StationOptions.LOCATION_EVENTS: # Show distance markers around all events for event in self.pyweed.iter_selected_events(): origin = get_preferred_origin(event) if origin: self.seismap.addMarkerToroid( markers, origin.latitude, origin.longitude, float(options["mindistance"]), float(options["maxdistance"]) ) except Exception as e: LOGGER.error("Failed to update seismap! %s", e, exc_info=True) def onEventsLoaded(self, events): """ Handler triggered when the EventsHandler finishes loading events """ self.eventsSpinner.hide() if isinstance(events, Exception): self.eventSelectionLabel.setText('Error! See log for details') msg = "Error loading events: %s" % events LOGGER.error(msg) self.showMessage(msg) return if not self.eventTableItems: self.eventTableItems = EventTableItems(self.eventsTable) self.eventTableItems.fill(events) # Add items to the map ------------------------------------------------- self.seismap.addEvents(events) self.onEventSelectionChanged() status = 'Finished loading events' LOGGER.info(status) self.showMessage(status) def getStations(self): """ Trigger the channel metadata retrieval from web services """ LOGGER.info('Loading stations...') self.stationsSpinner.show() self.getStationsButton.setEnabled(False) self.pyweed.fetch_stations() def onStationsLoaded(self, stations): """ Handler triggered when the StationsHandler finishes loading stations """ self.stationsSpinner.hide() if isinstance(stations, Exception): self.stationSelectionLabel.setText('Error! See log for details') msg = "Error loading stations: %s" % stations LOGGER.error(msg) self.showMessage(msg) return if not self.stationTableItems: self.stationTableItems = StationTableItems(self.stationsTable) self.stationTableItems.fill(stations) # Add items to the map ------------------------------------------------- self.seismap.addStations(stations) self.onStationSelectionChanged() status = 'Finished loading stations' LOGGER.info(status) self.showMessage(status) def getWaveforms(self): self.pyweed.openWaveformsDialog() def selectAllEvents(self): """ Select all events in the table. This is mainly for loading data from a summary file, where we want all the data to be pre-selected. """ self.eventsTable.selectAll() def onEventSelectionChanged(self): """ Handle a click anywhere in the table. """ # Get selected ids ids = [] for idx in self.eventsTable.selectionModel().selectedRows(): ids.append(int(self.eventsTable.item(idx.row(), 0).text())) numSelected = len(ids) numTotal = self.eventsTable.rowCount() self.eventSelectionLabel.setText( "Selected %d of %d events" % (numSelected, numTotal)) # Get locations and event IDs points = [] eventIDs = [] for id in ids: event = self.pyweed.events[id] origin = get_preferred_origin(event) if not origin: continue points.append((origin.latitude, origin.longitude)) eventIDs.append(event.resource_id.id) # Update the events_handler with the latest selection information self.pyweed.set_selected_event_ids(eventIDs) self.seismap.addEventsHighlighting(points) self.stationOptionsWidget.onEventSelectionChanged() self.manageGetWaveformsButton() def selectAllStations(self): """ Select all stations in the table. This is mainly for loading data from a summary file, where we want all the data to be pre-selected. """ self.stationsTable.selectAll() def onStationSelectionChanged(self): # Get selected sncls sncls = [] for idx in self.stationsTable.selectionModel().selectedRows(): sncls.append(self.stationsTable.item(idx.row(), 0).text()) numSelected = len(sncls) numTotal = self.stationsTable.rowCount() self.stationSelectionLabel.setText( "Selected %d of %d channels" % (numSelected, numTotal)) # Get locations points = [] for sncl in sncls: try: coordinates = self.pyweed.stations.get_coordinates(sncl) points.append((coordinates['latitude'], coordinates['longitude'])) except: pass # Update the stations_handler with the latest selection information self.pyweed.set_selected_station_ids(sncls) self.seismap.addStationsHighlighting(points) self.manageGetWaveformsButton() def manageGetWaveformsButton(self): """ Handle enabled/disabled status of the "Get Waveforms" button based on the presence/absence of selected events and stations """ if self.pyweed.selected_event_ids and self.pyweed.selected_station_ids: self.getWaveformsButton.setEnabled(True) else: self.getWaveformsButton.setEnabled(False) def closeEvent(self, event): """ When the main window closes, quit the application """ self.pyweed.closeApplication() event.ignore() def savePreferences(self): prefs = self.pyweed.preferences prefs.MainWindow.width = self.width() prefs.MainWindow.height = self.height() prefs.MainWindow.eventOptionsFloat = bool_to_str(self.eventOptionsDockWidget.isFloating()) prefs.MainWindow.stationOptionsFloat = bool_to_str(self.stationOptionsDockWidget.isFloating()) <file_sep># -*- coding: utf-8 -*- """ Manage the splash screen :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ import sys import logging from PyQt4 import QtGui, QtCore class SplashScreenHandler(logging.Handler): def __init__(self,): super(SplashScreenHandler, self).__init__(level=logging.INFO) pixmap = QtGui.QPixmap(":qrc/splash.png") self.splash = QtGui.QSplashScreen(pixmap, QtCore.Qt.WindowStaysOnTopHint) # Attach as handler to the root logger logger = logging.getLogger() logger.addHandler(self) self.splash.show() logger.info("Splash screen should be visible") def emit(self, record): msg = self.format(record) self.splash.showMessage(msg) QtGui.QApplication.processEvents() def finish(self, mainWin): super(SplashScreenHandler, self).close() self.splash.finish(mainWin) logger = logging.getLogger() logger.removeHandler(self) logger.info("Splash screen finished") <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyweed/gui/uic/WaveformDialog.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_WaveformDialog(object): def setupUi(self, WaveformDialog): WaveformDialog.setObjectName(_fromUtf8("WaveformDialog")) WaveformDialog.resize(1212, 724) self.verticalLayout = QtGui.QVBoxLayout(WaveformDialog) self.verticalLayout.setSpacing(0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.topFrame = QtGui.QFrame(WaveformDialog) self.topFrame.setFrameShape(QtGui.QFrame.NoFrame) self.topFrame.setFrameShadow(QtGui.QFrame.Plain) self.topFrame.setObjectName(_fromUtf8("topFrame")) self.horizontalLayout = QtGui.QHBoxLayout(self.topFrame) self.horizontalLayout.setMargin(2) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.downloadGroupBox = QtGui.QGroupBox(self.topFrame) self.downloadGroupBox.setEnabled(True) self.downloadGroupBox.setObjectName(_fromUtf8("downloadGroupBox")) self.verticalLayout_6 = QtGui.QVBoxLayout(self.downloadGroupBox) self.verticalLayout_6.setMargin(2) self.verticalLayout_6.setSpacing(2) self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6")) self.gridLayout = QtGui.QGridLayout() self.gridLayout.setVerticalSpacing(2) self.gridLayout.setObjectName(_fromUtf8("gridLayout")) self.secondsBeforeLabel = QtGui.QLabel(self.downloadGroupBox) self.secondsBeforeLabel.setObjectName(_fromUtf8("secondsBeforeLabel")) self.gridLayout.addWidget(self.secondsBeforeLabel, 0, 0, 1, 1) self.label = QtGui.QLabel(self.downloadGroupBox) self.label.setObjectName(_fromUtf8("label")) self.gridLayout.addWidget(self.label, 0, 2, 1, 1) self.secondsAfterPhaseComboBox = QtGui.QComboBox(self.downloadGroupBox) self.secondsAfterPhaseComboBox.setObjectName(_fromUtf8("secondsAfterPhaseComboBox")) self.gridLayout.addWidget(self.secondsAfterPhaseComboBox, 1, 3, 1, 1) self.secondsBeforePhaseComboBox = QtGui.QComboBox(self.downloadGroupBox) self.secondsBeforePhaseComboBox.setObjectName(_fromUtf8("secondsBeforePhaseComboBox")) self.gridLayout.addWidget(self.secondsBeforePhaseComboBox, 0, 3, 1, 1) spacerItem = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.gridLayout.addItem(spacerItem, 0, 4, 1, 1) self.secondsAfterSpinBox = QtGui.QSpinBox(self.downloadGroupBox) self.secondsAfterSpinBox.setMaximum(21600) self.secondsAfterSpinBox.setSingleStep(100) self.secondsAfterSpinBox.setProperty("value", 600) self.secondsAfterSpinBox.setObjectName(_fromUtf8("secondsAfterSpinBox")) self.gridLayout.addWidget(self.secondsAfterSpinBox, 1, 1, 1, 1) self.secondsBeforeSpinBox = QtGui.QSpinBox(self.downloadGroupBox) self.secondsBeforeSpinBox.setMaximum(3600) self.secondsBeforeSpinBox.setSingleStep(10) self.secondsBeforeSpinBox.setProperty("value", 60) self.secondsBeforeSpinBox.setObjectName(_fromUtf8("secondsBeforeSpinBox")) self.gridLayout.addWidget(self.secondsBeforeSpinBox, 0, 1, 1, 1) self.label_2 = QtGui.QLabel(self.downloadGroupBox) self.label_2.setObjectName(_fromUtf8("label_2")) self.gridLayout.addWidget(self.label_2, 1, 2, 1, 1) self.secondsAfterLabel = QtGui.QLabel(self.downloadGroupBox) self.secondsAfterLabel.setObjectName(_fromUtf8("secondsAfterLabel")) self.gridLayout.addWidget(self.secondsAfterLabel, 1, 0, 1, 1) self.verticalLayout_6.addLayout(self.gridLayout) self.widget_5 = QtGui.QWidget(self.downloadGroupBox) self.widget_5.setObjectName(_fromUtf8("widget_5")) self.horizontalLayout_7 = QtGui.QHBoxLayout(self.widget_5) self.horizontalLayout_7.setMargin(2) self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) self.downloadPushButton = QtGui.QPushButton(self.widget_5) self.downloadPushButton.setMinimumSize(QtCore.QSize(200, 0)) self.downloadPushButton.setCheckable(False) self.downloadPushButton.setObjectName(_fromUtf8("downloadPushButton")) self.horizontalLayout_7.addWidget(self.downloadPushButton) self.downloadStatusLabel = QtGui.QLabel(self.widget_5) self.downloadStatusLabel.setObjectName(_fromUtf8("downloadStatusLabel")) self.horizontalLayout_7.addWidget(self.downloadStatusLabel, QtCore.Qt.AlignLeft) self.verticalLayout_6.addWidget(self.widget_5) self.horizontalLayout.addWidget(self.downloadGroupBox) self.saveGroupBox = QtGui.QGroupBox(self.topFrame) self.saveGroupBox.setEnabled(True) self.saveGroupBox.setObjectName(_fromUtf8("saveGroupBox")) self.verticalLayout_5 = QtGui.QVBoxLayout(self.saveGroupBox) self.verticalLayout_5.setMargin(2) self.verticalLayout_5.setSpacing(2) self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) self.gridLayout_2 = QtGui.QGridLayout() self.gridLayout_2.setVerticalSpacing(2) self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2")) self.horizontalLayout_4 = QtGui.QHBoxLayout() self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) self.saveFormatComboBox = QtGui.QComboBox(self.saveGroupBox) self.saveFormatComboBox.setObjectName(_fromUtf8("saveFormatComboBox")) self.horizontalLayout_4.addWidget(self.saveFormatComboBox) spacerItem1 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem1) self.horizontalLayout_4.setStretch(1, 1) self.gridLayout_2.addLayout(self.horizontalLayout_4, 1, 1, 1, 1) self.saveDirectoryLabel = QtGui.QLabel(self.saveGroupBox) self.saveDirectoryLabel.setObjectName(_fromUtf8("saveDirectoryLabel")) self.gridLayout_2.addWidget(self.saveDirectoryLabel, 0, 0, 1, 1) self.saveFormatLabel = QtGui.QLabel(self.saveGroupBox) self.saveFormatLabel.setObjectName(_fromUtf8("saveFormatLabel")) self.gridLayout_2.addWidget(self.saveFormatLabel, 1, 0, 1, 1) self.horizontalLayout_6 = QtGui.QHBoxLayout() self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6")) self.saveDirectoryPushButton = QtGui.QPushButton(self.saveGroupBox) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.saveDirectoryPushButton.sizePolicy().hasHeightForWidth()) self.saveDirectoryPushButton.setSizePolicy(sizePolicy) self.saveDirectoryPushButton.setFocusPolicy(QtCore.Qt.NoFocus) self.saveDirectoryPushButton.setStyleSheet(_fromUtf8("QPushButton { text-align: left; }")) self.saveDirectoryPushButton.setObjectName(_fromUtf8("saveDirectoryPushButton")) self.horizontalLayout_6.addWidget(self.saveDirectoryPushButton) self.saveDirectoryBrowseToolButton = QtGui.QToolButton(self.saveGroupBox) self.saveDirectoryBrowseToolButton.setIconSize(QtCore.QSize(16, 16)) self.saveDirectoryBrowseToolButton.setObjectName(_fromUtf8("saveDirectoryBrowseToolButton")) self.horizontalLayout_6.addWidget(self.saveDirectoryBrowseToolButton) spacerItem2 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_6.addItem(spacerItem2) self.horizontalLayout_6.setStretch(2, 1) self.gridLayout_2.addLayout(self.horizontalLayout_6, 0, 1, 1, 1) self.verticalLayout_5.addLayout(self.gridLayout_2) self.widget_6 = QtGui.QWidget(self.saveGroupBox) self.widget_6.setObjectName(_fromUtf8("widget_6")) self.horizontalLayout_8 = QtGui.QHBoxLayout(self.widget_6) self.horizontalLayout_8.setMargin(2) self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8")) self.savePushButton = QtGui.QPushButton(self.widget_6) self.savePushButton.setMinimumSize(QtCore.QSize(200, 0)) self.savePushButton.setCheckable(False) self.savePushButton.setObjectName(_fromUtf8("savePushButton")) self.horizontalLayout_8.addWidget(self.savePushButton) self.saveStatusLabel = QtGui.QLabel(self.widget_6) self.saveStatusLabel.setObjectName(_fromUtf8("saveStatusLabel")) self.horizontalLayout_8.addWidget(self.saveStatusLabel, QtCore.Qt.AlignLeft) self.verticalLayout_5.addWidget(self.widget_6) self.horizontalLayout.addWidget(self.saveGroupBox) self.verticalLayout.addWidget(self.topFrame) self.selectionTableFrame = QtGui.QFrame(WaveformDialog) self.selectionTableFrame.setObjectName(_fromUtf8("selectionTableFrame")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.selectionTableFrame) self.verticalLayout_2.setMargin(2) self.verticalLayout_2.setSpacing(2) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.filterGroupBox = QtGui.QGroupBox(self.selectionTableFrame) self.filterGroupBox.setEnabled(True) self.filterGroupBox.setObjectName(_fromUtf8("filterGroupBox")) self.horizontalLayout_2 = QtGui.QHBoxLayout(self.filterGroupBox) self.horizontalLayout_2.setMargin(2) self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.eventComboBox = QtGui.QComboBox(self.filterGroupBox) self.eventComboBox.setObjectName(_fromUtf8("eventComboBox")) self.horizontalLayout_2.addWidget(self.eventComboBox) self.networkComboBox = QtGui.QComboBox(self.filterGroupBox) self.networkComboBox.setObjectName(_fromUtf8("networkComboBox")) self.horizontalLayout_2.addWidget(self.networkComboBox) self.stationComboBox = QtGui.QComboBox(self.filterGroupBox) self.stationComboBox.setObjectName(_fromUtf8("stationComboBox")) self.horizontalLayout_2.addWidget(self.stationComboBox) self.horizontalLayout_2.setStretch(0, 3) self.horizontalLayout_2.setStretch(1, 1) self.horizontalLayout_2.setStretch(2, 1) self.verticalLayout_2.addWidget(self.filterGroupBox) self.selectionTable = QtGui.QTableWidget(self.selectionTableFrame) self.selectionTable.setMinimumSize(QtCore.QSize(500, 100)) self.selectionTable.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) self.selectionTable.setSelectionMode(QtGui.QAbstractItemView.NoSelection) self.selectionTable.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows) self.selectionTable.setVerticalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel) self.selectionTable.setHorizontalScrollMode(QtGui.QAbstractItemView.ScrollPerPixel) self.selectionTable.setShowGrid(False) self.selectionTable.setObjectName(_fromUtf8("selectionTable")) self.selectionTable.setColumnCount(0) self.selectionTable.setRowCount(0) self.selectionTable.horizontalHeader().setStretchLastSection(False) self.selectionTable.verticalHeader().setVisible(True) self.verticalLayout_2.addWidget(self.selectionTable) self.verticalLayout.addWidget(self.selectionTableFrame) self.verticalLayout.setStretch(1, 1) self.retranslateUi(WaveformDialog) QtCore.QMetaObject.connectSlotsByName(WaveformDialog) def retranslateUi(self, WaveformDialog): WaveformDialog.setWindowTitle(_translate("WaveformDialog", "Dialog", None)) self.downloadGroupBox.setTitle(_translate("WaveformDialog", "Download / Preview Waveforms", None)) self.secondsBeforeLabel.setText(_translate("WaveformDialog", "Start:", None)) self.label.setText(_translate("WaveformDialog", "secs before", None)) self.label_2.setText(_translate("WaveformDialog", "secs after", None)) self.secondsAfterLabel.setText(_translate("WaveformDialog", "End:", None)) self.downloadPushButton.setText(_translate("WaveformDialog", "Download", None)) self.downloadStatusLabel.setText(_translate("WaveformDialog", "Download status", None)) self.saveGroupBox.setTitle(_translate("WaveformDialog", "Save Waveforms", None)) self.saveDirectoryLabel.setText(_translate("WaveformDialog", "To:", None)) self.saveFormatLabel.setText(_translate("WaveformDialog", "As:", None)) self.saveDirectoryPushButton.setText(_translate("WaveformDialog", "Directory", None)) self.saveDirectoryBrowseToolButton.setText(_translate("WaveformDialog", "Open", None)) self.savePushButton.setText(_translate("WaveformDialog", "Save", None)) self.saveStatusLabel.setText(_translate("WaveformDialog", "Save status", None)) self.filterGroupBox.setTitle(_translate("WaveformDialog", "Table Filters", None)) self.selectionTable.setSortingEnabled(True) <file_sep>import os.path __pkg_path___ = os.path.dirname(os.path.abspath(__file__)) # Use Python semantic versioning # https://packaging.python.org/tutorials/distributing-packages/#semantic-versioning-preferred __version__ = '1.0.0' __app_name__ = "PyWEED" <file_sep># -*- coding: utf-8 -*- """ Seismap is a subclass of Basemap, specialized for handling seismic data. Ideas and code borrowed from: * https://github.com/matplotlib/basemap/blob/master/examples/allskymap.py :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) import numpy as np from mpl_toolkits.basemap import Basemap from pyweed.pyweed_utils import get_bounding_circle, get_preferred_origin, get_distance from logging import getLogger from PyQt4 import QtCore from PyQt4.QtCore import pyqtSignal LOGGER = getLogger(__name__) class MapMarkers(object): """ Configures and tracks the markers (for items on the map and bounding boxes/toroids) on the map. This handles a single type, so there is one instance of this class for events and one for stations. """ color = '#FFFFFF' highlight_color = '#FFFF00' marker_type = 'o' marker_size = 6 highlight_marker_size = 12 bounds_linewidth = 2 bounds_linestyle = 'dashed' bounds_alpha = 0.5 markers = None highlights = None box_markers = None toroid_markers = None def __init__(self): self.markers = [] self.highlights = [] self.box_markers = [] self.toroid_markers = [] class EventMarkers(MapMarkers): color = '#FFFF00' highlight_color = '#FFA500' marker_type = 'o' # circle class StationMarkers(MapMarkers): color = '#FF0000' highlight_color = '#CD0000' marker_type = 'v' # inverted triangle class DrawEvent(object): """ Event emitted when drawing on the map starts/stops. """ def __init__(self, mode, points=None): #: The drawing mode being started/stopped self.mode = mode #: When stopping, we may pass back points representing the drawn area self.points = points class Seismap(QtCore.QObject): """ Map display using Basemap """ # Default kwargs DEFAULT_BASEMAP_KWARGS = dict( projection='cyl', # We only support cylindrical projection for now resolution='l', # c/l/i/h/f ) # Signals emitted when starting/ending a draw operation drawStart = pyqtSignal(object) drawEnd = pyqtSignal(object) # Cursors for pan and draw modes panCursor = QtCore.Qt.PointingHandCursor drawCursor = QtCore.Qt.CrossCursor # Markers eventMarkers = None stationMarkers = None def __init__(self, canvas): super(Seismap, self).__init__() self.canvas = canvas self.mapFigure = canvas.fig self.mapAxes = self.mapFigure.add_axes([0.01, 0.01, .98, .98]) # Trackers for the markers self.eventMarkers = EventMarkers() self.stationMarkers = StationMarkers() # Basic map features self.initBasemap() self.initDrawing() def initBasemap(self): # NOTE: http://matplotlib.org/basemap/api/basemap_api.html # NOTE: https://gist.github.com/dannguyen/eb1c4e70565d8cb82d63 self.mapAxes.clear() basemap_kwargs = {} basemap_kwargs.update(self.DEFAULT_BASEMAP_KWARGS) basemap_kwargs.update( ax=self.mapAxes ) self.basemap = Basemap(**basemap_kwargs) self.basemap.bluemarble(scale=0.25, alpha=0.42) self.basemap.drawcoastlines(color='#555566', linewidth=1) self.basemap.drawmeridians(np.arange(0, 360, 30)) self.basemap.drawparallels(np.arange(-90, 90, 30)) self.canvas.draw_idle() def getLatLon(self, x, y): """ Translate a canvas x/y coordinate to lat/lon """ (lon, lat) = self.basemap(x, y, inverse=True) return (lat, lon) def addMarkers(self, markers, points): """ Display marker locations @param markers: either self.eventMarkers or self.stationMarkers @param points: a list of (lat, lon) values """ self.clearMarkers(markers, redraw=False) self.clearHighlights(markers, redraw=False) # See http://matplotlib.org/api/markers_api.html#module-matplotlib.markers if len(points): (lats, lons) = zip(*points) # Plot in projection coordinates x, y = self.basemap(lons, lats) markers.markers.extend( self.basemap.plot( x, y, linestyle='None', marker=markers.marker_type, markersize=markers.marker_size, color=markers.color, markeredgecolor=markers.color ) ) self.canvas.draw_idle() def addHighlights(self, markers, points): """ Highlight selected items @param markers: either self.eventMarkers or self.stationMarkers @param points: a list of (lat, lon) values """ self.clearHighlights(markers, redraw=False) if len(points): (lats, lons) = zip(*points) # Plot in projection coordinates # TODO: Use self.scatter() with zorder=99 to keep highlighting on top? x, y = self.basemap(lons, lats) markers.highlights.extend( self.basemap.plot( x, y, linestyle='None', marker=markers.marker_type, markersize=markers.highlight_marker_size, color=markers.highlight_color ) ) self.canvas.draw_idle() def addMarkerBox(self, markers, n, e, s, w): """ Display a bounding box """ # Check for box wrapping around the map edge if e < w: # Need to create two paths paths = [ [[s, 180], [s, w], [n, w], [n, 180]], [[s, -180], [s, e], [n, e], [n, -180]] ] else: paths = [ [[n, w], [n, e], [s, e], [s, w], [n, w]] ] for path in paths: (lats, lons) = zip(*path) (x, y) = self.basemap(lons, lats) markers.box_markers.extend( self.basemap.plot( x, y, color=markers.color, linewidth=markers.bounds_linewidth, linestyle=markers.bounds_linestyle, alpha=markers.bounds_alpha )) self.canvas.draw_idle() def addMarkerToroid(self, markers, lat, lon, minradius, maxradius): """ Display a toroidal bounding area """ for r in (minradius, maxradius): if r > 0: paths = self.wrapPath(get_bounding_circle(lat, lon, r)) for path in paths: (lats, lons) = zip(*path) (x, y) = self.basemap(lons, lats) markers.toroid_markers.extend( self.basemap.plot( x, y, color=markers.color, linewidth=markers.bounds_linewidth, linestyle=markers.bounds_linestyle, alpha=markers.bounds_alpha )) self.canvas.draw_idle() def clearMarkers(self, markers, redraw=True): """ Remove existing marker elements """ # See http://stackoverflow.com/questions/4981815/how-to-remove-lines-in-a-matplotlib-plot try: while markers.markers: markers.markers.pop(0).remove() markers.markers = [] except IndexError: pass if redraw: self.canvas.draw_idle() def clearHighlights(self, markers, redraw=True): """ Remove existing highlights """ try: while markers.highlights: markers.highlights.pop(0).remove() markers.highlights = [] except IndexError: pass if redraw: self.canvas.draw_idle() def clearBoundingMarkers(self, markers, redraw=True): """ Remove existing bounding box/toroid markers """ try: while markers.box_markers: markers.box_markers.pop(0).remove() markers.box_markers = [] while markers.toroid_markers: markers.toroid_markers.pop(0).remove() markers.toroid_markers = [] except IndexError: pass if redraw: self.canvas.draw_idle() def addEvents(self, catalog): """ Display event locations """ points = [ (o.latitude, o.longitude) for o in [get_preferred_origin(e) for e in catalog] if o ] self.addMarkers(self.eventMarkers, points) def addEventsHighlighting(self, points): """ Highlights selected events """ self.addHighlights(self.eventMarkers, points) def addEventsBox(self, n, e, s, w): """ Display event box """ self.addMarkerBox(self.eventMarkers, n, e, s, w) def addEventsToroid(self, lat, lon, minradius, maxradius): """ Display event locations """ self.addMarkerToroid(self.eventMarkers, lat, lon, minradius, maxradius) def clearEventsBounds(self): """ Clear event bounding markers """ self.clearBoundingMarkers(self.eventMarkers) def addStations(self, inventory): """ Display station locations """ points = [ (s.latitude, s.longitude) for n in inventory.networks for s in n.stations ] self.addMarkers(self.stationMarkers, points) def addStationsHighlighting(self, points): """ Highlight selected stations """ self.addHighlights(self.stationMarkers, points) def addStationsBox(self, n, e, s, w): """ Display station box outline """ self.addMarkerBox(self.stationMarkers, n, e, s, w) def addStationsToroid(self, lat, lon, minradius, maxradius): """ Display station locations """ self.addMarkerToroid(self.stationMarkers, lat, lon, minradius, maxradius) def clearStationsBounds(self): """ Clear station bounding markers """ self.clearBoundingMarkers(self.stationMarkers) def wrapPath(self, path): """ Split a path of (lat, lon) values into a list of paths none of which crosses the map boundary This is a workaround for https://github.com/matplotlib/basemap/issues/214 """ lastPoint = None currentSubpath = [] subpaths = [currentSubpath] for point in path: # Detect the path wrapping around the map boundary midpoints = self.wrapPoint(lastPoint, point) if midpoints: # The first midpoint goes at the end of the previous subpath currentSubpath.append(midpoints[0]) currentSubpath = [] subpaths.append(currentSubpath) # The second midpoint goes at the start of the new subpath currentSubpath.append(midpoints[1]) currentSubpath.append(point) lastPoint = point # If the path crosses the map boundary, we will (usually?) have 3 subpaths, and the # first and last subpaths are actually contiguous so join them together if len(subpaths) > 2: subpaths[-1].extend(subpaths[0]) subpaths = subpaths[1:] return subpaths def wrapPoint(self, p1, p2): """ Given two lat/lon pairs representing a line segment to be plotted, if the segment crosses the map boundary this returns two points (one at each edge of the map) where the segment crosses the boundary, or None if the segment doesn't cross the boundary. For example: wrapPoint([20, 170], [10, -170]) returns [[15, 180], [15, -180]] This means that the segment should be split into: [20, 170] - [15, 180] [15, -180] - [10, -170] """ if p1 and p2: dlon = p2[1] - p1[1] if abs(dlon) > 180: # Interpolate the point where the segment crosses the boundary dlat = p2[0] - p1[0] if dlon < 0: # Wraps from east to west midlat = p1[0] + (180 - p1[1]) * dlat / (dlon + 360) return [[midlat, 180], [midlat, -180]] else: # Wraps from west to east midlat = p1[0] + (-180 - p1[1]) * dlat / (dlon - 360) return [[midlat, -180], [midlat, 180]] return None def zoomIn(self): """ Zoom into the map """ # Zoom in by 2, by trimming 1/4 from each edge xlim = self.mapAxes.get_xlim() xdelta = (xlim[1] - xlim[0]) / 4 ylim = self.mapAxes.get_ylim() ydelta = (ylim[1] - ylim[0]) / 4 self.mapAxes.set_xlim(xlim[0] + xdelta, xlim[1] - xdelta) self.mapAxes.set_ylim(ylim[0] + ydelta, ylim[1] - ydelta) self.canvas.draw_idle() def zoomOut(self): """ Zoom out on the map """ # Zoom out by 2, by adding 1/2 to each edge xlim = self.mapAxes.get_xlim() xdelta = (xlim[1] - xlim[0]) / 2 ylim = self.mapAxes.get_ylim() ydelta = (ylim[1] - ylim[0]) / 2 self.mapAxes.set_xlim(xlim[0] - xdelta, xlim[1] + xdelta) self.mapAxes.set_ylim(ylim[0] - ydelta, ylim[1] + ydelta) self.canvas.draw_idle() def zoomReset(self): """ Zoom all the way out of the map """ self.mapAxes.set_xlim(-180, 180) self.mapAxes.set_ylim(-90, 90) self.canvas.draw_idle() def fitCanvas(self, *args): canvas_w = self.canvas.width() canvas_h = self.canvas.height() map_xlim = self.mapAxes.get_xlim() map_ylim = self.mapAxes.get_ylim() map_w = map_xlim[1] - map_xlim[0] map_h = map_ylim[1] - map_ylim[0] prop_map_h = ((map_w * canvas_h) / canvas_w) adjustment = ((prop_map_h - map_h) / 2) self.mapAxes.set_ylim(map_ylim[0] - adjustment, map_ylim[1] + adjustment) self.canvas.draw_idle() def initDrawing(self): # Map drawing mode self.draw_mode = None # Indicates that we are actually drawing (ie. mouse button is down) self.drawing = False # If drawing, the start and end points self.draw_points = [] # Handler functions for mouse down/move/up, these are created when drawing is activated # See http://matplotlib.org/users/event_handling.html self.draw_handlers = { 'click': self.canvas.mpl_connect('button_press_event', self.onMouseDown), 'scroll_wheel': self.canvas.mpl_connect('scroll_event', self.onScrollWheel), 'resize': self.canvas.mpl_connect('resize_event', self.fitCanvas), } self.updateCursor() def setDrawMode(self, mode): """ Initialize the given drawing mode """ LOGGER.info("Drawing mode set to %s", mode) self.drawing = False self.draw_mode = mode self.drawStart.emit(DrawEvent(mode)) self.updateCursor() def clearDrawMode(self): """ Clear any active drawing mode """ if self.draw_mode: points = None if self.drawing: # If we finished drawing bounds, pass back the parameters indicated if self.draw_points: if 'box' in self.draw_mode: points = self.drawPointsToBox() elif 'toroid' in self.draw_mode: points = self.drawPointsToToroid() self.drawEnd.emit(DrawEvent(self.draw_mode, points)) self.drawing = False self.draw_mode = None self.updateCursor() def toggleDrawMode(self, mode, toggle): """ Event handler when a draw mode button is clicked """ if toggle: self.setDrawMode(mode) else: self.clearDrawMode() def updateCursor(self): """ Set the cursor on the canvas according to the current mode """ if self.draw_mode: self.canvas.setCursor(self.drawCursor) else: self.canvas.setCursor(self.panCursor) def drawPointsToBox(self): """ Convert self.draw_points to a tuple of (n, e, s, w) """ (lat1, lon1) = self.draw_points[0] (lat2, lon2) = self.draw_points[1] return ( max(lat1, lat2), max(lon1, lon2), min(lat1, lat2), min(lon1, lon2) ) def drawPointsToToroid(self): """ Convert self.draw_points to a tuple of (lat, lon, radius) """ (lat1, lon1) = self.draw_points[0] (lat2, lon2) = self.draw_points[1] radius = get_distance(lat1, lon1, lat2, lon2) return (lat1, lon1, radius) def onMouseDown(self, event): """ Handle a mouse click on the map """ if self.draw_mode: # Start a drawing operation (lat, lon) = self.getLatLon(event.xdata, event.ydata) if lat is not None and lon is not None: self.drawing = True self.draw_points = [[lat, lon], [lat, lon]] else: # If there's no draw operation, pan the map if event.inaxes == self.mapAxes: LOGGER.debug("Starting pan") self.drawing = True self.mapAxes.start_pan(event.x, event.y, event.button) # If we've started a drawing operation, connect listeners for activity if self.drawing: self.draw_handlers['release'] = self.canvas.mpl_connect('button_release_event', self.onMouseUp) self.draw_handlers['move'] = self.canvas.mpl_connect('motion_notify_event', self.onMouseMove) def onMouseUp(self, event): """ Handle a mouse up event, this should only be called while the user is drawing on the map """ # Disconnect the release/move handlers for event in ('release', 'move',): if event in self.draw_handlers: self.canvas.mpl_disconnect(self.draw_handlers[event]) del self.draw_handlers[event] # If there's no draw mode, we are probably panning so turn that off if not self.draw_mode: self.mapAxes.end_pan() # Exit drawing mode self.clearDrawMode() def onMouseMove(self, event): """ Handle a mouse move event, this should only be called while the user is drawing on the map """ if self.drawing: if self.draw_mode: (lat, lon) = self.getLatLon(event.xdata, event.ydata) if lat is not None and lon is not None: self.draw_points[1] = [lat, lon] LOGGER.debug("Draw points: %s" % self.draw_points) self.updateDrawBounds() else: # If we aren't drawing anything, pan the map self.mapAxes.drag_pan(event.button, event.key, event.x, event.y) self.canvas.draw_idle() def updateDrawBounds(self): """ Update the displayed bounding box/toroid as the user is drawing it """ # Clear any existing bounds if 'events' in self.draw_mode: self.clearEventsBounds() elif 'stations' in self.draw_mode: self.clearStationsBounds() # Build options values based on box or toroid if 'box' in self.draw_mode: (n, e, s, w) = self.drawPointsToBox() if 'events' in self.draw_mode: self.addEventsBox(n, e, s, w) elif 'stations' in self.draw_mode: self.addStationsBox(n, e, s, w) elif 'toroid' in self.draw_mode: (lat, lon, maxradius) = self.drawPointsToToroid() if 'events' in self.draw_mode: self.addEventsToroid(lat, lon, 0, maxradius) elif 'stations' in self.draw_mode: self.addStationsToroid(lat, lon, 0, maxradius) def onScrollWheel(self, event): """ Zoom on scroll wheel """ if event.step: if event.step > 0: self.zoomIn() else: self.zoomOut() <file_sep># -*- coding: utf-8 -*- """ Container for waveforms. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from __future__ import (absolute_import, division, print_function) import os from obspy import UTCDateTime from pyweed.signals import SignalingThread, SignalingObject import collections from PyQt4 import QtCore, QtGui import obspy from logging import getLogger import matplotlib import weakref from pyweed.pyweed_utils import get_sncl, get_event_id, TimeWindow,\ get_preferred_origin, get_preferred_magnitude, OUTPUT_FORMAT_EXTENSIONS,\ get_event_description, get_arrivals, format_time_str, get_distance, get_service_url, CancelledException from obspy.core.util.attribdict import AttribDict from obspy.io.sac.sactrace import SACTrace from obspy.core.stream import Stream import concurrent.futures LOGGER = getLogger(__name__) THREAD_POOL_SIZE = 10 class WaveformEntry(AttribDict): """ Class representing an event/channel combination and the relevant waveform request """ defaults = dict( # Weak refs to ObsPy event/channel event_ref=None, network_ref=None, station_ref=None, channel_ref=None, # Distance from event to station distance=None, # Phase arrivals arrivals=None, # Timing information event_time=None, start_time=None, end_time=None, start_string=None, end_string=None, # Reflects user checkbox in the table keep=True, # Tracking IDs waveform_id=None, # Other table display values sncl=None, event_time_str=None, event_description=None, event_mag=None, event_mag_value=None, event_depth=None, # Base directory to download files to (from WaveformsHandler) download_dir=None, # Time window settings (from WaveformHandler) time_window=None, # Base filename for mseed, image, etc. base_filename=None, # Full paths mseed_path=None, mseed_exists=False, image_path=None, image_exists=False, # Loading indicator loading=False, # Error message if unable to load error=None, ) def __init__(self, event, network, station, channel, *args, **kwargs): super(WaveformEntry, self).__init__(*args, **kwargs) self.event_ref = weakref.ref(event) self.network_ref = weakref.ref(network) self.station_ref = weakref.ref(station) self.channel_ref = weakref.ref(channel) self.sncl = get_sncl(network, station, channel) self.event_description = get_event_description(event) origin = get_preferred_origin(event) self.event_time = origin.time self.event_time_str = format_time_str(origin.time) self.event_depth = origin.depth / 1000 mag = get_preferred_magnitude(event) self.event_mag = "%s%s" % (mag.mag, mag.magnitude_type) self.event_mag_value = mag.mag self.waveform_id = '%s_%s' % (self.sncl, get_event_id(event)) self.distance = get_distance( origin.latitude, origin.longitude, station.latitude, station.longitude) def update_handler_values(self, waveform_handler): """ Update any values that come from the WaveformHander """ self.download_dir = waveform_handler.downloadDir self.time_window = waveform_handler.time_window def prepare(self): """ Calculate (or recalculate) values in preparation for doing work """ if not self.arrivals: self.arrivals = get_arrivals(self.distance, self.event_depth) (self.start_time, self.end_time) = self.time_window.calculate_window( self.event_time, self.arrivals) self.start_string = UTCDateTime(self.start_time).format_iris_web_service().replace(':', '_') self.end_string = UTCDateTime(self.end_time).format_iris_web_service().replace(':', '_') self.base_filename = "%s_%s_%s" % (self.sncl, self.start_string, self.end_string) self.mseed_path = os.path.join(self.download_dir, "%s.mseed" % self.base_filename) self.image_path = os.path.join(self.download_dir, "%s.png" % self.base_filename) self.check_files() def check_files(self): """ After calculating the paths for downloaded files, check to see if they're already there """ self.mseed_exists = os.path.exists(self.mseed_path) self.image_exists = os.path.exists(self.image_path) class WaveformResult(object): """ Container for a waveform result to be passed as a signal, includes the waveform ID so that the result can be correctly handled. """ def __init__(self, waveform_id, result): self.waveform_id = waveform_id self.result = result def load_waveform(client, waveform): """ Download the given waveform data and generate an image. This is a standalone function so we can run it in a separate thread. This modifies the waveform entry and returns a dummy value, or raises an exception on any error. """ plot_width = 600 plot_height = 120 waveform_id = waveform.waveform_id LOGGER.debug("Loading waveform: %s (%s)", waveform_id, QtCore.QThread.currentThreadId()) # LOGGER.debug("Adding slowness") # QtCore.QThread.currentThread().sleep(2) try: waveform.prepare() if waveform.image_exists: # No download needed LOGGER.info("Waveform %s already has an image" % waveform_id) return True mseedFile = waveform.mseed_path LOGGER.debug("%s save as MiniSEED", waveform_id) # Load data from disk or network as appropriate if os.path.exists(mseedFile): LOGGER.info("Loading waveform data for %s from %s", waveform_id, mseedFile) st = obspy.read(mseedFile) else: (network, station, location, channel) = waveform.sncl.split('.') service_url = get_service_url(client, 'dataselect', { "network": network, "station": station, "location": location, "channel": channel, "starttime": waveform.start_time, "endtime": waveform.end_time, }) LOGGER.info("Retrieving waveform data for %s from %s", waveform_id, service_url) st = client.get_waveforms( network, station, location, channel, waveform.start_string, waveform.end_string) # Write to file st.write(mseedFile, format="MSEED") # Generate image if necessary imageFile = waveform.image_path if not os.path.exists(imageFile): LOGGER.debug('Plotting waveform image to %s', imageFile) # In order to really customize the plotting, we need to return the figure and modify it h = st.plot(size=(plot_width, plot_height), handle=True) # Resize the subplot to a hard size, because otherwise it will do it inconsistently h.subplots_adjust(bottom=.2, left=.1, right=.95, top=.95) # Remove the title for c in h.get_children(): if isinstance(c, matplotlib.text.Text): c.remove() # Save with transparency h.savefig(imageFile) matplotlib.pyplot.close(h) waveform.check_files() except Exception as e: # Most common error is "no data" TODO: see https://github.com/obspy/obspy/issues/1656 if str(e).startswith("No data"): waveform.error = "No data available" else: waveform.error = str(e) # Reraise the exception to signal an error to the caller raise finally: # Mark as finished loading waveform.loading = False return True class WaveformsLoader(SignalingThread): """ Thread to download waveform data and generate an image """ progress = QtCore.pyqtSignal(object) def __init__(self, client, waveforms): """ Initialization. """ # Keep a reference to globally shared components self.client = client self.waveforms = waveforms self.futures = {} super(WaveformsLoader, self).__init__() def run(self): """ Make a webservice request for events using the passed in options. """ self.setPriority(QtCore.QThread.LowestPriority) self.clearFutures() self.futures = {} with concurrent.futures.ThreadPoolExecutor(THREAD_POOL_SIZE) as executor: for waveform in self.waveforms: # Dictionary to look up the waveform id by Future self.futures[executor.submit(load_waveform, self.client, waveform)] = waveform.waveform_id # Iterate through Futures as they complete for result in concurrent.futures.as_completed(self.futures): waveform_id = self.futures.get(result) if waveform_id: LOGGER.debug("Loader finished: %s", waveform_id) try: self.progress.emit(WaveformResult(waveform_id, result.result())) except Exception as e: self.progress.emit(WaveformResult(waveform_id, e)) self.futures = {} self.done.emit(None) def clearFutures(self): """ Cancel any outstanding tasks """ if self.futures: for future in self.futures: if not future.done(): LOGGER.debug("Cancelling unexecuted future") future.cancel() def cancel(self): """ User-requested cancel """ self.done.disconnect() self.progress.disconnect() self.clearFutures() class WaveformsHandler(SignalingObject): """ Manage the waveforms retrieval. The contents of self.waveforms is determined by the user selections in the main GUI events and SNCL tables. There will be a separate entry in self.waveforms for each event-SNCL combination regardless of any filtering that is applied in the WaveformsDialog to reduce the size of the visible table. """ progress = QtCore.pyqtSignal(object) def __init__(self, logger, preferences, client): """ Initialization. """ super(WaveformsHandler, self).__init__() # Keep a reference to globally shared components self.preferences = preferences self.client = client # Important preferences self.downloadDir = self.preferences.Waveforms.downloadDir # Loader component self.waveforms_loader = None # Thread to run the loader in self.thread = None # Asynchronous requests, each is working to download a single waveform self.requests = None # A TimeWindow object giving offsets and phase arrivals self.time_window = TimeWindow() # Current list of waveform entries self.waveforms = None # Waveforms indexed by id self.waveforms_by_id = None def create_waveforms(self, pyweed): """ Create a list of waveform entries based on the current event/station selections """ self.waveforms = [ WaveformEntry( event, network, station, channel ) for (event, network, station, channel) in pyweed.iter_selected_events_stations() ] self.waveforms_by_id = dict( (waveform.waveform_id, waveform) for waveform in self.waveforms ) def cancel_download(self): """ Cancel the loader if it's running """ LOGGER.debug('Cancelling existing downloads') if self.waveforms_loader: self.waveforms_loader.cancel() # Mark all the waveforms that are still marked as loading for waveform in self.waveforms: if waveform.loading: waveform.loading = False waveform.error = "Cancelled download" LOGGER.debug("Manually marking %s as cancelled", waveform.waveform_id) self.progress.emit(WaveformResult(waveform.waveform_id, None)) self.done.emit(CancelledException()) def download_waveforms(self, priority_ids, other_ids, time_window): """ Initiate a download of all the given waveforms """ LOGGER.info('Downloading waveforms') LOGGER.debug("Priority IDs: %s" % (priority_ids,)) LOGGER.debug("Other IDs: %s" % (other_ids,)) # Prepare the waveform entries self.time_window = time_window for waveform in self.waveforms: waveform.update_handler_values(self) # Clear error flag and set loading flag waveform.error = None waveform.loading = True # Get the waveforms ordered by priority waveform_ids = list(priority_ids) + list(other_ids) waveforms = [self.get_waveform(waveform_id) for waveform_id in waveform_ids] # Create a worker to load the data in a separate thread self.waveforms_loader = WaveformsLoader(self.client, waveforms) self.waveforms_loader.progress.connect(self.on_downloaded) self.waveforms_loader.done.connect(self.on_all_downloaded) self.waveforms_loader.start() def on_downloaded(self, result): """ Called for each downloaded waveform. :param result: a `WaveformResult` """ # LOGGER.debug("Downloaded waveform %s (%s)", result.waveform_id, QtCore.QThread.currentThreadId()) self.progress.emit(result) def on_all_downloaded(self, result): LOGGER.debug("All waveforms downloaded (%s)", QtCore.QThread.currentThreadId()) if self.waveforms_loader: self.waveforms_loader.quit() self.waveforms_loader.wait() LOGGER.debug("Download thread exited") self.done.emit(result) def get_waveform(self, waveform_id): """ Retrieve the Series for the given waveform """ return self.waveforms_by_id.get(waveform_id) def save_waveforms_iter(self, base_output_path, output_format, waveforms): """ Save waveforms, returning an iterator of WaveformResult objects whose values are True (saved), False (already saved), or Exception (error) This is so the GUI layer can handle save progress and errors in its own fashion """ if not os.path.exists(base_output_path): try: os.makedirs(base_output_path, 0o700) except Exception as e: raise Exception("Could not create the output path: %s" % str(e)) # Get the file extension to use extension = OUTPUT_FORMAT_EXTENSIONS[output_format] for waveform in waveforms: waveform_id = waveform.waveform_id try: output_file = os.path.extsep.join((waveform.base_filename, extension)) output_path = os.path.join(base_output_path, output_file) # Don't repeat any work that has already been done if not os.path.exists(output_path): LOGGER.debug('reading %s', waveform.mseed_path) st = obspy.read(waveform.mseed_path) self.save_waveform(st, output_path, output_format, waveform) yield WaveformResult(waveform_id, True) else: yield WaveformResult(waveform_id, False) except Exception as e: yield WaveformResult(waveform_id, e) def save_waveform(self, st, output_path, output_format, waveform): """ Save a single waveform. This should handle any special output features (eg. SAC metadata) """ LOGGER.debug('writing %s', output_path) if output_format in ('SAC', 'SACXY',): # For SAC output, we need to pull header data from the waveform record st = self.to_sac_stream(st, waveform) st.write(output_path, format=output_format) def to_sac_stream(self, st, waveform): """ Return a SACTrace based on the given stream, containing metadata headers from the waveform """ tr = SACTrace.from_obspy_trace(st[0]) tr.kevnm = waveform.event_description[:16] event = waveform.event_ref() if not event: LOGGER.warn("Lost reference to event %s", waveform.event_description) else: origin = get_preferred_origin(waveform.event_ref()) if origin: tr.evla = origin.latitude tr.evlo = origin.longitude tr.evdp = origin.depth / 1000 tr.o = origin.time - waveform.start_time magnitude = get_preferred_magnitude(waveform.event_ref()) if magnitude: tr.mag = magnitude.mag channel = waveform.channel_ref() if not channel: LOGGER.warn("Lost reference to channel %s", waveform.sncl) else: tr.stla = channel.latitude tr.stlo = channel.longitude tr.stdp = channel.depth tr.stel = channel.elevation tr.cmpaz = channel.azimuth tr.cmpinc = channel.dip + 90 tr.kinst = channel.sensor.description[:8] return Stream([tr.to_obspy_trace()]) # ------------------------------------------------------------------------------ # Helper functions # ------------------------------------------------------------------------------ # ------------------------------------------------------------------------------ # Main # ------------------------------------------------------------------------------ if __name__ == '__main__': import doctest doctest.testmod(exclude_empty=True) <file_sep>from selenium import webdriver import requests from io import BytesIO from PIL import Image, ImageEnhance import numpy as np # 1 准备工作 # 2 获取(下载)图片 # 3 分析图片,得到缺口的位置 # 4 根据缺口位置,进行移动操作 from selenium.webdriver import ActionChains def prepare(): """ 执行一些获取图片之前的准备工作。 """ driver.get("http://dun.163.com/trial/jigsaw") # 最大化窗口 driver.maximize_window() e = driver.find_element_by_css_selector(".is-right .u-mdtitle") # 执行JavaScripts语句。arguments可以用来获取实际参数。 driver.execute_script("arguments[0].scrollIntoView();", e) def download(selector): """根据css选择器下载指定的图片 :param selector css选择器 :return 下载之后的image图片对象。 """ e = driver.find_element_by_css_selector(selector) response = requests.get(e.get_attribute("src")) image = Image.open(BytesIO(response.content)) return image def get_image(): """ 处理下载的图像。 :return: 返回处理后的图像(背景图片与滑块图像)。 """ bg_image = download(".is-right img.yidun_bg-img") slider_image = download(".is-right img.yidun_jigsaw") # 获取图像的最小边界。【将纯黑色区域剪切掉】,返回最小边界的位置。 # 返回值是一个元组类型。元组中含有4个元素。分别是【左,上,右,下】的坐标位置。 bound = slider_image.getbbox() # 根据指定的边界(bound)进行图片的裁剪。返回裁剪之后的结果。 slider_image = slider_image.crop(bound) slider_image = slider_image.convert("L") slider_image = slider_image.point(lambda x: 0 if x == 0 else 255) slider_image.save("slider.jpg") # 处理图像对比度的操作。 ie = ImageEnhance.Contrast(bg_image) # 调整对比度。参数值越大,越明显。 bg_image = ie.enhance(100) bg_image = bg_image.convert("L") # 将背景图像进行裁剪。 bg_image = bg_image.crop((0, bound[1], bg_image.size[0], bound[3])) bg_image.save("bg.jpg") return bg_image, slider_image def get_edge(bg_image, slider_image): """ 根据背景图像与滑块图像,寻找缺位的位置。 :param bg_image: 背景图像 :param slider_image: 滑块图像 :return: 背景图像中缺口的位置 """ # 接收一个Image对象,返回该Image图像对应的像素值(数组)。 bg_array = np.array(bg_image) slider_array = np.array(slider_image) max_match = 0 match_index = 0 for i in range(slider_image.size[0], bg_image.size[0] - slider_image.size[0]): num = np.sum((bg_array[:, i: i + slider_image.size[0]] == slider_array) & (slider_array == 255)) #print(num) if num > max_match: max_match = num match_index = i print(match_index) return match_index def move(distance): """ 根据参数,将滑块移动指定的距离。 :param distance: 移动的距离 """ slider = driver.find_element_by_css_selector(".is-right div.yidun_slider") ActionChains(driver).click_and_hold(slider).perform() for i in range(distance): ActionChains(driver).move_by_offset(1, 0).perform() ActionChains(driver).release().perform() def main(): prepare() bg_image, slider_image = get_image() distance = get_edge(bg_image, slider_image) move(distance) if __name__ == "__main__": driver = webdriver.Chrome(executable_path=r"..\depend_soft\chromedriver") main() <file_sep># -*- coding: utf-8 -*- """ Custom QTableWidgetItem that embeds an image To be inserted into the QTableWidget with setItem(). http://stackoverflow.com/questions/14365875/qt-cannot-put-an-image-in-a-table :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtCore from PyQt4 import QtGui from pyweed.gui.TableWidget import CustomTableWidgetItemMixin class MyTableWidgetImageItem(CustomTableWidgetItemMixin, QtGui.QTableWidgetItem): def __init__(self, imagePath=None): super(MyTableWidgetImageItem, self).__init__() pic = QtGui.QPixmap(imagePath) # NOTE: From QPixmap we could use scaledToWidth() but the resulting images aren't so pretty # pic = pic.scaledToWidth(500) self.setData(QtCore.Qt.DecorationRole, pic) # NOTE: From QLabel we could use setScaledContents() but this doesn't preserve the aspect ratio # self.setScaledContents(True) <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyweed/gui/uic/PreferencesDialog.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_PreferencesDialog(object): def setupUi(self, PreferencesDialog): PreferencesDialog.setObjectName(_fromUtf8("PreferencesDialog")) PreferencesDialog.setWindowModality(QtCore.Qt.ApplicationModal) PreferencesDialog.resize(287, 241) PreferencesDialog.setModal(True) self.verticalLayout = QtGui.QVBoxLayout(PreferencesDialog) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.dataCentersGroupBox = QtGui.QGroupBox(PreferencesDialog) self.dataCentersGroupBox.setObjectName(_fromUtf8("dataCentersGroupBox")) self.formLayout_4 = QtGui.QFormLayout(self.dataCentersGroupBox) self.formLayout_4.setObjectName(_fromUtf8("formLayout_4")) self.label = QtGui.QLabel(self.dataCentersGroupBox) self.label.setObjectName(_fromUtf8("label")) self.formLayout_4.setWidget(0, QtGui.QFormLayout.LabelRole, self.label) self.eventDataCenterComboBox = QtGui.QComboBox(self.dataCentersGroupBox) self.eventDataCenterComboBox.setObjectName(_fromUtf8("eventDataCenterComboBox")) self.formLayout_4.setWidget(0, QtGui.QFormLayout.FieldRole, self.eventDataCenterComboBox) self.label_2 = QtGui.QLabel(self.dataCentersGroupBox) self.label_2.setObjectName(_fromUtf8("label_2")) self.formLayout_4.setWidget(1, QtGui.QFormLayout.LabelRole, self.label_2) self.stationDataCenterComboBox = QtGui.QComboBox(self.dataCentersGroupBox) self.stationDataCenterComboBox.setObjectName(_fromUtf8("stationDataCenterComboBox")) self.formLayout_4.setWidget(1, QtGui.QFormLayout.FieldRole, self.stationDataCenterComboBox) self.verticalLayout.addWidget(self.dataCentersGroupBox) self.groupBox = QtGui.QGroupBox(PreferencesDialog) self.groupBox.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.formLayout_3 = QtGui.QFormLayout(self.groupBox) self.formLayout_3.setObjectName(_fromUtf8("formLayout_3")) self.label_3 = QtGui.QLabel(self.groupBox) self.label_3.setObjectName(_fromUtf8("label_3")) self.formLayout_3.setWidget(0, QtGui.QFormLayout.LabelRole, self.label_3) self.cacheSizeSpinBox = QtGui.QSpinBox(self.groupBox) self.cacheSizeSpinBox.setMaximum(500) self.cacheSizeSpinBox.setObjectName(_fromUtf8("cacheSizeSpinBox")) self.formLayout_3.setWidget(0, QtGui.QFormLayout.FieldRole, self.cacheSizeSpinBox) self.verticalLayout.addWidget(self.groupBox) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setSpacing(2) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) spacerItem = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem) self.okButton = QtGui.QPushButton(PreferencesDialog) self.okButton.setDefault(True) self.okButton.setObjectName(_fromUtf8("okButton")) self.horizontalLayout.addWidget(self.okButton) self.cancelButton = QtGui.QPushButton(PreferencesDialog) self.cancelButton.setObjectName(_fromUtf8("cancelButton")) self.horizontalLayout.addWidget(self.cancelButton) self.verticalLayout.addLayout(self.horizontalLayout) self.verticalLayout.setStretch(2, 1) self.retranslateUi(PreferencesDialog) QtCore.QMetaObject.connectSlotsByName(PreferencesDialog) def retranslateUi(self, PreferencesDialog): PreferencesDialog.setWindowTitle(_translate("PreferencesDialog", "Preferences", None)) self.dataCentersGroupBox.setTitle(_translate("PreferencesDialog", "Data Centers", None)) self.label.setText(_translate("PreferencesDialog", "Events", None)) self.label_2.setText(_translate("PreferencesDialog", "Stations", None)) self.groupBox.setTitle(_translate("PreferencesDialog", "Advanced", None)) self.label_3.setText(_translate("PreferencesDialog", "Cache", None)) self.cacheSizeSpinBox.setSuffix(_translate("PreferencesDialog", " Mbytes", None)) self.okButton.setText(_translate("PreferencesDialog", "Save", None)) self.cancelButton.setText(_translate("PreferencesDialog", "Cancel", None)) <file_sep># -*- coding: utf-8 -*- """ Various Qt widget utilities :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore from logging import getLogger from PyQt4.QtCore import pyqtSlot LOGGER = getLogger(__name__) class ComboBoxAdapter(QtCore.QObject): """ Adapter for handling the fact that QComboBox can only display strings, but usually the "real" value is something else. """ #: Signal emitted when the QComboBox value changes, passing the actual value changed = QtCore.pyqtSignal(object) def __init__(self, comboBox, options, default=None): """ :param comboBox: A QComboBox :param options: A list of options in the form of (value, label) :param default: If nothing is selected, what should be returned? """ super(ComboBoxAdapter, self).__init__() self.comboBox = comboBox self.values = [option[0] for option in options] if default is None: default = self.values[0] self.default = default labels = [option[1] for option in options] self.comboBox.addItems(labels) self.comboBox.currentIndexChanged.connect(self.onChanged) def setValue(self, value): self.comboBox.setCurrentIndex(self.values.index(value)) def getValue(self, index=None): if index is None: index = self.comboBox.currentIndex() if index < 0: return self.default else: return self.values[index] @pyqtSlot(int) def onChanged(self, index): self.changed.emit(self.getValue(index)) <file_sep># -*- coding: utf-8 -*- """ Dialog containing an IPython console. :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from qtconsole.rich_ipython_widget import RichIPythonWidget from qtconsole.inprocess import QtInProcessKernelManager from PyQt4 import QtGui from pyweed.gui.BaseDialog import BaseDialog class EmbedIPython(RichIPythonWidget): def __init__(self, **kwarg): super(RichIPythonWidget, self).__init__() self.kernel_manager = QtInProcessKernelManager() self.kernel_manager.start_kernel() self.kernel = self.kernel_manager.kernel self.kernel.gui = 'qt4' self.kernel.shell.push(kwarg) self.kernel_client = self.kernel_manager.client() self.kernel_client.start_channels() class ConsoleDialog(BaseDialog): def __init__(self, pyweed, parent=None): super(ConsoleDialog, self).__init__(parent=parent) self.widget = EmbedIPython(pyweed=pyweed) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.widget) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) widget = ConsoleDialog() widget.show() sys.exit(app.exec_()) <file_sep># -*- coding: utf-8 -*- """ Station Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from pyweed.options import Options, DateOption, FloatOption, Option import copy from pyweed.dist_from_events import get_combined_locations, CrossBorderException from pyweed.pyweed_utils import get_preferred_origin from logging import getLogger LOGGER = getLogger(__name__) class StationOptions(Options): TIME_RANGE = 'timeBetween' TIME_EVENTS = 'timeFromEvents' time_choice = Option(hidden=True, default=TIME_RANGE) starttime = DateOption(default=-30) endtime = DateOption(default=0) network = Option(default="_GSN") station = Option(default="*") location = Option(default="*") channel = Option(default="?HZ") LOCATION_GLOBAL = 'locationGlobal' LOCATION_BOX = 'locationRange' LOCATION_POINT = 'locationDistanceFromPoint' LOCATION_EVENTS = 'locationDistanceFromEvents' location_choice = Option(hidden=True, default=LOCATION_GLOBAL) minlatitude = FloatOption(default=-90) maxlatitude = FloatOption(default=90) minlongitude = FloatOption(default=-180) maxlongitude = FloatOption(default=180) latitude = FloatOption() longitude = FloatOption() minradius = FloatOption() maxradius = FloatOption(default=30) # Special settings indicating the location is based on distance from selected events mindistance = FloatOption(hidden=True) maxdistance = FloatOption(hidden=True) event_locations = None def get_time_options(self): if self.time_choice == self.TIME_RANGE: return self.get_options(['starttime', 'endtime']) else: return {} def get_location_options(self): if self.location_choice == self.LOCATION_BOX: return self.get_options(['minlatitude', 'maxlatitude', 'minlongitude', 'maxlongitude']) elif self.location_choice == self.LOCATION_POINT: return self.get_options(['latitude', 'longitude', 'minradius', 'maxradius']) else: return {} def get_obspy_options(self): base_keys = ['network', 'station', 'location', 'channel'] options = self.get_options(keys=base_keys) # Default level is 'station' but we always(?) want 'channel' options['level'] = 'channel' options.update(self.get_time_options()) options.update(self.get_location_options()) return options def get_event_distances(self): """ If this is a event-based query, return those settings Note that this isn't part of the Obspy query! """ if self.location_choice == self.LOCATION_EVENTS: return self.get_options(['mindistance', 'maxdistance']) else: return {} <file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pyweed/gui/uic/EventOptionsWidget.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_EventOptionsWidget(object): def setupUi(self, EventOptionsWidget): EventOptionsWidget.setObjectName(_fromUtf8("EventOptionsWidget")) EventOptionsWidget.resize(302, 667) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(EventOptionsWidget.sizePolicy().hasHeightForWidth()) EventOptionsWidget.setSizePolicy(sizePolicy) self.verticalLayout = QtGui.QVBoxLayout(EventOptionsWidget) self.verticalLayout.setSpacing(4) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.timeGroupBox = QtGui.QGroupBox(EventOptionsWidget) self.timeGroupBox.setObjectName(_fromUtf8("timeGroupBox")) self.verticalLayout_2 = QtGui.QVBoxLayout(self.timeGroupBox) self.verticalLayout_2.setContentsMargins(-1, -1, -1, 4) self.verticalLayout_2.setSpacing(4) self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2")) self.verticalLayout_7 = QtGui.QVBoxLayout() self.verticalLayout_7.setSpacing(0) self.verticalLayout_7.setObjectName(_fromUtf8("verticalLayout_7")) self.formLayout_3 = QtGui.QFormLayout() self.formLayout_3.setFieldGrowthPolicy(QtGui.QFormLayout.FieldsStayAtSizeHint) self.formLayout_3.setFormAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignTop) self.formLayout_3.setHorizontalSpacing(4) self.formLayout_3.setVerticalSpacing(1) self.formLayout_3.setObjectName(_fromUtf8("formLayout_3")) self.starttimeLabel = QtGui.QLabel(self.timeGroupBox) self.starttimeLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter) self.starttimeLabel.setObjectName(_fromUtf8("starttimeLabel")) self.formLayout_3.setWidget(0, QtGui.QFormLayout.LabelRole, self.starttimeLabel) self.starttimeDateTimeEdit = QtGui.QDateTimeEdit(self.timeGroupBox) self.starttimeDateTimeEdit.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter) self.starttimeDateTimeEdit.setCalendarPopup(True) self.starttimeDateTimeEdit.setTimeSpec(QtCore.Qt.UTC) self.starttimeDateTimeEdit.setObjectName(_fromUtf8("starttimeDateTimeEdit")) self.formLayout_3.setWidget(0, QtGui.QFormLayout.FieldRole, self.starttimeDateTimeEdit) self.endtimeLabel = QtGui.QLabel(self.timeGroupBox) self.endtimeLabel.setObjectName(_fromUtf8("endtimeLabel")) self.formLayout_3.setWidget(1, QtGui.QFormLayout.LabelRole, self.endtimeLabel) self.endtimeDateTimeEdit = QtGui.QDateTimeEdit(self.timeGroupBox) self.endtimeDateTimeEdit.setCalendarPopup(True) self.endtimeDateTimeEdit.setTimeSpec(QtCore.Qt.UTC) self.endtimeDateTimeEdit.setObjectName(_fromUtf8("endtimeDateTimeEdit")) self.formLayout_3.setWidget(1, QtGui.QFormLayout.FieldRole, self.endtimeDateTimeEdit) self.verticalLayout_7.addLayout(self.formLayout_3) self.horizontalLayout_2 = QtGui.QHBoxLayout() self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2")) self.time30DaysPushButton = QtGui.QPushButton(self.timeGroupBox) self.time30DaysPushButton.setObjectName(_fromUtf8("time30DaysPushButton")) self.horizontalLayout_2.addWidget(self.time30DaysPushButton) self.time1YearPushButton = QtGui.QPushButton(self.timeGroupBox) self.time1YearPushButton.setObjectName(_fromUtf8("time1YearPushButton")) self.horizontalLayout_2.addWidget(self.time1YearPushButton) self.verticalLayout_7.addLayout(self.horizontalLayout_2) self.verticalLayout_2.addLayout(self.verticalLayout_7) self.line_2 = QtGui.QFrame(self.timeGroupBox) self.line_2.setFrameShape(QtGui.QFrame.HLine) self.line_2.setFrameShadow(QtGui.QFrame.Sunken) self.line_2.setObjectName(_fromUtf8("line_2")) self.verticalLayout_2.addWidget(self.line_2) self.timeFromStationsToolButton = QtGui.QToolButton(self.timeGroupBox) self.timeFromStationsToolButton.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.timeFromStationsToolButton.sizePolicy().hasHeightForWidth()) self.timeFromStationsToolButton.setSizePolicy(sizePolicy) self.timeFromStationsToolButton.setObjectName(_fromUtf8("timeFromStationsToolButton")) self.verticalLayout_2.addWidget(self.timeFromStationsToolButton) self.verticalLayout.addWidget(self.timeGroupBox) self.magnitudeGroupBox = QtGui.QGroupBox(EventOptionsWidget) self.magnitudeGroupBox.setObjectName(_fromUtf8("magnitudeGroupBox")) self.verticalLayout_3 = QtGui.QVBoxLayout(self.magnitudeGroupBox) self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3")) self.magnitudeLayout = QtGui.QHBoxLayout() self.magnitudeLayout.setSpacing(0) self.magnitudeLayout.setObjectName(_fromUtf8("magnitudeLayout")) self.verticalLayout_9 = QtGui.QVBoxLayout() self.verticalLayout_9.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.verticalLayout_9.setContentsMargins(0, -1, -1, -1) self.verticalLayout_9.setSpacing(1) self.verticalLayout_9.setObjectName(_fromUtf8("verticalLayout_9")) self.horizontalLayout_15 = QtGui.QHBoxLayout() self.horizontalLayout_15.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.horizontalLayout_15.setSpacing(4) self.horizontalLayout_15.setObjectName(_fromUtf8("horizontalLayout_15")) self.minMagDoubleSpinBox = QtGui.QDoubleSpinBox(self.magnitudeGroupBox) self.minMagDoubleSpinBox.setDecimals(1) self.minMagDoubleSpinBox.setMinimum(-2.0) self.minMagDoubleSpinBox.setMaximum(10.0) self.minMagDoubleSpinBox.setObjectName(_fromUtf8("minMagDoubleSpinBox")) self.horizontalLayout_15.addWidget(self.minMagDoubleSpinBox) self.label_11 = QtGui.QLabel(self.magnitudeGroupBox) self.label_11.setObjectName(_fromUtf8("label_11")) self.horizontalLayout_15.addWidget(self.label_11) self.maxMagDoubleSpinBox = QtGui.QDoubleSpinBox(self.magnitudeGroupBox) self.maxMagDoubleSpinBox.setDecimals(1) self.maxMagDoubleSpinBox.setMaximum(10.0) self.maxMagDoubleSpinBox.setObjectName(_fromUtf8("maxMagDoubleSpinBox")) self.horizontalLayout_15.addWidget(self.maxMagDoubleSpinBox) spacerItem = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_15.addItem(spacerItem) self.verticalLayout_9.addLayout(self.horizontalLayout_15) self.horizontalLayout = QtGui.QHBoxLayout() self.horizontalLayout.setSpacing(4) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.label_7 = QtGui.QLabel(self.magnitudeGroupBox) self.label_7.setObjectName(_fromUtf8("label_7")) self.horizontalLayout.addWidget(self.label_7) self.magTypeComboBox = QtGui.QComboBox(self.magnitudeGroupBox) self.magTypeComboBox.setEnabled(True) self.magTypeComboBox.setObjectName(_fromUtf8("magTypeComboBox")) self.magTypeComboBox.addItem(_fromUtf8("")) self.magTypeComboBox.addItem(_fromUtf8("")) self.magTypeComboBox.addItem(_fromUtf8("")) self.magTypeComboBox.addItem(_fromUtf8("")) self.magTypeComboBox.addItem(_fromUtf8("")) self.horizontalLayout.addWidget(self.magTypeComboBox) spacerItem1 = QtGui.QSpacerItem(1, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout.addItem(spacerItem1) self.verticalLayout_9.addLayout(self.horizontalLayout) self.magnitudeLayout.addLayout(self.verticalLayout_9) spacerItem2 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.magnitudeLayout.addItem(spacerItem2) self.magnitudeLayout.setStretch(1, 1) self.verticalLayout_3.addLayout(self.magnitudeLayout) self.verticalLayout.addWidget(self.magnitudeGroupBox) self.depthGroupBox = QtGui.QGroupBox(EventOptionsWidget) self.depthGroupBox.setObjectName(_fromUtf8("depthGroupBox")) self.verticalLayout_5 = QtGui.QVBoxLayout(self.depthGroupBox) self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5")) self.depthLayout = QtGui.QHBoxLayout() self.depthLayout.setSpacing(0) self.depthLayout.setObjectName(_fromUtf8("depthLayout")) self.horizontalLayout_16 = QtGui.QHBoxLayout() self.horizontalLayout_16.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.horizontalLayout_16.setSpacing(4) self.horizontalLayout_16.setObjectName(_fromUtf8("horizontalLayout_16")) self.minDepthDoubleSpinBox = QtGui.QDoubleSpinBox(self.depthGroupBox) self.minDepthDoubleSpinBox.setDecimals(1) self.minDepthDoubleSpinBox.setMaximum(6800.0) self.minDepthDoubleSpinBox.setObjectName(_fromUtf8("minDepthDoubleSpinBox")) self.horizontalLayout_16.addWidget(self.minDepthDoubleSpinBox) self.label_13 = QtGui.QLabel(self.depthGroupBox) self.label_13.setObjectName(_fromUtf8("label_13")) self.horizontalLayout_16.addWidget(self.label_13) self.maxDepthDoubleSpinBox = QtGui.QDoubleSpinBox(self.depthGroupBox) self.maxDepthDoubleSpinBox.setDecimals(1) self.maxDepthDoubleSpinBox.setMaximum(6800.0) self.maxDepthDoubleSpinBox.setObjectName(_fromUtf8("maxDepthDoubleSpinBox")) self.horizontalLayout_16.addWidget(self.maxDepthDoubleSpinBox) self.label_12 = QtGui.QLabel(self.depthGroupBox) self.label_12.setObjectName(_fromUtf8("label_12")) self.horizontalLayout_16.addWidget(self.label_12) self.depthLayout.addLayout(self.horizontalLayout_16) spacerItem3 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.depthLayout.addItem(spacerItem3) self.depthLayout.setStretch(1, 1) self.verticalLayout_5.addLayout(self.depthLayout) self.verticalLayout.addWidget(self.depthGroupBox) self.locationGroupBox = QtGui.QGroupBox(EventOptionsWidget) self.locationGroupBox.setObjectName(_fromUtf8("locationGroupBox")) self.verticalLayout_6 = QtGui.QVBoxLayout(self.locationGroupBox) self.verticalLayout_6.setContentsMargins(-1, -1, -1, 4) self.verticalLayout_6.setSpacing(4) self.verticalLayout_6.setObjectName(_fromUtf8("verticalLayout_6")) self.horizontalLayout_7 = QtGui.QHBoxLayout() self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7")) self.locationGlobalRadioButton = QtGui.QRadioButton(self.locationGroupBox) self.locationGlobalRadioButton.setChecked(True) self.locationGlobalRadioButton.setObjectName(_fromUtf8("locationGlobalRadioButton")) self.horizontalLayout_7.addWidget(self.locationGlobalRadioButton) self.verticalLayout_6.addLayout(self.horizontalLayout_7) self.line_4 = QtGui.QFrame(self.locationGroupBox) self.line_4.setFrameShape(QtGui.QFrame.HLine) self.line_4.setFrameShadow(QtGui.QFrame.Sunken) self.line_4.setObjectName(_fromUtf8("line_4")) self.verticalLayout_6.addWidget(self.line_4) self.verticalLayout_10 = QtGui.QVBoxLayout() self.verticalLayout_10.setSpacing(0) self.verticalLayout_10.setObjectName(_fromUtf8("verticalLayout_10")) self.horizontalLayout_4 = QtGui.QHBoxLayout() self.horizontalLayout_4.setSpacing(0) self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4")) self.locationRangeRadioButton = QtGui.QRadioButton(self.locationGroupBox) self.locationRangeRadioButton.setChecked(False) self.locationRangeRadioButton.setObjectName(_fromUtf8("locationRangeRadioButton")) self.horizontalLayout_4.addWidget(self.locationRangeRadioButton) spacerItem4 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_4.addItem(spacerItem4) self.drawLocationRangeToolButton = QtGui.QToolButton(self.locationGroupBox) self.drawLocationRangeToolButton.setCheckable(True) self.drawLocationRangeToolButton.setObjectName(_fromUtf8("drawLocationRangeToolButton")) self.horizontalLayout_4.addWidget(self.drawLocationRangeToolButton) self.verticalLayout_10.addLayout(self.horizontalLayout_4) self.locationRangeLayout = QtGui.QHBoxLayout() self.locationRangeLayout.setContentsMargins(24, -1, -1, -1) self.locationRangeLayout.setSpacing(0) self.locationRangeLayout.setObjectName(_fromUtf8("locationRangeLayout")) self.verticalLayout_8 = QtGui.QVBoxLayout() self.verticalLayout_8.setSpacing(1) self.verticalLayout_8.setObjectName(_fromUtf8("verticalLayout_8")) self.horizontalLayout_23 = QtGui.QHBoxLayout() self.horizontalLayout_23.setObjectName(_fromUtf8("horizontalLayout_23")) spacerItem5 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_23.addItem(spacerItem5) self.locationRangeNorthDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeNorthDoubleSpinBox.setMinimum(-90.0) self.locationRangeNorthDoubleSpinBox.setMaximum(90.0) self.locationRangeNorthDoubleSpinBox.setObjectName(_fromUtf8("locationRangeNorthDoubleSpinBox")) self.horizontalLayout_23.addWidget(self.locationRangeNorthDoubleSpinBox) spacerItem6 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_23.addItem(spacerItem6) self.verticalLayout_8.addLayout(self.horizontalLayout_23) self.horizontalLayout_24 = QtGui.QHBoxLayout() self.horizontalLayout_24.setObjectName(_fromUtf8("horizontalLayout_24")) self.locationRangeWestDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeWestDoubleSpinBox.setMinimum(-180.0) self.locationRangeWestDoubleSpinBox.setMaximum(180.0) self.locationRangeWestDoubleSpinBox.setObjectName(_fromUtf8("locationRangeWestDoubleSpinBox")) self.horizontalLayout_24.addWidget(self.locationRangeWestDoubleSpinBox) self.locationRangeEastDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeEastDoubleSpinBox.setMinimum(-180.0) self.locationRangeEastDoubleSpinBox.setMaximum(180.0) self.locationRangeEastDoubleSpinBox.setObjectName(_fromUtf8("locationRangeEastDoubleSpinBox")) self.horizontalLayout_24.addWidget(self.locationRangeEastDoubleSpinBox) self.verticalLayout_8.addLayout(self.horizontalLayout_24) self.horizontalLayout_25 = QtGui.QHBoxLayout() self.horizontalLayout_25.setObjectName(_fromUtf8("horizontalLayout_25")) spacerItem7 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_25.addItem(spacerItem7) self.locationRangeSouthDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.locationRangeSouthDoubleSpinBox.setMinimum(-90.0) self.locationRangeSouthDoubleSpinBox.setMaximum(90.0) self.locationRangeSouthDoubleSpinBox.setObjectName(_fromUtf8("locationRangeSouthDoubleSpinBox")) self.horizontalLayout_25.addWidget(self.locationRangeSouthDoubleSpinBox) spacerItem8 = QtGui.QSpacerItem(40, 20, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_25.addItem(spacerItem8) self.verticalLayout_8.addLayout(self.horizontalLayout_25) self.locationRangeLayout.addLayout(self.verticalLayout_8) spacerItem9 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.locationRangeLayout.addItem(spacerItem9) self.locationRangeLayout.setStretch(1, 1) self.verticalLayout_10.addLayout(self.locationRangeLayout) self.verticalLayout_6.addLayout(self.verticalLayout_10) self.line = QtGui.QFrame(self.locationGroupBox) self.line.setFrameShape(QtGui.QFrame.HLine) self.line.setFrameShadow(QtGui.QFrame.Sunken) self.line.setObjectName(_fromUtf8("line")) self.verticalLayout_6.addWidget(self.line) self.verticalLayout_11 = QtGui.QVBoxLayout() self.verticalLayout_11.setSpacing(0) self.verticalLayout_11.setObjectName(_fromUtf8("verticalLayout_11")) self.horizontalLayout_5 = QtGui.QHBoxLayout() self.horizontalLayout_5.setSpacing(0) self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5")) self.locationDistanceFromPointRadioButton = QtGui.QRadioButton(self.locationGroupBox) self.locationDistanceFromPointRadioButton.setEnabled(True) self.locationDistanceFromPointRadioButton.setObjectName(_fromUtf8("locationDistanceFromPointRadioButton")) self.horizontalLayout_5.addWidget(self.locationDistanceFromPointRadioButton) spacerItem10 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.horizontalLayout_5.addItem(spacerItem10) self.drawDistanceFromPointToolButton = QtGui.QToolButton(self.locationGroupBox) self.drawDistanceFromPointToolButton.setCheckable(True) self.drawDistanceFromPointToolButton.setObjectName(_fromUtf8("drawDistanceFromPointToolButton")) self.horizontalLayout_5.addWidget(self.drawDistanceFromPointToolButton) self.verticalLayout_11.addLayout(self.horizontalLayout_5) self.locationDistanceFromPointLayout = QtGui.QHBoxLayout() self.locationDistanceFromPointLayout.setContentsMargins(24, -1, -1, -1) self.locationDistanceFromPointLayout.setSpacing(0) self.locationDistanceFromPointLayout.setObjectName(_fromUtf8("locationDistanceFromPointLayout")) self.verticalLayout_4 = QtGui.QVBoxLayout() self.verticalLayout_4.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.verticalLayout_4.setContentsMargins(0, -1, -1, -1) self.verticalLayout_4.setSpacing(1) self.verticalLayout_4.setObjectName(_fromUtf8("verticalLayout_4")) self.horizontalLayout_14 = QtGui.QHBoxLayout() self.horizontalLayout_14.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint) self.horizontalLayout_14.setSpacing(4) self.horizontalLayout_14.setObjectName(_fromUtf8("horizontalLayout_14")) self.distanceFromPointMinRadiusDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointMinRadiusDoubleSpinBox.setMinimum(0.0) self.distanceFromPointMinRadiusDoubleSpinBox.setMaximum(180.0) self.distanceFromPointMinRadiusDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointMinRadiusDoubleSpinBox")) self.horizontalLayout_14.addWidget(self.distanceFromPointMinRadiusDoubleSpinBox) self.label_3 = QtGui.QLabel(self.locationGroupBox) self.label_3.setObjectName(_fromUtf8("label_3")) self.horizontalLayout_14.addWidget(self.label_3) self.distanceFromPointMaxRadiusDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointMaxRadiusDoubleSpinBox.setMinimum(0.0) self.distanceFromPointMaxRadiusDoubleSpinBox.setMaximum(180.0) self.distanceFromPointMaxRadiusDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointMaxRadiusDoubleSpinBox")) self.horizontalLayout_14.addWidget(self.distanceFromPointMaxRadiusDoubleSpinBox) self.label_8 = QtGui.QLabel(self.locationGroupBox) self.label_8.setEnabled(True) self.label_8.setAlignment(QtCore.Qt.AlignCenter) self.label_8.setObjectName(_fromUtf8("label_8")) self.horizontalLayout_14.addWidget(self.label_8) self.verticalLayout_4.addLayout(self.horizontalLayout_14) self.horizontalLayout_18 = QtGui.QHBoxLayout() self.horizontalLayout_18.setSpacing(4) self.horizontalLayout_18.setObjectName(_fromUtf8("horizontalLayout_18")) self.label_6 = QtGui.QLabel(self.locationGroupBox) self.label_6.setObjectName(_fromUtf8("label_6")) self.horizontalLayout_18.addWidget(self.label_6) self.distanceFromPointEastDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointEastDoubleSpinBox.setMinimum(-180.0) self.distanceFromPointEastDoubleSpinBox.setMaximum(180.0) self.distanceFromPointEastDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointEastDoubleSpinBox")) self.horizontalLayout_18.addWidget(self.distanceFromPointEastDoubleSpinBox) self.label_14 = QtGui.QLabel(self.locationGroupBox) self.label_14.setEnabled(True) self.label_14.setObjectName(_fromUtf8("label_14")) self.horizontalLayout_18.addWidget(self.label_14) self.distanceFromPointNorthDoubleSpinBox = QtGui.QDoubleSpinBox(self.locationGroupBox) self.distanceFromPointNorthDoubleSpinBox.setMinimum(-90.0) self.distanceFromPointNorthDoubleSpinBox.setMaximum(90.0) self.distanceFromPointNorthDoubleSpinBox.setObjectName(_fromUtf8("distanceFromPointNorthDoubleSpinBox")) self.horizontalLayout_18.addWidget(self.distanceFromPointNorthDoubleSpinBox) self.label_9 = QtGui.QLabel(self.locationGroupBox) self.label_9.setObjectName(_fromUtf8("label_9")) self.horizontalLayout_18.addWidget(self.label_9) self.verticalLayout_4.addLayout(self.horizontalLayout_18) self.locationDistanceFromPointLayout.addLayout(self.verticalLayout_4) spacerItem11 = QtGui.QSpacerItem(0, 0, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Minimum) self.locationDistanceFromPointLayout.addItem(spacerItem11) self.locationDistanceFromPointLayout.setStretch(1, 1) self.verticalLayout_11.addLayout(self.locationDistanceFromPointLayout) self.verticalLayout_6.addLayout(self.verticalLayout_11) self.line_3 = QtGui.QFrame(self.locationGroupBox) self.line_3.setFrameShape(QtGui.QFrame.HLine) self.line_3.setFrameShadow(QtGui.QFrame.Sunken) self.line_3.setObjectName(_fromUtf8("line_3")) self.verticalLayout_6.addWidget(self.line_3) self.locationFromStationsToolButton = QtGui.QToolButton(self.locationGroupBox) self.locationFromStationsToolButton.setEnabled(True) sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.MinimumExpanding, QtGui.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.locationFromStationsToolButton.sizePolicy().hasHeightForWidth()) self.locationFromStationsToolButton.setSizePolicy(sizePolicy) self.locationFromStationsToolButton.setObjectName(_fromUtf8("locationFromStationsToolButton")) self.verticalLayout_6.addWidget(self.locationFromStationsToolButton) self.verticalLayout.addWidget(self.locationGroupBox) spacerItem12 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem12) self.retranslateUi(EventOptionsWidget) QtCore.QMetaObject.connectSlotsByName(EventOptionsWidget) def retranslateUi(self, EventOptionsWidget): self.timeGroupBox.setTitle(_translate("EventOptionsWidget", "Time", None)) self.starttimeLabel.setText(_translate("EventOptionsWidget", "Start", None)) self.starttimeDateTimeEdit.setDisplayFormat(_translate("EventOptionsWidget", "yyyy-MM-dd hh:mm:ss", None)) self.endtimeLabel.setText(_translate("EventOptionsWidget", "End", None)) self.endtimeDateTimeEdit.setDisplayFormat(_translate("EventOptionsWidget", "yyyy-MM-dd hh:mm:ss", None)) self.time30DaysPushButton.setText(_translate("EventOptionsWidget", "Last 30 days", None)) self.time1YearPushButton.setText(_translate("EventOptionsWidget", "Last year", None)) self.timeFromStationsToolButton.setText(_translate("EventOptionsWidget", "Copy Time Range from Station Options <<", None)) self.magnitudeGroupBox.setTitle(_translate("EventOptionsWidget", "Magnitude", None)) self.label_11.setText(_translate("EventOptionsWidget", "-", None)) self.label_7.setText(_translate("EventOptionsWidget", "Type", None)) self.magTypeComboBox.setItemText(0, _translate("EventOptionsWidget", "All Types", None)) self.magTypeComboBox.setItemText(1, _translate("EventOptionsWidget", "Mw", None)) self.magTypeComboBox.setItemText(2, _translate("EventOptionsWidget", "mb", None)) self.magTypeComboBox.setItemText(3, _translate("EventOptionsWidget", "Ms", None)) self.magTypeComboBox.setItemText(4, _translate("EventOptionsWidget", "ML", None)) self.depthGroupBox.setTitle(_translate("EventOptionsWidget", "Depth", None)) self.label_13.setText(_translate("EventOptionsWidget", "-", None)) self.label_12.setText(_translate("EventOptionsWidget", "km", None)) self.locationGroupBox.setTitle(_translate("EventOptionsWidget", "Location", None)) self.locationGlobalRadioButton.setText(_translate("EventOptionsWidget", "Global", None)) self.locationRangeRadioButton.setText(_translate("EventOptionsWidget", "Within lat/lon box", None)) self.drawLocationRangeToolButton.setText(_translate("EventOptionsWidget", "Draw on map", None)) self.locationDistanceFromPointRadioButton.setText(_translate("EventOptionsWidget", "Distance from point", None)) self.drawDistanceFromPointToolButton.setText(_translate("EventOptionsWidget", "Draw on map", None)) self.label_3.setText(_translate("EventOptionsWidget", "-", None)) self.label_8.setText(_translate("EventOptionsWidget", "degrees", None)) self.label_6.setText(_translate("EventOptionsWidget", "from", None)) self.label_14.setText(_translate("EventOptionsWidget", "E", None)) self.label_9.setText(_translate("EventOptionsWidget", "N", None)) self.locationFromStationsToolButton.setText(_translate("EventOptionsWidget", "Copy Location from Station Options <<", None)) <file_sep># -*- coding: utf-8 -*- """ Widgets for use with a QTableWidgetItem :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore # QTableWidgetItem subclass type iterator _next_type = QtGui.QTableWidgetItem.UserType class CustomTableWidgetItemMixin(object): def __init__(self, *args, **kwargs): global _next_type _next_type += 1 return super(CustomTableWidgetItemMixin, self).__init__(*args, **kwargs, type=_next_type) <file_sep># -*- coding: utf-8 -*- """ Custom QDoubleValidator that pays attention to ranges https://gist.github.com/jirivrany/4473639 :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from sys import float_info from PyQt4.QtGui import QValidator from PyQt4.QtGui import QDoubleValidator class MyDoubleValidator(QDoubleValidator): ''' Custom QDoubleValidator that pays attention to ranges from https://gist.github.com/jirivrany/4473639 Note that the Validate API is different for QString v2 ''' def __init__(self, bottom=float_info.min, top=float_info.max, decimals=float_info.dig, parent=None): super(MyDoubleValidator, self).__init__(bottom, top, decimals, parent) def validate(self, input_value, pos): if input_value in ('', '.', '-'): return QValidator.Intermediate, input_value, pos state, value, pos = QDoubleValidator.validate(self, input_value, pos) if state != QValidator.Acceptable: return QValidator.Invalid, value, pos return QValidator.Acceptable, value, pos <file_sep>#!/usr/bin/env python # _*_coding:utf-8 _*_ import requests from bs4 import BeautifulSoup import base64 from PIL import Image from io import BytesIO import pytesseract __title__ = '' __author__ = "wenyali" __mtime__ = "2018/5/11" # 发起请求,获取服务器返回的response对象 response = requests.get("http://example.webscraping.com/places/default/user/register") # 将我们传入的内容进行解析,解析成一个树形的结构。 soup = BeautifulSoup(response.text, "html.parser") li = soup.select("#recaptcha > img") src = li[0].get("src") src = src.replace("data:image/png;base64,", "") # 对base64字符串进行解码,返回二进制形式。 binary = base64.b64decode(src) # with open("1.jpg", "wb") as f: # f.write(binary) # 读取本地的图片,返回一个Image类型的对象。 # image = Image.open("1.jpg") # Image.open函数需要一个文件对象(或者是类文件对象【指的就是像文件一样的对象,即具有read,write等方法的对象。】) # 很遗憾,不支持 # image = Image.open(binary) # 可以使用BytesIO这个类文件对象来实现。 image = Image.open(BytesIO(binary)) # 保存Image对象所代表的图片。 image.save("original.jpg") # 注意:需要执行tesseract文件所在的路径。 # 指定有两种方式: # 1 设置环境变量 # 2 pytesseract.pytesseract.tesseract_cmd = “tesseract所在的路径” pytesseract.pytesseract.tesseract_cmd = r'..\depend_soft\tesseract\Tesseract-OCR\tesseract' # 对图片进行处理,提取验证码的有效信息。【尽可能将验证码与背景色进行分离-区分度越明显越好】 # 将图片转换成灰度图。【该操作是一个复制操作,没有修改原有的Image对象。】 image = image.convert("L") # 将图片进行二值化。【将图片的所有像素点只含有两个值,0与255,目的是方便OCR进行识别。】 # point方法可以进行图像的像素处理。参数是一个函数,函数具有一个参数值,同时,具有一个返回值,返回值为像素点处理之后的值。 # 图像的每一个像素点调用一次该函数,传入像素点的值。 # def manage(pixel): # if pixel == 0: # return pixel # else: # return 255 image = image.point(lambda x: 0 if x == 0 else 255) image.save("binaryzation.jpg") # 显示图片 # image.show() # 传入一个Image对象,返回识别之后的结果。 text = pytesseract.image_to_string(image, config="--psm 7") print(text)<file_sep># -*- coding: utf-8 -*- """ Base classes for EventOptionsWidet and StationOptionsWidget :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore import logging from distutils.util import strtobool LOGGER = logging.getLogger(__name__) class BaseOptionsWidget(QtGui.QDialog): """ Base functionality for the EventOptionsWidget and StationOptionsWidget. """ # We want to watch for changes in the widget inputs, but every type of input has a different one so # we need to try a bunch of options INPUT_CHANGE_SIGNALS = ('valueChanged', 'textChanged', 'dateTimeChanged', 'clicked',) # Signal to indicate that the options have changed changed = QtCore.pyqtSignal(object) # Signal indicating that the user changed a location parameter changedCoords = QtCore.pyqtSignal(object) # Map of the individual inputs by name inputs = None def __init__(self, parent, options, otherOptions, dockWidget, toggleButton): super(BaseOptionsWidget, self).__init__(parent=parent) # This function just saves variables and do some low-level widget operations # then calls `initialize()` for the higher-level behavior. self.setupUi(self) self.inputs = self.mapInputs() self.options = options self.otherOptions = otherOptions # Add to dock dockWidget.setWidget(self) # Connect the toggle switch for hiding the dock toggleButton.toggled.connect(dockWidget.setVisible) dockWidget.visibilityChanged.connect(toggleButton.setChecked) # Call a separate function for the higher-level behavior, so subclasses can extend self.initialize() def initialize(self): """ Second part of the initialization, subclass initialization should extend this. """ # Push values to the inputs before connecting them self.setOptions() self.connectInputs() # Hook up the shortcut buttons self.time30DaysPushButton.clicked.connect(self.setTime30Days) self.time1YearPushButton.clicked.connect(self.setTime1Year) # Hook up the copy buttons self.get_timeFromOtherButton().clicked.connect(self.copyTimeOptions) self.get_locationFromOtherButton().clicked.connect(self.copyLocationOptions) def mapInputs(self): """ Subclasses override this to provide a map of keys to input widgets ex: return { 'network': self.networkLineEdit, 'station': self.stationLineEdit, 'location': self.locationLineEdit, 'channel': self.channelLineEdit, ... } """ raise NotImplementedError() def get_timeFromOtherButton(self): """ Return the button that triggers copying time from the other widget """ raise NotImplementedError() def get_locationFromOtherButton(self): """ Return the button that triggers copying location from the other widget """ raise NotImplementedError() def connectInput(self, key, one_input): # Different widgets emit different signals :P for signal_name in self.INPUT_CHANGE_SIGNALS: if hasattr(one_input, signal_name): LOGGER.debug("Listening to %s.%s" % (one_input, signal_name)) getattr(one_input, signal_name).connect(lambda: self.onInputChanged(key)) return def connectInputs(self): """ Set up listeners for the inputs """ for key, one_input in self.inputs.items(): self.connectInput(key, one_input) def onInputChanged(self, key): """ Called when any input is changed """ LOGGER.debug("Input changed: %s" % key) # Update the core options object self.options.set_options(self.getOptions()) # Emit a change event self.changed.emit(key) # Emit a coordinate change event if appropriate if self.isCoordinateInput(key): self.changedCoords.emit(key) def isCoordinateInput(self, key): """ Return true if the given key represents a coordinate input. Subclasses may override/extend this. """ for marker in ('latitude', 'longitude', 'radius', '_location', 'distance',): if marker in key: return True return False def getInputValue(self, key): """ Get the value of a single input. This is intended to Pythonify the Qt values that come natively from the widgets. (ie. return a Python date rather than a QDate). This is used internally by getOptions() """ one_input = self.inputs.get(key) if one_input: if isinstance(one_input, QtGui.QDateTimeEdit): # DateTime return one_input.dateTime().toString(QtCore.Qt.ISODate) elif isinstance(one_input, QtGui.QAbstractButton): # Radio/checkbox button return str(one_input.isChecked()) elif isinstance(one_input, QtGui.QComboBox): return one_input.currentText() elif hasattr(one_input, 'text'): return one_input.text() raise Exception("Couldn't identify the QWidget type for %s (%s)" % (key, one_input)) return None def setInputValue(self, key, value): """ Set the input value based on a string from the options """ one_input = self.inputs.get(key) if one_input: if isinstance(one_input, QtGui.QDateTimeEdit): # Ugh, complicated conversion from UTCDateTime dt = QtCore.QDateTime.fromString(value, QtCore.Qt.ISODate) one_input.setDateTime(dt) elif isinstance(one_input, QtGui.QDoubleSpinBox): # Float value one_input.setValue(float(value)) elif isinstance(one_input, QtGui.QComboBox): # Combo box index = one_input.findText(value) if index > -1: one_input.setCurrentIndex(index) elif isinstance(one_input, QtGui.QLineEdit): # Text input one_input.setText(value) elif isinstance(one_input, QtGui.QAbstractButton): # Radio/checkbox button one_input.setChecked(strtobool(str(value))) else: raise Exception("Don't know how to set an input for %s (%s)" % (key, one_input)) def setOptions(self): """ Put the current set of options into the mapped inputs """ # Get a dictionary of stringified options values for key, value in self.optionsToInputs(self.options.get_options(stringify=True)).items(): try: self.setInputValue(key, value) except Exception as e: LOGGER.warning("Unable to set input value for %s: %s", key, e) def optionsToInputs(self, values): """ Hook for subclasses to modify a dictionary of options to map to the input widgets """ return values def getOptions(self): """ Return a dictionary containing the input values, formatted as appropriate for a service call. """ inputValues = {} for key in self.inputs.keys(): try: inputValues[key] = self.getInputValue(key) except Exception as e: LOGGER.warning("Unable to get input value %s: %s", key, e) return self.inputsToOptions(inputValues) def inputsToOptions(self, values): """ Hook for subclasses to modify a dictionary of input values to map to the options """ return values def copyTimeOptions(self): """ Copy the time options from event_options/station_options """ LOGGER.info("Copying time to %s" % self.__class__) time_options = self.otherOptions.get_time_options() time_options.update(self.otherOptions.get_options(['time_choice'])) self.options.set_options(time_options) self.setOptions() self.changed.emit('time_choice') def copyLocationOptions(self): """ Copy the location options from event_options/station_options """ LOGGER.info("Copying location to %s" % self.__class__) loc_options = self.otherOptions.get_location_options() loc_options.update(self.otherOptions.get_options(['location_choice'])) self.options.set_options(loc_options) self.setOptions() self.changed.emit('location_choice') self.changedCoords.emit('location_choice') def setTime30Days(self): """ Set the start/end times to cover the last 30 days """ end = QtCore.QDateTime.currentDateTimeUtc() start = end.addDays(-30) self.starttimeDateTimeEdit.setDateTime(start) self.endtimeDateTimeEdit.setDateTime(end) self.changed.emit('time_choice') def setTime1Year(self): """ Set the start/end times to cover the last 30 days """ end = QtCore.QDateTime.currentDateTimeUtc() start = end.addYears(-1) self.starttimeDateTimeEdit.setDateTime(start) self.endtimeDateTimeEdit.setDateTime(end) self.changed.emit('time_choice') <file_sep># -*- coding: utf-8 -*- """ Custom widget that embeds an image To be inserted into the QTableWidget with setCellWidget() rather than setItem(). http://stackoverflow.com/questions/5553342/adding-images-to-a-qtablewidget-in-pyqt :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui class MyTableWidgetImageWidget(QtGui.QLabel): def __init__(self, parent=None, imagePath=None): super(MyTableWidgetImageWidget, self).__init__(parent) pic = QtGui.QPixmap(imagePath) # NOTE: From QPixmap we could use scaledToWidth() but the resulting images aren't so pretty # pic = pic.scaledToWidth(500) self.setPixmap(pic) # NOTE: From QLabel we could use setScaledContents() but this doesn't preserve the aspect ratio # self.setScaledContents(True) <file_sep>from selenium import webdriver # 步骤 # 1 图片展开之前的准备工作 # 2 获取图片,生成Image对象 # 3 分析Image对象,计算出缺口的位置,返回需要移动的距离。 # 4 根据上一步移动的距离,移动滑块。 from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait import time import random from PIL import Image, ImageChops, ImageFilter from io import BytesIO import numpy as np import pytweening def get_trace_list(dis): result = [] pre = 0 for i in range(1, dis + 1): # 获取位移的比例 y = pytweening.easeOutQuad(i / dis) v = round(dis * y) result.append(v - pre) pre = v return result def pause(min_time=1, max_time=2): """ 随机暂停参数指定的时间。单位:秒。 :param min_time: 最短的暂停时间。 :param max_time: 最长的暂停时间。 """ time.sleep(random.uniform(min_time, max_time)) def prepare(): """ 图片展开之前的准备工作。 """ driver.get("https://passport.cnblogs.com/user/signin") driver.maximize_window() driver.find_element_by_id("input1").send_keys("a") driver.find_element_by_id("input2").send_keys("b") driver.find_element_by_id("signin").click() # 等待按钮能够点击 wait.until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, "div.geetest_radar_tip"))) pause() driver.find_element_by_css_selector("div.geetest_radar_tip").click() # 等待图片可见 wait.until(expected_conditions.visibility_of_element_located((By.CSS_SELECTOR, "canvas.geetest_canvas_fullbg"))) def cut_image(element): """ 根据element所表示的元素,截取该元素的截图,并返回Image对象。 :param element: 代表图像的元素 :return: 返回截取之后的Image对象。 """ # 获取屏幕截图的二进制bytes(数组)。 image_bytes = driver.get_screenshot_as_png() full_image = Image.open(BytesIO(image_bytes)) x, y = element.location["x"], element.location["y"] # 此处无法获取size # width, height = element.size["width"], element.size["height"] # 注意:height与width是字符串类型,需要进行转换。 width, height = int(element.get_attribute("width")), int(element.get_attribute("height")) return full_image.crop( (x, y, x + width, y + height)) def get_image(): """ 获取我们需要分析的图片,并返回。 :return: 返回需要分析的图片。 """ # 很遗憾,元素的截图操作,Chrome浏览器不支持。 # bg_element = driver.find_element_by_css_selector("geetest_canvas_fullbg") # bg_element.screenshot() pause() bg_element = driver.find_element_by_css_selector("canvas.geetest_canvas_fullbg") bg_image = cut_image(bg_element) bg_image.save("1.png") driver.find_element_by_css_selector("div.geetest_slider_button").click() # 等待,确保图片红条消失。 pause(3, 3.5) # 注意:当点击滑块按钮后,背景元素会发生改变。 bg_element2 = driver.find_element_by_css_selector("canvas.geetest_canvas_slice") bg_image2 = cut_image(bg_element2) bg_image2.save("2.png") # 隐藏滑块图片,并截图。 driver.execute_script("arguments[0].style.opacity = 0;", bg_element2) pause() bg_image3 = cut_image(bg_element2) bg_image3.save("3.png") # 返回最开始的图片,还有缺口与滑块的图片与只含有缺口,而没有滑块的图片。 return bg_image, bg_image2, bg_image3 def get_edge(image1, image2): # 将两个Image图像对象进行差值化,返回差值之后的图像对象(Image) differ = ImageChops.difference(image1, image2) differ = differ.convert("L") differ = differ.filter(ImageFilter.FIND_EDGES) differ_array = np.array(differ) for i in range(differ.width): tmp_array = differ_array[:, i] if len(tmp_array[tmp_array > 100]) > 10: return i print("判定失败") return 0 def move(dis): action = ActionChains(driver) action.click_and_hold(driver.find_element_by_css_selector("div.geetest_slider_button")) trace_list = get_trace_list(dis) for i in trace_list: action.move_by_offset(i, 0) action.release().perform() def main(): prepare() bg_image, bg_image2, bg_image3 = get_image() # 获取滑块的起始位置 edge1 = get_edge(bg_image, bg_image2) # 获取缺口的起始位置 edge2 = get_edge(bg_image, bg_image3) print(edge1, edge2) print(edge2 - edge1) move(edge2 - edge1) if __name__ == "__main__": driver = webdriver.Chrome(executable_path=r"..\depend_soft\chromedriver") wait = WebDriverWait(driver, 10) main() <file_sep># -*- coding: utf-8 -*- """ Station Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore from pyweed.gui.uic import StationOptionsWidget import logging from pyweed.station_options import StationOptions from distutils.util import strtobool from pyweed.gui.OptionsWidget import BaseOptionsWidget LOGGER = logging.getLogger(__name__) class StationOptionsWidget(BaseOptionsWidget, StationOptionsWidget.Ui_StationOptionsWidget): """ Dialog window for event options used in creating a webservice query. """ def mapInputs(self): return { 'network': self.networkLineEdit, 'station': self.stationLineEdit, 'location': self.locationLineEdit, 'channel': self.channelLineEdit, 'starttime': self.starttimeDateTimeEdit, 'endtime': self.endtimeDateTimeEdit, 'minlongitude': self.locationRangeWestDoubleSpinBox, 'maxlongitude': self.locationRangeEastDoubleSpinBox, 'minlatitude': self.locationRangeSouthDoubleSpinBox, 'maxlatitude': self.locationRangeNorthDoubleSpinBox, 'minradius': self.distanceFromPointMinRadiusDoubleSpinBox, 'maxradius': self.distanceFromPointMaxRadiusDoubleSpinBox, 'longitude': self.distanceFromPointEastDoubleSpinBox, 'latitude': self.distanceFromPointNorthDoubleSpinBox, '_locationGlobal': self.locationGlobalRadioButton, '_locationRange': self.locationRangeRadioButton, '_locationDistanceFromPoint': self.locationDistanceFromPointRadioButton, '_locationDistanceFromEvents': self.locationDistanceFromEventsRadioButton, 'mindistance': self.distanceFromEventsMinDoubleSpinBox, 'maxdistance': self.distanceFromEventsMaxDoubleSpinBox, } def optionsToInputs(self, values): # Turn the option choice value into a set of radio values location_choice = values.get('location_choice') values['_locationGlobal'] = (location_choice == StationOptions.LOCATION_GLOBAL) values['_locationRange'] = (location_choice == StationOptions.LOCATION_BOX) values['_locationDistanceFromPoint'] = (location_choice == StationOptions.LOCATION_POINT) values['_locationDistanceFromEvents'] = (location_choice == StationOptions.LOCATION_EVENTS) return values def inputsToOptions(self, values): # Turn the radio values into an option choice value if strtobool(values.get('_locationGlobal', 'F')): values['location_choice'] = StationOptions.LOCATION_GLOBAL elif strtobool(values.get('_locationRange', 'F')): values['location_choice'] = StationOptions.LOCATION_BOX elif strtobool(values.get('_locationDistanceFromPoint', 'F')): values['location_choice'] = StationOptions.LOCATION_POINT elif strtobool(values.get('_locationDistanceFromEvents', 'F')): values['location_choice'] = StationOptions.LOCATION_EVENTS return values def get_timeFromOtherButton(self): return self.timeFromEventsToolButton def get_locationFromOtherButton(self): return self.locationFromEventsToolButton def onEventSelectionChanged(self): """ This should be called whenever the event selection has changed. If the "distance from selected events" is enabled, this will emit a change event. """ key = '_locationDistanceFromEvents' inputValue = self.getInputValue(key) LOGGER.debug("StationOptionsWidget.onEventSelectionChanged: %s", inputValue) if inputValue and strtobool(inputValue): self.changed.emit(key) self.changedCoords.emit(key) <file_sep># -*- coding: utf-8 -*- """ Event Options :copyright: Mazama Science, IRIS :license: GNU Lesser General Public License, Version 3 (http://www.gnu.org/copyleft/lesser.html) """ from PyQt4 import QtGui, QtCore from pyweed.gui.uic import EventOptionsWidget import logging from distutils.util import strtobool from pyweed.event_options import EventOptions from pyweed.gui.OptionsWidget import BaseOptionsWidget LOGGER = logging.getLogger(__name__) class EventOptionsWidget(BaseOptionsWidget, EventOptionsWidget.Ui_EventOptionsWidget): """ Dialog window for event options used in creating a webservice query. """ def mapInputs(self): return { 'starttime': self.starttimeDateTimeEdit, 'endtime': self.endtimeDateTimeEdit, 'minmagnitude': self.minMagDoubleSpinBox, 'maxmagnitude': self.maxMagDoubleSpinBox, 'mindepth': self.minDepthDoubleSpinBox, 'maxdepth': self.maxDepthDoubleSpinBox, 'magnitudetype': self.magTypeComboBox, 'minlongitude': self.locationRangeWestDoubleSpinBox, 'maxlongitude': self.locationRangeEastDoubleSpinBox, 'minlatitude': self.locationRangeSouthDoubleSpinBox, 'maxlatitude': self.locationRangeNorthDoubleSpinBox, 'minradius': self.distanceFromPointMinRadiusDoubleSpinBox, 'maxradius': self.distanceFromPointMaxRadiusDoubleSpinBox, 'longitude': self.distanceFromPointEastDoubleSpinBox, 'latitude': self.distanceFromPointNorthDoubleSpinBox, '_locationGlobal': self.locationGlobalRadioButton, '_locationRange': self.locationRangeRadioButton, '_locationDistanceFromPoint': self.locationDistanceFromPointRadioButton } def optionsToInputs(self, values): # Turn the option choice value into a set of radio values location_choice = values.get('location_choice') values['_locationGlobal'] = (location_choice == EventOptions.LOCATION_GLOBAL) values['_locationRange'] = (location_choice == EventOptions.LOCATION_BOX) values['_locationDistanceFromPoint'] = (location_choice == EventOptions.LOCATION_POINT) return values def inputsToOptions(self, values): # Turn the radio values into an option choice value if strtobool(values.get('_locationGlobal', 'F')): values['location_choice'] = EventOptions.LOCATION_GLOBAL elif strtobool(values.get('_locationRange', 'F')): values['location_choice'] = EventOptions.LOCATION_BOX elif strtobool(values.get('_locationDistanceFromPoint', 'F')): values['location_choice'] = EventOptions.LOCATION_POINT return values def get_timeFromOtherButton(self): return self.timeFromStationsToolButton def get_locationFromOtherButton(self): return self.locationFromStationsToolButton
2a0fec5f26e9b012d200f9e21fc61c06a643f088
[ "Markdown", "Python", "reStructuredText" ]
46
Python
wenyali/Decoding_code
1a1faf5daabfc697172e72856e3fa089df038673
8241cc5598caa3fa835be018e9831142c53794d1
refs/heads/master
<repo_name>joe1990/OpenGl3DModelViewer<file_sep>/OpenGl3DModelViewer/src/main/java/geometrie/Camera.java package geometrie; import org.lwjgl.input.Mouse; import org.lwjgl.util.vector.Vector3f; /** * Diese Klasse ist für alle Operationen betreffend der Kamera zuständig. * Sie beinhaltet eine Methode zum Verschieben der Kamera-Position und auch Methoden um Kameraeigenschaften abzufragen * (z.B. Position, Pitch oder Yaw) * Pitch: Rotation um die X-Achse der Kamera * Yaw: Rotation um die Y-Achse der Kamera */ public class Camera { private float distanceModel = 60; private float angleAroundModel = 180; private Vector3f position = new Vector3f(0,0,0); //Kamera Position private float yaw; //Rotation um die Y-Achse der Kamera private float pitch = 30; //Rotation um die X-Achse der Kamera /** * Verschiebt die Kamera abhängig vom Input des Users, d.h. abhängig von der Drehung am Mausrad und auch abhängig * von der Rechts-, Links-, Oben-, Unten-Verschiebung. */ public void move(){ //Zoom float zoomLevel = Mouse.getDWheel() * 0.05f; distanceModel -= zoomLevel; //Pitch (Rotation um die X-Achse) if(Mouse.isButtonDown(0)){ float pitchChange = Mouse.getDY() * 0.2f; pitch -= pitchChange; } //angle around Model if(Mouse.isButtonDown(0)){ float angleChange = Mouse.getDX() * 0.2f; angleAroundModel -= angleChange; } //Distanz float distanceHorizontal = distanceModel * (float)Math.cos(Math.toRadians(pitch)); float distanceVertical = distanceModel * (float)Math.sin(Math.toRadians(pitch)); //Position float xPos = distanceHorizontal * (float)Math.sin(Math.toRadians(angleAroundModel)); float zPos = distanceHorizontal * (float)Math.cos(Math.toRadians(angleAroundModel)); position.x = - xPos; position.z = - zPos; position.y = distanceVertical; this.yaw = 180 - angleAroundModel; } /** * Gibt die Kamera-Position zurück. * * @return Kamera-Position. */ public Vector3f getPosition() { return position; } /** * Gibt den Yaw-Wert (Rotation um die Y-Achse der Kamera) zurück. * * @return Aktueller Yaw-Wert. */ public float getYaw() { return yaw; } /** * Gibt den Pitch Wert (Rotation um die X-Achse der Kamera) zurück. * * @return Aktueller Pitch-Wert. */ public float getPitch() { return pitch; } } <file_sep>/OpenGl3DModelViewer/src/main/java/renderEngine/GPUInterface.java package renderEngine; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL15; import org.lwjgl.opengl.GL20; import org.lwjgl.opengl.GL30; import java.awt.*; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; /** * Lädt Daten in die Grafikkarte (GPU-Schnittstelle). * Klasse für das Vertex Array Object (VAO) und Vertex Buffer Object (VBO). */ public class GPUInterface { private ArrayList<Integer> vbo_list = new ArrayList<Integer>(); private ArrayList<Integer> vao_list = new ArrayList<Integer>(); /** * Lädt Daten ins Vertex Array Object (VAO). * * @param positions * @param indices * @param normals * @param colour * @return */ public Model loadVAO(float[] positions, int[] indices, float normals[], Color colour){ int vaoID = GL30.glGenVertexArrays(); vao_list.add(vaoID); GL30.glBindVertexArray(vaoID); bindIndicesBuffer(indices); storeDataInAttributList(0, 3, positions); storeDataInAttributList(1, 3, normals); float[] colours = new float[positions.length]; for(int i=0; i<positions.length; i+=3){ colours[i] = colour.getRed()/255; colours[i+1] = colour.getGreen()/255; colours[i+2] = colour.getBlue()/255; } storeDataInAttributList(2, 3, colours); GL30.glBindVertexArray(0); return new Model(vaoID, indices.length); } /** * Lädt Daten ins Vertex Array Object (VAO). * * @param positions * @param indices * @return */ public Model loadVAO(float[] positions, int[] indices){ int vaoID = GL30.glGenVertexArrays(); vao_list.add(vaoID); GL30.glBindVertexArray(vaoID); bindIndicesBuffer(indices); storeDataInAttributList(0, 3, positions); GL30.glBindVertexArray(0); return new Model(vaoID, indices.length); } /** * Löscht die Daten aus dem Vertex Array Object (VAO) und aus dem Vertex Buffer Object (VBO). */ public void cleanUp(){ for(int vao:vao_list){ GL30.glDeleteVertexArrays(vao); } for(int vbo:vbo_list){ GL30.glDeleteFramebuffers(vbo); } } /** * Speichert Daten in einer Attribut-Liste. * @param attribut * @param coords * @param data */ private void storeDataInAttributList(int attribut, int coords, float[] data){ int vboID = GL15.glGenBuffers(); vbo_list.add(vboID); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vboID); FloatBuffer buffer = this.storeDataInFloatBuffer(data); GL15.glBufferData(GL15.GL_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); GL20.glVertexAttribPointer(attribut, coords, GL11.GL_FLOAT, false, 0, 0); GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0); } /** * Bindet Index-Buffers * @param indices */ private void bindIndicesBuffer(int[] indices){ int vboID = GL15.glGenBuffers(); vbo_list.add(vboID); GL15.glBindBuffer(GL15.GL_ELEMENT_ARRAY_BUFFER, vboID); IntBuffer buffer = this.storeDataInIntBuffer(indices); GL15.glBufferData(GL15.GL_ELEMENT_ARRAY_BUFFER, buffer, GL15.GL_STATIC_DRAW); } /** * Speichert Daten in einem Int-Buffer * @param data * @return */ private IntBuffer storeDataInIntBuffer(int[] data){ IntBuffer buffer = BufferUtils.createIntBuffer(data.length); buffer.put(data); buffer.flip(); return buffer; } /** * Speichert Daten in einem Float-Buffer. * @param data * @return */ private FloatBuffer storeDataInFloatBuffer(float[] data){ FloatBuffer buffer = BufferUtils.createFloatBuffer(data.length); buffer.put(data); buffer.flip(); return buffer; } } <file_sep>/OpenGl3DModelViewer/src/main/java/renderEngine/Entity.java package renderEngine; import org.lwjgl.util.vector.Vector3f; /** * Klasse, welche eine Entität (Einheit) in unserer Applikation darstellt. * Eine Entität ist beispielsweise die Sonne, oder eine Linie des Gitternetzes. */ public class Entity { private Vector3f rotation; private Vector3f translation; private float scale; private Model model; /** * Konstruktor. Erzeugt eine neue Entität für die übergebenen Parameter. */ public Entity(Model model, Vector3f translation, float rotX, float rotY, float rotZ, float scale) { this.model = model; this.translation = translation; this.rotation = new Vector3f(rotX, rotY, rotZ); this.scale = scale; } /** * Gibt das Model der Entität zurück. * @return model Model der Entität. */ public Model getModel() { return model; } /** * Gibt die Translation der Entität zurück. * @return translation Translation der Entität. */ public Vector3f getTranslation() { return translation; } /** * Gibt die Rotation der Entität um die X-Achse zurück. * @return Rotation der Entität um die X-Achse. */ public float getRotX() { return rotation.x; } /** * Gibt die Rotation der Entität um die Y-Achse zurück. * @return Rotation der Entität um die Y-Achse. */ public float getRotY() { return rotation.y; } /** * Gibt die Rotation der Entität um die Z-Achse zurück. * @return Rotation der Entität um die Z-Achse. */ public float getRotZ() { return rotation.z; } /** * Gibt den Skalierungsfaktor der Entität zurück. * @return Skalierungsfaktor der Entität. */ public float getScale() { return scale; } } <file_sep>/README.md # OpenGl Wavefront Viewer <file_sep>/OpenGl3DModelViewer/src/main/java/tester/Main.java package tester; import geometrie.Camera; import geometrie.Light; import geometrie.Line; import org.lwjgl.Sys; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.lwjgl.util.vector.Vector3f; import renderEngine.*; import shaders.ShaderCollection; import userInterface.DisplayManager; import userInterface.Window; import java.awt.*; import java.io.File; import java.util.ArrayList; /** * Main-Klasse des OpenGL Wavefront Viewer. * Lädt das Gitternetz und das Punktlicht (Sonne) und wartet auf die Aktion des Users zum Laden des Wavefront OBJ-Files. */ public class Main { public static void main(String[] args) { DisplayManager.create(); Entity entity = null; //Initialisiert den Shader GPUInterface loader = new GPUInterface(); ShaderCollection shader = new ShaderCollection(); Renderer renderer = new Renderer(shader); //Initialisiert das Punktlicht Light light = new Light(new Vector3f(20,20,0), new Vector3f(1,1,1)); Model sunModel = OBJReader.loadObjModel(new File("ressources/sphere.obj"), loader, Color.yellow); Entity sunEntity = new Entity(sunModel, new Vector3f(20,20,0), 0, 0, 0, 1); //Initialisiert die Kamera Camera camera = new Camera(); //Erstellt das Gitternetz Model lineModel = loader.loadVAO(Line.getVertices(), Line.getIndices()); ArrayList<Entity> lineGrid = new ArrayList<Entity>(); for(int i=0; i<21; i++) { //Horizontale Linien Entity h_xz = new Entity(lineModel, new Vector3f(0, 0, i), 0, 0, 0, 20); lineGrid.add(h_xz); Entity h_xnz = new Entity(lineModel, new Vector3f(0, 0, -i), 0, 0, 0, 20); lineGrid.add(h_xnz); Entity h_nxz = new Entity(lineModel, new Vector3f(0, 0, i), 0, 180, 0, 20); lineGrid.add(h_nxz); Entity h_nxnz = new Entity(lineModel, new Vector3f(0, 0, -i), 0, 180, 0, 20); lineGrid.add(h_nxnz); //Vertikale Linien Entity v_xz = new Entity(lineModel, new Vector3f(i, 0, 0), 0, 90, 0, 20); lineGrid.add(v_xz); Entity v_xnz = new Entity(lineModel, new Vector3f(-i, 0, 0), 0, 90, 0, 20); lineGrid.add(v_xnz); Entity v_nxz = new Entity(lineModel, new Vector3f(i, 0, 0), 0, 270, 0, 20); lineGrid.add(v_nxz); Entity v_nxnz = new Entity(lineModel, new Vector3f(-i, 0, 0), 0, 270, 0, 20); lineGrid.add(v_nxnz); } //Das hier ist der Main-Loop von Open-GL. while(DisplayManager.isNotCloseRequested()){ //Render Logik camera.move(); renderer.prepare(); //Shader starten shader.start(); shader.loadLight(light); shader.loadViewMatrix(camera); //Die Linien des Gitternetzes rendern for(Entity line : lineGrid) { renderer.renderLines(line, shader); } //Sonne (Punktlicht) rendern renderer.renderTriangles(sunEntity, shader); //3D-Model/Figur aus dem Wavefront OBJ-File rendern. File wavefrontFile = Window.getWavefrontFile(); if(wavefrontFile != null){ Model rawModel = OBJReader.loadObjModel(wavefrontFile, loader, Color.red); entity = new Entity(rawModel, new Vector3f(0,0,0) ,0,0,0,1); } if(entity != null) { renderer.renderTriangles(entity, shader); } //Shader stoppen und das GUI updated. shader.stop(); DisplayManager.update(); } //Dies sind Debug-Informationen. System.out.println("OpenGL version: " + GL11.glGetString(GL11.GL_VERSION)); System.out.println("Display driver version: " + Display.getVersion()); System.out.println("LWJGL version: " + Sys.getVersion()); //Shader, VAO and VBO wieder löschen. shader.cleanUp(); loader.cleanUp(); DisplayManager.close(); } } <file_sep>/OpenGl3DModelViewer/src/main/java/geometrie/Line.java package geometrie; /** * Klasse welche eine einfache Linie darstellt. */ public class Line { /** * gibt die Knoten der Linie in einem Array zurück. * @return Knoten der Linie. */ public static float[] getVertices() { float[] vertices = { 0, 0, 0, 1, 0, 0, }; return vertices; } /** * Gibt die Indizies der Linie (0 und 1) als Knoten zurück * @return Indizies der Linie (0 und 1) */ public static int[] getIndices() { int[] indices = { 0, 1 }; return indices; } } <file_sep>/OpenGl3DModelViewer/src/main/java/geometrie/Light.java package geometrie; import org.lwjgl.util.vector.Vector3f; /** * Diese Klasse erzeugt ein Punktlicht (Bei uns als Sonne dargestellt). */ public class Light { private Vector3f position; private Vector3f colour; /** * Erstellt ein Punktlicht aus der übergebenen Position und Farbe. * * @param position Position des Punktlichts. * @param colour Farbe des Punktlichts. */ public Light(Vector3f position, Vector3f colour) { this.position = position; this.colour = colour; } /** * Gibt die Position des Punktlichts zurück. * @return position Position des Punktlichts. */ public Vector3f getPosition() { return position; } /** * Gibt die Farbe des Punktlichts zurück. * @return colour Farbe des Punktlichts. */ public Vector3f getColour() { return colour; } } <file_sep>/OpenGl3DModelViewer/src/main/java/userInterface/Window.java package userInterface; import javax.swing.*; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; /** * Klasse erstellt das Fenster des User-Interfaces. */ public class Window { private static JFrame frame; private JTextField textField; private Canvas canvas; private static String wavefrontFile; public static boolean closeRequested = false; /** * Konstruktor. Initialisiert das Fenster und blendet das initialisierte Fenster ein. */ public Window() { initialize(); frame.setVisible(true); } /** * Initialisiert das Fenster */ private void initialize() { frame = new JFrame(); frame.setTitle("OpenGL Wavefront Viewer"); frame.setBounds(100, 100, 1200, 800); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setResizable(false); //Fenster-Icon ImageIcon img = new ImageIcon("ressources\\logo.png"); frame.setIconImage(img.getImage()); //Canvas canvas = new Canvas(); frame.getContentPane().add(canvas); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closeRequested = true; } }); //Panel JPanel panel = new JPanel(); frame.getContentPane().add(panel, BorderLayout.NORTH); //Textfeld zur Angabe des Filepfads des Wavefront OBJ-File textField = new JTextField(); textField.setColumns(69); Font font = new Font("Arial", Font.BOLD, 16); textField.setFont(font); panel.add(textField); //Buttons zur Auswahl des Wavefront OBJ-Files JButton btnSelect = new JButton("Select a file"); JButton btnOpen = new JButton("Open"); btnSelect.setPreferredSize(new Dimension(100,22)); btnOpen.setPreferredSize(new Dimension(100,22)); //ActionListener für den "Select a File"-Button-Klick -> FileOpenDialog einblenden, welche die Auswahl eines Wavefront OBJ-Files //ermöglicht. btnSelect.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { FileFilter filter = new FileNameExtensionFilter("Wavefront OBJ", "obj"); JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle("Open Wavefront"); // Filter wird dem JFileChooser hinzugefügt fileChooser.setFileFilter(filter); fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); wavefrontFile = selectedFile.getAbsolutePath(); textField.setText(wavefrontFile); } } }); //ActionListener für den "Open"-Button-Klick. Öffnet das im Eingabefeld angegebene Wavefront OBJ-File. btnOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { File file = new File(textField.getText()); if(file.exists() && !file.isDirectory()) { wavefrontFile = textField.getText(); }else{ System.out.println("File " + textField.getText() + " not found"); } } }); panel.add(btnSelect); panel.add(btnOpen); } /** * Setzt den Titel des Fensters. Dem Titel des Fenster wird der übergebene Titel angehängt. * @param title Titel, welcher zum statischen Titel "OpenGL Wavefront Viewer - " angehängt werden soll. */ public static void setTitle(String title){ frame.setTitle("OpenGL Wavefront Viewer - " + title); } /** * Gibt das Canvas des Fenster zurück. * @return canvas */ public Canvas getCanvas(){ return canvas; } /** * dispose */ public void dispose(){ frame.dispose(); } /** * Gibt die Höhe des Canvas zurück. * * @return canvas Höhe */ public int getCanvasHeight(){ return canvas.getHeight(); } /** * Gibt die Breite des Canvas zurück. * * @return canvas Breite. */ public int getCanvasWidth(){ return canvas.getWidth(); } /** * Gibt das geöffnete Wavefront OBJ-File zurück. * @return Geöffnetes wavefront file */ public static File getWavefrontFile(){ if(wavefrontFile != null && !wavefrontFile.isEmpty()) { File file = new File(wavefrontFile); wavefrontFile = new String(); return file; }else{ return null; } } }
05da229f16a9a07935ed7a839cdc08d41ca28788
[ "Markdown", "Java" ]
8
Java
joe1990/OpenGl3DModelViewer
4e503eaab25d19a13c29b39757d0d96864f744f3
032d51649e36c03e7802326f8b2e8aa092bffd5d
refs/heads/master
<file_sep>include ':app' rootProject.name='SpotifyCloneApp' <file_sep>package com.iafnstudios.spotifycloneapp import retrofit2.Call import retrofit2.http.GET interface SpotifyApiService { @GET("popularRadios.json") fun getPopularRadios():Call<List<Radio>> @GET("locationRadios.json") fun getLocationRadios():Call<List<Radio>> }<file_sep>package com.iafnstudios.spotifycloneapp.main import android.content.Context import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentStatePagerAdapter import com.iafnstudios.spotifycloneapp.R import com.iafnstudios.spotifycloneapp.favorites.FavoritesFragment import com.iafnstudios.spotifycloneapp.radios.RadiosFragment import java.lang.IllegalStateException class MainPagerAdapter(context: Context,fm: FragmentManager, behavior: Int) : FragmentStatePagerAdapter(fm, behavior) { private val tabs = context.applicationContext.resources.getStringArray(R.array.tabs) override fun getItem(position: Int): Fragment { return when(position){ TAB_INDEX_RADIOS -> RadiosFragment.newInstance() TAB_INDEX_FAVORITES -> FavoritesFragment.newInstance() else -> throw IllegalStateException("Can not found.") } } override fun getCount() = 2 override fun getPageTitle(position: Int): CharSequence? { return tabs[position] } companion object { private const val TAB_INDEX_RADIOS = 0 private const val TAB_INDEX_FAVORITES = 1 } }<file_sep>package com.iafnstudios.spotifycloneapp.radios import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.iafnstudios.spotifycloneapp.R import com.iafnstudios.spotifycloneapp.Radio import com.iafnstudios.spotifycloneapp.RadioServiceProvider import retrofit2.Call import retrofit2.Callback import retrofit2.Response class RadiosFragment : Fragment() { private val radioServiceProvider = RadioServiceProvider() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_radios, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) radioServiceProvider .getRadioService() .getPopularRadios().enqueue(object : Callback<List<Radio>> { override fun onFailure(call: Call<List<Radio>>, t: Throwable) { Log.v("TEST", "Failed!") } override fun onResponse(call: Call<List<Radio>>, response: Response<List<Radio>>) { Log.v("TEST", "Success: ${response.body()}") } }) radioServiceProvider .getRadioService() .getLocationRadios().enqueue(object : Callback<List<Radio>> { override fun onFailure(call: Call<List<Radio>>, t: Throwable) { Log.v("TEST", "Failed! ${t.toString()}") } override fun onResponse(call: Call<List<Radio>>, response: Response<List<Radio>>) { Log.v("TEST", "Success: ${response.body()}") } } ) } companion object { fun newInstance(): Fragment { return RadiosFragment() } } }
902064d0f12af8d0320b44fd382102224487a5a9
[ "Kotlin", "Gradle" ]
4
Gradle
abdullahsen/SpotifyCloneApp
1015d25cab1ef78b1adeebcef5711b18c4375465
a415414822735cefaf88b221871509424b1bbdc3
refs/heads/main
<file_sep>""" The main method for the program used to edit an excel file of wind turbine information Author: <NAME> """ # Imports import pandas as pd import time_generation as tg import dataframe_manipulation as em # Method in progress to create new excel file with conditions given # Input: Excel file # Output: Creates file on desktop def fileReader(inputFile, outputFile, dstActive): df = pd.read_excel(inputFile) # Create time column em.appendTimeFlag(df) # Generate missing times, by finding times = tg.makeTimes(df['time'].tolist(), dstActive) # Add missing times to excel file em.addNewTimes(df, times) # Create and update VTWS Flags for missing values em.appendVTWSFlag(df) em.updateVTWSFlag(df) # Export file df.to_excel(outputFile, index=False) # Main function, to ensure correct running enviroment. # Please replace inputFile, outputFile, and dstActive to the desired variables. # Set inputFile to input excel file, outputFile to desired output location, # and dstActive to whether DST is recognized in the given area (On by default) if __name__ == '__main__': inputFile = '/Users/patrick/Desktop/test 2021-05-06 start.xlsx' outputFile = '/Users/patrick/Desktop/check results.xlsx' dstActive = True fileReader(inputFile, outputFile, dstActive) <file_sep>""" The module used for timestamp generation between two defined timestamps, properly formatted Author: <NAME> """ # Imports from datetime import datetime as date, timedelta import pytz import pandas as pd # Immutables. Used for Timezone and DST Parsing. 2020 DST tzsNormal = {"-0500": 'US/Eastern', "-0600": 'US/Central', "-0700": 'US/Mountain', "-0800": 'US/Pacific'} tzsDST = {"-0400": 'US/Eastern', "-0500": 'US/Central', "-0600": 'US/Mountain', "-0700": 'US/Pacific'} dstStartNaive, dstEndNaive = date(2020, 3, 8, 1), date(2020, 11, 1, 1) # Method to create list of all times in hourly intervals between two given times. Timezone and DST sensitive. # Input: First time and last time as strings # Output: List of all times in hourly intervals between those times def makeTimes(currentTimes, dstActive): # Initializations. List to be filled, as well as datetime objects of the bookend times timesList = [] firstTime = currentTimes[0] lastTime = currentTimes[-1] timeObj = date.strptime(firstTime, '%Y-%m-%d %H:00:00%z') lastTimeObj = date.strptime(lastTime, '%Y-%m-%d %H:00:00%z') # Timezone object creation and DST object creation offset = timeObj.strftime("%z") #Checks if object is DST by removing timezone information, then comparing to start and end dates isDst = dstCheck(timeObj.replace(tzinfo=None)) # Gets timezone from known offset and DST status if isDst: tz = pytz.timezone(tzsDST[offset]) else: tz = pytz.timezone(tzsNormal[offset]) # Localizes DST start and end for relevant comparisons dstStartTZ, dstEndTZ = tz.localize(date(2020, 3, 8, 1), is_dst=False), tz.localize(date(2020, 11, 1, 1), is_dst=True) # While we are before the last time, we will loop and add more times while timeObj < lastTimeObj: # Add current time to list, if not currently in dataframe if timeEdit(timeObj.strftime('%Y-%m-%d %H:00:00%z')) not in currentTimes: timesList.append(timeEdit(timeObj.strftime('%Y-%m-%d %H:00:00%z'))) # If daylight savings starts, or ends on the current hour. # Note: Whenever we are at the last time object, we will be DST or not as that time is. # Flipping back and forth will lead to the correct instance when we reach the final time. if timeObj == dstStartTZ and dstActive == True: #Change the time to account for it, add the new time to list, and account for the last time being in DST timeObj = tz.localize(timeObj.replace(tzinfo=None), is_dst=True) # Add current time to list, if not currently in dataframe if timeEdit(timeObj.strftime('%Y-%m-%d %H:00:00%z')) not in currentTimes: timesList.append(timeEdit(timeObj.strftime('%Y-%m-%d %H:00:00%z'))) lastTimeObj -= timedelta(hours=1) # If it ends elif timeObj == dstEndTZ and dstActive == True: #Change the time to account for it, add the new time to list, and account for the last time NOT being in DST timeObj = tz.localize(timeObj.replace(tzinfo=None), is_dst=False) # Add current time to list, if not currently in dataframe if timeEdit(timeObj.strftime('%Y-%m-%d %H:00:00%z')) not in currentTimes: timesList.append(timeEdit(timeObj.strftime('%Y-%m-%d %H:00:00%z'))) lastTimeObj += timedelta(hours=1) # Add an hour, creating the next time to add to the list timeObj = timeObj + timedelta(hours=1) # Return the finalized list return timesList # Method To edit output of datetime strings properly format timezone # Input: Improperly formatted string # Output: Properly formatted string, with colon present def timeEdit(string): return "{0}:{1}".format( string[:-2], string[-2:] ) # Method to check if given time is in DST # Input: Datetime object # Output: Boolean representing DST or not def dstCheck(time): if time > dstStartNaive and time < dstEndNaive: return True return False<file_sep># scout-pandas-assignment A repository for Scout's Assignment for the Data Science Intern Position. Given a file of information sampled from a wind turbine at a given interval, this code will fill in the missing information needed to complete the file. Input a files of wind turbine information with missing information. Output a file with created information and correct timestamps. Built in Python using the Pandas, Datetime, Numpy, and Pytz modules. Authored by <NAME> <file_sep>""" The module for the program used to edit the dataframe for excel Author: <NAME> """ #imports import pandas as pd import numpy as np # Method to add timestamp flag to dataframe of information, # indicating if timestamp data was present originally # Input: dataframe # Output: dataframe with 'timestamp_flag' present def appendTimeFlag(df): flags = [0]*len(df) df['timestamp_flag'] = flags # Method to add VTWS flag to dataframe of information, # indicating if VTWS data was present originally # Input: dataframe # Output: dataframe with 'timestamp_flag' present def appendVTWSFlag(df): flags = [0]*len(df) df['data_qc_flag_VTWS_AVG'] = flags # Method to add new timestamps with correct IDs and indices to dataframe # Input: Dataframe and times to add # Output: Dataframe with times added, with correct IDs and indices def addNewTimes(df, times): # Adds new information for t in times: df.loc[len(df)] = [None, t, None, None, None, None, None, 1] # Sorts values, resetting the indices to be correct df.sort_values(by=['time'], inplace=True) df.reset_index(drop=True, inplace=True) # Sets the ID to be correct df['id'] = df.index # Drops the generated index column df.drop(df.columns[2], axis=1) # Method to set new VTWS flags with Erroneous or null, depending on if value were present or not # Input: Dataframe # Output: Dataframe column edited to say erroneous where VTWS is not present def updateVTWSFlag(df): df['data_qc_flag_VTWS_AVG'] = np.where(df.VTWS_AVG.isnull(), "Erroneous", None)
c089bbe852ec5aa66cd13194bd4a5a8ca8fd4614
[ "Markdown", "Python" ]
4
Python
patdan10/scout-pandas-assignment
eba1720b4ba9ef0d00751805e8203700c3e4e088
4f49e2b00250ca36845ed8c280d9c91192c3cf93
refs/heads/master
<file_sep>import React from "react"; import CurrentWeather from "./CurrentWeather"; import "./MainSection.css"; import Signature from "./Signature"; export default function MainSection() { return ( <div className="MainSection"> <div className="row"> <CurrentWeather defaultCity="Pittsburgh" /> <Signature /> </div> </div> ); } <file_sep>import React from "react"; import "./Signature.css"; export default function TodaysWeather() { return ( <div className="Signature"> <a href="https://github.com/oxenreiterlm/react-weather-app" target="blank" title="GitHub repository" className="gitHubLink" > Open-source code </a>{" "} by{" "} <a href="https://gifted-edison-603b21.netlify.app/" target="blank" title="Portfolio" className="profileLink" > <NAME> </a> </div> ); } <file_sep>import React from "react"; import WeatherIcon from "./WeatherIcon.js"; export default function WeatherForecastDay(props) { function maxTemperature() { let temperature = Math.round(props.data.temp.max); return `${temperature}`; } function minTemperature() { let temperature = Math.round(props.data.temp.min); return `${temperature}`; } function day() { let date = new Date(props.data.dt * 1000); let day = date.getDay(); let days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; return days[day]; } function precipitation() { let chanceOfPrecip = Math.round(props.data.pop * 100); return `${chanceOfPrecip}`; } return ( <div className="WeatherForecastDay"> <div className="dailyForecast day">{day()}</div> <div className="d-flex justify-content-center"> <WeatherIcon code={props.data.weather[0].icon} size={40} /> </div> <div className="forecastTemps d-flex justify-content-center"> <span className="maxTemp pe-1">{maxTemperature()}°</span> <span className="minTemp">{minTemperature()}°</span> </div> <div className="d-flex justify-content-center precipitationPercent"> {precipitation()}%💧 </div> </div> ); } <file_sep>import React from "react"; import FormattedDate from "./FormattedDate"; import WeatherIcon from "./WeatherIcon.js"; import WeatherTemperature from "./WeatherTemperature"; export default function WeatherInfo(props) { return ( <div className="WeatherInfo"> <div className="currentLocAndTime"> <h2 className="cityUpdate">{props.data.city}</h2> <div className="currentDateTime"> <h6 id="date-time-now"> <FormattedDate date={props.data.date} /> </h6> </div> </div> <div className="row weatherToday"> <div className="col"> <div className="currentWeatherIcon"> <WeatherIcon code={props.data.icon} size={84} /> </div> </div> <div className="col align-self-center p-0"> <div className="row currentTempWithUnits p-0"> <WeatherTemperature fahrenheit={Math.round(props.data.temperature)} /> </div> </div> <div className="col-sm-5 p-0 align-self-center"> <h4 className="otherCurrentDesc"> <div>{props.data.description}</div> <div id="wind-speed-input"> wind speed: {Math.round(props.data.wind)} mph </div> <div id="humidity-input">humidity: {props.data.humidity}%</div> </h4> </div> </div> </div> ); }
91145f216b26be90d69104a62dc8f6480d557609
[ "JavaScript" ]
4
JavaScript
oxenreiterlm/react-weather-app
558ae54b31e6209c6c94a38984b0a23ea0b10663
68563cd5852b0bc27d66cc14874f9add51bc9782
refs/heads/master
<repo_name>isqad/Thumbsup<file_sep>/app/src/main/java/ru/funnyhourse/thumbsup/ui/fragments/ChatsFragment.kt package ru.funnyhourse.thumbsup.ui.fragments import ru.funnyhourse.thumbsup.R class ChatsFragment : BaseFragment(R.layout.fragment_chats) { override fun onResume() { super.onResume() } } <file_sep>/app/src/main/java/ru/funnyhourse/thumbsup/ui/objects/AppDrawer.kt package ru.funnyhourse.thumbsup.ui.objects import android.view.View import androidx.appcompat.widget.Toolbar import com.mikepenz.materialdrawer.AccountHeader import com.mikepenz.materialdrawer.AccountHeaderBuilder import com.mikepenz.materialdrawer.Drawer import com.mikepenz.materialdrawer.DrawerBuilder import com.mikepenz.materialdrawer.model.DividerDrawerItem import com.mikepenz.materialdrawer.model.PrimaryDrawerItem import com.mikepenz.materialdrawer.model.ProfileDrawerItem import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem import ru.funnyhourse.thumbsup.MainActivity import ru.funnyhourse.thumbsup.R import ru.funnyhourse.thumbsup.ui.fragments.SettingsFragment class AppDrawer(private val activity: MainActivity, private val toolbar: Toolbar) { private val accountHeader: AccountHeader = AccountHeaderBuilder().withActivity(activity) .withHeaderBackground(R.drawable.header).addProfiles( ProfileDrawerItem().withName("<NAME>").withEmail("+7 (912) 657-60-39") ).build() fun create() { DrawerBuilder(). withActivity(activity). withToolbar(toolbar). withActionBarDrawerToggle(true). withSelectedItem(-1). withAccountHeader(accountHeader). addDrawerItems( PrimaryDrawerItem(). withIdentifier(100). withIconTintingEnabled(true). withName(R.string.new_group). withSelectable(false). withIcon(R.drawable.ic_menu_create_groups), PrimaryDrawerItem(). withIdentifier(101). withIconTintingEnabled(true). withName(R.string.new_secret_chat). withSelectable(false). withIcon(R.drawable.ic_menu_secret_chat), PrimaryDrawerItem(). withIdentifier(102). withIconTintingEnabled(true). withName(R.string.new_channel). withSelectable(false). withIcon(R.drawable.ic_menu_create_channel), PrimaryDrawerItem(). withIdentifier(103). withIconTintingEnabled(true). withName(R.string.contacts). withSelectable(false). withIcon(R.drawable.ic_menu_contacts), PrimaryDrawerItem(). withIdentifier(104). withIconTintingEnabled(true). withName(R.string.calls). withSelectable(false). withIcon(R.drawable.ic_menu_phone), PrimaryDrawerItem(). withIdentifier(105). withIconTintingEnabled(true). withName(R.string.favorite). withSelectable(false). withIcon(R.drawable.ic_menu_favorites), PrimaryDrawerItem(). withIdentifier(106). withIconTintingEnabled(true). withName(R.string.settings). withSelectable(false). withIcon(R.drawable.ic_menu_settings), DividerDrawerItem(), PrimaryDrawerItem(). withIdentifier(107). withIconTintingEnabled(true). withName(R.string.invite_friends). withSelectable(false). withIcon(R.drawable.ic_menu_invate), PrimaryDrawerItem(). withIdentifier(108). withIconTintingEnabled(true). withName(R.string.faq). withSelectable(false). withIcon(R.drawable.ic_menu_help) ).withOnDrawerItemClickListener(object : Drawer.OnDrawerItemClickListener { override fun onItemClick( view: View?, position: Int, drawerItem: IDrawerItem<*> ): Boolean { when (position) { 7 -> activity.supportFragmentManager.beginTransaction(). addToBackStack(null). replace(R.id.data_container, SettingsFragment() ). commit() } return false } }).build() } }<file_sep>/settings.gradle rootProject.name='Thumbsup' include ':app' <file_sep>/app/src/main/java/ru/funnyhourse/thumbsup/ui/fragments/SettingsFragment.kt package ru.funnyhourse.thumbsup.ui.fragments import ru.funnyhourse.thumbsup.R class SettingsFragment : BaseFragment(R.layout.fragment_settings) { override fun onResume() { super.onResume() } }
ffaacca5b29f65911d2ba65be288d5523ca5cc65
[ "Kotlin", "Gradle" ]
4
Kotlin
isqad/Thumbsup
cd8ca0fdd91a8704f80f59fb82408fb1c36b1ed8
eaaa17920cd5d4d3d53d4ff62d39f3a6d902fed1
refs/heads/main
<file_sep>// // Copyright (c) 2021 <NAME> <<EMAIL>> // MIT license // #pragma once #import <atomic> #import <memory> #import <vector> #import <CoreAudio/CoreAudio.h> #import <AudioToolbox/AudioToolbox.h> #import "SFBCABufferList.hpp" #import "SFBCARingBuffer.hpp" #import "SFBHALAudioDevice.hpp" namespace SFB { class AudioUnitRecorder; } class SFBScheduledAudioSlice; class SFBAUv2IO { public: /// Creates a new @c SFBAUv2IO for the default system input and output devices SFBAUv2IO(); // This class is non-copyable SFBAUv2IO(const SFBAUv2IO& rhs) = delete; // This class is non-assignable SFBAUv2IO& operator=(const SFBAUv2IO& rhs) = delete; ~SFBAUv2IO(); // This class is non-movable SFBAUv2IO(SFBAUv2IO&& rhs) = delete; // This class is non-move assignable SFBAUv2IO& operator=(SFBAUv2IO&& rhs) = delete; SFBAUv2IO(AudioObjectID inputDeviceID, AudioObjectID outputDeviceID); SFB::HALAudioDevice InputDevice() const; SFB::HALAudioDevice OutputDevice() const; void Start(); void StartAt(const AudioTimeStamp& timeStamp); void Stop(); bool IsRunning() const; bool OutputIsRunning() const; bool InputIsRunning() const; void Play(CFURLRef url); void PlayAt(CFURLRef url, const AudioTimeStamp& timeStamp); void GetInputFormat(AudioStreamBasicDescription& format); void GetPlayerFormat(AudioStreamBasicDescription& format); void GetOutputFormat(AudioStreamBasicDescription& format); void SetInputRecordingURL(CFURLRef url, AudioFileTypeID fileType, const AudioStreamBasicDescription& format); void SetPlayerRecordingURL(CFURLRef url, AudioFileTypeID fileType, const AudioStreamBasicDescription& format); void SetOutputRecordingURL(CFURLRef url, AudioFileTypeID fileType, const AudioStreamBasicDescription& format); private: void Initialize(AudioObjectID inputDeviceID, AudioObjectID outputDeviceID); void CreateInputAU(AudioObjectID inputDeviceID); void CreateOutputAU(AudioObjectID outputDeviceID); void CreateMixerAU(); void CreatePlayerAU(); void BuildGraph(); UInt32 MinimumInputLatency() const; UInt32 MinimumOutputLatency() const; inline UInt32 MinimumThroughLatency() const { return MinimumOutputLatency() + MinimumInputLatency(); } std::unique_ptr<SFB::AudioUnitRecorder> mInputRecorder; std::unique_ptr<SFB::AudioUnitRecorder> mPlayerRecorder; std::unique_ptr<SFB::AudioUnitRecorder> mOutputRecorder; AudioUnit mInputUnit; AudioUnit mPlayerUnit; AudioUnit mMixerUnit; AudioUnit mOutputUnit; std::atomic<double> mFirstInputSampleTime; std::atomic<double> mFirstOutputSampleTime; Float64 mThroughLatency; SFB::CABufferList mInputBufferList; SFB::CARingBuffer mInputRingBuffer; static OSStatus InputRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); static OSStatus OutputRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); static OSStatus MixerInputRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData); SFBScheduledAudioSlice *mScheduledAudioSlices; static void ScheduledAudioSliceCompletionProc(void *userData, ScheduledAudioSlice *slice); }; <file_sep>// // Copyright (c) 2021 <NAME> <<EMAIL>> // MIT license // #import "SFBAUv2IO.hpp" #import <cstring> #import <limits> #import <memory> #import <new> #import <stdexcept> #import <os/log.h> #import "SFBAudioUnitRecorder.hpp" #import "SFBCABufferList.hpp" #import "SFBCAPropertyAddress.hpp" #import "SFBCAStreamBasicDescription.hpp" #import "SFBCATimeStamp.hpp" #import "SFBCAExtAudioFile.hpp" #import "SFBHALAudioStream.hpp" #import "SFBHALAudioSystemObject.hpp" namespace { const size_t kScheduledAudioSliceCount = 16; SFB::CABufferList ReadFileContents(CFURLRef url, const AudioStreamBasicDescription& format) { SFB::CAExtAudioFile eaf; eaf.OpenURL(url); eaf.SetClientDataFormat(format); auto frameLength = eaf.FrameLength(); if(frameLength > std::numeric_limits<UInt32>::max()) throw std::overflow_error("Frame length > std::numeric_limits<UInt32>::max()"); SFB::CABufferList abl; if(!abl.Allocate(format, static_cast<UInt32>(frameLength))) throw std::bad_alloc(); eaf.Read(abl); return abl; } } class SFBScheduledAudioSlice : public ScheduledAudioSlice { public: SFBScheduledAudioSlice() { std::memset(this, 0, sizeof(ScheduledAudioSlice)); mAvailable = true; } ~SFBScheduledAudioSlice() { std::free(mBufferList); } void Clear() { std::free(mBufferList); std::memset(this, 0, sizeof(ScheduledAudioSlice)); } std::atomic_bool mAvailable; }; SFBAUv2IO::SFBAUv2IO() : mInputUnit(nullptr), mPlayerUnit(nullptr), mMixerUnit(nullptr), mOutputUnit(nullptr), mFirstInputSampleTime(-1), mFirstOutputSampleTime(-1), mScheduledAudioSlices(nullptr) { SFB::HALAudioSystemObject systemObject; Initialize(systemObject.DefaultInputDevice(), systemObject.DefaultOutputDevice()); mScheduledAudioSlices = new SFBScheduledAudioSlice [kScheduledAudioSliceCount]; } SFBAUv2IO::SFBAUv2IO(AudioObjectID inputDeviceID, AudioObjectID outputDeviceID) : mInputUnit(nullptr), mPlayerUnit(nullptr), mMixerUnit(nullptr), mOutputUnit(nullptr), mFirstInputSampleTime(-1), mFirstOutputSampleTime(-1), mScheduledAudioSlices(nullptr) { Initialize(inputDeviceID, outputDeviceID); mScheduledAudioSlices = new SFBScheduledAudioSlice [kScheduledAudioSliceCount]; } SFBAUv2IO::~SFBAUv2IO() { if(mOutputUnit) AudioOutputUnitStop(mOutputUnit); if(mInputUnit) AudioOutputUnitStop(mInputUnit); if(mInputRecorder) mInputRecorder->Stop(); if(mPlayerRecorder) mPlayerRecorder->Stop(); if(mOutputRecorder) mOutputRecorder->Stop(); if(mInputUnit) { AudioUnitUninitialize(mInputUnit); AudioComponentInstanceDispose(mInputUnit); } if(mPlayerUnit) { AudioUnitUninitialize(mPlayerUnit); AudioComponentInstanceDispose(mPlayerUnit); } if(mMixerUnit) { AudioUnitUninitialize(mMixerUnit); AudioComponentInstanceDispose(mMixerUnit); } if(mOutputUnit) { AudioUnitUninitialize(mOutputUnit); AudioComponentInstanceDispose(mOutputUnit); } delete [] mScheduledAudioSlices; } SFB::HALAudioDevice SFBAUv2IO::InputDevice() const { AudioObjectID deviceID; UInt32 size = sizeof(deviceID); auto result = AudioUnitGetProperty(mInputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceID, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioOutputUnitProperty_CurrentDevice)"); return SFB::HALAudioDevice(deviceID); } SFB::HALAudioDevice SFBAUv2IO::OutputDevice() const { AudioObjectID deviceID; UInt32 size = sizeof(deviceID); auto result = AudioUnitGetProperty(mOutputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceID, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioOutputUnitProperty_CurrentDevice)"); return SFB::HALAudioDevice(deviceID); } void SFBAUv2IO::Start() { if(IsRunning()) return; if(mInputRecorder) mInputRecorder->Start(); if(mPlayerRecorder) mPlayerRecorder->Start(); if(mOutputRecorder) mOutputRecorder->Start(); auto result = AudioOutputUnitStart(mInputUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioOutputUnitStart (mInputUnit)"); result = AudioOutputUnitStart(mOutputUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioOutputUnitStart (mOutputUnit)"); } void SFBAUv2IO::StartAt(const AudioTimeStamp& timeStamp) { if(IsRunning()) return; AudioOutputUnitStartAtTimeParams startAtTime = { .mTimestamp = timeStamp, .mFlags = 0 }; // For some reason this is causing errors in AudioOutputUnitStart() auto result = AudioUnitSetProperty(mInputUnit, kAudioOutputUnitProperty_StartTime, kAudioUnitScope_Global, 0, &startAtTime, sizeof(startAtTime)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_StartTime)"); result = AudioUnitSetProperty(mOutputUnit, kAudioOutputUnitProperty_StartTime, kAudioUnitScope_Global, 0, &startAtTime, sizeof(startAtTime)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_StartTime)"); Start(); } void SFBAUv2IO::Stop() { if(!IsRunning()) return; auto result = AudioOutputUnitStop(mInputUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioOutputUnitStop (mInputUnit)"); result = AudioOutputUnitStop(mOutputUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioOutputUnitStop (mOutputUnit)"); result = AudioUnitReset(mPlayerUnit, kAudioUnitScope_Global, 0); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitReset (mPlayerUnit)"); if(mInputRecorder) mInputRecorder->Stop(); if(mPlayerRecorder) mPlayerRecorder->Stop(); if(mOutputRecorder) mOutputRecorder->Stop(); mFirstInputSampleTime = -1; mFirstOutputSampleTime = -1; } bool SFBAUv2IO::IsRunning() const { return InputIsRunning() || OutputIsRunning(); } bool SFBAUv2IO::OutputIsRunning() const { UInt32 value; UInt32 size = sizeof(value); auto result = AudioUnitGetProperty(mOutputUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, 0, &value, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioOutputUnitProperty_IsRunning)"); return value != 0; } bool SFBAUv2IO::InputIsRunning() const { UInt32 value; UInt32 size = sizeof(value); auto result = AudioUnitGetProperty(mInputUnit, kAudioOutputUnitProperty_IsRunning, kAudioUnitScope_Global, 0, &value, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioOutputUnitProperty_IsRunning)"); return value != 0; } void SFBAUv2IO::Play(CFURLRef url) { PlayAt(url, SFB::CATimeStamp{}); } void SFBAUv2IO::PlayAt(CFURLRef url, const AudioTimeStamp& timeStamp) { SFB::CAStreamBasicDescription format; UInt32 size = sizeof(format); auto result = AudioUnitGetProperty(mPlayerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioUnitProperty_StreamFormat)"); auto abl = ReadFileContents(url, format); SFBScheduledAudioSlice *slice = nullptr; for(size_t i = 0; i < kScheduledAudioSliceCount; ++i) { if(mScheduledAudioSlices[i].mAvailable) { slice = mScheduledAudioSlices + i; break; } } if(!slice) throw std::runtime_error("No available slices"); slice->Clear(); slice->mTimeStamp = timeStamp; slice->mCompletionProc = ScheduledAudioSliceCompletionProc; slice->mCompletionProcUserData = this; slice->mNumberFrames = abl.FrameLength(); slice->mBufferList = abl.RelinquishABL(); slice->mAvailable = false; result = AudioUnitSetProperty(mPlayerUnit, kAudioUnitProperty_ScheduleAudioSlice, kAudioUnitScope_Global, 0, slice, sizeof(*slice)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioUnitProperty_ScheduleAudioSlice)"); SFB::CATimeStamp currentPlayTime; size = sizeof(currentPlayTime); result = AudioUnitGetProperty(mPlayerUnit, kAudioUnitProperty_CurrentPlayTime, kAudioUnitScope_Global, 0, &currentPlayTime, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioUnitProperty_CurrentPlayTime)"); if(currentPlayTime.SampleTimeIsValid() && currentPlayTime.mSampleTime == -1) { SFB::CATimeStamp startTime{-1.0}; result = AudioUnitSetProperty(mPlayerUnit, kAudioUnitProperty_ScheduleStartTimeStamp, kAudioUnitScope_Global, 0, &startTime, sizeof(startTime)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioUnitProperty_ScheduleStartTimeStamp)"); } } void SFBAUv2IO::GetInputFormat(AudioStreamBasicDescription& format) { UInt32 size = sizeof(format); auto result = AudioUnitGetProperty(mInputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioUnitProperty_StreamFormat)"); } void SFBAUv2IO::GetPlayerFormat(AudioStreamBasicDescription& format) { UInt32 size = sizeof(format); auto result = AudioUnitGetProperty(mPlayerUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioUnitProperty_StreamFormat)"); } void SFBAUv2IO::GetOutputFormat(AudioStreamBasicDescription& format) { UInt32 size = sizeof(format); auto result = AudioUnitGetProperty(mOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &format, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioUnitProperty_StreamFormat)"); } void SFBAUv2IO::SetInputRecordingURL(CFURLRef url, AudioFileTypeID fileType, const AudioStreamBasicDescription& format) { mInputRecorder = std::make_unique<SFB::AudioUnitRecorder>(mInputUnit, url, fileType, format, 1); } void SFBAUv2IO::SetPlayerRecordingURL(CFURLRef url, AudioFileTypeID fileType, const AudioStreamBasicDescription& format) { mPlayerRecorder = std::make_unique<SFB::AudioUnitRecorder>(mPlayerUnit, url, fileType, format); } void SFBAUv2IO::SetOutputRecordingURL(CFURLRef url, AudioFileTypeID fileType, const AudioStreamBasicDescription& format) { mOutputRecorder = std::make_unique<SFB::AudioUnitRecorder>(mOutputUnit, url, fileType, format); } void SFBAUv2IO::Initialize(AudioObjectID inputDeviceID, AudioObjectID outputDeviceID) { CreateInputAU(inputDeviceID); CreateOutputAU(outputDeviceID); CreateMixerAU(); CreatePlayerAU(); BuildGraph(); mThroughLatency = MinimumThroughLatency(); } void SFBAUv2IO::CreateInputAU(AudioObjectID inputDeviceID) { if(inputDeviceID == kAudioObjectUnknown) throw std::invalid_argument("inputDevice == kAudioObjectUnknown"); SFB::HALAudioDevice inputDevice(inputDeviceID); #if DEBUG auto deviceName = inputDevice.Name(); if(deviceName) os_log_debug(OS_LOG_DEFAULT, "Using input device %{public}@ (0x%x)", deviceName.Object(), inputDeviceID); #endif AudioComponentDescription componentDescription = { .componentType = kAudioUnitType_Output, .componentSubType = kAudioUnitSubType_HALOutput, .componentManufacturer = kAudioUnitManufacturer_Apple, .componentFlags = kAudioComponentFlag_SandboxSafe, .componentFlagsMask = 0 }; auto component = AudioComponentFindNext(nullptr, &componentDescription); if(!component) throw std::runtime_error("kAudioUnitSubType_HALOutput missing"); auto result = AudioComponentInstanceNew(component, &mInputUnit); SFB::ThrowIfCAAudioObjectError(result, "AudioComponentInstanceNew"); UInt32 enableIO = 1; result = AudioUnitSetProperty(mInputUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_EnableIO)"); enableIO = 0; result = AudioUnitSetProperty(mInputUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_EnableIO)"); result = AudioUnitSetProperty(mInputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &inputDeviceID, sizeof(inputDeviceID)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_CurrentDevice)"); UInt32 startAtZero = 0; result = AudioUnitSetProperty(mInputUnit, kAudioOutputUnitProperty_StartTimestampsAtZero, kAudioUnitScope_Global, 0, &startAtZero, sizeof(startAtZero)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_StartTimestampsAtZero)"); AURenderCallbackStruct inputCallback = { .inputProc = InputRenderCallback, .inputProcRefCon = this }; result = AudioUnitSetProperty(mInputUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &inputCallback, sizeof(inputCallback)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_SetInputCallback)"); SFB::CAPropertyAddress theAddress(kAudioDevicePropertyNominalSampleRate); auto inputDeviceSampleRate = inputDevice.NominalSampleRate(); SFB::CAStreamBasicDescription inputUnitInputFormat; UInt32 size = sizeof(inputUnitInputFormat); result = AudioUnitGetProperty(mInputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &inputUnitInputFormat, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioUnitProperty_StreamFormat)"); // CFShow(inputUnitInputFormat.Description("input AU input format: ")); SFB::CAStreamBasicDescription inputUnitOutputFormat; size = sizeof(inputUnitOutputFormat); result = AudioUnitGetProperty(mInputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &inputUnitOutputFormat, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioUnitProperty_StreamFormat)"); assert(inputDeviceSampleRate == inputUnitInputFormat.mSampleRate); // inputUnitOutputFormat.mSampleRate = inputDeviceSampleRate; inputUnitOutputFormat.mSampleRate = inputUnitInputFormat.mSampleRate; inputUnitOutputFormat.mChannelsPerFrame = inputUnitInputFormat.mChannelsPerFrame; result = AudioUnitSetProperty(mInputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &inputUnitOutputFormat, sizeof(inputUnitOutputFormat)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioUnitProperty_StreamFormat)"); // CFShow(inputUnitOutputFormat.Description("input AU output format: ")); // UInt32 maxFramesPerSlice; // size = sizeof(maxFramesPerSlice); // result = AudioUnitGetProperty(mInputUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &maxFramesPerSlice, &size); // SFBAudioUnitThrowIfError(result, "AudioUnitGetProperty"); UInt32 bufferFrameSize; size = sizeof(bufferFrameSize); result = AudioUnitGetProperty(mInputUnit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, &bufferFrameSize, &size); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitGetProperty (kAudioDevicePropertyBufferFrameSize)"); if(!mInputBufferList.Allocate(inputUnitOutputFormat, bufferFrameSize)) throw std::bad_alloc(); if(!mInputRingBuffer.Allocate(inputUnitOutputFormat, 20 * bufferFrameSize)) throw std::bad_alloc(); result = AudioUnitInitialize(mInputUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitInitialize"); } void SFBAUv2IO::CreateOutputAU(AudioObjectID outputDeviceID) { if(outputDeviceID == kAudioObjectUnknown) throw std::invalid_argument("outputDevice == kAudioObjectUnknown"); #if DEBUG { SFB::HALAudioDevice outputDevice(outputDeviceID); auto deviceName = outputDevice.Name(); if(deviceName) os_log_debug(OS_LOG_DEFAULT, "Using output device %{public}@ (0x%x)", deviceName.Object(), outputDeviceID); } #endif AudioComponentDescription componentDescription = { .componentType = kAudioUnitType_Output, .componentSubType = kAudioUnitSubType_HALOutput, .componentManufacturer = kAudioUnitManufacturer_Apple, .componentFlags = kAudioComponentFlag_SandboxSafe, .componentFlagsMask = 0 }; auto component = AudioComponentFindNext(nullptr, &componentDescription); if(!component) throw std::runtime_error("kAudioUnitSubType_HALOutput missing"); auto result = AudioComponentInstanceNew(component, &mOutputUnit); SFB::ThrowIfCAAudioObjectError(result, "AudioComponentInstanceNew"); result = AudioUnitSetProperty(mOutputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &outputDeviceID, sizeof(outputDeviceID)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_CurrentDevice)"); UInt32 startAtZero = 0; result = AudioUnitSetProperty(mOutputUnit, kAudioOutputUnitProperty_StartTimestampsAtZero, kAudioUnitScope_Global, 0, &startAtZero, sizeof(startAtZero)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioOutputUnitProperty_StartTimestampsAtZero)"); AURenderCallbackStruct outputCallback = { .inputProc = OutputRenderCallback, .inputProcRefCon = this }; result = AudioUnitSetProperty(mOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &outputCallback, sizeof(outputCallback)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioUnitProperty_SetRenderCallback)"); result = AudioUnitInitialize(mOutputUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitInitialize"); } void SFBAUv2IO::CreateMixerAU() { AudioComponentDescription componentDescription = { .componentType = kAudioUnitType_Mixer, .componentSubType = kAudioUnitSubType_MultiChannelMixer, .componentManufacturer = kAudioUnitManufacturer_Apple, .componentFlags = kAudioComponentFlag_SandboxSafe, .componentFlagsMask = 0 }; auto component = AudioComponentFindNext(nullptr, &componentDescription); if(!component) throw std::runtime_error("kAudioUnitSubType_MultiChannelMixer missing"); auto result = AudioComponentInstanceNew(component, &mMixerUnit); SFB::ThrowIfCAAudioObjectError(result, "AudioComponentInstanceNew"); } void SFBAUv2IO::CreatePlayerAU() { AudioComponentDescription componentDescription = { .componentType = kAudioUnitType_Generator, .componentSubType = kAudioUnitSubType_ScheduledSoundPlayer, .componentManufacturer = kAudioUnitManufacturer_Apple, .componentFlags = kAudioComponentFlag_SandboxSafe, .componentFlagsMask = 0 }; auto component = AudioComponentFindNext(nullptr, &componentDescription); if(!component) throw std::runtime_error("kAudioUnitSubType_ScheduledSoundPlayer missing"); auto result = AudioComponentInstanceNew(component, &mPlayerUnit); SFB::ThrowIfCAAudioObjectError(result, "AudioComponentInstanceNew"); } void SFBAUv2IO::BuildGraph() { // player out -> mixer input 0 AudioUnitConnection conn = { .sourceAudioUnit = mPlayerUnit, .sourceOutputNumber = 0, .destInputNumber = 0 }; auto result = AudioUnitSetProperty(mMixerUnit, kAudioUnitProperty_MakeConnection, kAudioUnitScope_Input, 0, &conn, sizeof(conn)); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetProperty (kAudioUnitProperty_MakeConnection)"); result = AudioUnitInitialize(mMixerUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitInitialize"); result = AudioUnitInitialize(mPlayerUnit); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitInitialize"); // Set mixer volumes result = AudioUnitSetParameter(mMixerUnit, kMultiChannelMixerParam_Volume, kAudioUnitScope_Input, 0, 1, 0); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetParameter (kMultiChannelMixerParam_Volume)"); result = AudioUnitSetParameter(mMixerUnit, kMultiChannelMixerParam_Volume, kAudioUnitScope_Output, 0, 1, 0); SFB::ThrowIfCAAudioUnitError(result, "AudioUnitSetParameter (kMultiChannelMixerParam_Volume)"); } UInt32 SFBAUv2IO::MinimumInputLatency() const { auto inputDevice = InputDevice(); auto safetyOffset = inputDevice.SafetyOffset(SFB::HALAudioObjectDirectionalScope::input); auto bufferFrameSize = inputDevice.BufferFrameSize(); #if DEBUG auto latency = inputDevice.Latency(SFB::HALAudioObjectDirectionalScope::input); auto streams = inputDevice.Streams(SFB::HALAudioObjectDirectionalScope::input); for(auto stream : streams) { auto streamLatency = stream.Latency(); os_log_debug(OS_LOG_DEFAULT, "Input stream 0x%x latency %d", stream.ObjectID(), streamLatency); } os_log_debug(OS_LOG_DEFAULT, "Minimum input latency %d (%d safety offset + %d buffer size) [device latency %d]", safetyOffset + bufferFrameSize, safetyOffset, bufferFrameSize, latency); #endif return safetyOffset + bufferFrameSize; } UInt32 SFBAUv2IO::MinimumOutputLatency() const { auto outputDevice = OutputDevice(); auto safetyOffset = outputDevice.SafetyOffset(SFB::HALAudioObjectDirectionalScope::output); auto bufferFrameSize = outputDevice.BufferFrameSize(); #if DEBUG auto latency = outputDevice.Latency(SFB::HALAudioObjectDirectionalScope::output); auto streams = outputDevice.Streams(SFB::HALAudioObjectDirectionalScope::output); for(auto stream : streams) { auto streamLatency = stream.Latency(); os_log_debug(OS_LOG_DEFAULT, "Output stream 0x%x latency %d", stream.ObjectID(), streamLatency); } os_log_debug(OS_LOG_DEFAULT, "Minimum output latency %d (%d safety offset + %d buffer size) [device latency %d]", safetyOffset + bufferFrameSize, safetyOffset, bufferFrameSize, latency); #endif return safetyOffset + bufferFrameSize; } OSStatus SFBAUv2IO::InputRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { SFBAUv2IO *THIS = static_cast<SFBAUv2IO *>(inRefCon); if(THIS->mFirstInputSampleTime < 0) THIS->mFirstInputSampleTime = inTimeStamp->mSampleTime; THIS->mInputBufferList.Reset(); auto result = AudioUnitRender(THIS->mInputUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, THIS->mInputBufferList); // SFBAudioUnitThrowIfError(result, "AudioUnitRender (mInputUnit)"); if(result != noErr) os_log_error(OS_LOG_DEFAULT, "Error rendering input: %d", result); if(!THIS->mInputRingBuffer.Write(THIS->mInputBufferList, inNumberFrames, static_cast<int64_t>(inTimeStamp->mSampleTime))) os_log_debug(OS_LOG_DEFAULT, "SFBCARingBuffer::Write failed at sample time %.0f", inTimeStamp->mSampleTime); return result; } OSStatus SFBAUv2IO::OutputRenderCallback(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData) { SFBAUv2IO *THIS = static_cast<SFBAUv2IO *>(inRefCon); // Input not yet running if(THIS->mFirstInputSampleTime < 0) { *ioActionFlags = kAudioUnitRenderAction_OutputIsSilence; for(UInt32 i = 0; i < ioData->mNumberBuffers; ++i) std::memset(ioData->mBuffers[i].mData, 0, ioData->mBuffers[i].mDataByteSize); return noErr; } if(THIS->mFirstOutputSampleTime < 0) { THIS->mFirstOutputSampleTime = inTimeStamp->mSampleTime; auto delta = THIS->mFirstOutputSampleTime - THIS->mFirstInputSampleTime; #if DEBUG os_log_debug(OS_LOG_DEFAULT, "output → input sample Δ %.0f\n", delta); #endif THIS->mThroughLatency += delta; #if DEBUG os_log_debug(OS_LOG_DEFAULT, "Adjusted through latency %.0f\n", THIS->mThroughLatency); #endif *ioActionFlags = kAudioUnitRenderAction_OutputIsSilence; for(UInt32 i = 0; i < ioData->mNumberBuffers; ++i) std::memset(ioData->mBuffers[i].mData, 0, ioData->mBuffers[i].mDataByteSize); return noErr; } auto result = AudioUnitRender(THIS->mMixerUnit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData); // SFBAudioUnitThrowIfError(result, "AudioUnitRender (mMixerUnit)"); if(result != noErr) os_log_error(OS_LOG_DEFAULT, "Error rendering mixer output: %d", result); return result; } void SFBAUv2IO::ScheduledAudioSliceCompletionProc(void *userData, ScheduledAudioSlice *slice) { // SFBAUv2IO *THIS = static_cast<SFBAUv2IO *>(userData); static_cast<SFBScheduledAudioSlice *>(slice)->mAvailable = true; }
a70aca1a07115bd267bb89c4a2f4b25adede043f
[ "C++" ]
2
C++
sbooth/SFBAUv2IO
50930aae036e495339a19dacae724fedd69e6486
92b9b6ea811ce5028973f5d31b3326c9080db036
refs/heads/master
<repo_name>pcdd05java/TibaWeAPP<file_sep>/app/src/main/java/idv/ca107g2/tibawe/QRCodeSignInActivity.java package idv.ca107g2.tibawe; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.hannesdorfmann.swipeback.Position; import com.hannesdorfmann.swipeback.SwipeBack; import java.lang.reflect.Type; import java.util.Map; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.tools.Util; public class QRCodeSignInActivity extends AppCompatActivity{ SharedPreferences preferences; int msg_code; String distance; private static final String TAG = "QRCodeSignInActivity"; private CommonTask lastQRCheckTask; private static final String CHANNEL_ID = "id"; private static final String CHANNEL_NAME = "name"; private NotificationManager manager; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); TextView qr_result, tvQRDate, tvQRInterval, tvQRCourse, tvQRTime, lastcheck_result, qr_distance; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_qrcode_sign_in); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); preferences =this.getSharedPreferences(Util.PREF_FILE, MODE_PRIVATE); qrResult(); lastQRCheck(); // Init the swipe back SwipeBack.attach(this, Position.LEFT) .setSwipeBackView(R.layout.swipeback_default); } public void qrResult(){ qr_result = findViewById(R.id.qr_result); qr_distance = findViewById(R.id.qr_distance); msg_code = getIntent().getIntExtra("msg_code", 0); distance = getIntent().getStringExtra("distance"); switch (msg_code){ case 0: qr_result.setText(R.string.msg_qr_0_failed); break; case 1: qr_result.setText(R.string.msg_qr_1_invalid_date); break; case 2: qr_result.setText(R.string.msg_qr_2_no_need); break; case 3: qr_result.setText(R.string.msg_qr_3_invalid_delayed); break; case 4: qr_result.setText(R.string.msg_qr_4_success); qr_distance.setText("您目前距學校定位"+ distance+"公尺"); qr_distance.setVisibility(View.VISIBLE); createNotification(); break; case 5: qr_result.setText(R.string.msg_qr_5_already); break; case 6: qr_result.setText(R.string.msg_qr_6_invalid_interval); break; case 7: qr_result.setText(R.string.msg_qr_7_norecord); break; case 8: qr_result.setText(R.string.msg_qr_8_cancel); break; case 9: qr_result.setText(R.string.msg_qr_9_toofar); qr_distance.setText("您目前距學校定位"+ distance+"公尺"); qr_distance.setVisibility(View.VISIBLE); } // Util.showToast(this, Util.msgCode(msg_code)); } public void lastQRCheck() { Map lastCourse = null; lastcheck_result = findViewById(R.id.lastcheck_result); tvQRDate = findViewById(R.id.tvQRDate); tvQRInterval = findViewById(R.id.tvQRInterval); tvQRCourse = findViewById(R.id.tvQRCourse); tvQRTime = findViewById(R.id.tvQRTime); String url = Util.URL + "AttendanceServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "lastQRCheckTask"); jsonObject.addProperty("memberaccount", preferences.getString("memberaccount", "")); String jsonOut = jsonObject.toString(); if (Util.networkConnected(this)) { lastQRCheckTask = new CommonTask(url, jsonOut); try { String result = lastQRCheckTask.execute().get(); Log.e("time", result); Type collectionType = new TypeToken<Map>() { }.getType(); lastCourse = gson.fromJson(result, collectionType); } catch (Exception e) { Log.e(TAG, e.toString()); } } else { Util.showToast(this, R.string.msg_NoNetwork); } if (lastCourse.get("qrecord").toString().isEmpty()) { msg_code = 7; lastcheck_result.setText(R.string.msg_qr_7_norecord); lastcheck_result.setVisibility(View.VISIBLE); } else { // tvQRDate.setText(lastCourse.get("sdate").toString()); tvQRDate.setText((String)lastCourse.get("sdate")); String interval = (String)lastCourse.get("interval"); switch (interval) { case "1": tvQRInterval.setText("上午"); break; case "2": tvQRInterval.setText("下午"); break; case "3": tvQRInterval.setText("夜間"); break; } tvQRCourse.setText((String)lastCourse.get("subjectName")); tvQRTime.setText((String)lastCourse.get("qrecord")); } } private void createNotification() { Intent intent = new Intent(QRCodeSignInActivity.this, ValidMainActivity.class); // Bundle bundle = new Bundle(); // bundle.putString("title", "從通知訊息切換過來的"); // bundle.putString("content", "老師在你背後,他很火!"); // intent.putExtras(bundle); /* Intent指定好要幹嘛後,就去做了,如startActivity(intent); 而PendingIntent則是先把某個Intent包好,以後再去執行Intent要幹嘛 */ PendingIntent pendingIntent = PendingIntent.getActivity(QRCodeSignInActivity.this , 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Uri uri = Uri.parse(URL); // Intent intent2 = new Intent(Intent.ACTION_VIEW, uri); // PendingIntent pendingIntent2 = PendingIntent.getActivity( // MainActivity.this, 0, intent2, PendingIntent.FLAG_CANCEL_CURRENT); Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo_icon_transparent); // NotificationCompat.Action action = new NotificationCompat.Action.Builder( // android.R.drawable.ic_menu_share, "Go!", pendingIntent2 // ).build(); NotificationCompat.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); manager.createNotificationChannel(channel); builder = new NotificationCompat.Builder(this, CHANNEL_ID); } else { builder = new NotificationCompat.Builder(this); builder.setPriority(Notification.PRIORITY_MAX); } Notification notification = builder // 訊息面板的標題 .setContentTitle("簽到成功") // 訊息面板的內容文字 .setContentText("今天也很準時哪,又是活力滿滿的一天!") // // 訊息的小圖示 .setSmallIcon(R.drawable.icons8_checked_24) // 訊息的大圖示 .setLargeIcon(bitmap) // 使用者點了之後才會執行指定的Intent .setContentIntent(pendingIntent) // 加入音效 .setSound(soundUri) // 點擊後會自動移除狀態列上的通知訊息 .setAutoCancel(true) // // 加入狀態列下拉後的進一步操作 // .addAction(action) .build(); manager.notify(1, notification); } @Override public void onBackPressed(){ super.onBackPressed(); overridePendingTransition(R.anim.swipeback_stack_to_front, R.anim.swipeback_stack_right_out); } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/ValidMainMenuFragment.java package idv.ca107g2.tibawe; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import idv.ca107g2.tibawe.tools.Util; /** * A simple {@link Fragment} subclass. */ public class ValidMainMenuFragment extends Fragment { private String class_no; SharedPreferences preferences; String memberType; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_validmain_menu, container, false); preferences = getActivity().getSharedPreferences(Util.PREF_FILE, getActivity().MODE_PRIVATE); memberType = preferences.getString("memberType", ""); if(!memberType.equals("1")){ FrameLayout frameCampusMenu = (FrameLayout) view.findViewById(R.id.frameCampusMenu); ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) frameCampusMenu.getLayoutParams(); params.setMargins(100, 0, 100, 0); frameCampusMenu.setLayoutParams(params); FrameLayout frameClassMenu = (FrameLayout) view.findViewById(R.id.frameClassMenu); frameClassMenu.setLayoutParams(params); FrameLayout frameLifeMenu = (FrameLayout) view.findViewById(R.id.frameLifeMenu); frameLifeMenu.setLayoutParams(params); } return view; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/lifezone/RhiAdapter.java package idv.ca107g2.tibawe.lifezone; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.task.ImageTask; import idv.ca107g2.tibawe.vo.Renting_House_Information_VO; class RhiAdapter extends RecyclerView.Adapter<RhiAdapter.ViewHolder> { private List<Renting_House_Information_VO> rhiList; private Listener listener; private ImageTask rhiImageTask; private int imageSize; interface Listener { void onClick(int position); } public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public RhiAdapter(List<Renting_House_Information_VO> rhiList , int imageSize){ this.rhiList = rhiList; this.imageSize = imageSize; } @NonNull @Override public RhiAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_rhi, parent, false); return new ViewHolder(cv); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { CardView cardView = holder.cardView; ImageView cvivRhiPic = cardView.findViewById(R.id.cvivRhiPic); final Renting_House_Information_VO rhiVO = rhiList.get(position); String url = Util.URL + "Renting_House_Information_Servlet"; String pk_no = rhiVO.getRhi_no(); rhiImageTask = new ImageTask(url, pk_no, imageSize, cvivRhiPic); rhiImageTask.execute(); TextView cvtvRhiTitle = cardView.findViewById(R.id.cvtvRhiTitle); if(!rhiVO.getRhi_content().isEmpty()) { cvtvRhiTitle.setText(rhiVO.getRhi_content().split(",")[4]); }else{ cvtvRhiTitle.setText("---");} TextView cvtvRhiLoc = cardView.findViewById(R.id.cvtvRhiLoc); if(!rhiVO.getRhi_content().isEmpty()) { cvtvRhiLoc.setText(rhiVO.getRhi_content().split(",")[5].substring(0,6));}else{ cvtvRhiLoc.setText("---");} cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null){ listener.onClick(position); } } }); } @Override public int getItemCount() { return rhiList.size(); } public void setListener(Listener listener){ this.listener = listener; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/campuszone/CampusZoneFragment.java package idv.ca107g2.tibawe.campuszone; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.tools.Util; /** * A simple {@link Fragment} subclass. */ public class CampusZoneFragment extends Fragment { String memberType; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { RecyclerView infoRecycler = (RecyclerView) inflater.inflate(R.layout.recyclerview_fragment, container, false); SharedPreferences preferences = getActivity().getSharedPreferences(Util.PREF_FILE, getActivity().MODE_PRIVATE); memberType = preferences.getString("memberType", ""); if(memberType.equals("1")) { int[] infoTitles = new int[CampusZone.CAMPUS_ZONES.length]; for(int i = 0 ; i <infoTitles.length; i++){ infoTitles[i] = CampusZone.CAMPUS_ZONES[i].getInfoTitle(); } int[] infoPics = new int[CampusZone.CAMPUS_ZONES.length]; for(int i = 0; i<infoPics.length; i++){ infoPics[i] = CampusZone.CAMPUS_ZONES[i].getInfoPicId(); } CampusZoneAdapter adapter = new CampusZoneAdapter(infoTitles, infoPics); infoRecycler.setAdapter(adapter); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); infoRecycler.setLayoutManager(layoutManager); adapter.setListener(new CampusZoneAdapter.Listener() { @Override public void onClick(int position) { switch (position) { case 0: Intent intent0 = new Intent(getActivity(), CampusNewsActivity.class); getActivity().startActivity(intent0); getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); break; case 1: Intent intent1 = new Intent(getActivity(), AttendanceActivity.class); getActivity().startActivity(intent1); getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); break; case 2: Intent intent2 = new Intent(getActivity(), TeachingLogActivity.class); getActivity().startActivity(intent2); break; case 3: Intent intent3 = new Intent(getActivity(), AbsApplyActivity.class); getActivity().startActivity(intent3); break; case 4: Intent intent4 = new Intent(getActivity(), ClrrActivity.class); getActivity().startActivity(intent4); break; case 5: Intent intent5 = new Intent(getActivity(), RafActivity.class); getActivity().startActivity(intent5); break; } } }); } else{ int[] infoTitles = new int[CampusZoneTeacher.CAMPUS_ZONES.length]; for(int i = 0 ; i <infoTitles.length; i++){ infoTitles[i] = CampusZoneTeacher.CAMPUS_ZONES[i].getInfoTitle(); } int[] infoPics = new int[CampusZoneTeacher.CAMPUS_ZONES.length]; for(int i = 0; i<infoPics.length; i++){ infoPics[i] = CampusZoneTeacher.CAMPUS_ZONES[i].getInfoPicId(); } CampusZoneAdapter adapterTeacher = new CampusZoneAdapter(infoTitles, infoPics); infoRecycler.setAdapter(adapterTeacher); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); infoRecycler.setLayoutManager(layoutManager); adapterTeacher.setListener(new CampusZoneAdapter.Listener() { @Override public void onClick(int position) { switch (position) { case 0: Intent intent0 = new Intent(getActivity(), CampusNewsActivity.class); getActivity().startActivity(intent0); getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); break; case 1: Intent intent1 = new Intent(getActivity(), TeachingLogActivity.class); getActivity().startActivity(intent1); getActivity().overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); break; case 2: Intent intent2 = new Intent(getActivity(), ClrrActivity.class); getActivity().startActivity(intent2); break; case 3: Intent intent3 = new Intent(getActivity(), RafActivity.class); getActivity().startActivity(intent3); break; } } }); } return infoRecycler; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/lifezone/DBDQueryActivity.java package idv.ca107g2.tibawe.lifezone; import android.annotation.SuppressLint; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.hannesdorfmann.swipeback.Position; import com.hannesdorfmann.swipeback.SwipeBack; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.vo.DBDMemberVO; import idv.ca107g2.tibawe.vo.DBDOderVO; import idv.ca107g2.tibawe.vo.StoreInformationVO; import idv.ca107g2.tibawe.vo.StoreMenuVO; public class DBDQueryActivity extends AppCompatActivity { private static final String TAG = "DBDQueryActivity"; private CommonTask dbdQueryTask; private Button btnChangeDBD; // private Dialog changeDBDDialog; private TextView cvtvQueryDBDDate, cvtvQueryDBDclass,cvtvQueryDBDhost, cvtvQueryDBDstore, cvtvQueryDBDItem, cvtvQueryDBDStatus, dbdQuery_result; private String memberaccount; private RecyclerView dbdQueryRecycler; private Map<String, List> dbdQueryMap; private List<DBDMemberVO> dbdMemberQuertlist; private List<Map<String, String>> dbdQueryhostDatalist; private List<DBDOderVO> dbdOderQueryVOlist; private List<StoreMenuVO> dbdStoreMenuQueryVOlist; private List<StoreInformationVO> dbdQuerystoreInformationVOlist; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dbd_query); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); SharedPreferences preferences = this.getSharedPreferences( Util.PREF_FILE, MODE_PRIVATE); memberaccount = preferences.getString("memberaccount", ""); dbdQueryRecycler = findViewById(R.id.rvDBDQuery); dbdQuery_result = findViewById(R.id.dbdQuery_result); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); dbdQueryRecycler.setLayoutManager(layoutManager); findDBDQuery(memberaccount); // Init the swipe back SwipeBack.attach(this, Position.LEFT) .setSwipeBackView(R.layout.swipeback_default); } public void findDBDQuery(String memberaccount) { String url = Util.URL + "DBDMemberServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "queryDBD"); jsonObject.addProperty("memberAccount", memberaccount); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(this)) { dbdQueryTask = new CommonTask(url, jsonOut); try { String result = dbdQueryTask.execute().get(); Type collectionTypeMap = new TypeToken<Map<String, List>>() { }.getType(); dbdQueryMap = gson.fromJson(result, collectionTypeMap); } catch (Exception e) { Log.e(TAG, e.toString()); } if (dbdQueryMap.isEmpty()) { Util.showToast(this, R.string.msg_nodata); dbdQuery_result.setVisibility(View.VISIBLE); dbdQueryRecycler.setVisibility(View.GONE); } else { Type collectionTypeListDBDMemberVO = new TypeToken<List<DBDMemberVO>>() { }.getType(); dbdMemberQuertlist = gson.fromJson(dbdQueryMap.get("dbdMemberQuertlist").toString(), collectionTypeListDBDMemberVO); Type collectionTypeListMap = new TypeToken<List<Map>>() { }.getType(); dbdQueryhostDatalist = gson.fromJson(dbdQueryMap.get("dbdQueryhostDatalist").toString(), collectionTypeListMap); Type collectionTypeListDBDOderVO = new TypeToken<List<DBDOderVO>>() { }.getType(); dbdOderQueryVOlist = gson.fromJson(dbdQueryMap.get("dbdOderQueryVOlist").toString(), collectionTypeListDBDOderVO); Type collectionTypeListStoreMenuVO = new TypeToken<List<StoreMenuVO>>() { }.getType(); dbdStoreMenuQueryVOlist = gson.fromJson(dbdQueryMap.get("dbdStoreMenuQueryVOlist").toString(), collectionTypeListStoreMenuVO); Type collectionTypeListStoreInformationVO = new TypeToken<List<StoreInformationVO>>() { }.getType(); dbdQuerystoreInformationVOlist = gson.fromJson(dbdQueryMap.get("dbdQuerystoreInformationVOlist").toString(), collectionTypeListStoreInformationVO); DBDQueryAdapter dbdQueryadapter = new DBDQueryAdapter(dbdMemberQuertlist, dbdQueryhostDatalist, dbdOderQueryVOlist, dbdStoreMenuQueryVOlist, dbdQuerystoreInformationVOlist); dbdQueryRecycler.setAdapter(dbdQueryadapter); dbdQueryadapter.setListener(new DBDQueryAdapter.Listener() { @SuppressLint("ResourceAsColor") @Override public void onClick(int position) { Util.showToast(DBDQueryActivity.this, "功能開發中"); // openchangeDBDDialog(position); } }); } } else { Util.showToast(this, R.string.msg_NoNetwork); } } }<file_sep>/app/src/main/java/idv/ca107g2/tibawe/BeforeMainActivity.java package idv.ca107g2.tibawe; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPropertyAnimatorCompat; import android.support.v4.view.ViewPropertyAnimatorListener; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.DecelerateInterpolator; import android.widget.ImageView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.Map; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.tools.Util; public class BeforeMainActivity extends AppCompatActivity { private CommonTask isMemberTask; private static final String TAG = "BeforMainActivity"; private ImageView ivLogoIcon, ivLogoTiba, ivLogoWe, ivLogoTibaweCH, ivLogoTop, ivLogoRight, ivLogoRightBottom, ivLogoLeftBottom, ivLogoLeft; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_before_main); ivLogoIcon = findViewById(R.id.ivLogoIcon); ivLogoTiba = findViewById(R.id.ivLogoTiba); ivLogoWe = findViewById(R.id.ivLogoWe); ivLogoTibaweCH = findViewById(R.id.ivLogoTibaweCH); ivLogoTop = findViewById(R.id.ivLogoTop); ivLogoRight = findViewById(R.id.ivLogoRight); ivLogoRightBottom = findViewById(R.id.ivLogoRightBottom); ivLogoLeftBottom = findViewById(R.id.ivLogoLeftBottom); ivLogoLeft = findViewById(R.id.ivLogoLeft); ViewGroup container = findViewById(R.id.container); for (int i = 0; i < container.getChildCount(); i++) { View view = container.getChildAt(i); ViewPropertyAnimatorCompat viewAnimator; if (view.getId() == R.id.ivLogoIcon){ viewAnimator = ViewCompat.animate(view) .alpha(0.5f) .setDuration(1500); }else if (view.getId() == R.id.ivLogoTiba){ viewAnimator = ViewCompat.animate(view) .alpha(1) .setDuration(1500); }else if (view.getId() == R.id.ivLogoTibaweCH){ viewAnimator = ViewCompat.animate(view) .translationY(+80).alpha(1) .setStartDelay(300) .setDuration(1000); }else if (view.getId() == R.id.ivLogoWe){ viewAnimator = ViewCompat.animate(view) .alpha(1) .setStartDelay(600) .setDuration(1500); }else if (view.getId() == R.id.ivLogoTop){ viewAnimator = ViewCompat.animate(view) .setStartDelay(700) .alpha(1); }else if (view.getId() == R.id.ivLogoRight){ viewAnimator = ViewCompat.animate(view) .setStartDelay(1100) .alpha(1); }else if (view.getId() == R.id.ivLogoRightBottom){ viewAnimator = ViewCompat.animate(view) .setStartDelay(1400) .alpha(1); }else if (view.getId() == R.id.ivLogoLeftBottom){ viewAnimator = ViewCompat.animate(view) .setStartDelay(1700) .alpha(1); }else{ viewAnimator = ViewCompat.animate(view) .setStartDelay(2000) .setDuration(100) .alpha(1); ViewCompat.animate(view).setListener(new ViewPropertyAnimatorListener() { @Override public void onAnimationStart(View view) { } @Override public void onAnimationEnd(View view) { checkLogin(); } @Override public void onAnimationCancel(View view) { } }); } viewAnimator.setInterpolator(new DecelerateInterpolator(1.5f)).start(); } } private void checkLogin(){ SharedPreferences preferences = getSharedPreferences(Util.PREF_FILE, MODE_PRIVATE); boolean login = preferences.getBoolean("login", false); if (login) { String memberaccount = preferences.getString("memberaccount", ""); String memberpass = preferences.getString("memberpass", ""); if (isMember(memberaccount, memberpass)) { Util.showToast(this, R.string.login_auto); setResult(RESULT_OK); Intent intent = new Intent(BeforeMainActivity.this, ValidMainActivity.class); startActivity(intent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); finish(); } }else{ Intent intent = new Intent(BeforeMainActivity.this, MainActivity.class); startActivity(intent); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); finish(); } } private boolean isMember(final String memberaccount, final String memberpass) { boolean isMember = false; if (Util.networkConnected(this)) { String url = Util.URL + "MemberServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "isMember"); jsonObject.addProperty("memberaccount", memberaccount); jsonObject.addProperty("memberpass", memberpass); String jsonOut = jsonObject.toString(); isMemberTask = new CommonTask(url, jsonOut); try { String result = isMemberTask.execute().get(); Type collectionType = new TypeToken<Map>() { }.getType(); Map data = gson.fromJson(result, collectionType); isMember = Boolean.valueOf(data.get("isMember").toString()); } catch (Exception e) { Log.e(TAG, e.toString()); isMember = false; } } else { Util.showToast(this, R.string.msg_NoNetwork); finish(); } return isMember; } @Override protected void onStop() { super.onStop(); if (isMemberTask != null) { isMemberTask.cancel(true); } } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/classzone/CampusRuleActivity.java package idv.ca107g2.tibawe.classzone; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.TextView; import com.hannesdorfmann.swipeback.Position; import com.hannesdorfmann.swipeback.SwipeBack; import idv.ca107g2.tibawe.R; public class CampusRuleActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_campus_rule); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); findView(); // Init the swipe back SwipeBack.attach(this, Position.LEFT) .setSwipeBackView(R.layout.swipeback_default); } public void findView(){ TextView tvRuleTitle = findViewById(R.id.tvRuleTitle); TextView tvRuleVersion = findViewById(R.id.tvRuleVersion); TextView tvP1title = findViewById(R.id.tvP1title); TextView tvP1content = findViewById(R.id.tvP1content); TextView tvP2title = findViewById(R.id.tvP2title); TextView tvP2content = findViewById(R.id.tvP2content); TextView tvP3title = findViewById(R.id.tvP3title); TextView tvP3content = findViewById(R.id.tvP3content); TextView tvP4title = findViewById(R.id.tvP4title); TextView tvP4content = findViewById(R.id.tvP4content); tvRuleTitle.setText("學員受訓須知"); tvRuleVersion.setText("修訂時間:一○七年三月五日"); tvP1title.setText("壹、中心介紹"); tvP1content.setText("\n"+"一、本中心隸屬資訊工業策進會數位教育研究所,其成立宗旨以辦理資訊人才推廣教育與資訊軟體研究發展為主。\n" + "\n" + "二、本中心資訊人才推廣教育係與國立中央大學合作,受中央大學指導與支援。\n" + "\n" + "三、本中心現有教學大樓位於中央大學工程二館的一至三樓。\n" + "\n" + "四、配合中央大學規定,本中心教學大樓全面禁煙。"); tvP2title.setText("貳、教務行政"); tvP2content.setText("\n"+"一、本中心教學大樓開放時間為八時三十分至二十二時三十分,若遇重大節日將不開放,屆時將另行通告。\n" + "\n" + "二、本中心上課時間如下:\n" + "     上午09:00~12:00\n"+"" + "     下午13:30~16:30\n"+"" + "     夜間18:30~21:30\n" + "\n" + "三、每節上課所使用的教室及機房,可參考網路課表上所刊載者,若有臨時異動會通知大家。\n" + "\n" + "四、訓練資源有限,請善加珍惜,務必請準時上課,並儘量保持全勤。\n" + "\n" + "五、每位學員務必於上、下午及夜間上課時使用紙本簽到,簽名時請簽全名,並可看出是簽哪些字,勿使用印章或代簽。可簽到時間的規定請依中心規範。\n" + "\n" + "六、受訓學員無故不到者視同曠課,曠課時數將以兩倍計算。若不能上課請事先請假,請假包含事假、病假、公假、產假、喪假五種。事假須事前請,病假三日以上(含)須醫院證明,公假須附證明文件,喪假須有訃文。\n" + "\n" + "七、每日上午9:15、下午1:45、夜間6:45之後無法簽到,若是當天遲到者請填寫黃色補簽到單,並請上課老師簽名後,拿至一樓櫃台才能補簽名。補簽到單及請假單請至一樓櫃檯拿取。\n" + "\n" + "八、短期班(四週或 100小時以下)請假(含公假)達到上課總時數五分之一者,長期班(四週或 100小時以上(含))請假(含公假)達到上課總時數十分之一者,即公告退訓,並不發結業證書。曠課乙次以請假兩次時數計算。\n" + "\n" + "九、總平均成績未達標準(60分或等級F)者,不核發結業證書。\n" + "\n" + "十、上課時間由教務行政人員不定期抽點到課情況,抽點不到視同曠課乙次。\n" + "\n" + "十一、請假記錄總表於結訓後函知委訓單位,退訓者亦函知委訓單位。\n" + "\n" + "十二、學員如要查詢課表,可至中心網站『班級課表系統』查詢,網址為:http://140.115.236.11。\n" + "\n" + "十三、使用實習機房時請勿攜帶茶水、食物及雨具入內,亦請不要在實習機房內長期放置私人物品或設備,應保持機房或教室內的整齊清潔,本中心將定期清理。\n" + "\n" + "十四、不得在機房或教室內煮食食物,包含使用咖啡機煮熱飲。也請勿於機房或教室內吸菸。\n" + "\n" + "十五、實習時,遇機器設備有問題,應立即向實習老師反映,並自行填妥機房內之「故障紀錄單」,絕對禁止拆開機器,或任意將機器設備搬離定位、換接插頭,情節嚴重者將可能退訓。\n" + "\n" + "十六、實習機房週一至週五夜間開放上機至22:30,週六、日部份機房開放至21:30,遇重大節日將不開放,將另行通告。夜間機房與假日機房需依規定提出線上使用申請,若中心有夜間或假日的課程活動時,或有其他原因,得調度某間機房或教室做臨時使用,則此時該班學員在使用夜間或假日機房時,請依循中心相關的彈性調動,與其他班學員共同使用同一間機房或教室。\n" + "\n" + "十七、若遇中心有機房或教室座位容量之調度考量,得於受訓期間內變動或更換各班級原使用的機房或教室,請學員配合搬遷,以利中心所有學員都能享有最大的學習效益。\n" + "\n" + "十八、本中心設有學員休息室,開放時間為08:30-22:30。\n" + "\n" + "十九、學員休息室報章雜誌,僅供當場閱讀,不外借。 \n" + "\n" + "二十、配合環保與資源再利用政策,本中心各樓層設有資源回收設備,請依分類投入各回收資源。\n" + "\n" + "二十一、偷竊中心硬體設備、違法盜拷軟體或使用、下載、安裝非法軟體者,將移送法辦。若因學員前述違法行為,致資策會與委訓單位被請求或被訴,學員應賠償資策會與委訓單位之一切損失(包括但不限於律師費、訴訟費用等)。\n" + "\n" + "二十二、為使課程順利進行,上課中請學員關閉行動電話。且為免侵害講師或資策會之權利,嚴禁學員錄音、攝影或錄影等,否則一切法律責任 請學員自負。"); tvP3title.setText("參、日常生活"); tvP3content.setText("\n"+"一、中央大學內有學生餐廳,後門、側門有快餐、客飯,按餐計費,費用自理。\n" + "\n" + "二、若有受傷,本中心學員可至中央大學保健室上藥。\n" + "\n" + "三、個人若有突發性疾病,請於報到後立刻告知室友、同學或導師急救之方式及所需之藥品。\n" + "\n" + "  急救電話:壢新醫院   (03)4941234" + "\n" + "       陽明醫院   (03)4929929" + "\n" + "       署立桃園醫院 (03)3699721" + "\n" + "       林口長庚醫院 (03)3281200" + "\n" + "四、依據國立中央大學車輛管理實施要點:車輛入校需計時收費, 每小時20元。並請依校方之規定將汽車停放於劃有停車位置之停車格內。  \n" + "\n" + "五、學員之郵寄信件請註明地址為「中央大學郵局第01號信箱 XXXXX班」。若是要郵寄包裹或快遞包裹,請改寄到「桃園市中壢區中大路300-1號 中央大學工程二館 資策會 XXXXX班」。班級名稱請務必註明。\n" + "\n" + "六、本中心辦公室電話、影印機及傳真機專供中心教職員使用,不對學員開放,惟親友若有緊急情事,於上班時間內可利用本中心電話留言,請本中心代為轉達。辦公室電話:(03)4257387。\n" + "\n" + "七、一樓營運服務組備有多種球具可供登記借用,請最慢隔天歸還。\n" + "\n" + "八、本中心係設於中央大學校區內,請共同遵守中央大學有關規定(如:不踐踏校區草地,不著背心、短褲、拖鞋進入餐廳、教室等公共場所等)。"); tvP4title.setText("肆、校外宿舍管理規章"); tvP4content.setText("\n"+"一、宿舍內之私人財物請妥善保管,中心不負保管之責。\n" + "\n" + "二、如有任何緊急狀況,上班時間請聯絡導師或營運服務組\n" + "聯絡電話:03-4257387  \n" + "\n" + "三、非上班時段如有任何緊急狀況,請撥打下列電話:\n" + "\n" + "中心電話03-4257387 撥通後按“0”接總機\n" + "\n" + "營運服務組 湯士慶先生0975200081。\n" + "中央大學警衛室電話:03-4267144、03-4267158\n" + "\n" + "急救電話:壢新醫院   (03)4941234" + "\n" + "     陽明醫院  (03)4929929" + "\n" + "     署立桃園醫院 (03)3699721" + "\n" + "     林口長庚醫院 (03)3281200"); } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/classzone/ClassSeatAdapter.java package idv.ca107g2.tibawe.classzone; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.TextView; import idv.ca107g2.tibawe.R; class ClassSeatAdapter extends RecyclerView.Adapter<ClassSeatAdapter.ViewHolder> { private String[] seatArray; // private Listener listener; // interface Listener { // void onClick(int position); // } public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public ClassSeatAdapter(String[] realSeat){ this.seatArray = realSeat; } @NonNull @Override public ClassSeatAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_seat, parent, false); return new ViewHolder(cv); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { CardView cardView = holder.cardView; TextView cvtvSeatName = cardView.findViewById(R.id.cvtvSeatName); cvtvSeatName.setText(seatArray[position]); // cardView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // // if (listener != null){ // listener.onClick(position); // } // } // }); } @Override public int getItemCount() { return seatArray.length; } // public void setListener(Listener listener){ // this.listener = listener; // } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/classzone/ClassSeatActivity.java package idv.ca107g2.tibawe.classzone; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.HorizontalScrollView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import com.hannesdorfmann.swipeback.Position; import com.hannesdorfmann.swipeback.SwipeBack; import java.lang.reflect.Type; import java.util.List; import java.util.Map; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.vo.ClassaVO; public class ClassSeatActivity extends AppCompatActivity { private static final String TAG = "ClassSeatActivity"; private CommonTask classSeatTask, getClassNameTask; private TextView tvcsClassName, cvtvSeatName; private String memberaccount, class_no, className; private String[] seatArray; private Map classSeatData; private TextView teacher_deafult, blackboard; private List<ClassaVO> classaVOList; String memberType; SharedPreferences preferences; private RecyclerView rvClassSeat; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_class_seat); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); preferences = this.getSharedPreferences( Util.PREF_FILE, MODE_PRIVATE); memberType = preferences.getString("memberType", ""); memberaccount = preferences.getString("memberaccount", ""); class_no = preferences.getString("class_no", ""); rvClassSeat = findViewById(R.id.rvClassSeat); tvcsClassName = findViewById(R.id.tvcsClassName); teacher_deafult = findViewById(R.id.teacher_deafult); blackboard = findViewById(R.id.blackboard); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(10, StaggeredGridLayoutManager.VERTICAL); rvClassSeat.setLayoutManager(layoutManager); final HorizontalScrollView horizontalview = findViewById(R.id.horizontalview); // Init the swipe back SwipeBack.attach(this, Position.LEFT) .setSwipeBackView(R.layout.swipeback_default) .setOnInterceptMoveEventListener( new SwipeBack.OnInterceptMoveEventListener() { @Override public boolean isViewDraggable(View v, int dx, int x, int y) { if (v == horizontalview) { return (horizontalview.fullScroll(-1)); } return false; } }); if(memberType.equals("1")) { class_no = preferences.getString("class_no", ""); findSeat(class_no); }else{ teacher_deafult.setVisibility(View.VISIBLE); blackboard.setVisibility(View.GONE); findClassName(); } } public void findClassName(){ String url = Util.URL + "ClassInformationServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "getall"); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(this)) { getClassNameTask = new CommonTask(url, jsonOut); try { String result = getClassNameTask.execute().get(); Type collectionType = new TypeToken<List<ClassaVO>>() { }.getType(); classaVOList = gson.fromJson(result, collectionType); } catch (Exception e) { Log.e(TAG, e.toString()); } if (classaVOList.isEmpty()) { // view = inflater.inflate(R.layout.fragment_course_query, container, false); Util.showToast(this, R.string.msg_nodata); } } else { // view = inflater.inflate(R.layout.fragment_course_query, container, false); Util.showToast(this, R.string.msg_NoNetwork); } } @Override public boolean onCreateOptionsMenu(Menu menu) { if (!memberType.equals("1")) { // 為了讓Toolbar的 Menu有作用,這邊的程式不可以拿掉 getMenuInflater().inflate(R.menu.menu_top_teacher, menu); for (int i = 0; i < classaVOList.size(); i++) { menu.add(0, i, i, classaVOList.get(i).getClassName()); } } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (!memberType.equals("1")) { if(item.getItemId()==android.R.id.home){ onBackPressed(); return true; } if(item.getItemId()<classaVOList.size()){ int id = item.getItemId(); class_no = classaVOList.get(id).getClass_no(); } findSeat(class_no); } return true; } public void findSeat(String class_no) { teacher_deafult.setVisibility(View.GONE); blackboard.setVisibility(View.VISIBLE); String url = Util.URL + "ClassaServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "querySeat"); jsonObject.addProperty("memberAccount", memberaccount); jsonObject.addProperty("class_no", class_no); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(this)) { classSeatTask = new CommonTask(url, jsonOut); try { String result = classSeatTask.execute().get(); Type collectionTypeMap = new TypeToken<Map>() { }.getType(); classSeatData = gson.fromJson(result, collectionTypeMap); className = gson.fromJson(classSeatData.get("className").toString(), String.class); seatArray = gson.fromJson(classSeatData.get("seatArray").toString(), String[].class); Log.d("className", className); } catch (Exception e) { Log.e(TAG, e.toString()); } if (seatArray.length==0) { Util.showToast(this, R.string.msg_nodata); } else { tvcsClassName.setText(className); ClassSeatAdapter classSeatadapter = new ClassSeatAdapter(seatArray); rvClassSeat.setAdapter(classSeatadapter); } } else { Util.showToast(this, R.string.msg_NoNetwork); } } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/classzone/ClassZoneAdapter.java package idv.ca107g2.tibawe.classzone; import android.graphics.drawable.Drawable; import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.ImageView; import android.widget.TextView; import idv.ca107g2.tibawe.R; class ClassZoneAdapter extends RecyclerView.Adapter<ClassZoneAdapter.ViewHolder> { private int[] informations; private int[] imageIds; private Listener listener; interface Listener { void onClick(int position); } public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public ClassZoneAdapter(int[] informations, int[] imageIds){ this.informations = informations; this.imageIds = imageIds; } @NonNull @Override public ClassZoneAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_validmain, parent, false); return new ViewHolder(cv); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { CardView cardView = holder.cardView; ImageView imageView = cardView.findViewById(R.id.cvivValidmainPic); Drawable drawable = ContextCompat.getDrawable(cardView.getContext(), imageIds[position]); imageView.setImageDrawable(drawable); TextView textView = cardView.findViewById(R.id.cvtvValidmainTitle); textView.setText(informations[position]); cardView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //ScaleAnimation(float fromX, float toX, float fromY, float toY) //(fromX,toX)X軸從fromX的倍率放大/縮小至toX的倍率 //(fromY,toY)X軸從fromY的倍率放大/縮小至toX的倍率 // Animation am = new AlphaAnimation(0.7f, 1f); Animation am2 = new ScaleAnimation(1.025f, 0.975f, 1.025f, 0.975f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); // Animation am = new ScaleAnimation(1f, 0.7f, 1f, 0.7f); //setDuration (long durationMillis) 設定動畫開始到結束的執行時間 am2.setDuration(100); //setRepeatCount (int repeatCount) 設定重複次數 -1為無限次數 0 am2.setRepeatCount(0); //將動畫參數設定到圖片並開始執行動畫 v.startAnimation(am2); return false; } }); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null){ listener.onClick(position); } } }); } @Override public int getItemCount() { return informations.length; } public void setListener(Listener listener){ this.listener = listener; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/campuszone/ClrrQueryFragment.java package idv.ca107g2.tibawe.campuszone; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.vo.ClrrVO; import static android.content.Context.MODE_PRIVATE; import static android.support.v4.view.PagerAdapter.POSITION_NONE; /** * A simple {@link Fragment} subclass. */ public class ClrrQueryFragment extends Fragment { private static final String TAG = "ClrrQueryFragment"; private CommonTask clrrQueryTask; private String memberaccount, membername, class_no; private RecyclerView rvCLRRquery; private List<ClrrVO> clrrVOList; private TextView clrr_result, clrr_records; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SharedPreferences preferences = getActivity().getSharedPreferences( Util.PREF_FILE, MODE_PRIVATE); memberaccount = preferences.getString("memberaccount", ""); membername = preferences.getString("membername", ""); class_no = preferences.getString("class_no", ""); View view = inflater.inflate(R.layout.fragment_clrr_query, container, false); rvCLRRquery = view.findViewById(R.id.rvCLRRquery); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL); layoutManager.scrollToPosition(0); rvCLRRquery.setLayoutManager(layoutManager); clrr_result = view.findViewById(R.id.clrr_result); findClrrQuery(memberaccount); return view; } @Override public void onResume() { ((ClrrActivity)getActivity()).pager.getAdapter().getItemPosition(POSITION_NONE); super.onResume(); } public void findClrrQuery(String memberaccount) { String url = Util.URL + "ClrrServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "queryCLRR"); jsonObject.addProperty("memberaccount", memberaccount); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(getActivity())) { clrrQueryTask = new CommonTask(url, jsonOut); try { String result = clrrQueryTask.execute().get(); Type collectionType = new TypeToken<List<ClrrVO>>() { }.getType(); clrrVOList = gson.fromJson(result, collectionType); } catch (Exception e) { Log.e(TAG, e.toString()); } if (clrrVOList.isEmpty()) { clrr_result.setText(R.string.msg_clrr_norecord); } else { rvCLRRquery.setAdapter(new ClrrAdapter(clrrVOList, membername)); } } else { Util.showToast(getContext(), R.string.msg_NoNetwork); } } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/tools/Util.java package idv.ca107g2.tibawe.tools; import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import idv.ca107g2.tibawe.R; //import idv.david.bookstoreandroid.book.BookActivity; //import idv.david.bookstoreandroid.member.MemberShipActivity; //import idv.david.bookstoreandroid.order.CartActivity; //import idv.david.bookstoreandroid.order.OrderBook; public class Util { // 模擬器連Tomcat // public static String URL = "http://10.0.2.2:8081/CA107G2_APP/"; // 手機連雲端GCP public static String URL = "http://172.16.31.10:8081/CA107G2_APP/"; // 全組GCP // public static String URL = "http://ca107g2.tk/CA107G2_APP/"; // 彥志LocalHost // public static String URL = "http://192.168.196.215:8081/CA107G2_APP/"; // 偏好設定檔案名稱 public final static String PREF_FILE = "preference"; public static int qrmsg; public static int msgCode(int msg_code){ switch(msg_code){ case 0: qrmsg = R.string.msg_qr_0_failed; break; case 1: qrmsg = R.string.msg_qr_1_invalid_date; break; case 2: qrmsg = R.string.msg_qr_2_no_need; break; case 3: qrmsg = R.string.msg_qr_3_invalid_delayed; break; case 4: qrmsg = R.string.msg_qr_4_success; break; case 5: qrmsg = R.string.msg_qr_5_already; break; case 6: qrmsg = R.string.msg_qr_6_invalid_interval; break; case 7: qrmsg = R.string.msg_qr_7_norecord; break; } return qrmsg; } // 功能分類 // public final static Page[] PAGES = { // new Page(0, "Book", R.drawable.books, BookActivity.class), // new Page(1, "Order", R.drawable.cart_empty, CartActivity.class), // new Page(2, "Member", R.drawable.user, MemberShipActivity.class), // new Page(3, "Setting", R.drawable.setting, ChangeUrlActivity.class) // }; // 要讓商品在購物車內順序能夠一定,且使用RecyclerView顯示時需要一定順序,List較佳 // public static ArrayList<OrderBook> CART = new ArrayList<>(); // check if the device connect to the network public static boolean networkConnected(Activity activity) { ConnectivityManager conManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conManager != null ? conManager.getActiveNetworkInfo() : null; return networkInfo != null && networkInfo.isConnected(); } public static void showToast(Context context, int messageResId) { Toast.makeText(context, messageResId, Toast.LENGTH_SHORT).show(); } public static void showToast(Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } public static void showLToast(Context context, String message) { Toast.makeText(context, message, Toast.LENGTH_LONG).show(); } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/lifezone/DBDFragment.java package idv.ca107g2.tibawe.lifezone; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.os.CountDownTimer; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.ScaleAnimation; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.vo.DBDMemberVO; import idv.ca107g2.tibawe.vo.DBDOderVO; import idv.ca107g2.tibawe.vo.StoreInformationVO; import idv.ca107g2.tibawe.vo.StoreMenuVO; /** * A simple {@link Fragment} subclass. */ public class DBDFragment extends Fragment { private static final String TAG = "DBDFragment"; private CommonTask getDBDTask; private List<DBDOderVO> dbdOderVOlist; private List<StoreInformationVO> storeInformationVOlist; private List<List<DBDMemberVO>> dbdMemberTop3list; private List<String> dbdMemberCountlist; private List<Map<String, String>> hostDatalist; private List<Long> fnl_timelist; private RecyclerView rvDBDlist, rvDBD; private TextView lastdbd_result, orderDBD, ttlnumDBD, numDBD; private Map<String, List> dbdMap; private Dialog dbdDialog; private CommonTask getStoreMenuTask, addDBDTask; private List<StoreMenuVO> smList; public boolean clicked = false; private Map addoderData = new HashMap(); ImageButton plus1DBD, minus1DBD, cancel1DBD; Button btnDBDsubmit, btnDBDreset; LinearLayout lySelectedDBD; private String memberaccount; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_dbd, container, false); rvDBDlist = view.findViewById(R.id.rvDBDlist); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL); layoutManager.scrollToPosition(0); rvDBDlist.setLayoutManager(layoutManager); lastdbd_result = view.findViewById(R.id.lastdbd_result); SharedPreferences preferences = getActivity().getSharedPreferences(Util.PREF_FILE, getActivity().MODE_PRIVATE); memberaccount = preferences.getString("memberaccount", ""); findDBD(); return view; } public void findDBD() { String url = Util.URL + "DBDOderServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "getNowDBD"); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(getActivity())) { getDBDTask = new CommonTask(url, jsonOut); try { String result = getDBDTask.execute().get(); Type collectionTypeMap = new TypeToken<Map<String, List>>() { }.getType(); dbdMap = gson.fromJson(result, collectionTypeMap); Type collectionTypeListDBDOderVO = new TypeToken<List<DBDOderVO>>() { }.getType(); dbdOderVOlist = gson.fromJson(dbdMap.get("dbdOderVOlist").toString(), collectionTypeListDBDOderVO); } catch (Exception e) { Log.e(TAG, e.toString()); } if (dbdOderVOlist.size()==0) { lastdbd_result.setVisibility(View.VISIBLE); rvDBDlist.setVisibility(View.GONE); } else { Type collectionTypeListDBDOderVO = new TypeToken<List<DBDOderVO>>() { }.getType(); dbdOderVOlist = gson.fromJson(dbdMap.get("dbdOderVOlist").toString(), collectionTypeListDBDOderVO); Type collectionTypeListStoreInformationVO = new TypeToken<List<StoreInformationVO>>() { }.getType(); storeInformationVOlist = gson.fromJson(dbdMap.get("storeInformationVOlist").toString(), collectionTypeListStoreInformationVO); Type collectionTypeListListDBDMemberVO = new TypeToken<List<List<DBDMemberVO>>>() { }.getType(); dbdMemberTop3list = gson.fromJson(dbdMap.get("dbdMemberTop3list").toString(), collectionTypeListListDBDMemberVO); Type collectionTypeListMap = new TypeToken<List<Map>>() { }.getType(); hostDatalist = gson.fromJson(dbdMap.get("hostDatalist").toString(), collectionTypeListMap); Type collectionTypeListString = new TypeToken<List<String>>() { }.getType(); dbdMemberCountlist = gson.fromJson(dbdMap.get("dbdMemberCountlist").toString(), collectionTypeListString); Type collectionTypeListLong = new TypeToken<List<Long>>() { }.getType(); fnl_timelist = gson.fromJson(dbdMap.get("fnl_timelist").toString(), collectionTypeListLong); DBDAdapter adapter = new DBDAdapter(dbdOderVOlist, storeInformationVOlist, dbdMemberTop3list, hostDatalist, dbdMemberCountlist, fnl_timelist); rvDBDlist.setAdapter(adapter); adapter.setListener(new DBDAdapter.Listener() { @SuppressLint("ResourceAsColor") @Override public void onClick(int position) { openDBDdialog(position); //// } }); } } else { // view = inflater.inflate(R.layout.fragment_course_query, container, false); Util.showToast(getContext(), R.string.msg_NoNetwork); } } private void openDBDdialog(final int position) { DBDOderVO dbdOderVO = dbdOderVOlist.get(position); String dbdo_no = dbdOderVO.getDbdo_no(); String store_no = dbdOderVO.getStore_no(); addoderData.put("dbdo_no", dbdo_no); dbdDialog = new Dialog(getContext()); dbdDialog.setCancelable(true); dbdDialog.setContentView(R.layout.dialog_dbd_order); Toolbar dbdtoolbar = dbdDialog.findViewById(R.id.dialog_dbd_toolbar); dbdtoolbar.setLogo(R.drawable.icons8_buy_24); dbdtoolbar.setTitle(" 參加揪團"); Window dbddialogWindow = dbdDialog.getWindow(); dbddialogWindow.setGravity(Gravity.CENTER); WindowManager m = getActivity().getWindowManager(); Display d = m.getDefaultDisplay(); // 取得螢幕寬、高用 WindowManager.LayoutParams p = dbddialogWindow.getAttributes(); // 獲取對話視窗當前的参數值 p.height = (int) (d.getHeight() * 0.75); // 高度設置為螢幕的0.6 (60%) p.width = (int) (d.getWidth() * 0.95); // 寬度設置為螢幕的0.95 (95%) dbddialogWindow.setAttributes(p); rvDBD = dbdDialog.findViewById(R.id.rvDBD); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL); layoutManager.scrollToPosition(0); rvDBD.setLayoutManager(layoutManager); findMenu(store_no); plus1DBD = dbdDialog.findViewById(R.id.plus1DBD); minus1DBD = dbdDialog.findViewById(R.id.minus1DBD); cancel1DBD = dbdDialog.findViewById(R.id.cancel1DBD); btnDBDsubmit = dbdDialog.findViewById(R.id.btnDBDsubmit); btnDBDreset = dbdDialog.findViewById(R.id.btnDBDreset); lySelectedDBD = dbdDialog.findViewById(R.id.lySelectedDBD); orderDBD = dbdDialog.findViewById(R.id.orderDBD); ttlnumDBD = dbdDialog.findViewById(R.id.ttlnumDBD); numDBD = dbdDialog.findViewById(R.id.numDBD); plus1DBD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int numcount = Integer.parseInt(numDBD.getText().toString()); if (numcount != 0) { int ttlnumcount = Integer.parseInt(ttlnumDBD.getText().toString()); int perprice = ttlnumcount / numcount; numcount++; numDBD.setText(String.valueOf(numcount)); ttlnumDBD.setText(String.valueOf(ttlnumcount + perprice)); } } }); minus1DBD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int numcount = Integer.parseInt(numDBD.getText().toString()); if(numcount!=0) { int ttlnumcount = Integer.parseInt(ttlnumDBD.getText().toString()); int perprice = ttlnumcount / numcount; if (numcount > 1) { numcount--; numDBD.setText(String.valueOf(numcount)); ttlnumDBD.setText(String.valueOf(ttlnumcount - perprice)); } } } }); cancel1DBD.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { for (int j = 0; j < rvDBD.getChildCount(); j++) { StoreMenuAdapter.MyViewHolder holder = (StoreMenuAdapter.MyViewHolder) rvDBD.findViewHolderForAdapterPosition(j); holder.cvtvcartDBDitem.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartItemNo.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartDBDitemprice.setTextColor(R.color.colorPrimaryDark); lySelectedDBD.setVisibility(View.INVISIBLE); ttlnumDBD.setVisibility(View.INVISIBLE); holder.cartaddDBD.setVisibility(View.VISIBLE); clicked = false; addoderData.put("storem_no", ""); addoderData.put("numDBD", "0"); addoderData.put("ttlnumDBD" ,"0"); } } }); btnDBDreset.setOnClickListener(new View.OnClickListener() { @SuppressLint("ResourceAsColor") @Override public void onClick(View v) { for (int j = 0; j < rvDBD.getChildCount(); j++) { StoreMenuAdapter.MyViewHolder holder = (StoreMenuAdapter.MyViewHolder) rvDBD.findViewHolderForAdapterPosition(j); holder.cvtvcartDBDitem.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartItemNo.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartDBDitemprice.setTextColor(R.color.colorPrimaryDark); lySelectedDBD.setVisibility(View.INVISIBLE); ttlnumDBD.setVisibility(View.INVISIBLE); holder.cartaddDBD.setVisibility(View.VISIBLE); clicked = false; addoderData.put("storem_no", ""); addoderData.put("numDBD", "0"); addoderData.put("ttlnumDBD" ,"0"); } } }); btnDBDsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(!clicked){ lySelectedDBD.setVisibility(View.VISIBLE); orderDBD.setText("您尚未點餐"); numDBD.setText("0"); }else if (clicked){ addoderData.put("numDBD", numDBD.getText()); addoderData.put("ttlnumDBD" , ttlnumDBD.getText()); String url = Util.URL + "DBDMemberServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "addodermember"); jsonObject.addProperty("memberaccount", memberaccount); jsonObject.addProperty("dbdo_no", addoderData.get("dbdo_no").toString()); jsonObject.addProperty("storem_no", addoderData.get("storem_no").toString()); jsonObject.addProperty("dbdm_q", addoderData.get("numDBD").toString()); jsonObject.addProperty("dbdm_change", addoderData.get("ttlnumDBD").toString()); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(getActivity())) { addDBDTask = new CommonTask(url, jsonOut); try { String result = addDBDTask.execute().get(); String checkDBD = result; if(checkDBD.equals("\"done\"")){ DBDFragment.AlertFragment alertFragment = new DBDFragment.AlertFragment(); FragmentManager fm = getFragmentManager(); alertFragment.show(fm, "alertDBD"); }else{ Util.showToast(getActivity(), "something wrong.."); } } catch (Exception e) { Log.e(TAG, e.toString()); } }else { Util.showToast(getContext(), R.string.msg_NoNetwork); } dbdDialog.cancel(); } } }); // // // dbdDialog.setOnShowListener(new DialogInterface.OnShowListener() { @SuppressLint("ResourceAsColor") @Override public void onShow(DialogInterface dialog) { for (int j = 0; j < rvDBD.getChildCount(); j++) { StoreMenuAdapter.MyViewHolder holder = (StoreMenuAdapter.MyViewHolder) rvDBD.findViewHolderForAdapterPosition(j); holder.cvtvcartDBDitem.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartItemNo.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartDBDitemprice.setTextColor(R.color.colorPrimaryDark); lySelectedDBD.setVisibility(View.INVISIBLE); ttlnumDBD.setVisibility(View.INVISIBLE); holder.cartaddDBD.setVisibility(View.VISIBLE); clicked = false; } } }); dbdDialog.show(); } public void findMenu(String store_no){ String url = Util.URL + "StoreMenuServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "getStoreMenu"); jsonObject.addProperty("store_no", store_no); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(getActivity())) { getStoreMenuTask = new CommonTask(url, jsonOut); try { String result = getStoreMenuTask.execute().get(); Type collectionType = new TypeToken<List<StoreMenuVO>>() { }.getType(); smList = gson.fromJson(result, collectionType); } catch (Exception e) { Log.e(TAG, e.toString()); } rvDBD.setAdapter(new StoreMenuAdapter(getContext(), smList)); }else { Util.showToast(getContext(), R.string.msg_NoNetwork); } } private class StoreMenuAdapter extends RecyclerView.Adapter<StoreMenuAdapter.MyViewHolder> { private Context context; private LayoutInflater layoutInflater; List<StoreMenuVO> smList; StoreMenuAdapter(Context context, List<StoreMenuVO> smList) { this.context = context; layoutInflater = LayoutInflater.from(context); this.smList = smList; } class MyViewHolder extends RecyclerView.ViewHolder { TextView cvtvcartItemNo, cvtvcartDBDitem, cvtvcartDBDitemprice; private ImageButton cartaddDBD; MyViewHolder(View itemView) { super(itemView); cvtvcartItemNo = itemView.findViewById(R.id.cvtvcartItemNo); cvtvcartDBDitem = itemView.findViewById(R.id.cvtvcartDBDitem); cvtvcartDBDitemprice = itemView.findViewById(R.id.cvtvcartDBDitemprice); cartaddDBD = itemView.findViewById(R.id.cartaddDBD); } } @Override public int getItemCount() { return smList.size(); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = layoutInflater.inflate(R.layout.cardview_dbd_cart, parent, false); return new MyViewHolder(itemView); } @SuppressLint("ResourceAsColor") @Override public void onBindViewHolder(final MyViewHolder holder, int position) { final StoreMenuVO storeMenuVO = smList.get(position); holder.cvtvcartItemNo.setText(String.valueOf(position+1)); holder.cvtvcartDBDitem.setText(storeMenuVO.getStorem_name()); holder.cvtvcartDBDitemprice.setText("$ ".concat(String.valueOf(storeMenuVO.getStorem_price()))); if (clicked) { holder.cvtvcartDBDitem.setTextColor(Color.argb(60,0,0,0)); holder.cvtvcartItemNo.setTextColor(Color.argb(60,0,0,0)); holder.cvtvcartDBDitemprice.setTextColor(Color.argb(60,0,0,0)); lySelectedDBD.setVisibility(View.VISIBLE); ttlnumDBD.setVisibility(View.VISIBLE); holder.cartaddDBD.setVisibility(View.INVISIBLE); } else { holder.cvtvcartDBDitem.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartItemNo.setTextColor(R.color.colorPrimaryDark); holder.cvtvcartDBDitemprice.setTextColor(R.color.colorPrimaryDark); lySelectedDBD.setVisibility(View.INVISIBLE); ttlnumDBD.setVisibility(View.INVISIBLE); holder.cartaddDBD.setVisibility(View.VISIBLE); } holder.cartaddDBD.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { //ScaleAnimation(float fromX, float toX, float fromY, float toY) //(fromX,toX)X軸從fromX的倍率放大/縮小至toX的倍率 //(fromY,toY)X軸從fromY的倍率放大/縮小至toX的倍率 // Animation am = new AlphaAnimation(1f, 1.5f); Animation am = new ScaleAnimation(1.025f, 0.975f, 1.025f, 0.975f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); //setDuration (long durationMillis) 設定動畫開始到結束的執行時間 am.setDuration(500); //setRepeatCount (int repeatCount) 設定重複次數 -1為無限次數 0 am.setRepeatCount(0); //將動畫參數設定到圖片並開始執行動畫 LinearLayout lv = (LinearLayout) v.getParent(); lv.startAnimation(am); return false; } }); holder.cartaddDBD.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { orderDBD.setText(storeMenuVO.getStorem_name()); numDBD.setText("1"); ttlnumDBD.setText(String.valueOf(storeMenuVO.getStorem_price())); addoderData.put("storem_no", storeMenuVO.getStorem_no()); clicked = true; notifyDataSetChanged(); } }); } } public static class AlertFragment extends DialogFragment implements DialogInterface.OnClickListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { final AlertDialog alertDialog = new AlertDialog.Builder(getActivity()) //設定圖示 .setIcon(R.drawable.icons8_checkout_24) .setTitle(R.string.DBD_today) //設定訊息內容 .setMessage(R.string.msg_DBD_success) //設定確認鍵 (positive用於確認) .setPositiveButton(R.string.abs_alert_return, this) .create(); alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { new CountDownTimer(2000, 1000) { @Override public void onTick(long millisUntilFinished) { // TODO Auto-generated method stub } @Override public void onFinish() { // TODO Auto-generated method stub Intent intent = new Intent(getContext(), DBDQueryActivity.class); startActivity(intent); getActivity().overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); alertDialog.dismiss(); } }.start(); Button posbtn = alertDialog.getButton(DialogInterface.BUTTON_POSITIVE); posbtn.setTextColor(getResources().getColor(R.color.colorDarkBlue)); } }); return alertDialog; } @Override public void onClick(DialogInterface dialog, int which) { switch (which) { case DialogInterface.BUTTON_POSITIVE: Intent intent = new Intent(getActivity(), DBDQueryActivity.class); startActivity(intent); getActivity().overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); getActivity().finish(); break; default: break; } } } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/vo/StoreInformationVO.java package idv.ca107g2.tibawe.vo; import java.io.Serializable; public class StoreInformationVO implements Serializable { private String store_no; private String store_name; private String store_phone; private String store_adress; private byte[] store_pic; private byte[] store_pic2; private String store_note; private Integer store_attr; public String getStore_no() { return store_no; } public String getStore_adress() { return store_adress; } public void setStore_adress(String store_adress) { this.store_adress = store_adress; } public void setStore_no(String store_no) { this.store_no = store_no; } public String getStore_name() { return store_name; } public void setStore_name(String store_name) { this.store_name = store_name; } public String getStore_phone() { return store_phone; } public void setStore_phone(String store_phone) { this.store_phone = store_phone; } public byte[] getStore_pic() { return store_pic; } public void setStore_pic(byte[] store_pic) { this.store_pic = store_pic; } public byte[] getStore_pic2() { return store_pic2; } public void setStore_pic2(byte[] store_pic2) { this.store_pic2 = store_pic2; } public String getStore_note() { return store_note; } public void setStore_note(String store_note) { this.store_note = store_note; } public Integer getStore_attr() { return store_attr; } public void setStore_attr(Integer store_attr) { this.store_attr = store_attr; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/classzone/ClassInformationAdapter.java package idv.ca107g2.tibawe.classzone; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.vo.ClassInformationVO; public class ClassInformationAdapter extends RecyclerView.Adapter<ClassInformationAdapter.ViewHolder>{ private List<ClassInformationVO> classInformationList; // private Listener listener; // interface Listener { // void onClick(int position); // } public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public ClassInformationAdapter(List<ClassInformationVO> classInformationList){ this.classInformationList = classInformationList; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_information, parent, false); return new ViewHolder(cv); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { CardView cardView = holder.cardView; final ClassInformationVO classInformationVO = classInformationList.get(position); TextView cvtvClassInfoDate = cardView.findViewById(R.id.cvtvClassInfoDate); if(!classInformationVO.getIdate().toString().isEmpty()) { cvtvClassInfoDate.setText(classInformationVO.getIdate().toString()); }else{ cvtvClassInfoDate.setText("---");} TextView cvtvClassInfo = cardView.findViewById(R.id.cvtvClassInfo); if(!classInformationVO.getInformationcontent().isEmpty()) { cvtvClassInfo.setText(classInformationVO.getInformationcontent()); }else{ cvtvClassInfo.setText("---");} TextView cvtvClassName = cardView.findViewById(R.id.cvtvClassName); if(!classInformationVO.getClass_no().isEmpty()) { cvtvClassName.setText(classInformationVO.getClass_no()); }else{ cvtvClassName.setText("---");} // cardView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (listener != null){ // listener.onClick(position); // } // } // }); } @Override public int getItemCount() { return classInformationList.size(); } // public void setListener(Listener listener){ // this.listener = listener; // } } <file_sep>/README.md # TibaWeAPP I had attended to a Java programming boot camp from 2018.12~2019.05. For our graduated project, our group(6ppl) decided to built an Information System for the education institute where we learn programming, and I was in charged for the whole APP system, including back-end. (Others were for the website). This is my 1st Android APP project in learning JAVA and Android. This APP was aimed for built an Information System for the education institute where I learn programming. <file_sep>/app/src/main/java/idv/ca107g2/tibawe/vo/DBDMemberVO.java package idv.ca107g2.tibawe.vo; public class DBDMemberVO { private String dbdm_no; private String memberAccount; private String dbdo_no; private String storem_no; private Integer dbdm_q; private Integer dbdm_change; private Integer dbdm_attr; public Integer getDbdm_change() { return dbdm_change; } public void setDbdm_change(Integer dbdm_change) { this.dbdm_change = dbdm_change; } public String getDbdo_no() { return dbdo_no; } public void setDbdo_no(String dbdo_no) { this.dbdo_no = dbdo_no; } public String getStorem_no() { return storem_no; } public void setStorem_no(String storem_no) { this.storem_no = storem_no; } public String getDbdm_no() { return dbdm_no; } public void setDbdm_no(String dbdm_no) { this.dbdm_no = dbdm_no; } public String getMemberAccount() { return memberAccount; } public void setMemberAccount(String memberAccount) { this.memberAccount = memberAccount; } public Integer getDbdm_q() { return dbdm_q; } public void setDbdm_q(Integer dbdm_q) { this.dbdm_q = dbdm_q; } public Integer getDbdm_attr() { return dbdm_attr; } public void setDbdm_attr(Integer dbdm_attr) { this.dbdm_attr = dbdm_attr; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/campuszone/RafQueryFragment.java package idv.ca107g2.tibawe.campuszone; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.vo.RafVO; import static android.content.Context.MODE_PRIVATE; import static android.support.v4.view.PagerAdapter.POSITION_NONE; /** * A simple {@link Fragment} subclass. */ public class RafQueryFragment extends Fragment { private static final String TAG = "RafQueryFragment"; private CommonTask rafQueryTask; private String memberaccount, membername, class_no; private RecyclerView rvRafquery; private List<RafVO> rafVOList; private TextView raf_result, raf_records; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SharedPreferences preferences = getActivity().getSharedPreferences( Util.PREF_FILE, MODE_PRIVATE); memberaccount = preferences.getString("memberaccount", ""); membername = preferences.getString("membername", ""); class_no = preferences.getString("class_no", ""); View view = inflater.inflate(R.layout.fragment_raf_query, container, false); rvRafquery = view.findViewById(R.id.rvRafquery); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL); layoutManager.scrollToPosition(0); rvRafquery.setLayoutManager(layoutManager); raf_result = view.findViewById(R.id.raf_result); findRafQuery(memberaccount); return view; } @Override public void onResume() { ((RafActivity)getActivity()).pager.getAdapter().getItemPosition(POSITION_NONE); super.onResume(); } public void findRafQuery(String memberaccount) { String url = Util.URL + "RafServlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "queryRAF"); jsonObject.addProperty("memberaccount", memberaccount); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(getActivity())) { rafQueryTask = new CommonTask(url, jsonOut); try { String result = rafQueryTask.execute().get(); Type collectionType = new TypeToken<List<RafVO>>() { }.getType(); rafVOList = gson.fromJson(result, collectionType); } catch (Exception e) { Log.e(TAG, e.toString()); } if (rafVOList.isEmpty()) { raf_result.setText(R.string.msg_raf_norecord); } else { rvRafquery.setAdapter(new RafAdapter(rafVOList, membername)); } } else { Util.showToast(getContext(), R.string.msg_NoNetwork); } } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/vo/Renting_House_Information_VO.java package idv.ca107g2.tibawe.vo; public class Renting_House_Information_VO implements java.io.Serializable{ private String rhi_no; private String rhi_content; private int rhi_status; private java.sql.Date rhi_date; private byte[] rhi_p1; private byte[] rhi_p2; private byte[] rhi_p3; private byte[] rhi_p4; private byte[] rhi_p5; public String getRhi_no() { return rhi_no; } public void setRhi_no(String rhi_no) { this.rhi_no = rhi_no; } public String getRhi_content() { return rhi_content; } public void setRhi_content(String rhi_content) { this.rhi_content = rhi_content; } public int getRhi_status() { return rhi_status; } public void setRhi_status(int rhi_status) { this.rhi_status = rhi_status; } public java.sql.Date getRhi_date() { return rhi_date; } public void setRhi_date(java.sql.Date rhi_date) { this.rhi_date = rhi_date; } public byte[] getRhi_p1() { return rhi_p1; } public void setRhi_p1(byte[] rhi_p1) { this.rhi_p1 = rhi_p1; } public byte[] getRhi_p2() { return rhi_p2; } public void setRhi_p2(byte[] rhi_p2) { this.rhi_p2 = rhi_p2; } public byte[] getRhi_p3() { return rhi_p3; } public void setRhi_p3(byte[] rhi_p3) { this.rhi_p3 = rhi_p3; } public byte[] getRhi_p4() { return rhi_p4; } public void setRhi_p4(byte[] rhi_p4) { this.rhi_p4 = rhi_p4; } public byte[] getRhi_p5() { return rhi_p5; } public void setRhi_p5(byte[] rhi_p5) { this.rhi_p5 = rhi_p5; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/campuszone/LatestNewsAdapter.java package idv.ca107g2.tibawe.campuszone; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.vo.Latest_News_VO; public class LatestNewsAdapter extends RecyclerView.Adapter<LatestNewsAdapter.ViewHolder>{ private List<Latest_News_VO> latest_news_list; // private Listener listener; // interface Listener { // void onClick(int position); // } public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public LatestNewsAdapter(List<Latest_News_VO> latest_news_list){ this.latest_news_list = latest_news_list; } @NonNull @Override public LatestNewsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_latest_news, parent, false); return new ViewHolder(cv); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { CardView cardView = holder.cardView; final Latest_News_VO latest_news_VO = latest_news_list.get(position); TextView cvtvNewsTitle = cardView.findViewById(R.id.cvtvNewsTitle); if(!latest_news_VO.getLn_title().isEmpty()) { cvtvNewsTitle.setText(latest_news_VO.getLn_title()); }else{ cvtvNewsTitle.setText("---");} TextView cvtvNewsDate = cardView.findViewById(R.id.cvtvNewsDate); if(!latest_news_VO.getLn_date().toString().isEmpty()) { cvtvNewsDate.setText(latest_news_VO.getLn_date().toString()); }else{ cvtvNewsDate.setText("---");} TextView cvtvNewsContent = cardView.findViewById(R.id.cvtvNewsContent); if(!latest_news_VO.getLn_content().isEmpty()) { cvtvNewsContent.setText(latest_news_VO.getLn_content()); }else{ cvtvNewsContent.setText("---");} // cardView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // if (listener != null){ // listener.onClick(position); // } // } // }); } @Override public int getItemCount() { return latest_news_list.size(); } // public void setListener(Listener listener){ // this.listener = listener; // } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/classzone/PhoneBookAdapter.java package idv.ca107g2.tibawe.classzone; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.vo.MemberVO; public class PhoneBookAdapter extends RecyclerView.Adapter<PhoneBookAdapter.ViewHolder>{ private List<MemberVO> memberVOlist; public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public PhoneBookAdapter(List<MemberVO> memberVOlist){ this.memberVOlist = memberVOlist; } @NonNull @Override public PhoneBookAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_phonebook, parent, false); return new ViewHolder(cv); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { CardView cardView = holder.cardView; final MemberVO memberVO = memberVOlist.get(position); TextView tvpbNo = cardView.findViewById(R.id.tvpbNo); if(!memberVO.getMemberAccount().isEmpty()) { tvpbNo.setText(String.valueOf(position+1)); }else{ tvpbNo.setText("-");} TextView tvpbName = cardView.findViewById(R.id.tvpbName); if(!memberVO.getMemberName().isEmpty()) { tvpbName.setText(memberVO.getMemberName()); }else{ tvpbName.setText("---");} TextView tvpbTel = cardView.findViewById(R.id.tvpbTel); if(!memberVO.getMemberPhone().toString().isEmpty()) { tvpbTel.setText(memberVO.getMemberPhone().toString()); }else{ tvpbTel.setText("---");} TextView tvpbEmail = cardView.findViewById(R.id.tvpbEmail); if(!memberVO.getMemberEmail().isEmpty()) { tvpbEmail.setText(memberVO.getMemberEmail()); }else{ tvpbEmail.setText("---");} TextView tvpbAdd = cardView.findViewById(R.id.tvpbAdd); if(!memberVO.getMemberAddress().isEmpty()) { tvpbAdd.setText(memberVO.getMemberAddress()); }else{ tvpbAdd.setText("---");} } @Override public int getItemCount() { return memberVOlist.size(); } } <file_sep>/settings.gradle include ':app', ':lib-zxingcore' <file_sep>/app/src/main/java/idv/ca107g2/tibawe/campuszone/RafActivity.java package idv.ca107g2.tibawe.campuszone; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import com.hannesdorfmann.swipeback.Position; import com.hannesdorfmann.swipeback.SwipeBack; import idv.ca107g2.tibawe.R; public class RafActivity extends AppCompatActivity { public static ViewPager pager; private int mPagerPosition; private int mPagerOffsetPixels; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_raf); // Init the swipe back SwipeBack.attach(this, Position.LEFT) .setSwipeBackView(R.layout.swipeback_toolbarandtab) .setOnInterceptMoveEventListener( new SwipeBack.OnInterceptMoveEventListener() { @Override public boolean isViewDraggable(View v, int dx, int x, int y) { if (v == pager) { return !(mPagerPosition == 0 && mPagerOffsetPixels == 0) || dx < 0; } return false; } }); Toolbar toolbar = findViewById(R.id.toolbar_repair_apply); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); RepairApplyPagerAdapter pagerAdapter = new RepairApplyPagerAdapter(getSupportFragmentManager()); pager = findViewById(R.id.vpRepairApply); pager.setOffscreenPageLimit(0); pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { mPagerPosition = position; mPagerOffsetPixels = positionOffsetPixels;} @Override public void onPageSelected(int i) { } @Override public void onPageScrollStateChanged(int i) { } }); pager.setAdapter(pagerAdapter); pager.setCurrentItem(0); TabLayout tabLayout = findViewById(R.id.tbRepairApply); tabLayout.setupWithViewPager(pager); } private class RepairApplyPagerAdapter extends FragmentPagerAdapter { public RepairApplyPagerAdapter (FragmentManager fm){ super(fm); } @Override public int getCount() { return 2; } @Override public Fragment getItem(int position) { switch (position){ case 0: return new RafFragment(); case 1: return new RafQueryFragment(); } return null; } public CharSequence getPageTitle(int position){ switch (position){ case 0: return getResources().getText(R.string.repair_apply_tab); case 1: return getResources().getText(R.string.repair_query_tab); } return null; } @Override public int getItemPosition(Object object) { return PagerAdapter.POSITION_NONE; } } @Override public void onBackPressed(){ super.onBackPressed(); overridePendingTransition(R.anim.swipeback_stack_to_front, R.anim.swipeback_stack_right_out); } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/lifezone/RhiDetailActivity.java package idv.ca107g2.tibawe.lifezone; import android.annotation.SuppressLint; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.PagerSnapHelper; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.hannesdorfmann.swipeback.Position; import com.hannesdorfmann.swipeback.SwipeBack; import java.io.IOException; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.task.CommonTask; import idv.ca107g2.tibawe.task.ImageTask; import idv.ca107g2.tibawe.tools.CirclePagerIndicatorDecoration; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.vo.Renting_House_Information_VO; public class RhiDetailActivity extends AppCompatActivity implements OnMapReadyCallback { private static final String TAG = "RhiDetailActivity"; private Renting_House_Information_VO rhiVO; private TextView tvRhiDetailNote, tvRhiDetailTitle, tvRhiDetailName,tvRhiDetailPrice, tvRhiDetailPhone, tvRhiDetailLoc; private RecyclerView rvRhiDetailPic; private ImageTask rhiDetailImageTask; private CommonTask getPiccountTask; private int piccount; private List<Renting_House_Information_VO> rhiList; private GoogleMap map; Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_rhi_detail); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); Bundle bundle=getIntent().getExtras(); rhiVO = (Renting_House_Information_VO) bundle.getSerializable("rhiVO"); rvRhiDetailPic = findViewById(R.id.rvRhiDetailPic); LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); rvRhiDetailPic.setLayoutManager(layoutManager); rvRhiDetailPic.addItemDecoration(new CirclePagerIndicatorDecoration()); rvRhiDetailPic.setAdapter(new RhiDetailPicAdapter(this, rhiVO)); rvRhiDetailPic.setHorizontalScrollBarEnabled(false); PagerSnapHelper snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(rvRhiDetailPic); getView(); // Init the swipe back SwipeBack.attach(this, Position.LEFT) .setSwipeBackView(R.layout.swipeback_default) .setOnInterceptMoveEventListener( new SwipeBack.OnInterceptMoveEventListener() { @Override public boolean isViewDraggable(View v, int dx, int x, int y) { if (v == rvRhiDetailPic) { return (rvRhiDetailPic.canScrollHorizontally(-1)); } return false; } }); SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.rhiMap); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap map) { this.map = map; setUpMap(); } @SuppressLint("MissingPermission") private void setUpMap() { map.setMyLocationEnabled(true); map.getUiSettings().setZoomControlsEnabled(true); String locationName = tvRhiDetailLoc.getText().toString().trim(); if (locationName.length() > 0) { locationNameToMarker(locationName); } else { Toast.makeText(this, getString(R.string.msg_nodata), Toast.LENGTH_SHORT).show(); } } // 將地名或地址轉成位置後在地圖打上對應標記 private void locationNameToMarker(String locationName) { // 增加新標記前,先清除舊有標記 map.clear(); Geocoder geocoder = new Geocoder(this); List<Address> addressList = null; int maxResults = 1; try { // 解譯地名/地址後可能產生多筆位置資訊,所以回傳List<Address> // 將maxResults設為1,限定只回傳1筆 addressList = geocoder.getFromLocationName(locationName, maxResults); // geocoder.getFromLocation() // 如果無法連結到提供服務的伺服器,會拋出IOException } catch (IOException ie) { Log.e(TAG, ie.toString()); } if (addressList == null || addressList.isEmpty()) { Toast.makeText(this, getString(R.string.msg_nodata), Toast.LENGTH_SHORT).show(); } else { // 因為當初限定只回傳1筆,所以只要取得第1個Address物件即可 Address address = addressList.get(0); // Address物件可以取出緯經度並轉成LatLng物件 LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude()); // 將地址取出當作標記的描述文字 String snippet = address.getAddressLine(0); String code = address.getPostalCode(); // 將地名或地址轉成位置後在地圖打上對應標記 map.addMarker(new MarkerOptions() .position(latLng) .title(code + locationName) .snippet(snippet)); // 將鏡頭焦點設定在使用者輸入的地點上 CameraPosition cameraPosition = new CameraPosition.Builder() .target(latLng) .zoom(17) .build(); map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } } public void getView(){ tvRhiDetailNote = findViewById(R.id.tvRhiDetailNote); tvRhiDetailNote.setText(rhiVO.getRhi_content().split(",")[3]); tvRhiDetailTitle = findViewById(R.id.tvRhiDetailTitle); tvRhiDetailTitle.setText(rhiVO.getRhi_content().split(",")[4]); tvRhiDetailName = findViewById(R.id.tvRhiDetailName); tvRhiDetailName.setText(rhiVO.getRhi_content().split(",")[0]); tvRhiDetailPrice = findViewById(R.id.tvRhiDetailPrice); tvRhiDetailPrice.setText("$ ".concat(rhiVO.getRhi_content().split(",")[2])); tvRhiDetailPhone = findViewById(R.id.tvRhiDetailPhone); tvRhiDetailPhone.setText(rhiVO.getRhi_content().split(",")[1]); tvRhiDetailLoc = findViewById(R.id.tvRhiDetailLoc); tvRhiDetailLoc.setText(rhiVO.getRhi_content().split(",")[5]); } ///////////StorePic private class RhiDetailPicAdapter extends RecyclerView.Adapter<RhiDetailPicAdapter.MyViewHolder> { private Context context; private LayoutInflater layoutInflater; private Renting_House_Information_VO rhiVO; private int imageSize; RhiDetailPicAdapter(Context context, Renting_House_Information_VO rhiVO) { this.context = context; layoutInflater = LayoutInflater.from(context); this.rhiVO = rhiVO; /* 螢幕寬度當作將圖的尺寸 */ imageSize = getResources().getDisplayMetrics().widthPixels; } class MyViewHolder extends RecyclerView.ViewHolder { ImageView cvivDetailPic; MyViewHolder(View itemView) { super(itemView); cvivDetailPic = itemView.findViewById(R.id.cvivDetailPic); } } @Override public int getItemCount() { String url = Util.URL + "Renting_House_Information_Servlet"; JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("action", "getPiccount"); String pk_no = rhiVO.getRhi_no(); jsonObject.addProperty("pk_no", pk_no); String jsonOut = jsonObject.toString(); // Util.showToast(getContext(), jsonOut); if (Util.networkConnected(RhiDetailActivity.this)) { getPiccountTask = new CommonTask(url, jsonOut); try { piccount = Integer.valueOf(getPiccountTask.execute().get()); } catch (Exception e) { Log.e(TAG, e.toString()); } }else { Util.showToast(RhiDetailActivity.this, R.string.msg_NoNetwork); } return piccount; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = layoutInflater.inflate(R.layout.cardview_detail_pic, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, int position) { String url = Util.URL + "Renting_House_Information_Servlet"; String pk_no = rhiVO.getRhi_no(); int picnum = position+1; rhiDetailImageTask = new ImageTask(url, pk_no, imageSize, holder.cvivDetailPic, picnum); rhiDetailImageTask.execute(); } } @Override public void onBackPressed(){ super.onBackPressed(); overridePendingTransition(R.anim.swipeback_stack_to_front, R.anim.swipeback_stack_right_out); } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/campuszone/AbsApplyAdapter.java package idv.ca107g2.tibawe.campuszone; import android.annotation.SuppressLint; import android.graphics.Color; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import java.util.List; import java.util.Map; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.tools.Util; class AbsApplyAdapter extends RecyclerView.Adapter<AbsApplyAdapter.ViewHolder> { private List<Map<String, String>> absList; public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public AbsApplyAdapter(List<Map<String, String>> absList) { this.absList = absList; } @NonNull @Override public AbsApplyAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_abs_query, parent, false); return new ViewHolder(cv); } @SuppressLint("ResourceAsColor") @Override public void onBindViewHolder(@NonNull AbsApplyAdapter.ViewHolder holder, final int position) { CardView cardView = holder.cardView; final Map absMap = absList.get(position); TextView tvAbsqNO = cardView.findViewById(R.id.tvAbsqNO); tvAbsqNO.setText((String)absMap.get("absno")); // // TextView tvAbsqDate = cardView.findViewById(R.id.tvAbsqDate); // tvAbsqDate.setText((absMap.get("absDate")).toString()); TextView tvAbsqDate = cardView.findViewById(R.id.tvAbsqDate); if(absMap.get("absDate") != null) { tvAbsqDate.setText((absMap.get("absDate")).toString()); }else{ tvAbsqDate.setText("---");} //Morning TextView tvAbsqInterval = cardView.findViewById(R.id.tvAbsqInterval); if(absMap.get("absInterval") != null) { switch((String)absMap.get("absInterval")){ case"1": tvAbsqInterval.setText(R.string.tvMorning); break; case"2": tvAbsqInterval.setText(R.string.tvAfternoon); break; case"3": tvAbsqInterval.setText(R.string.tvEvening); break; } }else{tvAbsqInterval.setText("---");} TextView tvAbsqCourse = cardView.findViewById(R.id.tvAbsqCourse); if(absMap.get("absCourse") != null) { tvAbsqCourse.setText((String) absMap.get("absCourse")); }else if(Integer.valueOf(String.valueOf(absMap.get("absInterval")))== 4){ tvAbsqCourse.setText("全日課程"); } else{ tvAbsqCourse.setText("---"); } TextView tvAbsqTeacher1 = cardView.findViewById(R.id.tvAbsqTeacher1); if(absMap.get("absTeacher1") != null) { tvAbsqTeacher1.setText((String) absMap.get("absTeacher1")); tvAbsqTeacher1.setVisibility(View.VISIBLE); }else{ tvAbsqTeacher1.setVisibility(View.GONE); tvAbsqCourse.setGravity(Gravity.CENTER);} TextView tvAbsqTeacher2 = cardView.findViewById(R.id.tvAbsqTeacher2); if(absMap.get("absTeacher2") != null) { tvAbsqTeacher2.setText((String) absMap.get("absTeacher2")); tvAbsqTeacher2.setVisibility(View.VISIBLE); tvAbsqTeacher1.setGravity(Gravity.CENTER|Gravity.BOTTOM); tvAbsqCourse.setGravity(Gravity.CENTER|Gravity.BOTTOM); }else{ tvAbsqTeacher2.setVisibility(View.GONE);} TextView tvAbsqTeacher3 = cardView.findViewById(R.id.tvAbsqTeacher3); if(absMap.get("absTeacher3") != null) { tvAbsqTeacher3.setText((String) absMap.get("absTeacher3")); tvAbsqTeacher3.setVisibility(View.VISIBLE); tvAbsqTeacher1.setGravity(Gravity.CENTER|Gravity.BOTTOM); tvAbsqCourse.setGravity(Gravity.CENTER|Gravity.BOTTOM); }else{ tvAbsqTeacher3.setVisibility(View.GONE);} TextView tvAbsqReason = cardView.findViewById(R.id.tvAbsqReason); if(absMap.get("absReason") != null) { switch((String)absMap.get("absReason")){ case"1": tvAbsqReason.setText("事假"); break; case"2": tvAbsqReason.setText("公假"); break; case"3": tvAbsqReason.setText("病假"); break; case"4": tvAbsqReason.setText("喪假"); break; case"5": tvAbsqReason.setText("其他"); break; } }else{tvAbsqReason.setText("---");} TextView tvAbsqOutcome = cardView.findViewById(R.id.tvAbsqOutcome); Button btnAbsqUpdate = cardView.findViewById(R.id.btnAbsqUpdate); if(absMap.get("absOutcome") != null) { switch((String)absMap.get("absOutcome")){ case"0": tvAbsqOutcome.setText("審核不通過"); tvAbsqOutcome.setTextColor(Color.rgb(209, 8, 55)); break; case"1": tvAbsqOutcome.setText("已通過"); tvAbsqOutcome.setTextColor(Color.rgb(22, 82, 193)); break; case"2": tvAbsqOutcome.setText("審核中"); btnAbsqUpdate.setVisibility(View.INVISIBLE);//修改假單按鈕顯示 break; } } else{ tvAbsqOutcome.setText("---"); btnAbsqUpdate.setVisibility(View.GONE); } TextView tvAbsqNote = cardView.findViewById(R.id.tvAbsqNote); if(absMap.get("absNote") != null) { tvAbsqNote.setText((absMap.get("absNote")).toString()); }else{ tvAbsqNote.setText("---");} btnAbsqUpdate = cardView.findViewById(R.id.btnAbsqUpdate); btnAbsqUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Util.showToast(v.getContext(), "功能開發中"); } }); } @Override public int getItemCount() { return absList.size(); } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/vo/MemberVO.java package idv.ca107g2.tibawe.vo; public class MemberVO implements java.io.Serializable{ private String memberAccount; private String memberName; private Integer memberPhone; private String memberAddress; private String memberEmail; private Integer memberEmailStatus; private Integer memberType; private String member_ID; private String class_no; private String memberpass; private String udm_Name; private String udm_emps; public String getMemberAccount() { return memberAccount; } public void setMemberAccount(String memberAccount) { this.memberAccount = memberAccount; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public Integer getMemberPhone() { return memberPhone; } public void setMemberPhone(Integer memberPhone) { this.memberPhone = memberPhone; } public String getMemberAddress() { return memberAddress; } public void setMemberAddress(String memberAddress) { this.memberAddress = memberAddress; } public String getMemberEmail() { return memberEmail; } public void setMemberEmail(String memberEmail) { this.memberEmail = memberEmail; } public Integer getMemberEmailStatus() { return memberEmailStatus; } public void setMemberEmailStatus(Integer memberEmailStatus) { this.memberEmailStatus = memberEmailStatus; } public Integer getMemberType() { return memberType; } public void setMemberType(Integer memberType) { this.memberType = memberType; } public String getMember_ID() { return member_ID; } public void setMember_ID(String member_ID) { this.member_ID = member_ID; } public String getClass_no() { return class_no; } public void setClass_no(String class_no) { this.class_no = class_no; } public String getMemberpass() { return memberpass; } public void setMemberpass(String memberpass) { this.memberpass = memberpass; } public String getUdm_Name() { return udm_Name; } public void setUdm_Name(String udm_Name) { this.udm_Name = udm_Name; } public String getUdm_emps() { return udm_emps; } public void setUdm_emps(String udm_emps) { this.udm_emps = udm_emps; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/classzone/ClassZoneTeacher.java package idv.ca107g2.tibawe.classzone; import idv.ca107g2.tibawe.R; public class ClassZoneTeacher { private int infoTitle; private int infoPicId; public static final ClassZoneTeacher[] CLASS_ZONES = { new ClassZoneTeacher(R.string.class_news, R.drawable.d), new ClassZoneTeacher(R.string.course_query, R.drawable.d), new ClassZoneTeacher(R.string.seattable, R.drawable.d), new ClassZoneTeacher(R.string.phonebook, R.drawable.d), }; private ClassZoneTeacher(int infoTitle, int infoPicId){ this.infoTitle = infoTitle; this.infoPicId = infoPicId; } public int getInfoTitle(){ return infoTitle; } public int getInfoPicId(){ return infoPicId; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/vo/Latest_News_VO.java package idv.ca107g2.tibawe.vo; public class Latest_News_VO implements java.io.Serializable{ private String ln_no; private String ln_title; private String ln_content; private java.sql.Date ln_date; public String getLn_title() { return ln_title; } public void setLn_title(String ln_title) { this.ln_title = ln_title; } public String getLn_no() { return ln_no; } public void setLn_no(String ln_no) { this.ln_no = ln_no; } public String getLn_content() { return ln_content; } public void setLn_content(String ln_content) { this.ln_content = ln_content; } public java.sql.Date getLn_date() { return ln_date; } public void setLn_date(java.sql.Date ln_date) { this.ln_date = ln_date; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/vo/CrVO.java package idv.ca107g2.tibawe.vo; import java.io.Serializable; public class CrVO implements Serializable { private String cr_no; private String cr_name; private Integer cr_status; public CrVO() { } public String getCr_no() { return cr_no; } public void setCr_no(String cr_no) { this.cr_no = cr_no; } public String getCr_name() { return cr_name; } public void setCr_name(String cr_name) { this.cr_name = cr_name; } public Integer getCr_status() { return cr_status; } public void setCr_status(Integer cr_status) { this.cr_status = cr_status; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/lifezone/StoreInformationAdapter.java package idv.ca107g2.tibawe.lifezone; import android.support.annotation.NonNull; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.util.List; import idv.ca107g2.tibawe.R; import idv.ca107g2.tibawe.tools.Util; import idv.ca107g2.tibawe.task.ImageTask; import idv.ca107g2.tibawe.vo.StoreInformationVO; class StoreInformationAdapter extends RecyclerView.Adapter<StoreInformationAdapter.ViewHolder> { private List<StoreInformationVO> storeInformationList; private Listener listener; private ImageTask storeImageTask; private int imageSize; interface Listener { void onClick(int position); } public static class ViewHolder extends RecyclerView.ViewHolder{ private CardView cardView; public ViewHolder(CardView v){ super(v); cardView = v; } } public StoreInformationAdapter(List<StoreInformationVO> storeInformationList , int imageSize){ this.storeInformationList = storeInformationList; this.imageSize = imageSize; } @NonNull @Override public StoreInformationAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_store_info, parent, false); return new ViewHolder(cv); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, final int position) { CardView cardView = holder.cardView; ImageView cvivInfoPic = cardView.findViewById(R.id.cvivInfoPic); final StoreInformationVO storeInformationVO = storeInformationList.get(position); String url = Util.URL + "StoreInformationServlet"; String pk_no = storeInformationVO.getStore_no(); storeImageTask = new ImageTask(url, pk_no, imageSize, cvivInfoPic); storeImageTask.execute(); TextView cvtvInfoTitle = cardView.findViewById(R.id.cvtvInfoTitle); if(!storeInformationVO.getStore_name().isEmpty()) { cvtvInfoTitle.setText(storeInformationVO.getStore_name()); }else{ cvtvInfoTitle.setText("---");} TextView cvtvInfoTel = cardView.findViewById(R.id.cvtvInfoTel); if(!storeInformationVO.getStore_phone().isEmpty()) { cvtvInfoTel.setText(storeInformationVO.getStore_phone()); }else{ cvtvInfoTel.setText("---");} // // ImageView cvivInfoPic = cardView.findViewById(R.id.cvivInfoPic); // Drawable drawable = ContextCompat.getDrawable(cardView.getContext(), imageIds[position]); // cvivInfoPic.setImageDrawable(drawable); // cvivInfoPic.setContentDescription(storeInformationVO.getStore_name()); cardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (listener != null){ listener.onClick(position); } } }); } @Override public int getItemCount() { return storeInformationList.size(); } public void setListener(Listener listener){ this.listener = listener; } } <file_sep>/app/src/main/java/idv/ca107g2/tibawe/vo/ClassaVO.java package idv.ca107g2.tibawe.vo; import java.sql.Date; public class ClassaVO implements java.io.Serializable { private static final long serialVersionUID = 1L; private String class_no; private String classType_no; private String className; private Date initialDate; private Date endDate; private String seatingPlan; public String getClass_no() { return class_no; } public void setClass_no(String class_no) { this.class_no = class_no; } public String getClassType_no() { return classType_no; } public void setClassType_no(String classType_no) { this.classType_no = classType_no; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public Date getInitialDate() { return initialDate; } public void setInitialDate(Date initialDate) { this.initialDate = initialDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public String getSeatingPlan() { return seatingPlan; } public void setSeatingPlan(String seatingPlan) { this.seatingPlan = seatingPlan; } }
4dca4617692f850a299e167428344192cc3f19d5
[ "Markdown", "Java", "Gradle" ]
31
Java
pcdd05java/TibaWeAPP
872ca197973e24d12465ba6aae6a7073b506ba78
17528c33ff81c15e54c0ca6233f12d33c5678b08
refs/heads/master
<repo_name>JohnTitor/garando<file_sep>/garando_syntax/src/lib.rs //! The Rust parser and macro expander. //! //! # Note //! //! This API is completely unstable and subject to change. pub use garando_errors as errors; use garando_pos as syntax_pos; mod rustc_data_structures; // A variant of 'try!' that panics on an Err. This is used as a crutch on the // way towards a non-panic!-prone parser. It should be used for fatal parsing // errors; eventually we plan to convert all code using panictry to just use // normal try. // Exported for syntax_ext, not meant for general use. #[macro_export] macro_rules! panictry { ($e:expr) => {{ use crate::errors::FatalError; use std::result::Result::{Err, Ok}; match $e { Ok(e) => e, Err(mut e) => { e.emit(); panic!("{}", FatalError); } } }}; } #[macro_export] macro_rules! unwrap_or { ($opt:expr, $default:expr) => { match $opt { Some(x) => x, None => $default, } }; } #[macro_use] pub mod diagnostics { #[macro_use] pub mod macros; pub mod metadata; pub mod plugin; } pub mod util { pub mod move_map; pub mod parser; #[cfg(test)] pub mod parser_testing; pub mod small_vector; mod thin_vec; pub use self::thin_vec::ThinVec; mod rc_slice; pub use self::rc_slice::RcSlice; } pub mod syntax { pub use crate::ast; pub use crate::ext; pub use crate::parse; } pub mod abi; pub mod ast; pub mod attr; pub mod codemap; #[macro_use] pub mod config; pub mod entry; pub mod feature_gate; pub mod fold; pub mod parse; pub mod ptr; pub mod std_inject; pub mod str; pub use crate::syntax_pos::symbol; pub mod tokenstream; pub mod visit; pub mod print { pub mod pp; pub mod pprust; } pub mod ext { pub use crate::syntax_pos::hygiene; pub mod base; pub mod build; pub mod derive; pub mod expand; pub mod placeholders; pub mod quote; pub mod source_util; pub mod tt { pub mod macro_parser; pub mod macro_rules; pub mod quoted; pub mod transcribe; } } <file_sep>/garando_syntax/src/rustc_data_structures/leb128.rs #[inline] /// encodes an integer using unsigned leb128 encoding and stores /// the result using a callback function. /// /// The callback `write` is called once for each position /// that is to be written to with the byte to be encoded /// at that position. pub fn write_unsigned_leb128_to<W>(mut value: u128, mut write: W) -> usize where W: FnMut(usize, u8), { let mut position = 0; loop { let mut byte = (value & u128::from(0x7Fu64)) as u8; value >>= 7; if value != u128::from(0u64) { byte |= 0x80; } write(position, byte); position += 1; if value == u128::from(0u64) { break; } } position } #[inline] /// encodes an integer using signed leb128 encoding and stores /// the result using a callback function. /// /// The callback `write` is called once for each position /// that is to be written to with the byte to be encoded /// at that position. pub fn write_signed_leb128_to<W>(mut value: i128, mut write: W) -> usize where W: FnMut(usize, u8), { let mut position = 0; loop { let mut byte = (value as u8) & 0x7f; value >>= 7; let more = !(((value == i128::from(0)) && ((byte & 0x40) == 0)) || ((value == i128::from(-1)) && ((byte & 0x40) != 0))); if more { byte |= 0x80; // Mark this byte to show that more bytes will follow. } write(position, byte); position += 1; if !more { break; } } position } <file_sep>/garando_syntax/src/util/rc_slice.rs use std::fmt; use std::ops::Deref; use std::rc::Rc; use crate::rustc_data_structures::stable_hasher::{HashStable, StableHasher, StableHasherResult}; #[derive(Clone)] pub struct RcSlice<T> { data: Rc<Box<[T]>>, offset: u32, len: u32, } impl<T> RcSlice<T> { pub fn new(vec: Vec<T>) -> Self { RcSlice { offset: 0, len: vec.len() as u32, data: Rc::new(vec.into_boxed_slice()), } } } impl<T> Deref for RcSlice<T> { type Target = [T]; fn deref(&self) -> &[T] { &self.data[self.offset as usize..(self.offset + self.len) as usize] } } impl<T: fmt::Debug> fmt::Debug for RcSlice<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self.deref(), f) } } impl<CTX, T> HashStable<CTX> for RcSlice<T> where T: HashStable<CTX>, { fn hash_stable<W: StableHasherResult>(&self, hcx: &mut CTX, hasher: &mut StableHasher<W>) { (**self).hash_stable(hcx, hasher); } } <file_sep>/garando_syntax/Cargo.toml [package] name = "garando_syntax" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] license = "MIT/Apache-2.0" description = "Backport of libsyntax" repository = "https://github.com/JohnTitor/garando" documentation = "https://docs.rs/garando_syntax" readme = "README.md" include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] edition = "2018" [dependencies] bitflags = "1.2.1" log = "0.4" serde = { version = "1.0", features = ["derive", "rc"] } serde_json = "1.0" garando_errors = { version = "0.1", path = "../garando_errors" } garando_pos = { version = "0.1", path = "../garando_pos" } unicode-xid = "0.2" <file_sep>/garando_syntax/src/parse/common.rs //! Common routines shared by parser mods use crate::parse::token; /// `SeqSep` : a sequence separator (token) /// and whether a trailing separator is allowed. pub struct SeqSep { pub sep: Option<token::Token>, pub trailing_sep_allowed: bool, } impl SeqSep { pub fn trailing_allowed(t: token::Token) -> SeqSep { SeqSep { sep: Some(t), trailing_sep_allowed: true, } } pub fn none() -> SeqSep { SeqSep { sep: None, trailing_sep_allowed: false, } } } <file_sep>/garando_syntax/src/str.rs pub fn char_at(s: &str, byte: usize) -> char { s[byte..].chars().next().unwrap() } <file_sep>/garando_pos/Cargo.toml [package] name = "garando_pos" version = "0.1.0" authors = ["<NAME> <<EMAIL>>"] license = "MIT/Apache-2.0" description = "Backport of libsyntax_pos" repository = "https://github.com/JohnTitor/garando" documentation = "https://docs.rs/garando_pos" readme = "README.md" include = ["Cargo.toml", "src/**/*.rs", "README.md", "LICENSE-APACHE", "LICENSE-MIT"] edition = "2018" [dependencies] serde = { version = "1.0", features = ["derive"] } <file_sep>/garando_syntax/src/parse/obsolete.rs //! Support for parsing unsupported, old syntaxes, for the purpose of reporting errors. Parsing of //! these syntaxes is tested by compile-test/obsolete-syntax.rs. //! //! Obsolete syntax that becomes too hard to parse can be removed. use crate::parse::parser; use crate::syntax_pos::Span; /// The specific types of unsupported syntax #[derive(Copy, Clone, PartialEq, Eq, Hash)] pub enum ObsoleteSyntax { // Nothing here at the moment } pub trait ParserObsoleteMethods { fn report(&mut self, sp: Span, kind: ObsoleteSyntax, kind_str: &str, error: bool); } impl<'a> ParserObsoleteMethods for parser::Parser<'a> { fn report(&mut self, sp: Span, kind: ObsoleteSyntax, kind_str: &str, error: bool) { let mut err = if error { self.diagnostic() .struct_span_err(sp, &format!("obsolete syntax: {}", kind_str)) } else { self.diagnostic() .struct_span_warn(sp, &format!("obsolete syntax: {}", kind_str)) }; if !self.obsolete_set.contains(&kind) && (error || self.sess.span_diagnostic.can_emit_warnings) { self.obsolete_set.insert(kind); } err.emit(); } } <file_sep>/Cargo.toml [workspace] members = [ "garando_pos", "garando_errors", "garando_syntax", ] <file_sep>/garando_syntax/src/diagnostics/macros.rs // FIXME garando macro_rules! __diagnostic_used { ($code:tt) => {}; } #[macro_export] macro_rules! span_err { ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ __diagnostic_used!($code); $session.span_err_with_code($span, &format!($($message)*), stringify!($code)) }) } #[macro_export] macro_rules! struct_span_err { ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({ __diagnostic_used!($code); $session.struct_span_err_with_code($span, &format!($($message)*), stringify!($code)) }) } <file_sep>/garando_syntax/src/std_inject.rs use crate::{ast, attr}; pub fn injected_crate_name(krate: &ast::Crate) -> Option<&'static str> { if attr::contains_name(&krate.attrs, "no_core") { None } else if attr::contains_name(&krate.attrs, "no_std") { Some("core") } else { Some("std") } } <file_sep>/garando_syntax/src/abi.rs use std::fmt; use serde::{Deserialize, Serialize}; #[derive(PartialEq, Eq, Hash, Serialize, Deserialize, Clone, Copy, Debug)] pub enum Abi { // NB: This ordering MUST match the AbiDatas array below. // (This is ensured by the test indices_are_correct().) // Single platform ABIs Cdecl, Stdcall, Fastcall, Vectorcall, Thiscall, Aapcs, Win64, SysV64, PtxKernel, Msp430Interrupt, X86Interrupt, // Multiplatform / generic ABIs Rust, C, System, RustIntrinsic, RustCall, PlatformIntrinsic, Unadjusted, } #[derive(Copy, Clone)] pub struct AbiData { abi: Abi, /// Name of this ABI as we like it called. name: &'static str, } #[allow(non_upper_case_globals)] const AbiDatas: &'static [AbiData] = &[ // Platform-specific ABIs AbiData { abi: Abi::Cdecl, name: "cdecl", }, AbiData { abi: Abi::Stdcall, name: "stdcall", }, AbiData { abi: Abi::Fastcall, name: "fastcall", }, AbiData { abi: Abi::Vectorcall, name: "vectorcall", }, AbiData { abi: Abi::Thiscall, name: "thiscall", }, AbiData { abi: Abi::Aapcs, name: "aapcs", }, AbiData { abi: Abi::Win64, name: "win64", }, AbiData { abi: Abi::SysV64, name: "sysv64", }, AbiData { abi: Abi::PtxKernel, name: "ptx-kernel", }, AbiData { abi: Abi::Msp430Interrupt, name: "msp430-interrupt", }, AbiData { abi: Abi::X86Interrupt, name: "x86-interrupt", }, // Cross-platform ABIs AbiData { abi: Abi::Rust, name: "Rust", }, AbiData { abi: Abi::C, name: "C", }, AbiData { abi: Abi::System, name: "system", }, AbiData { abi: Abi::RustIntrinsic, name: "rust-intrinsic", }, AbiData { abi: Abi::RustCall, name: "rust-call", }, AbiData { abi: Abi::PlatformIntrinsic, name: "platform-intrinsic", }, AbiData { abi: Abi::Unadjusted, name: "unadjusted", }, ]; /// Returns the ABI with the given name (if any). pub fn lookup(name: &str) -> Option<Abi> { AbiDatas .iter() .find(|abi_data| name == abi_data.name) .map(|&x| x.abi) } pub fn all_names() -> Vec<&'static str> { AbiDatas.iter().map(|d| d.name).collect() } impl Abi { #[inline] pub fn index(&self) -> usize { *self as usize } #[inline] pub fn data(&self) -> &'static AbiData { &AbiDatas[self.index()] } pub fn name(&self) -> &'static str { self.data().name } } impl fmt::Display for Abi { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "\"{}\"", self.name()) } } #[allow(non_snake_case)] #[test] fn lookup_Rust() { let abi = lookup("Rust"); assert!(abi.is_some() && abi.unwrap().data().name == "Rust"); } #[test] fn lookup_cdecl() { let abi = lookup("cdecl"); assert!(abi.is_some() && abi.unwrap().data().name == "cdecl"); } #[test] fn lookup_baz() { let abi = lookup("baz"); assert!(abi.is_none()); } #[test] fn indices_are_correct() { for (i, abi_data) in AbiDatas.iter().enumerate() { assert_eq!(i, abi_data.abi.index()); } } <file_sep>/garando_syntax/src/diagnostics/plugin.rs use std::cell::RefCell; use std::collections::BTreeMap; use crate::ast::Name; use crate::ext::base::{ExtCtxt, MacEager, MacResult}; use crate::ext::build::AstBuilder; use crate::parse::token; use crate::syntax_pos::Span; use crate::tokenstream::TokenTree; pub use crate::errors::*; thread_local! { static REGISTERED_DIAGNOSTICS: RefCell<ErrorMap> = { RefCell::new(BTreeMap::new()) } } /// Error information type. pub struct ErrorInfo { pub description: Option<Name>, pub use_site: Option<Span>, } /// Mapping from error codes to metadata. pub type ErrorMap = BTreeMap<Name, ErrorInfo>; fn with_registered_diagnostics<T, F>(f: F) -> T where F: FnOnce(&mut ErrorMap) -> T, { REGISTERED_DIAGNOSTICS.with(move |slot| f(&mut *slot.borrow_mut())) } pub fn expand_diagnostic_used<'cx>( ecx: &'cx mut ExtCtxt, span: Span, token_tree: &[TokenTree], ) -> Box<dyn MacResult + 'cx> { let code = match (token_tree.len(), token_tree.get(0)) { (1, Some(&TokenTree::Token(_, token::Ident(code)))) => code, _ => unreachable!(), }; with_registered_diagnostics(|diagnostics| { match diagnostics.get_mut(&code.name) { // Previously used errors. Some(&mut ErrorInfo { description: _, use_site: Some(previous_span), }) => { ecx.struct_span_warn(span, &format!("diagnostic code {} already used", code)) .span_note(previous_span, "previous invocation") .emit(); } // Newly used errors. Some(ref mut info) => { info.use_site = Some(span); } // Unregistered errors. None => { ecx.span_err( span, &format!("used diagnostic code {} not registered", code), ); } } }); MacEager::expr(ecx.expr_tuple(span, Vec::new())) } <file_sep>/CONTRIBUTING.md # Contributing We use this crate in ctest2, which is used in libc CI. So we generally don't accept major changes but if you find tiny stuff to be fixed like typo, feel free to send PRs, thanks! <file_sep>/README.md garando, Rust syntax backport ==================== [![CI](https://github.com/JohnTitor/garando/actions/workflows/ci.yml/badge.svg)](https://github.com/JohnTitor/garando/actions/workflows/ci.yml) [![Latest Version](https://img.shields.io/crates/v/garando_syntax.svg)](https://crates.io/crates/garando_syntax) This repository contains a backport of the following unstable crates from the Rust compiler. - `libsyntax` => [`garando_syntax`] - `libsyntax_pos` => [`garando_pos`] - `librustc_errors` => [`garando_errors`] [`garando_syntax`]: https://docs.rs/garando_syntax [`garando_pos`]: https://docs.rs/garando_pos [`garando_errors`]: https://docs.rs/garando_errors The code compiles on the most recent stable release of Rust. ## License garando is licensed under either of * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) * MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) at your option. ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in garando by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. <file_sep>/garando_syntax/src/ext/derive.rs use crate::ast; use crate::attr::HasAttrs; use crate::codemap::{ExpnFormat, ExpnInfo, NameAndSpan}; use crate::ext::base::ExtCtxt; use crate::ext::build::AstBuilder; use crate::parse::parser::PathStyle; use crate::symbol::Symbol; use crate::syntax_pos::Span; use std::collections::HashSet; pub fn collect_derives(cx: &mut ExtCtxt, attrs: &mut Vec<ast::Attribute>) -> Vec<ast::Path> { let mut result = Vec::new(); attrs.retain(|attr| { if attr.path != "derive" { return true; } match attr.parse_list(cx.parse_sess, |parser| { parser.parse_path_allowing_meta(PathStyle::Mod) }) { Ok(ref traits) if traits.is_empty() => { cx.span_warn(attr.span, "empty trait list in `derive`"); false } Ok(traits) => { result.extend(traits); true } Err(mut e) => { e.emit(); false } } }); result } pub fn add_derived_markers<T>(cx: &mut ExtCtxt, span: Span, traits: &[ast::Path], item: T) -> T where T: HasAttrs, { let (mut names, mut pretty_name) = (HashSet::new(), "derive(".to_owned()); for (i, path) in traits.iter().enumerate() { if i > 0 { pretty_name.push_str(", "); } pretty_name.push_str(&path.to_string()); names.insert(unwrap_or!(path.segments.get(0), continue).identifier.name); } pretty_name.push(')'); cx.current_expansion.mark.set_expn_info(ExpnInfo { call_site: span, callee: NameAndSpan { format: ExpnFormat::MacroAttribute(Symbol::intern(&pretty_name)), span: None, allow_internal_unstable: true, }, }); let span = Span { ctxt: cx.backtrace(), ..span }; item.map_attrs(|mut attrs| { if names.contains(&Symbol::intern("Eq")) && names.contains(&Symbol::intern("PartialEq")) { let meta = cx.meta_word(span, Symbol::intern("structural_match")); attrs.push(cx.attribute(span, meta)); } if names.contains(&Symbol::intern("Copy")) && names.contains(&Symbol::intern("Clone")) { let meta = cx.meta_word(span, Symbol::intern("rustc_copy_clone_marker")); attrs.push(cx.attribute(span, meta)); } attrs }) } <file_sep>/garando_syntax/src/rustc_data_structures/blake2b.rs // An implementation of the Blake2b cryptographic hash function. // The implementation closely follows: https://tools.ietf.org/html/rfc7693 // // "BLAKE2 is a cryptographic hash function faster than MD5, SHA-1, SHA-2, and // SHA-3, yet is at least as secure as the latest standard SHA-3." // according to their own website :) // // Indeed this implementation is two to three times as fast as our SHA-256 // implementation. If you have the luxury of being able to use crates from // crates.io, you can go there and find still faster implementations. use std::mem; use std::slice; pub struct Blake2bCtx { b: [u8; 128], h: [u64; 8], t: [u64; 2], c: usize, outlen: u16, finalized: bool, #[cfg(debug_assertions)] fnv_hash: u64, } #[cfg(debug_assertions)] impl ::std::fmt::Debug for Blake2bCtx { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(fmt, "{:x}", self.fnv_hash) } } #[cfg(not(debug_assertions))] impl ::std::fmt::Debug for Blake2bCtx { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { write!(fmt, "Enable debug_assertions() for more info.") } } #[inline(always)] fn b2b_g(v: &mut [u64; 16], a: usize, b: usize, c: usize, d: usize, x: u64, y: u64) { v[a] = v[a].wrapping_add(v[b]).wrapping_add(x); v[d] = (v[d] ^ v[a]).rotate_right(32); v[c] = v[c].wrapping_add(v[d]); v[b] = (v[b] ^ v[c]).rotate_right(24); v[a] = v[a].wrapping_add(v[b]).wrapping_add(y); v[d] = (v[d] ^ v[a]).rotate_right(16); v[c] = v[c].wrapping_add(v[d]); v[b] = (v[b] ^ v[c]).rotate_right(63); } // Initialization vector const BLAKE2B_IV: [u64; 8] = [ 0x6A09E667F3BCC908, 0xBB67AE8584CAA73B, 0x3C6EF372FE94F82B, 0xA54FF53A5F1D36F1, 0x510E527FADE682D1, 0x9B05688C2B3E6C1F, 0x1F83D9ABFB41BD6B, 0x5BE0CD19137E2179, ]; fn blake2b_compress(ctx: &mut Blake2bCtx, last: bool) { const SIGMA: [[usize; 16]; 12] = [ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4], [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8], [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13], [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9], [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11], [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10], [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5], [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3], ]; let mut v: [u64; 16] = [ ctx.h[0], ctx.h[1], ctx.h[2], ctx.h[3], ctx.h[4], ctx.h[5], ctx.h[6], ctx.h[7], BLAKE2B_IV[0], BLAKE2B_IV[1], BLAKE2B_IV[2], BLAKE2B_IV[3], BLAKE2B_IV[4], BLAKE2B_IV[5], BLAKE2B_IV[6], BLAKE2B_IV[7], ]; v[12] ^= ctx.t[0]; // low 64 bits of offset v[13] ^= ctx.t[1]; // high 64 bits if last { v[14] = !v[14]; } { // Re-interpret the input buffer in the state as an array // of little-endian u64s, converting them to machine // endianness. It's OK to modify the buffer in place // since this is the last time this data will be accessed // before it's overwritten. let m: &mut [u64; 16] = unsafe { let b: &mut [u8; 128] = &mut ctx.b; ::std::mem::transmute(b) }; if cfg!(target_endian = "big") { for word in &mut m[..] { *word = u64::from_le(*word); } } for i in 0..12 { b2b_g(&mut v, 0, 4, 8, 12, m[SIGMA[i][0]], m[SIGMA[i][1]]); b2b_g(&mut v, 1, 5, 9, 13, m[SIGMA[i][2]], m[SIGMA[i][3]]); b2b_g(&mut v, 2, 6, 10, 14, m[SIGMA[i][4]], m[SIGMA[i][5]]); b2b_g(&mut v, 3, 7, 11, 15, m[SIGMA[i][6]], m[SIGMA[i][7]]); b2b_g(&mut v, 0, 5, 10, 15, m[SIGMA[i][8]], m[SIGMA[i][9]]); b2b_g(&mut v, 1, 6, 11, 12, m[SIGMA[i][10]], m[SIGMA[i][11]]); b2b_g(&mut v, 2, 7, 8, 13, m[SIGMA[i][12]], m[SIGMA[i][13]]); b2b_g(&mut v, 3, 4, 9, 14, m[SIGMA[i][14]], m[SIGMA[i][15]]); } } for i in 0..8 { ctx.h[i] ^= v[i] ^ v[i + 8]; } } fn blake2b_update(ctx: &mut Blake2bCtx, mut data: &[u8]) { assert!(!ctx.finalized, "Blake2bCtx already finalized"); let mut bytes_to_copy = data.len(); let mut space_in_buffer = ctx.b.len() - ctx.c; while bytes_to_copy > space_in_buffer { checked_mem_copy(data, &mut ctx.b[ctx.c..], space_in_buffer); ctx.t[0] = ctx.t[0].wrapping_add(ctx.b.len() as u64); if ctx.t[0] < (ctx.b.len() as u64) { ctx.t[1] += 1; } blake2b_compress(ctx, false); ctx.c = 0; data = &data[space_in_buffer..]; bytes_to_copy -= space_in_buffer; space_in_buffer = ctx.b.len(); } if bytes_to_copy > 0 { checked_mem_copy(data, &mut ctx.b[ctx.c..], bytes_to_copy); ctx.c += bytes_to_copy; } #[cfg(debug_assertions)] { // compute additional FNV hash for simpler to read debug output const MAGIC_PRIME: u64 = 0x00000100000001b3; for &byte in data { ctx.fnv_hash = (ctx.fnv_hash ^ byte as u64).wrapping_mul(MAGIC_PRIME); } } } fn blake2b_final(ctx: &mut Blake2bCtx) { assert!(!ctx.finalized, "Blake2bCtx already finalized"); ctx.t[0] = ctx.t[0].wrapping_add(ctx.c as u64); if ctx.t[0] < ctx.c as u64 { ctx.t[1] += 1; } while ctx.c < 128 { ctx.b[ctx.c] = 0; ctx.c += 1; } blake2b_compress(ctx, true); // Modify our buffer to little-endian format as it will be read // as a byte array. It's OK to modify the buffer in place since // this is the last time this data will be accessed. if cfg!(target_endian = "big") { for word in &mut ctx.h { *word = word.to_le(); } } ctx.finalized = true; } #[inline(always)] fn checked_mem_copy<T1, T2>(from: &[T1], to: &mut [T2], byte_count: usize) { let from_size = from.len() * mem::size_of::<T1>(); let to_size = to.len() * mem::size_of::<T2>(); assert!(from_size >= byte_count); assert!(to_size >= byte_count); let from_byte_ptr = from.as_ptr() as *const u8; let to_byte_ptr = to.as_mut_ptr() as *mut u8; unsafe { ::std::ptr::copy_nonoverlapping(from_byte_ptr, to_byte_ptr, byte_count); } } pub struct Blake2bHasher(Blake2bCtx); impl ::std::hash::Hasher for Blake2bHasher { fn write(&mut self, bytes: &[u8]) { blake2b_update(&mut self.0, bytes); } fn finish(&self) -> u64 { assert!( self.0.outlen == 8, "Hasher initialized with incompatible output length" ); u64::from_le(self.0.h[0]) } } impl Blake2bHasher { pub fn finalize(&mut self) -> &[u8] { if !self.0.finalized { blake2b_final(&mut self.0); } debug_assert!(mem::size_of_val(&self.0.h) >= self.0.outlen as usize); let raw_ptr = (&self.0.h[..]).as_ptr() as *const u8; unsafe { slice::from_raw_parts(raw_ptr, self.0.outlen as usize) } } } impl ::std::fmt::Debug for Blake2bHasher { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { write!(fmt, "{:?}", self.0) } } <file_sep>/garando_syntax/src/ext/source_util.rs use crate::ast; use crate::ext::base; use crate::ext::base::*; use crate::ext::build::AstBuilder; use crate::parse; use crate::parse::{token, DirectoryOwnership}; use crate::print::pprust; use crate::ptr::P; use crate::symbol::Symbol; use crate::syntax_pos::{self, Pos, Span}; use crate::tokenstream; use crate::util::small_vector::SmallVector; use std::fs::File; use std::io::prelude::*; use std::path::{Path, PathBuf}; use std::rc::Rc; // These macros all relate to the file system; they either return // the column/row/filename of the expression, or they include // a given file into the current one. /// line!(): expands to the current line number pub fn expand_line( cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'static> { base::check_zero_tts(cx, sp, tts, "line!"); let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.codemap().lookup_char_pos(topmost.lo); base::MacEager::expr(cx.expr_u32(topmost, loc.line as u32)) } /* column!(): expands to the current column number */ pub fn expand_column( cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'static> { base::check_zero_tts(cx, sp, tts, "column!"); let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.codemap().lookup_char_pos(topmost.lo); base::MacEager::expr(cx.expr_u32(topmost, loc.col.to_usize() as u32)) } /// file!(): expands to the current filename */ /// The filemap (`loc.file`) contains a bunch more information we could spit /// out if we wanted. pub fn expand_file( cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'static> { base::check_zero_tts(cx, sp, tts, "file!"); let topmost = cx.expansion_cause().unwrap_or(sp); let loc = cx.codemap().lookup_char_pos(topmost.lo); base::MacEager::expr(cx.expr_str(topmost, Symbol::intern(&loc.file.name))) } pub fn expand_stringify( cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'static> { let s = pprust::tts_to_string(tts); base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&s))) } pub fn expand_mod( cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'static> { base::check_zero_tts(cx, sp, tts, "module_path!"); let mod_path = &cx.current_expansion.module.mod_path; let string = mod_path .iter() .map(|x| x.to_string()) .collect::<Vec<String>>() .join("::"); base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&string))) } /// include! : parse the given file as an expr /// This is generally a bad idea because it's going to behave /// unhygienically. pub fn expand_include<'cx>( cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'cx> { let file = match get_single_str_from_tts(cx, sp, tts, "include!") { Some(f) => f, None => return DummyResult::expr(sp), }; // The file will be added to the code map by the parser let path = res_rel_file(cx, sp, Path::new(&file)); let directory_ownership = DirectoryOwnership::Owned; let p = parse::new_sub_parser_from_file(cx.parse_sess(), &path, directory_ownership, None, sp); struct ExpandResult<'a> { p: parse::parser::Parser<'a>, } impl<'a> base::MacResult for ExpandResult<'a> { fn make_expr(mut self: Box<ExpandResult<'a>>) -> Option<P<ast::Expr>> { Some(panictry!(self.p.parse_expr())) } fn make_items(mut self: Box<ExpandResult<'a>>) -> Option<SmallVector<P<ast::Item>>> { let mut ret = SmallVector::new(); while self.p.token != token::Eof { match panictry!(self.p.parse_item()) { Some(item) => ret.push(item), None => panic!("{}", self.p.diagnostic().span_fatal( self.p.span, &format!("expected item, found `{}`", self.p.this_token_to_string()) )), } } Some(ret) } } Box::new(ExpandResult { p: p }) } // include_str! : read the given file, insert it as a literal string expr pub fn expand_include_str( cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'static> { let file = match get_single_str_from_tts(cx, sp, tts, "include_str!") { Some(f) => f, None => return DummyResult::expr(sp), }; let file = res_rel_file(cx, sp, Path::new(&file)); let mut bytes = Vec::new(); match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) { Ok(..) => {} Err(e) => { cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e)); return DummyResult::expr(sp); } }; match String::from_utf8(bytes) { Ok(src) => { // Add this input file to the code map to make it available as // dependency information let filename = format!("{}", file.display()); cx.codemap().new_filemap_and_lines(&filename, &src); base::MacEager::expr(cx.expr_str(sp, Symbol::intern(&src))) } Err(_) => { cx.span_err(sp, &format!("{} wasn't a utf-8 file", file.display())); DummyResult::expr(sp) } } } pub fn expand_include_bytes( cx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree], ) -> Box<dyn base::MacResult + 'static> { let file = match get_single_str_from_tts(cx, sp, tts, "include_bytes!") { Some(f) => f, None => return DummyResult::expr(sp), }; let file = res_rel_file(cx, sp, Path::new(&file)); let mut bytes = Vec::new(); match File::open(&file).and_then(|mut f| f.read_to_end(&mut bytes)) { Err(e) => { cx.span_err(sp, &format!("couldn't read {}: {}", file.display(), e)); DummyResult::expr(sp) } Ok(..) => { // Add this input file to the code map to make it available as // dependency information, but don't enter it's contents let filename = format!("{}", file.display()); cx.codemap().new_filemap_and_lines(&filename, ""); base::MacEager::expr(cx.expr_lit(sp, ast::LitKind::ByteStr(Rc::new(bytes)))) } } } // resolve a file-system path to an absolute file-system path (if it // isn't already) fn res_rel_file(cx: &mut ExtCtxt, sp: syntax_pos::Span, arg: &Path) -> PathBuf { // NB: relative paths are resolved relative to the compilation unit if !arg.is_absolute() { let callsite = sp.source_callsite(); let mut cu = PathBuf::from(&cx.codemap().span_to_filename(callsite)); cu.pop(); cu.push(arg); cu } else { arg.to_path_buf() } } <file_sep>/garando_pos/src/hygiene.rs //! Machinery for hygienic macros, inspired by the MTWT[1] paper. //! //! [1] <NAME>, <NAME>, <NAME>, and <NAME>. //! 2012. *Macros that work together: Compile-time bindings, partial expansion, //! and definition contexts*. J. Funct. Program. 22, 2 (March 2012), 181-216. //! DOI=10.1017/S0956796812000093 http://dx.doi.org/10.1017/S0956796812000093 use crate::symbol::Symbol; use crate::Span; use std::cell::RefCell; use std::collections::HashMap; use std::fmt; use serde::{Deserialize, Deserializer, Serialize, Serializer}; /// A SyntaxContext represents a chain of macro expansions (represented by marks). #[derive(Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord, Hash)] pub struct SyntaxContext(u32); pub const NO_EXPANSION: SyntaxContext = SyntaxContext(0); #[derive(Copy, Clone, Default)] pub struct SyntaxContextData { pub outer_mark: Mark, pub prev_ctxt: SyntaxContext, pub modern: SyntaxContext, } /// A mark is a unique id associated with a macro expansion. #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Default, Serialize, Deserialize)] pub struct Mark(u32); #[derive(Default)] struct MarkData { parent: Mark, modern: bool, expn_info: Option<ExpnInfo>, } impl Mark { pub fn fresh(parent: Mark) -> Self { HygieneData::with(|data| { data.marks.push(MarkData { parent, modern: false, expn_info: None, }); Mark(data.marks.len() as u32 - 1) }) } /// The mark of the theoretical expansion that generates freshly parsed, unexpanded AST. pub fn root() -> Self { Mark(0) } pub fn as_u32(self) -> u32 { self.0 } pub fn expn_info(self) -> Option<ExpnInfo> { HygieneData::with(|data| data.marks[self.0 as usize].expn_info.clone()) } pub fn set_expn_info(self, info: ExpnInfo) { HygieneData::with(|data| data.marks[self.0 as usize].expn_info = Some(info)) } pub fn is_descendant_of(mut self, ancestor: Mark) -> bool { HygieneData::with(|data| { while self != ancestor { if self == Mark::root() { return false; } self = data.marks[self.0 as usize].parent; } true }) } } struct HygieneData { marks: Vec<MarkData>, syntax_contexts: Vec<SyntaxContextData>, markings: HashMap<(SyntaxContext, Mark), SyntaxContext>, } impl HygieneData { fn new() -> Self { HygieneData { marks: vec![MarkData::default()], syntax_contexts: vec![SyntaxContextData::default()], markings: HashMap::new(), } } fn with<T, F: FnOnce(&mut HygieneData) -> T>(f: F) -> T { thread_local! { static HYGIENE_DATA: RefCell<HygieneData> = RefCell::new(HygieneData::new()); } HYGIENE_DATA.with(|data| f(&mut *data.borrow_mut())) } } impl SyntaxContext { pub fn empty() -> Self { NO_EXPANSION } /// Extend a syntax context with a given mark pub fn apply_mark(self, mark: Mark) -> SyntaxContext { HygieneData::with(|data| { let syntax_contexts = &mut data.syntax_contexts; let ctxt_data = syntax_contexts[self.0 as usize]; if mark == ctxt_data.outer_mark { return ctxt_data.prev_ctxt; } let modern = if data.marks[mark.0 as usize].modern { *data .markings .entry((ctxt_data.modern, mark)) .or_insert_with(|| { let modern = SyntaxContext(syntax_contexts.len() as u32); syntax_contexts.push(SyntaxContextData { outer_mark: mark, prev_ctxt: ctxt_data.modern, modern, }); modern }) } else { ctxt_data.modern }; *data.markings.entry((self, mark)).or_insert_with(|| { syntax_contexts.push(SyntaxContextData { outer_mark: mark, prev_ctxt: self, modern, }); SyntaxContext(syntax_contexts.len() as u32 - 1) }) }) } pub fn remove_mark(&mut self) -> Mark { HygieneData::with(|data| { let outer_mark = data.syntax_contexts[self.0 as usize].outer_mark; *self = data.syntax_contexts[self.0 as usize].prev_ctxt; outer_mark }) } pub fn modern(self) -> SyntaxContext { HygieneData::with(|data| data.syntax_contexts[self.0 as usize].modern) } pub fn outer(self) -> Mark { HygieneData::with(|data| data.syntax_contexts[self.0 as usize].outer_mark) } } impl fmt::Debug for SyntaxContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "#{}", self.0) } } /// Extra information for tracking spans of macro and syntax sugar expansion #[derive(Clone, Hash, Debug)] pub struct ExpnInfo { /// The location of the actual macro invocation or syntax sugar , e.g. /// `let x = foo!();` or `if let Some(y) = x {}` /// /// This may recursively refer to other macro invocations, e.g. if /// `foo!()` invoked `bar!()` internally, and there was an /// expression inside `bar!`; the call_site of the expression in /// the expansion would point to the `bar!` invocation; that /// call_site span would have its own ExpnInfo, with the call_site /// pointing to the `foo!` invocation. pub call_site: Span, /// Information about the expansion. pub callee: NameAndSpan, } #[derive(Clone, Hash, Debug)] pub struct NameAndSpan { /// The format with which the macro was invoked. pub format: ExpnFormat, /// Whether the macro is allowed to use #[unstable]/feature-gated /// features internally without forcing the whole crate to opt-in /// to them. pub allow_internal_unstable: bool, /// The span of the macro definition itself. The macro may not /// have a sensible definition span (e.g. something defined /// completely inside libsyntax) in which case this is None. pub span: Option<Span>, } impl NameAndSpan { pub fn name(&self) -> Symbol { match self.format { ExpnFormat::MacroAttribute(s) | ExpnFormat::MacroBang(s) | ExpnFormat::CompilerDesugaring(s) => s, } } } /// The source of expansion. #[derive(Clone, Hash, Debug, PartialEq, Eq)] pub enum ExpnFormat { /// e.g. #[derive(...)] <item> MacroAttribute(Symbol), /// e.g. `format!()` MacroBang(Symbol), /// Desugaring done by the compiler during HIR lowering. CompilerDesugaring(Symbol), } impl Serialize for SyntaxContext { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { // FIXME(jseyfried) intercrate hygiene serializer.serialize_unit() } } impl<'de> Deserialize<'de> for SyntaxContext { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { // FIXME(jseyfried) intercrate hygiene Deserialize::deserialize(deserializer).map(|()| SyntaxContext::empty()) } } <file_sep>/garando_syntax/src/rustc_data_structures/mod.rs pub mod stable_hasher; mod blake2b; mod leb128; <file_sep>/garando_errors/src/diagnostic.rs use crate::snippet::Style; use crate::syntax_pos::{MultiSpan, Span}; use crate::CodeSuggestion; use crate::Level; use crate::RenderSpan; use crate::Substitution; use serde::{Deserialize, Serialize}; #[must_use] #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Diagnostic { pub level: Level, pub message: Vec<(String, Style)>, pub code: Option<String>, pub span: MultiSpan, pub children: Vec<SubDiagnostic>, pub suggestions: Vec<CodeSuggestion>, } /// For example a note attached to an error. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SubDiagnostic { pub level: Level, pub message: Vec<(String, Style)>, pub span: MultiSpan, pub render_span: Option<RenderSpan>, } #[derive(PartialEq, Eq)] pub struct DiagnosticStyledString(pub Vec<StringPart>); #[derive(PartialEq, Eq)] pub enum StringPart { Normal(String), Highlighted(String), } impl Diagnostic { pub fn new_with_code(level: Level, code: Option<String>, message: &str) -> Self { Diagnostic { level: level, message: vec![(message.to_owned(), Style::NoStyle)], code: code, span: MultiSpan::default(), children: vec![], suggestions: vec![], } } /// Cancel the diagnostic (a structured diagnostic must either be emitted or /// cancelled or it will panic when dropped). /// BEWARE: if this DiagnosticBuilder is an error, then creating it will /// bump the error count on the Handler and cancelling it won't undo that. /// If you want to decrement the error count you should use `Handler::cancel`. pub fn cancel(&mut self) { self.level = Level::Cancelled; } pub fn cancelled(&self) -> bool { self.level == Level::Cancelled } /// Add a span/label to be included in the resulting snippet. /// This is pushed onto the `MultiSpan` that was created when the /// diagnostic was first built. If you don't call this function at /// all, and you just supplied a `Span` to create the diagnostic, /// then the snippet will just include that `Span`, which is /// called the primary span. pub fn span_label<T: Into<String>>(&mut self, span: Span, label: T) -> &mut Self { self.span.push_span_label(span, label.into()); self } pub fn highlighted_note(&mut self, msg: Vec<(String, Style)>) -> &mut Self { self.sub_with_highlights(Level::Note, msg, MultiSpan::default(), None); self } pub fn span_note<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self { self.sub(Level::Note, msg, sp.into(), None); self } pub fn span_warn<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self { self.sub(Level::Warning, msg, sp.into(), None); self } pub fn help(&mut self, msg: &str) -> &mut Self { self.sub(Level::Help, msg, MultiSpan::default(), None); self } pub fn span_help<S: Into<MultiSpan>>(&mut self, sp: S, msg: &str) -> &mut Self { self.sub(Level::Help, msg, sp.into(), None); self } /// Prints out a message with a suggested edit of the code. /// /// See `diagnostic::CodeSuggestion` for more information. pub fn span_suggestion(&mut self, sp: Span, msg: &str, suggestion: String) -> &mut Self { self.suggestions.push(CodeSuggestion { substitution_parts: vec![Substitution { span: sp, substitutions: vec![suggestion], }], msg: msg.to_owned(), }); self } pub fn set_span<S: Into<MultiSpan>>(&mut self, sp: S) -> &mut Self { self.span = sp.into(); self } pub fn code(&mut self, s: String) -> &mut Self { self.code = Some(s); self } pub fn message(&self) -> String { self.message .iter() .map(|i| i.0.to_owned()) .collect::<String>() } pub fn styled_message(&self) -> &Vec<(String, Style)> { &self.message } /// Convenience function for internal use, clients should use one of the /// public methods above. fn sub( &mut self, level: Level, message: &str, span: MultiSpan, render_span: Option<RenderSpan>, ) { let sub = SubDiagnostic { level: level, message: vec![(message.to_owned(), Style::NoStyle)], span: span, render_span: render_span, }; self.children.push(sub); } /// Convenience function for internal use, clients should use one of the /// public methods above. fn sub_with_highlights( &mut self, level: Level, message: Vec<(String, Style)>, span: MultiSpan, render_span: Option<RenderSpan>, ) { let sub = SubDiagnostic { level: level, message: message, span: span, render_span: render_span, }; self.children.push(sub); } } impl SubDiagnostic { pub fn message(&self) -> String { self.message .iter() .map(|i| i.0.to_owned()) .collect::<String>() } pub fn styled_message(&self) -> &Vec<(String, Style)> { &self.message } }
c98c6f7e7d2dcbeb54dc0c4558252019fb87b835
[ "TOML", "Rust", "Markdown" ]
21
Rust
JohnTitor/garando
ef91102626153ecf88274a9f272ba36127ae6847
6631050049720e787ea8d6927a5d00c7e1fa7080
refs/heads/master
<file_sep># thor A real time file tagging application <file_sep>//Very light wrapper over a normal module.exports = function(code, message, responseCode, logError) { var error = new Error(message); error.code = code; error.responseCode = responseCode || 500; //Log errors if not specified if(typeof logError === 'undefined') { logError = true; } if(logError) { console.error(error); } return error; }; <file_sep>var kNodeTools = require('k-node-tools'), thorError = require('./lib/thorError.js'), CONSTANTS = require('./CONSTANTS.js'), firebaseWrap = require('./lib/firebaseWrap.js'), async = require('async'); var server = kNodeTools.restServer(CONSTANTS.FIREBASE_URL); server.get('/', function(req, res) { kNodeTools.walkDir(CONSTANTS.FILE_MOUNT_PATH, '.', function(error, data) { async.each(data, function(item, cb) { var filesRef = firebaseWrap('files'); filesRef.push({ fileName: item }); cb(); }, function() { res.json(data); }); }); }); server.get('/exampleError', function(req, res) { return endWithError(res, thorError('Code_123', 'Looks like error 123 occured', 401)); }); server.listen(85, function() { console.log('Server running'); }); function endWithError(res, error) { res.status(error.responseCode || 500); res.json({ code: error.code, message: error.message }); res.end(); }
edf80a19c8a56abda0ba2830abaaf0c385cb34d9
[ "Markdown", "JavaScript" ]
3
Markdown
aashtonk/thor
17237a358247d461a102f2a13d4953bf8e76019f
4690bae790ffdc0522cff49d6d2671813b626164
refs/heads/master
<repo_name>andrerafaelmezzalira/cliente<file_sep>/README.md # Cliente Para construir o aplicativo, foi usado as seguintes ferramentas: Eclipse como IDE para codificação. Java 8 J2EE 7 Servidor Jboss EAP 7 Maven como organizador de pacotes Banco de dados Postgresql e o driver postgresql para java HTML 5, AngularJs e Materializecss na camada view. JAX-RS para comunicação entre a view e o server. EJB 3.1 para a camada de negócio. Repository (entityManager), com JPA e hibernate na camada de acesso a dados. Para instalar, basta criar a base de dados de nome 'cliente', conforme definido em persistence.xml. Adicionar o banco de dados em arquivo standalone.xml, na parte de datasources, conforme abaixo <datasource jta="true" jndi-name="java:jboss/cliente" pool-name="cliente" enabled="true" use-ccm="true"> <connection-url>jdbc:postgresql://localhost:5432/cliente</connection-url> <driver-class>org.postgresql.Driver</driver-class> <driver>postgresql-9.4-1204.jdbc4.jar</driver> <security> <user-name>postgres</user-name> <password><PASSWORD></password> </security> <validation> <valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLValidConnectionChecker"/> <background-validation>true</background-validation> <exception-sorter class-name="org.jboss.jca.adapters.jdbc.extensions.postgres.PostgreSQLExceptionSorter"/> </validation> </datasource> Se rodar pelo eclipse, pode importar o projeto do tipo maven project via eclipse e rodar o comando maven install. Adicione o projeto no jboss e start o servidor. Caso contrário, poderá rodar o comando mvn install via linha de comando, pegar o arquivo war gerado e adicionar ao jboss. O url do sistema deverá ser: http://localhost:8080/cliente <file_sep>/cliente/src/main/webapp/app/cliente/cliente.service.js (function() { function ClienteService($http) { var url = 'resources/cliente'; return ({ listar : listar, salvar : salvar, excluir : excluir }); function listar() { return $http.get(url); } function salvar(cliente) { return $http[!cliente.id ? 'post' : 'put'](url, cliente); } function excluir(id) { return $http['delete'](url, { params : { id : id } }); } } ClienteService.$inject = [ '$http' ]; angular.module('app.services').service('ClienteService', ClienteService); })(); <file_sep>/cliente/src/main/java/br/com/cliente/repository/ClienteRepository.java package br.com.cliente.repository; import br.com.cliente.arq.AbstractRepository; import br.com.cliente.domain.Cliente; public class ClienteRepository extends AbstractRepository<Cliente> { public ClienteRepository() { super(Cliente.class); } }<file_sep>/cliente/src/main/java/br/com/cliente/exception/CamposObrigatoriosException.java package br.com.cliente.exception; public class CamposObrigatoriosException extends Exception { private static final long serialVersionUID = 1L; public CamposObrigatoriosException(String message) { super(message); } } <file_sep>/cliente/src/main/java/br/com/cliente/service/ClienteService.java package br.com.cliente.service; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; import br.com.cliente.domain.Cliente; import br.com.cliente.exception.CamposObrigatoriosException; import br.com.cliente.repository.ClienteRepository; @Stateless public class ClienteService { @Inject private ClienteRepository repository; public List<Cliente> listar() { return repository.listAll(); } public void salvar(Cliente cliente) throws CamposObrigatoriosException { boolean nomeValido = cliente.getNome() != null && !"".equals(cliente.getNome()); boolean emailValido = cliente.getEmail() != null && !"".equals(cliente.getEmail()); if (!nomeValido || !emailValido) { throw new CamposObrigatoriosException("Existem campos obrigatórios"); } if (cliente.getId() != null) { repository.update(cliente); } else { cliente.setAtivo(true); cliente.setDataCadastro(new Date()); repository.insert(cliente); } } public Cliente excluir(Integer id) { Cliente cliente = repository.findById(id); return repository.delete(cliente); } }
51b5606a8e769edb75b023921ec21592a913783e
[ "Markdown", "Java", "JavaScript" ]
5
Markdown
andrerafaelmezzalira/cliente
b12249e4b836ab3707528946b931d8230046a5dc
ab2a37e91d14c001c9d1ee435bc5c2d7710df03b
refs/heads/master
<repo_name>syedsaleem703/cpp<file_sep>/3n+1problem1.c #include <iostream> using namespace std; int main () { unsigned int i,j, cl, mcl; while(cin >> i >> j){ unsigned int i2, j2; i2 = i<=j ? i:j; j2 = i<=j ? j:i; cl=0; mcl=0; for(int k=i2; k<=j2; k++) { cl=0; int k2=k; while(k2 !=1 ) { if(k2%2 ==1) { k2 = k2*3 +1; cl++; } else { k2 /= 2; cl++; } } cl++; if(cl>mcl) mcl =cl; } cout << i << " " << j << " " << mcl << "\n"; } return 0; } <file_sep>/vactorErase.cpp int N, temp; vector<int> v; cin >> N; for(int i = 0; i < N; i++){ cin >> temp; v.push_back(temp); } cin >> temp; if( rem < v.size() ) v.erase(v.begin() + rem - 1); int a, b; cin >> a >> b; if( a < b && b < v.size() ) v.erase(v.begin() + a - 1, v.begin() + b - 1); cout << v.size() << endl; for(auto _v : v) cout << _v << " "; cout << endl; return 0; }
753bdae1ad4752cc50553412b08c9f057ac8e064
[ "C", "C++" ]
2
C
syedsaleem703/cpp
e70acebbace4166f4660f770d98b4027433a4958
805158ead00bba8ad2c3a54e493c0f4a0db2a89e
refs/heads/master
<repo_name>JCEDO1/ANLJC<file_sep>/August/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' import axios from 'axios' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) Vue.config.productionTip = false var sessionStorage = window.sessionStorage; import Store from './store/index.js' //拦截 //axios封装 //http://192.168.191.1:8080 http://192.168.127.12:81 axios.defaults.baseURL = 'http://192.168.127.12:81'; axios.timeout = 1000; const get = (url,params) =>{ return new Promise((resolve,reject)=>{ axios.get(url,{params:params}) .then(res=>{ resolve(res.data); }).catch(err=>{ reject(err); }) }) }; const post = (url,params) =>{ return new Promise((resolve,reject)=>{ axios.post(url,params) .then(res=>{ resolve(res.data); }).catch(err=>{ reject(err); }) }) }; Vue.prototype.$get = get; Vue.prototype.$post = post; /*=============================获取本地数据并提交==================================================*/ const getLocalData = ()=>{ var localAgeData = sessionStorage.getItem('localAgeData'); if(localAgeData!=''&&localAgeData!=null){ Store.commit('changeGlobalAgeData',JSON.parse(localAgeData)); } var localSignedData = JSON.parse(sessionStorage.getItem('localSignedData')); setTimeout(function () { if(localSignedData!='' && localSignedData!=null){ Store.commit('cleanItemGroupData'); localSignedData.forEach(v=>{ if(v.match_id == store.state.matchId){ Store.commit('changeItemGroupData',v); }else{ console.log(v.match_id); Vue.Message({ message:'数据错误', type:'error' }) } }) } },0) } Vue.prototype.$getLocalData = getLocalData; /* eslint-disable no-new */ new Vue({ el: '#app', store, router, components: { App }, template: '<App/>', }) //axios封装 $get\$post直接引用 不需要加.catch <file_sep>/August/static/ueditor1_4_3_3/dialogs/template/a.js var tarHtml = '' var coachName,leaderName,unitName; window.onload = function (){ h = function(arr){ let dh = ''; for(let i = 0 ; i < arr.length ; i++){ if(i == 0){ dh += '&nbsp;&nbsp;<span>'+arr[i].id+'</span>'+ '&nbsp;&nbsp;&nbsp;<span>'+arr[i].name+'</span>'; }else if((i+1)%3 == 0){ dh += '&nbsp;&nbsp;<span>'+arr[i].id+'</span>'+ '&nbsp;&nbsp;&nbsp;<span>'+arr[i].name+'</span>'+ '</p>'+ '<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' }else{ dh += '&nbsp;&nbsp;<span>'+arr[i].id+'</span>'+ '&nbsp;&nbsp;&nbsp;<span>'+arr[i].name+'</span>' } } dh += '</p>'; let index = dh.indexOf('<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</p>'); if(index !== -1){ dh = dh.slice(0,index); } return dh; } var xhr = new XMLHttpRequest(); xhr.open('POST','http://192.168.127.12:81/v1/control/eachunitpeople',true); xhr.setRequestHeader("Content-Type","application/json; charset=utf-8"); xhr.onreadystatechange = function (){ if(xhr.readyState == 4){ if(xhr.status >= 200 && xhr.status <= 300){ var resData = JSON.parse(xhr.responseText); msg = resData.msg; console.log(msg); for(let i = 0 ; i < msg.length ; i++){ unitName = msg[i].unitname; leaderName = msg[i].leadername; coachName = msg[i].coachname; tarHtml += '<p style="margin-top:30px;">'+ '<h1>'+msg[i].unitname+'</h1>'+ '</p>'+ '<p style="text-indent: 3em;">'+ '<span>领队:&nbsp;&nbsp;'+msg[i].leadername+'</span>'+ '</p>'+ '<p style="text-indent: 3em;">'+ '<span>教练:&nbsp;&nbsp;'+msg[i].coachname+'</span>'+ '</p>'; for(var prop in msg[i]){ if(prop == 'adult' && msg[i][prop].length!==0){ tarHtml += '<p style="text-indent:1em;">'+ '<span>青成年组:</span>'+ h(msg[i][prop])+ '</p>'; continue; }else if(prop == 'teen' && msg[i][prop].length!==0){ tarHtml += '<p style="text-indent:2em;">'+ '<span>少年组:</span>'+ h(msg[i][prop])+ '</p>'; continue; }else if(prop == 'child' && msg[i][prop].length!==0){ tarHtml += '<p style="text-indent:2em;">'+ '<span>儿童组:</span>'+ h(msg[i][prop])+ '</p>'; continue; } } } var u = document.getElementById('unitData'); u.innerHTML = tarHtml; } } } xhr.send(JSON.stringify({"match_id":6})); } <file_sep>/August/src/router/index.js import Vue from 'vue' import Router from 'vue-router' // import Login from '../pages/Login.vue' // import GameManager from '../pages/GameManager.vue' // import NavMenu from '../components/NavMenu.vue' // import Nav from '../components/Nav.vue' // // import AgeSet from '../pages/AgeSet.vue' // import GroupSet from '../pages/GroupSet.vue' // import RuleSet from '../pages/RuleSet.vue' // import UpLoad from '../pages/UpLoad.vue' // import SingleSign from '../pages/SingleSign.vue' import ErrorPage from '../components/404.vue' import Store from '../store' import {Message} from 'element-ui' Vue.use(Router) const Login = r => require.ensure([], () => r(require('../pages/Login.vue'))) const GameManager = r => require.ensure([], () => r(require('../pages/GameManager.vue'))) const NavMenu = r => require.ensure([], () => r(require('../components/NavMenu.vue'))) const Nav = r => require.ensure([], () => r(require('../components/Nav.vue'))) const AgeSet = r => require.ensure([], () => r(require('../pages/AgeSet.vue'))) const GroupSet = r => require.ensure([], () => r(require('../pages/GroupSet.vue'))) const RuleSet = r => require.ensure([], () => r(require('../pages/RuleSet.vue'))) const UpLoad = r => require.ensure([], () => r(require('../pages/UpLoad.vue'))) const SingleSign = r => require.ensure([], () => r(require('../pages/SingleSign.vue'))) const UpLoadAll = r => require.ensure([], () => r(require('../pages/UpLoadAll.vue'))) const Order = r => require.ensure([], () => r(require('../pages/Order.vue'))) const Sign = r => require.ensure([], () => r(require('../pages/Sign.vue'))) const UEditor = r => require.ensure([], () => r(require('../pages/UEditor.vue'))) // const Login = () => import('@/pages/Login.vue') var sessionStorage = window.sessionStorage; const router = new Router({ mode:'history', routes: [ { path:'/T', name:'T', component:UEditor }, { path: '/Login', name: 'Login', component:Login },{ path:'/GameManager', name:'GameManager', component:GameManager },{ path:'/NavMenu', name:'NavMenu', component:NavMenu },{ path:'/Nav', name:'Nav', component:Nav, children:[ { path:'/Nav/AgeSet', name:'AgeSet', component:AgeSet, },{ path:'/Nav/GroupSet', name:'GroupSet', component:GroupSet },{ path:'/Nav/RuleSet', name:'RuleSet', component:RuleSet },{ path:'/Nav/UpLoad', name:'UpLoad', component:UpLoad, },{ path:'/Nav/SingleSign', name:'SingleSign', component:SingleSign },{ path:'/Nav/UpLoadAll', name:'UpLoadAll', component:UpLoadAll },{ path:'/Nav/Order', name:'Order', component:Order },{ path:'/Nav/Sign', name:'Sign', component:Sign } ] }, ] }) // router.afterEach((to,from)=>{ // if(from.name != 'Login'){ // let sessionStorageIsLoginState = sessionStorage.getItem('isLoginState'); // if(sessionStorageIsLoginState!=null&&sessionStorageIsLoginState!=''&&sessionStorageIsLoginState==='1'){ // Store.state.isLogin = 1; // } // } // // }) // // router.beforeEach((to,from,next)=>{ // if(to.name !== 'Login'){ // if(Store.state.isLogin == 1){ // next(); // }else if(Store.state.isLogin == 0){ // next({path:'/Login'}); // return // } // }else{ // next(); // } // // }) export default router <file_sep>/August/README.md # 轮滑管理系统 > A Vue.js project ## Build Setup ``` bash # install dependencies npm install # serve with hot reload at localhost:8080 npm run dev # build for production with minification npm run build # build for production and view the bundle analyzer report npm run build --report # run unit tests npm run unit # run e2e tests npm run e2e # run all tests npm test ``` For a detailed explanation on how things work, check out the [guide](http://vuejs-templates.github.io/webpack/) and [docs for vue-loader](http://vuejs.github.io/vue-loader). #功能说明 >登陆功能 ``` 1、获取用户输入,发送请求验证。 通过 - 进入赛事管理页面 失败 - 反馈失败信息给用户 2、所以页面内置退出按钮,可一退回登陆页面。 3、赛事管理页面后退即可退回登陆页面。 Axios 请求验证用户账号密码 Vuex关联 state - isLogin 是否登陆 0否 1是 mutations - changeIsLogin (state,b) b为整型 ``` >赛事选择 ``` 1、获取赛事列表 mounted - 挂载即获取 成功 - 有数据 失败 - 暂无数据 2、新建赛事 填写相应表单新建 3、进入赛事 点击查看按钮进入NavMenu (1)记录matchId、matchName到Vuex中 (2)使用sessionStorage储存到本地 Axios 1、获取赛事 2、新建赛事 Vuex state - matchId、matchName mutation - changeMatchId、changeMatchName SessionStorage matchId、matchName ```
7b6cd30dcc51ba3d9cf0f405f88fb82a76954d9f
[ "JavaScript", "Markdown" ]
4
JavaScript
JCEDO1/ANLJC
42cbc2b710d2e3fbce16b713948d9a5fd21c3691
7f8362dde7399bc135280cc9602e396e57ab89af
refs/heads/master
<repo_name>nikbakht5/secured-psa-packetfilter<file_sep>/copy_psa_to_ned.sh #!/bin/bash # # This script copies the PSA codes into the NED v0.6 implementation folders, namely: # 1) PSCM/userList # 2) TVDM/psaConfigs/[psaID] folder # 3) TVDM/PSAManifest/[psaID] file # 4) TVDM/userGraph/[psaID] file # # One parameter is required - the full path to your destination NED v0.5.1 dir, e.g., /home/ned/NED/. # Note: This will overwrite existing configurations for the PSA_ID and the USER inside your NED! if [ $# -ne 1 ] ; then echo "Usage: $0 [Full path to NED directory where the PSA files are to be copied (e.g., /home/ned/NED/)]" exit 1 fi NED_VERSION=v0.5.1 # Note: If you use this for other PSAs, please rename the PSA_ID as such (the config folders have to match in NED_files/TVDM/)! PSA_ID="iptablesPSA" USER="test" PW=" <PASSWORD>" PSCM_PATH=$1PSCM/ NED_PATH=$1 USER_LIST=userList TEMPLATES=NED_files_template/TVDM/ if [ ! -f $PSCM_PATH$USER_LIST ]; then echo "$PSCM_PATH$USER_LIST file does not exist." echo "Usage: $0 [full path to NED directory where the PSA files are to be copied (e.g., /home/ned/NED/)]" exit 1 fi # 1 ################################################################################# echo "Checking if PSA user exists in PSCM/userList" user_pw=" <PASSWORD>" user_cred=$PSA_ID$user_pw if grep -q "$USER" $PSCM_PATH"$USER_LIST"; then echo "User existed in PSCM/userList, skipping creation of new user." else echo "User not in PSCM/userList file, creating new user." echo $USER$PW >> $PSCM_PATH$USER_LIST fi # 2 ################################################################################# echo "Copying PSA files into NED $NED_VERSION folders" cp -avr NED_files/TVDM $NED_PATH <file_sep>/PSA/psaEE.py # # File: psaEE.py # Created: 27/08/2014 # Author: BSC # # Description: # Web service running on the PSA interacting with the PSC # # import falcon import json import Config import logging import subprocess from execInterface import execInterface from getConfiguration import getConfiguration from psaExceptions import psaExceptions from dumpLogFile import dumpLogFile #old conf = Config.Configuration() date_format = "%m/%d/%Y %H:%M:%S" log_format = "[%(asctime)s.%(msecs)d] [%(module)s] %(message)s" logging.basicConfig(filename=conf.LOG_FILE,level=logging.DEBUG,format=log_format, datefmt=date_format) #older logging #logging.basicConfig(filename=conf.LOG_FILE,level=logging.DEBUG,format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') pscAddr = conf.PSC_ADDRESS configsPath = conf.PSA_CONFIG_PATH psaID = conf.PSA_ID #confID = conf.CONF_ID logging.info("--------") logging.info("PSA EE init.") logging.info("PSA ID: " + str(psaID)) logging.info("PSA NAME: " + str(conf.PSA_NAME)) logging.info("PSA VERSION: " + str(conf.PSA_VERSION)) logging.info("PSA-PSC API version: " + str(conf.PSA_API_VERSION)) logging.info("PSA log location: " + str(conf.PSA_LOG_LOCATION)) logging.info("--------") # instantiate class object to manage REST interface to the PSC execIntf = execInterface(configsPath, conf.PSA_SCRIPTS_PATH, conf.PSA_LOG_LOCATION, psaID) #confHand = getConfiguration(pscAddr, configsPath, confID, psaID) confHand = getConfiguration(pscAddr, configsPath, conf.PSA_SCRIPTS_PATH, psaID, str(conf.PSA_API_VERSION)) # start the HTTP falcon proxy and adds reachable resources as routes app = falcon.API() #app.add_route('/execInterface', excIntf) app.add_route("/" + str(conf.PSA_API_VERSION) + '/execInterface/{command}', execIntf) dumpLog = dumpLogFile() #FOR DEBUGGING ONLY, REMOVE IN PRODUCTION app.add_route("/" + str(conf.PSA_API_VERSION) + '/execInterface/dump-log-ctrl', dumpLog) logging.info("execInterface routes added.") # Inform our PSC that we are up #TODO ''' try: start_res = confHand.send_start_event() # We don't need to enable anything #proc = subprocess.Popen(confScript, stdout=subprocess.PIPE, shell=True) #(out, err) = proc.communicate() except psaExceptions as exc: pass ''' # Pull configuration and start the PSA. try: confScript = confHand.pullPSAconf() execIntf.callStartScript() except psaExceptions as exc: pass logging.info("PSA start done.") # http request to ask for the configuration and start the script ''' try: confScript = confHand.pullPSAconf() proc = subprocess.Popen(confScript, stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() except psaExceptions as exc: pass ''' <file_sep>/PSA/scripts/current_config.sh #!/bin/bash # # current_config.sh # # This script is called by the PSA API when the PSA's current runtime configuration is requested. # # Return value: # Current configuration # COMMAND_OUTPUT="$(cat /home/psa/pythonScript/psaConfigs/psaconf)" printf '%s\n' "${COMMAND_OUTPUT[@]}" exit 1; <file_sep>/PSA/scripts/status.sh #!/bin/bash # # status.sh # # This script is called by the PSA API when the PSA's runtime status is requested. # # Return value: # 1: PSA is alive # 0: PSA not running correctly. # STATUS_OUTPUT="$(iptables -L)" len=${#STATUS_OUTPUT} # Just a quick hack: iptables -L length with empty config is 274, so check that there's something if [ $len -gt 273 ] then echo 1 else echo 0 fi exit 1; <file_sep>/PSA/execInterface.py # # File: execInterface.py # Created: 27/08/2014 # Author: BSC, VTT # # Description: # Web service running on the PSA receiving the configuration for the PSA from the PSC # # import falcon import logging import json import sys import subprocess import os import stat class execInterface(): def __init__(self, configsPath, scriptsPath, psaLogLocation, psaID): self.confsPath = configsPath self.scripts_path = scriptsPath self.log_location = psaLogLocation self.psaID = psaID def on_post(self, request, response, command): print "onPost" try: res = {} res["command"] = command if command == "init": script_file = self.confsPath + "/psaconf" fp=open(script_file, 'wb') while True: chunk = request.stream.read(4096) fp.write(chunk) if not chunk: break fp.close() # Make script executable for current user # hazardous.. we're root #st = os.stat(script_file) #os.chmod(script_file, st.st_mode | stat.S_IEXEC) # Run the init.sh and return it's return value res["ret_code"] = str(self.callInitScript()) logging.info("PSA "+self.psaID+" configuration registered") elif command == "start": res["ret_code"] = str(self.callStartScript()) elif command == "stop": res["ret_code"] = str(self.callStopScript()) else: logging.info("POST: unknown command: " + command) response.status = falcon.HTTP_404 return response.body = json.dumps(res) response.status = falcon.HTTP_200 response.set_header("Content-Type", "application/json") except Exception as e: logging.exception(sys.exc_info()[0]) response.status = falcon.HTTP_501 def on_get(self, request, response, command): try: res = {} res["command"] = command if command == "status": res["ret_code"] = self.callStatusScript().replace("\n", "") elif command == "configuration": res["ret_code"] = self.callGetConfigurationScript() elif command == "internet": res["ret_code"] = self.callGetInternetScript() elif command == "log": # Return PSA log or 501 log = self.callGetLogScript() if log != None: response.body = log response.status = falcon.HTTP_200 response.set_header("Content-Type", "text/plain; charset=UTF-8") else: #res["ret_code"] = "not_available" #response.body = json.dumps(res) #response.set_header("Accept", "application/json") response.status = falcon.HTTP_501 return else: logging.info("GET: unknown command: " + command) response.status = falcon.HTTP_404 return response.body = json.dumps(res) response.status = falcon.HTTP_200 response.set_header("Content-Type", "application/json") except Exception as e: logging.exception(sys.exc_info()[0]) response.status = falcon.HTTP_501 def callInitScript(self): logging.info("callInitScript()") ret = subprocess.call(['.' + self.scripts_path + 'init.sh']) return ret def callStartScript(self): logging.info("callStartScript()") ret = subprocess.call(['.' + self.scripts_path + 'start.sh']) return ret def callStopScript(self): logging.info("callStopScript()") ret = subprocess.call(['.' + self.scripts_path + 'stop.sh']) return ret def callStatusScript(self): proc = subprocess.Popen(['.' + self.scripts_path + 'status.sh'], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() return out def callGetConfigurationScript(self): logging.info("callGetConfigurationScript()") proc = subprocess.Popen(['.' + self.scripts_path + 'current_config.sh'], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() return out def callGetInternetScript(self): logging.info("callGetInternetScript()") proc = subprocess.Popen(['.' + self.scripts_path + 'ping.sh'], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() return out def callGetLogScript(self): logging.info("callGetLogScript()") ret = None try: with open(self.log_location, "r") as f: ret = f.read() except Exception as e: logging.exception(sys.exc_info()[0]) return ret def get_client_address(self,environ): try: return environ['HTTP_X_FORWARDED_FOR'].split(',')[-1].strip() except KeyError: return environ['REMOTE_ADDR'] <file_sep>/PSA/psaExceptions.py # # File: psaExceptions.py # Created: 05/09/2014 # Author: BSC # # Description: # Custom execption class to manage error in the PSC # class psaExceptions(): class confRetrievalFailed(Exception): pass <file_sep>/PSA/getConfiguration.py # # File: getConfiguration.py # Created: 05/09/2014 # Author: BSC # Modified: 29/10/2015 # Author: VTT # # Description: # Web service running on the PSA interacting with the PSC # # import json import requests import logging from psaExceptions import psaExceptions import subprocess import base64 class getConfiguration(): def __init__(self, pscAddr, configsPath, scriptsPath, psaID, psaAPIVersion): self.pscAddr = pscAddr self.configsPath = configsPath self.scripts_path = scriptsPath self.psaID = psaID self.psaAPI = psaAPIVersion def send_start_event(self): logging.info("PSA: send_start_event") logging.info("PSA: "+self.psaID+" calling PSC") resp = requests.get(self.pscAddr + "/" + self.psaAPI + "/psa_up/" + self.psaID) logging.info("PSA: "+self.psaID+" calling PSC done") return resp.content def pullPSAconf(self): header = {'Content-Type':'application/octet-stream'} resp = requests.get(self.pscAddr + "/" +self.psaAPI + "/getConf/"+self.psaID, headers=header) if (resp.status_code == requests.codes.ok): json_config = False try: conf = json.loads(resp.content) logging.info("PSA JSON conf received:") logging.info(conf) # Handle different config formats if conf["conf_type"] == "base64": decoded_conf = base64.b64decode(conf["conf"]) elif conf["conf_type"] == "text": decoded_conf = conf["conf"] else: # Use default format, presume text. decoded_conf = conf["conf"] json_config = True except Exception as e: logging.info("Could not load JSON config, reverting to old text format") decoded_conf = resp.content fp=open(self.configsPath+"/psaconf", 'wb') fp.write(decoded_conf) fp.close() self.callInitScript() if json_config: self.enforceConfiguration(conf) logging.info("PSA "+self.psaID+" configuration registered") return resp.content else: logging.error("Bad configuration request for PSA "+self.psaID) raise psaExceptions.confRetrievalFailed() def callInitScript(self): logging.info("callInitScript()") ret = subprocess.call(['.' + self.scripts_path + 'init.sh']) return ret def enforceConfiguration(self, jsonConf): req_keys = ("IP", "dns", "netmask", "gateway") has_req = False if all (key in jsonConf for key in req_keys): has_req = True if has_req: logging.info("PSA requires IP, configuring...") ip = jsonConf["IP"] dns = jsonConf["dns"] netmask = jsonConf["netmask"] gateway = jsonConf["gateway"] logging.info("ip: " + str(ip)) logging.info("gateway: " + str(gateway)) logging.info("dns: " + str(dns)) logging.info("netmask: " + str(netmask)) ret = subprocess.call(['.' + self.scripts_path + 'ip_conf.sh', ip, gateway, dns, netmask]) logging.info("Result of setting config: " + str(ret)) else: logging.info("PSA doesn't require IP, skipping configuration.") <file_sep>/PSA/scripts/stop.sh #!/bin/bash # # stop.sh # # This script is called by the PSA API when the PSA is requested to be stopped. # # We don't need to save current config #iptables-save > psaConfigs/12345 # Flush iptables iptables -F iptables -X iptables -t nat -F iptables -t nat -X iptables -t mangle -F iptables -t mangle -X iptables -P INPUT ACCEPT iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT echo "PSA Stopped" exit 1; <file_sep>/README.md # 1. End-user ## 1.1 Description / general readme This PSA implements a classical firewall application. It makes possible to allow or deny specific traffic by specifying a category or a list (whitelist or blacklist). The available traffic category are: * Internet traffic: i.e. the traffic of the public network * Intranet traffic: i.e. the traffic of the internal network defined by a list of IP addresses * DNS traffic: i.e. the traffic that uses port UDP/53 * VOIP traffic: i.e. the traffic that belongs to the following set of ports: 5060/UDP, 5060/TCP, 5061/UDP, 5061/TCP, 389/TCP, 4000/TCP-4005/TCP, 522/TCP, 1731/TCP, 1720/TCP, 16384/UDP-32767/UDP * all traffic: i.e. every type of traffic A list (whitelist or blacklist) contains a set of IP addresses that must be allowed or blocked. A list is defined as XML file packed into the SECURED GGUI. Currently, the provided predefined lists are: * antiparental_control_proxies: that contains the list of IP addresses of proxies that could be used for bypassing parental control. This is typically used as a blacklist * family_shield_dns: that contains the list of approved DNS servers. This is typically used as a whitelist. ## 1.2 Features / Capabilities The list of capabilities are (extracted from manifest): * L4 filtering The L4 filtering capability is equivalent to classical firewall functionality. Therefore, this capability permits to allow and deny traffic identified by IP addresses. ## 1.3 Security policy examples The following examples list *all possibly policies* that can be enabled from the SECURED GGUI. Note that the following policies are also available by considering *is authorized to access* and by omitting the name of the user. ``` Alice is not authorized to access Internet traffic (traffic_target, {antiparental_control_proxies}) ``` - This policy configures iptables PSA to block use of proxies for the IP address of Alice. The list of proxies are defined into a blacklist (XML) file, packed into the SECURED GGUI. ``` Alice is authorized to access Internet traffic (time period, {18:30-20:00 Europe/Rome}) ``` - This policy configures iptables PSA to allow Internet traffic for IP address of Alice only between 18:30 and 20:00 considering the timezone of Europe/Rome. ``` Alice is not authorized to access Internet traffic ``` - This policy configures iptables PSA to block Internet traffic for the IP address of Alice. ``` Alice is not authorized to access Intranet traffic ``` - This policy configures iptables PSA to block Intranet traffic for the IP address of Alice. ``` Alice is not authorized to access DNS traffic ``` - This policy configures iptables PSA to block DNS traffic for the IP address of Alice. As described above, the blocked port is 53/UDP. ``` Alice is authorized to access DNS traffic (traffic_target, {family_shield_dns}) ``` - This policy configures iptables PSA to allow DNS traffic (only coming from/to the approved set of DNS servers) for the IP address of Alice. As described above, the family_shield_dns is a whitelist. ``` Alice is not authorized to access VOIP traffic ``` - This policy configures iptables PSA to block VOIP traffic for the IP address of Alice. As described above, the blocked ports are: 5060/UDP, 5060/TCP, 5061/UDP, 5061/TCP, 389/TCP, 4000/TCP-4005/TCP, 522/TCP, 1731/TCP, 1720/TCP, 16384/UDP-32767/UDP. ``` Alice is not authorized to access all traffic ``` - This policy configures iptables PSA to block all traffic for the IP address of Alice. Note: the set of policies defined for a user must have the same action (*is authorized to access* or *is not authorized to access*). ## 1.4 Support, troubleshooting / known issues If there are any known issues, list them here. # 2. Developer / admin ## Description / general readme iptables PSA has born with the aim to permit and block communications up to layer 4 of the ISO/OSI stack. Conceptually this PSA is transparent to user, once it is enabled from the NED client. ## Components and Requirements VM technology allows creating a full system for the PSA. The components used in this PSA are: * Operative System: Debian 7 "wheezy" * iptables * brigde-utils * xtables-addons-common * python * gunicorn * pip * falcon * requests The most important requirement is the need of an IP address in the PSA belonging to the same LAN than End user. ## Detailed architecture There is only a component in the internal architecture: * **L4 Filtering**. iptables allows to implement a transparent filtering up to layer 4 traffic in the bridge from the user side interface (eth0) to the Internet side (eth1). ![iptables PSA](docs/PSA_iptables_internal.jpg) ## Virtual machine image creation The procedure to create a valid PSA image from scratch start with the prerequisite instructions defined in [PSA Developer guide](https://github.com/SECURED-FP7/secured-psa-develop-test) to obtain a valid base image for PSA. Install the software netfilter/iptables. ``` apt-get install iptables ``` Change passwords for user 'root' and user 'psa' for security reasons. ## Support, troubleshooting / known issues Currently, no issues are reported. ## Files required In order to make PSA running correctly no additional files are required. ### PSA application image PSA is based on a Virtual machine image in KVM- kernel module format ".img". A [sample image has been included](https://vm-images.secured-fp7.eu/images/priv/iptables_time.img) in the project. ### Manifest The PSA manifest is available at [Manifest](docs/iptables_Manifest.xml). And reflects the capabilities described below. This file must be stored in the PSAR. ### HSPL The HSLP is define as follows: * D4.1 Format: ``` Alice is not authorized to access Internet traffic (traffic_target, {antiparental_control_proxies}) ``` ``` Alice is authorized to access Internet traffic (time period, {18:30-20:00 Europe/Rome}) ``` * More friendly expression Deny Internet access to proxies for Alice Authorize Internet access from 18:30 to 20:00 considering Europe/Rome timezone ### MSPL An example of MSPL for this PSA are accesible at SPM project. [MSPL.xml](docs/MSPL.xml) is a configuration that denies Internet access to Alice. [MSPL_iptables.xml](docs/MSPL.xml) is a configuration that blocks some traffic during working hours. ### M2L Plug-in The M2l plug-in is available at [M2LPlugin](https://github.com/SECURED-FP7/secured-spm/blob/master/M2LService/code/M2LPluginIptables/src/eu/securedfp7/m2lservice/plugin/M2LPlugin.java) Current version of this plugin will generate different possible low level configurations. Some examples are available at [Config](https://github.com/SECURED-FP7/secured-spm/blob/master/M2LService/code/M2LPluginIptables) This plugin do not need additional external information in this version that must be store in the PSAR. ## Features/Capabilities The list of capabilities are (extracted from manifest): * L4 Filtering. ## Testing Testing scripts are available at [test folder](tests) # 3. License Please refer to project LICENSE file. # Additional Information ## Partners involved * Application: POLITO * MSPL: POLITO * M2L Plugin: POLITO # Status (OK/No/Partial) * OK # TODO: Software improvements: * nothing # Schedule * 05/04/2016. Updates on HSPL, security policy examples and virtual machine image creation * 16/03/2016. Basic documentation inserted <file_sep>/PSA/README.md # Software for PSA Execution Environment (*ctrlmgmtd* agent) These files or functionality need to be a part of the PSA Execution Environment template. <file_sep>/tests/NEDtest.py ''' This library contains functions to execute NED test scripts ''' import time import selenium, re from selenium import webdriver #################################### #TEST CONNECTION AND LOGGING IN/OUT# #################################### def login(driver, username, password, login_address): try: driver.get(login_address) except: print "In webpage title: %s" % driver.title assert 0, timeout(login_address) driver.find_element_by_id("input-username").clear() driver.find_element_by_id("input-username").send_keys(username) driver.find_element_by_id("input-password").clear() driver.find_element_by_id("input-password").send_keys(<PASSWORD>) driver.find_element_by_id("submit").click() def logout(driver): try: driver.find_element_by_id("logout").click() except: assert 0, 'Could not found element \"logout\" from page %s' % driver.current_url assert driver.find_element_by_id("login-form"), "Could not found login-form" def allowedWebpage(driver, webpage): try: driver.get(webpage) except: print "In webpage title: %s" % driver.title assert 0, timeout(webpage) def blockedWebpage(driver, webpage, title): timeout = 'FALSE' try: driver.get(webpage) except: timeout = 'TRUE' print 'Website title: %s' % driver.title print 'Expected website title: %s' % title print 'Timeout occured: %s' % timeout if 'Problem loading page' in driver.title: timeout = 'TRUE' elif title in driver.title: assert 0, notBlocked(webpage) elif timeout == 'FALSE': assert 0, problemLoading(driver.title, webpage) return timeout def connectionNotloggedin(driver): webpage = 'http://www.secured-fp7.eu' title = 'SECURED' noConnection = 'FALSE' try: driver.get(webpage) except: noConnection = 'TRUE' if 'Problem loading page' in driver.title: noConnection = 'TRUE' elif title in driver.title: assert 0, 'User had access to SECURED website before logging in to NED' elif noConnection == 'FALSE': assert 0, problemLoading(driver.title, webpage) return noConnection def getUserIPfromPSC(driver, manager_address): userIP = '' try: driver.get(manager_address) except: print "In webpage title: %s" % driver.title assert 0, timeout(manager_address) try: userIP = driver.find_element_by_id("user-ip").text except: print "In webpage title: %s" % driver.title assert 0, 'Could not found element \"user-ip\" from %s' % manager_address print "User\'s IP is: %s" % userIP return userIP def checkSECUREDok(driver, manager_address): manager_counter = 0 time_counter = 0 counter_timeout = 60 interval = 5 status_text = '' start_time = 0.000 start_time = time.time() while True: try: driver.get(manager_address) if manager_counter >= counter_timeout: print "Try: In webpage title: %s" % driver.title assert 0, timeout(manager_address) if driver.title != 'Problem loading page': break else: time.sleep(interval) manager_counter += interval except: if manager_counter >= counter_timeout: print "Except: In webpage title: %s" % driver.title assert 0, timeout(manager_address) time.sleep(interval) manager_counter += interval while True: try: status_text = driver.find_element_by_id("status").text except: if time_counter >= counter_timeout: assert 0, 'Could not found status text. Status text: %s' % (status_text) time.sleep(interval) time_counter += interval if 'wait' in status_text: if time_counter >= counter_timeout: assert 0, 'It took over %d seconds to load PSA(s)\n %s' % (counter_timeout, status_text) time.sleep(interval) time_counter += interval elif 'OK' in status_text: print 'It took %.3f seconds to load PSA(s)' % (time.time() - start_time) break elif 'Error' in status_text: print driver.find_element_by_id('page').text assert 0, 'Text error in status text' ######### #LOGGING# ######### def getLogAddress(driver, manager_address, log_address): ip = [] ip_list = [] try: driver.get(manager_address) except: print "In webpage title: %s" % driver.title timeout(manager_address) try: ip = re.findall(r'[0-9]+(?:\.[0-9]+){3}', driver.find_element_by_id("psa-list-online").text) except: print "Not able to found IP number from element psa-list-online" print "In webpage title: %s" % driver.title for x in ip: ip_list.append(log_address + x) return ip_list def writeLog(driver, logPath, logAddress): logFile = open(logPath, 'w+') try: driver.get(logAddress) except: print "In webpage title: %s" % driver.title timeout(logAddress) try: logFile.write(driver.find_element_by_xpath('/html/body/pre').text + '\n') except: print "Not able to write dump log file from %s to %s" % (logAddress, logPath) logFile.close() ################ #ERROR HANDLING# ################ def timeout(url): print "Could not load page %s. Connection timed out." % url def notBlocked(url): print "User had access to blocked page %s." % url def problemLoading(title, webpage): print '\"%s\" reported in %s title. Connection should timeout.' % (title, webpage) def emptyList(listname): print "IP address list %s is empty." % listname def titleNotfound(expected, found): print 'Text \"%s\" not found in webpage title. Found \"%s\" instead' % (expected, found) <file_sep>/PSA/scripts/start.sh #!/bin/bash # # start.sh # # This script is called by the PSA API when the PSA is requested to be started. # Load PSA's current configuration iptables-restore < psaConfigs/psaconf echo "PSA Started" exit 1; <file_sep>/PSA/scripts/init.sh #!/bin/bash # # init.sh # # This script is called by the PSA API when the PSA's is initialized and psaconf file is saved to psaConfigs/ folder. # This script should do what is required with that configuration and peform any other initialization tasks. # After this has been executed the PSA should be startable by calling START (start.sh). # # Return value: # 1: init ok # 0: init not ok # exit 1;
0a5f6428e8ee10811b398f73c52e6f252f4c55d9
[ "Markdown", "Python", "Shell" ]
13
Shell
nikbakht5/secured-psa-packetfilter
82705ca9ba62e0525d093f61e7286c7cb48f4fba
73bc18b536266d77f8478dde11475aa1d2f2031b
refs/heads/master
<file_sep>package main import ( "encoding/json" "log" "net/http" "github.com/zenazn/goji" "github.com/zenazn/goji/web" ) func setupWebRoutes(config *MailServer) { goji.Get("/status", func(c web.C, w http.ResponseWriter, r *http.Request) { status(config, c, w, r) }) goji.Get("/mail", func(c web.C, w http.ResponseWriter, r *http.Request) { allMails(config, c, w, r) }) goji.Get("/inbox/:email", func(c web.C, w http.ResponseWriter, r *http.Request) { inbox(config, c, w, r) }) goji.Get("/email/:id", func(c web.C, w http.ResponseWriter, r *http.Request) { mailByID(config, c, w, r) }) goji.Delete("/inbox/:email", func(c web.C, w http.ResponseWriter, r *http.Request) { deleteMails(config, c, w, r) }) goji.Delete("/email/:id", func(c web.C, w http.ResponseWriter, r *http.Request) { deleteByID(config, c, w, r) }) } func status(config *MailServer, c web.C, w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) } func databaseToJSON(mails []MailConnection) []byte { result, err := json.MarshalIndent(mails, "", " ") if err != nil { log.Panic(err) } return result } func allMails(config *MailServer, c web.C, w http.ResponseWriter, r *http.Request) { w.Write(databaseToJSON(config.database)) } func inbox(config *MailServer, c web.C, w http.ResponseWriter, r *http.Request) { email := c.URLParams["email"] var result []MailConnection for _, msg := range config.database { if msg.To == email { result = append(result, msg) } } if len(result) == 0 { http.NotFound(w, r) } w.Write(databaseToJSON(result)) } func mailByID(config *MailServer, c web.C, w http.ResponseWriter, r *http.Request) { id := c.URLParams["id"] found := false for _, msg := range config.database { if msg.MailId == id { jsonData := databaseToJSON(config.database) w.Write(jsonData) found = true } } if !found { http.NotFound(w, r) } } func deleteMails(config *MailServer, c web.C, w http.ResponseWriter, r *http.Request) { email := c.URLParams["email"] var result []MailConnection for _, msg := range config.database { if msg.To != email { result = append(result, msg) } } config.database = result } func deleteByID(config *MailServer, c web.C, w http.ResponseWriter, r *http.Request) { id := c.URLParams["id"] var result []MailConnection log.Println("Deleting ", id) for _, msg := range config.database { if msg.MailId != id { result = append(result, msg) } } config.database = result } <file_sep># Moved to https://gitlab.com/sorenmat/gosmtpd # A very simple SMTP server with a REST API [![Build Status](https://drone.io/github.com/sorenmat/gosmtpd/status.png)](https://drone.io/github.com/sorenmat/gosmtpd/latest) [![Coverage Status](https://coveralls.io/repos/sorenmat/gosmtpd/badge.svg)](https://coveralls.io/r/sorenmat/gosmtpd) A server that accepts smtp request and saves the emails in memory for later retrieval. ## Usage ```shell usage: gosmtpd [<flags>] Flags: --help Show help (also see --help-long and --help-man). --webport="8000" Port the web server should run on --hostname="localhost" Hostname for the smtp server to listen to --port="2525" Port for the smtp server to listen to --forwardhost=FORWARDHOST The hostname after the @ that we should forward i.e. gmail.com --forwardsmtp=FORWARDSMTP SMTP server to forward the mail to --forwardport="25" The port on which email should be forwarded --forwarduser=FORWARDUSER The username for the forward host --forwardpassword=FORWARDPASSWORD Password for the user --mailexpiration=300 Time in seconds for a mail to expire, and be removed from database --version Show application version. ``` ## GET /status Returns a 200 if the service is up ## GET /mail List all mails ## GET /inbox/:email List all email for a given email address ## GET /email/:id Get an email by id ## DELETE /inbox/:email Delete all mails for a given email ## DELETE /email/:id Delete a email via the id # Trying it out You can install it by doing ``docker pull sorenmat/gosmtpd`` ``docker start sorenmat/gosmtpd`` # Building gosmtpd are using vendoring to keep track of dependencies, we are using govendor for this. `go get -u github.com/kardianos/govendor´ To download the dependencies do `govendor sync` This is a extremely modified version of https://github.com/bradfitz/go-smtpd all credits goes to @bradfitz <file_sep>#!/bin/bash ./gosmtpd <file_sep>package main import "strings" func isCommand(str, substr string) bool { trimmed := strings.ToUpper(strings.Trim(str, " \n\r")) return strings.Index(trimmed, substr) == 0 } <file_sep>package main import ( "errors" "io" "log" "net" "net/mail" "strconv" "strings" "time" ) func (mc *MailConnection) resetDeadLine() { mc.connection.SetDeadline(time.Now().Add(timeout * time.Second)) } func (mc *MailConnection) nextLine() (string, error) { return mc.reader.ReadString('\n') } func (mc *MailConnection) inDataMode() bool { return mc.state == READ_DATA } // Flush the response buffer to the n func (mc *MailConnection) flush() bool { mc.resetDeadLine() size, err := mc.writer.WriteString(mc.response) mc.writer.Flush() mc.response = mc.response[size:] if err != nil { if err == io.EOF { // connection closed return false } if neterr, ok := err.(net.Error); ok && neterr.Timeout() { // a timeout return false } } if mc.dropConnection { return false } return true } func processClientRequest(mc *MailConnection) { defer mc.connection.Close() greeting := "220 " + mc.mailserver.hostname + " SMTP goSMTPd #" + mc.MailId + " " + time.Now().Format(time.RFC1123Z) for i := 0; i < 100; i++ { switch mc.state { case INITIAL: answer(mc, greeting) mc.state = NORMAL case NORMAL: handleNormalMode(mc) case READ_DATA: var err error mc.Data, err = readFrom(mc) if err == nil { if status := mc.mailserver.saveMail(mc); status { answer(mc, "250 OK : queued as "+mc.MailId) } else { answer(mc, "554 Error: transaction failed.") } } else { log.Printf("DATA read error: %v\n", err) } mc.state = NORMAL } cont := mc.flush() if !cont { return } } } func handleNormalMode(mc *MailConnection) { line, err := readFrom(mc) if err != nil { return } switch { case isCommand(line, HELLO): if len(line) > 5 { mc.helo = line[5:] } answer(mc, "250 "+*hostname+" Hello ") case isCommand(line, EHLO): if len(line) > 5 { mc.helo = line[5:] } answer(mc, "250-"+*hostname+" Hello "+mc.helo+"["+mc.address+"]"+"\r\n") answer(mc, "250-SIZE "+strconv.Itoa(mailMaxSize)+"\r\n") answer(mc, "250 HELP") case isCommand(line, MAIL_FROM): if len(line) > 10 { mc.From = line[10:] } answer(mc, OK) case isCommand(line, RCPT_TO): if len(line) > 8 { mc.recepient = append(mc.recepient, line[8:]) mc.To = line[8:] } answer(mc, OK) case isCommand(line, DATA): answer(mc, "354 Start mail input; end with <CRLF>.<CRLF>") mc.state = READ_DATA case isCommand(line, NO_OP): answer(mc, OK) case isCommand(line, RESET): mc.From = "" mc.To = "" answer(mc, OK) case isCommand(line, "QUIT"): answer(mc, "221 Goodbye") killClient(mc) default: answer(mc, "500 5.5.1 Unrecognized command.") } } func answer(mc *MailConnection, line string) { mc.response = line + "\r\n" } func killClient(mc *MailConnection) { mc.dropConnection = true } func getTerminateString(state State) string { terminateString := "\r\n" if state == READ_DATA { // DATA state terminateString = "\r\n.\r\n" } return terminateString } func readFrom(mc *MailConnection) (input string, err error) { var read string terminateString := getTerminateString(mc.state) for err == nil { mc.resetDeadLine() read, err = mc.nextLine() if err != nil { break } if read != "" { input = input + read if len(input) > mailMaxSize { err = errors.New("DATA size exceeded (" + strconv.Itoa(mailMaxSize) + ")") return input, err } if mc.inDataMode() { scanForSubject(mc, read) } } if strings.HasSuffix(input, terminateString) { break } } return input, err } func scanForSubject(mc *MailConnection, line string) { if mc.Subject == "" && strings.Index(strings.ToUpper(line), SUBJECT) == 0 { mc.Subject = line[9:] } else if strings.HasSuffix(mc.Subject, "\r\n") { // remove the newline stuff mc.Subject = mc.Subject[0 : len(mc.Subject)-2] if (strings.HasPrefix(line, " ")) || (strings.HasPrefix(line, "\t")) { // multiline subject mc.Subject = mc.Subject + line[1:] } } } func isEmailAddressesValid(mc *MailConnection) error { if from, err := cleanupEmail(mc.From); err == nil { mc.From = from } else { log.Println("From is not valid") return err } if to, err := cleanupEmail(mc.To); err == nil { mc.To = to } else { log.Println("To is not valid: ", mc.To) return err } return nil } func cleanupEmail(str string) (email string, err error) { address, err := mail.ParseAddress(str) if err != nil { return "", err } return address.Address, nil } <file_sep>package main import ( "bytes" "crypto/rand" "encoding/json" "fmt" "io/ioutil" "log" "net" "net/http" "net/smtp" "sync" "testing" "time" ) var mailconfig = MailServer{port: "2525", httpport: "8000", forwardEnabled: false, expireinterval: 1, mu: &sync.Mutex{}} func init() { go serve(&mailconfig) } func getMailConnection(email string) ([]MailConnection, int) { resp, err := http.Get("http://localhost:8000/inbox/" + email) if err != nil { log.Fatal(err) } decoder := json.NewDecoder(resp.Body) var d []MailConnection decoder.Decode(&d) return d, resp.StatusCode } func getAllMails() ([]MailConnection, int) { resp, _ := http.Get("http://localhost:8000/mail") decoder := json.NewDecoder(resp.Body) var d []MailConnection decoder.Decode(&d) return d, resp.StatusCode } func BenchmarkSendMails(b *testing.B) { for i := 0; i < b.N; i++ { SendMailWithMessage("<EMAIL>", "message") } d, _ := getMailConnection("<EMAIL>") if b.N != len(d) { b.Errorf("Wrong number of email expected %d got %d\n", b.N, len(d)) } } func TestStatusResource(t *testing.T) { resp, _ := http.Get("http://localhost:8000/status") if resp.StatusCode != 200 { t.Error("Server should respond with status code 200") } body, _ := ioutil.ReadAll(resp.Body) if string(body) != "OK" { t.Errorf("Expected body to be ok but was '%s'\n", string(body)) } } func TestSendingMailWithMultilines(t *testing.T) { // PORT = getPort() // we need to force this, since we don't parse the commandline email_address := randomEmail() SendMailWithMessage(email_address, `This is a test`) d, _ := getMailConnection(email_address) if len(d) != 1 { t.Error("To many email ", len(d)) } //email, _ := getEmailByHash(d[0].MailId) // This is broken //if email.To == "" { // t.Errorf("To should not be empty was '%v'\n%v", email.To, d[0].MailId) //} } func TestSendingMail(t *testing.T) { SendMail("<EMAIL>") d, _ := getMailConnection("<EMAIL>") if len(d) != 1 { t.Error("To many email") } getEmailByHash(d[0].MailId) } func isMailBoxSize(email string, size int, t *testing.T) bool { d, _ := getMailConnection(email) if len(d) != size { t.Errorf("Wrong number of emails, expected %d but was %d", size, len(d)) return false } return true } func TestSendingMailsToMultipleReceivers(t *testing.T) { SendMails([]string{"<EMAIL>", "<EMAIL>", "<EMAIL>"}) isMailBoxSize("<EMAIL>", 1, t) isMailBoxSize("<EMAIL>", 1, t) isMailBoxSize("<EMAIL>", 1, t) } func TestSendingMailsToMultipleReceiversAndDeletingThem(t *testing.T) { SendMails([]string{"<EMAIL>", "<EMAIL>", "<EMAIL>"}) isMailBoxSize("<EMAIL>", 1, t) emptyMailBox("<EMAIL>") isMailBoxSize("<EMAIL>", 0, t) isMailBoxSize("<EMAIL>", 1, t) emptyMailBox("<EMAIL>") isMailBoxSize("<EMAIL>", 0, t) isMailBoxSize("<EMAIL>", 1, t) emptyMailBox("<EMAIL>") isMailBoxSize("<EMAIL>", 0, t) } func TestSendingMailsToMultipleReceiversAndDeletingById(t *testing.T) { SendMails([]string{"<EMAIL>", "<EMAIL>", "<EMAIL>"}) mail, _ := getMailConnection("<EMAIL>") if len(mail) != 1 { t.Error("Wrong number of emails") } deleteEmailByID(mail[0].MailId) mails, _ := getMailConnection("<EMAIL>") if len(mails) != 0 { t.Error("Should be empty ,but was ", len(mails)) } mails, _ = getMailConnection("<EMAIL>") if len(mails) == 0 { t.Error("Was empty, but shouldn't be") } } func TestSendingMailAndDeletingIt(t *testing.T) { email := randomEmail() SendMail(email) d, _ := getMailConnection(email) if len(d) != 1 { t.Error("Expected one email got ", len(d)) } deleteEmailByID(d[0].MailId) d, _ = getMailConnection(email) if len(d) != 0 { t.Errorf("Not the correct number '%d' of emails\n ", len(d)) } } func TestMailExpiry(t *testing.T) { old := mailconfig.expireinterval defer func() { mailconfig.expireinterval = old }() log.Println("Starting expiray test !!") mails, _ := getAllMails() mailconfig.expireinterval = 1 for i := 0; i < 100; i++ { email := randomEmail() SendMail(email) } time.Sleep(4 * time.Second) after_mails, _ := getAllMails() if len(after_mails) != 0 { t.Error("All mails should have expired but found ", len(after_mails)) } // wait for expiary fmt.Println(mails, after_mails) } func TestGettingANonExistingInbox(t *testing.T) { email := randomEmail() _, status := getMailConnection(email) if status != 404 { t.Error("Should return 404") } } func TestGettingANonExistingId(t *testing.T) { email := randomEmail() _, status := getEmailByHash(email) if status != 404 { t.Error("Should return 404, but was ", status) } } func getEmailByHash(hash string) (MailConnection, int) { resp, _ := http.Get("http://localhost:8000/email/" + hash) decoder := json.NewDecoder(resp.Body) var d MailConnection err := decoder.Decode(&d) if err != nil { fmt.Println(err) } return d, resp.StatusCode } func deleteRequest(url string) (*http.Response, error) { client := &http.Client{} req, err := http.NewRequest( "DELETE", url, bytes.NewBuffer([]byte("")), ) req.Header.Set("Content-Type", "application/json") reply, err := client.Do(req) if err != nil { log.Panic(err) } return reply, err } // Delete a specific mail by finding via the id func deleteEmailByID(hash string) { deleteRequest("http://localhost:8000/email/" + hash) } // Delete all mails in an inbox func emptyMailBox(email string) { deleteRequest("http://localhost:8000/inbox/" + email) } func SendMails(receiver []string) { err := smtp.SendMail("localhost:2525", nil, "<EMAIL>", // sender receiver, //recipient []byte("Subject: Testing\nThis is $the email body.\nAnd it is the bomb"), ) if err != nil { log.Fatal(err) } } func SendMail(receiver string) { err := smtp.SendMail("localhost:2525", nil, "<EMAIL>", // sender []string{receiver}, //recipient []byte("Subject: Testing\nThis is $the email body.\nAnd it is the bomb"), ) if err != nil { log.Fatal(err) } } func SendMailWithMessage(receiver string, msg string) { err := smtp.SendMail("localhost:2525", nil, "<EMAIL>", // sender []string{receiver}, //recipient []byte(msg), ) if err != nil { log.Fatal(err) } } func TestForwardHostname(t *testing.T) { host := "something.com" port := "2525" result := net.JoinHostPort(host, port) if result != "something.com:2525" { t.Error("Expected something.com:2525 got ", result) } } func TestForwardHostnameWithoutPort(t *testing.T) { host := "something.com" port := "" result := net.JoinHostPort(host, port) if result != "something.com:" { t.Error("Expected 'something.com:' got ", result) } } func TestEmail(t *testing.T) { emails := []string{"<EMAIL>", " <EMAIL>", " <EMAIL> "} for _, email := range emails { name, err := cleanupEmail(email) if name != "<EMAIL>" { t.Error("Expected '<EMAIL>' got ", name) } if err != nil { t.Error("Cleanup email resulted in an error ", err) } } } func TestExtractSubjectOnSingleLine(t *testing.T) { mc := &MailConnection{} line := `SUBJECT: Testing` scanForSubject(mc, line) if mc.Subject != "Testing" { t.Error("Expected 'Testing' got ", mc.Subject) } } func TestExtractSubjectOnSingleNotFormattedLine(t *testing.T) { mc := &MailConnection{} line := `SUBJECT: Testing ` scanForSubject(mc, line) if mc.Subject != " Testing " { t.Error("Exptected ' Testing ' got ", mc.Subject) } } func TestExtractSubjectWithNewLine(t *testing.T) { mc := &MailConnection{} line := `SUBJECT: Testing` scanForSubject(mc, line) if mc.Subject != "\nTesting" { t.Error(mc.Subject, len(mc.Subject)) } } func TestExtractSubjectOnMultipleLines(t *testing.T) { mc := &MailConnection{} line := `SUBJECT: Testing Multiline subject` scanForSubject(mc, line) if mc.Subject != "\nTesting\nMultiline subject" { t.Error(mc.Subject, len(mc.Subject)) } } func randomEmail() string { var dictionary string dictionary = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" var bytes = make([]byte, 10) rand.Read(bytes) for k, v := range bytes { bytes[k] = dictionary[v%byte(len(dictionary))] } return string(bytes) + "@test.com" } <file_sep>package main import ( "bufio" "log" "net" "sync" "time" "github.com/google/uuid" "github.com/zenazn/goji" "gopkg.in/alecthomas/kingpin.v2" ) const timeout time.Duration = time.Duration(10) const mailMaxSize = 1024 * 1024 * 2 // 2 MB var webport = kingpin.Flag("webport", "Port the web server should run on").Default("8000").OverrideDefaultFromEnvar("WEBPORT").String() var hostname = kingpin.Flag("hostname", "Hostname for the smtp server to listen to").Default("localhost").String() var port = kingpin.Flag("port", "Port for the smtp server to listen to").Default("2525").String() var forwardhost = kingpin.Flag("forwardhost", "The hostname after the @ that we should forward i.e. gmail.com").Default("").OverrideDefaultFromEnvar("FORWARD_HOST").String() var forwardsmtp = kingpin.Flag("forwardsmtp", "SMTP server to forward the mail to").Default("").OverrideDefaultFromEnvar("FORWARD_SMTP").String() var forwardport = kingpin.Flag("forwardport", "The port on which email should be forwarded").Default("25").OverrideDefaultFromEnvar("FORWARD_PORT").String() var forwarduser = kingpin.Flag("forwarduser", "The username for the forward host").Default("").OverrideDefaultFromEnvar("FORWARD_USER").String() var forwardpassword = kingpin.Flag("forwardpassword", "<PASSWORD> the user").Default("").OverrideDefaultFromEnvar("FORWARD_PASSWORD").String() var cleanupInterval = kingpin.Flag("mailexpiration", "Time in seconds for a mail to expire, and be removed from database").Default("300").Int() func createListener(server *MailServer) net.Listener { addr := "0.0.0.0:" + server.port listener, err := net.Listen("tcp", addr) if err != nil { panic(err) } else { log.Println("Listening on tcp ", addr) } return listener } func serve(mailserver *MailServer) { if mailserver.httpport == "" { log.Fatal("HTTPPort needs to be configured") } mailserver.database = make([]MailConnection, 0) mailserver.mu = &sync.Mutex{} go func() { for { mailserver.cleanupDatabase() time.Sleep(time.Duration(mailserver.expireinterval) * time.Second) } }() setupWebRoutes(mailserver) listener := createListener(mailserver) go func() { for { conn, err := listener.Accept() if err != nil { log.Panicf("Unable to accept: %s\n", err) continue } go processClientRequest(&MailConnection{ mailserver: mailserver, connection: conn, address: conn.RemoteAddr().String(), reader: bufio.NewReader(conn), writer: bufio.NewWriter(conn), MailId: uuid.New().String(), Mail: Mail{Received: time.Now().Unix()}, }) } }() log.Println("Trying to bind web to port ", mailserver.httpport) l, lerr := net.Listen("tcp", ":"+mailserver.httpport) if lerr != nil { log.Fatalf("Unable to bind to port %s.\n%s\n. ", mailserver.httpport, lerr) } goji.ServeListener(l) } func main() { kingpin.Version("0.1.1") kingpin.Parse() forwardEnabled := false if *forwardhost != "" && *forwardport != "" { forwardEnabled = true } log.Println("Clenaup interval ", *cleanupInterval) serve(&MailServer{hostname: *hostname, port: *port, httpport: *webport, forwardEnabled: forwardEnabled, forwardHost: *forwardhost, forwardPort: *forwardport, expireinterval: *cleanupInterval}) } <file_sep>package main import ( "bufio" "net" "time" ) // Basic structure of the mail, this is used for serializing the mail to the storage type Mail struct { To, From, Subject, Data, CC, Bcc string Received int64 } // When a connection is made to the server, a MailConnection object is made, to keep track // of the specific client connection type MailConnection struct { Mail recepient []string state State helo string response string address string MailId string connection net.Conn reader *bufio.Reader writer *bufio.Writer dropConnection bool mailserver *MailServer expireStamp time.Time } // State representating the flow of the connection type State int const ( INITIAL State = iota NORMAL State = iota READ_DATA State = iota ) const ( OK = "250 OK" EHLO = "EHLO" NO_OP = "NOOP" HELLO = "HELO" SUBJECT = "SUBJECT: " CC = "CC: " BCC = "BCC: " DATA = "DATA" MAIL_FROM = "MAIL FROM:" RCPT_TO = "RCPT TO:" RESET = "RSET" ) <file_sep>package main import ( "log" "net/smtp" "testing" ) func TestCleanUpEmail(t *testing.T) { email := "<<EMAIL>>" ce, err := cleanupEmail(email) if err != nil { t.Error(err) } if ce != "<EMAIL>" { t.Error("Address is wrong, when cleaning emails") } } func init() { /* log.Println("MailTest init") os.Setenv("WEBPORT", "8383") os.Setenv("FORWARD_HOST", "smtp.gmail.com") os.Setenv("FORWARD_SMtP", "tradeshift.com") kingpin.Parse() go serve(MailConfig{port: "2626", httpport: "8383", forwardEnabled: true}) SendMailOnPort("<EMAIL>", "2525") */ } func SendMailOnPort(receiver string, port string) { err := smtp.SendMail("localhost:"+port, nil, "<EMAIL>", // sender []string{receiver}, //recipient []byte("Subject: Testing\nThis is $the email body.\nAnd it is the bomb"), ) if err != nil { log.Fatal(err) } } func TestIsEmailAddressesValid(t *testing.T) { } <file_sep>package main import ( "log" "strings" "sync" "time" "github.com/google/uuid" ) type MailServer struct { hostname string port string forwardEnabled bool forwardHost string forwardPort string // In-Memory database database []MailConnection mu *sync.Mutex httpport string expireinterval int } func (server *MailServer) saveMail(mail *MailConnection) bool { server.mu.Lock() defer server.mu.Unlock() if err := isEmailAddressesValid(mail); err != nil { log.Printf("Email from '%s' doesn't have a valid email address the error was %s\n", mail.From, err.Error()) return false } for _, rcpt := range mail.recepient { to, err := cleanupEmail(rcpt) if err != nil { log.Println("Cleaning up email gave an error ", err) } mail.To = to mail.expireStamp = time.Now().Add(time.Duration(mail.mailserver.expireinterval) * time.Second) mail.Received = time.Now().Unix() mail.MailId = uuid.New().String() server.database = append(server.database, *mail) } if *forwardhost != "" && *forwardport != "" { if strings.Contains(mail.To, *forwardhost) { forwardEmail(mail) } } return true } func (server *MailServer) cleanupDatabase() { server.mu.Lock() dbcopy := []MailConnection{} log.Printf("About to expire entries from database older then %d seconds, current length %d\n", server.expireinterval, len(server.database)) for _, v := range server.database { if time.Since(v.expireStamp).Seconds() < 0 { dbcopy = append(dbcopy, v) } } server.database = dbcopy log.Println("After expire entries in database, new length ", len(server.database)) server.mu.Unlock() } <file_sep>package main import "testing" func TestForwarding(t *testing.T) { /* FORWARD_ENABLED = true forwardhost = forwardHost() forwardport = forwardPort() // start the forward host config := MailConfig{hostname: "localhost", port: "2626", forwardEnabled: true, forwardHost: "localhost", forwardPort: "2626"} os.Setenv("PORT", "8181") go serve(config) SendMail("<EMAIL>") FORWARD_ENABLED = false fmt.Println(config.database) */ } func forwardHost() *string { test := "localhost" return &test } func forwardPort() *string { test := "2525" return &test } <file_sep>package main import ( "log" "net" "net/smtp" ) func getForwardHost() string { return net.JoinHostPort(*forwardsmtp, *forwardport) } func forwardEmail(client *MailConnection) { log.Printf("Forwarding mail to: %v using host %v ", client.To, getForwardHost()) err := smtp.SendMail(getForwardHost(), getAuth(), client.From, []string{client.To}, []byte(client.Data)) if err != nil { log.Println("Forward error: ", err) } } func getAuth() smtp.Auth { if *forwarduser == "" && *forwardpassword == "" { return nil } auth := smtp.PlainAuth( "", *forwarduser, *forwardpassword, *forwardsmtp, ) return auth } <file_sep>cat <<EOF > ~/.dockercfg { "https://index.docker.io/v1/": { "auth": "$AUTH", "email": "$EMAIL" } } EOF
606795e2a7f16e6cc4c9df49de7a833028133078
[ "Markdown", "Go", "Shell" ]
13
Go
sorenmat/gosmtpd
69c7428083d0c1417848f229cb3765c759d41d3b
c15d5c21d4be16c1da2a615e9c104a28cae4d886
refs/heads/master
<file_sep>package gdu.test.oraclecrud.vo; public class Board { private int boardId; private String boardTitle; private String boardContent; private String boardWriter; public int getBoardId() { return boardId; } public void setBoardId(int boardId) { this.boardId = boardId; } public String getBoardTitle() { return boardTitle; } public void setBoardTitle(String boardTitle) { this.boardTitle = boardTitle; } public String getBoardContent() { return boardContent; } public void setBoardContent(String boardContent) { this.boardContent = boardContent; } public String getBoardWriter() { return boardWriter; } public void setBoardWriter(String boardWriter) { this.boardWriter = boardWriter; } @Override public String toString() { return "Board [boardId=" + boardId + ", boardTitle=" + boardTitle + ", boardContent=" + boardContent + ", boardWriter=" + boardWriter + "]"; } } <file_sep>package gdu.test.oraclecrud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import gdu.test.oraclecrud.service.BoardService; import gdu.test.oraclecrud.vo.Board; @Controller public class BoardController { @Autowired private BoardService boardService; // 메인화면 @GetMapping("/index") public String index() { return "index"; } // 보드 리스트 페이지 @GetMapping("/boardList") public List<Board> boardList(Model model) { List<Board> list = boardService.getBoardList(); model.addAttribute("list", list); return list; } // 보드 상세보기 페이지 @GetMapping("/boardOne") public String boardOne(Model model, @RequestParam(value="boardId") int boardId) { Board board = boardService.getBoardOne(boardId); model.addAttribute("board", board); return "boardOne"; } // 보드 추가 페이지 @GetMapping("/insertBoard") public String insertBoard() { return "insertBoard"; } // 보드 추가 @PostMapping("/insertBoard") public String insertBoard(Board board) { boardService.getInsertBoard(board); return "redirect:/boardList"; } // 보드 삭제 @GetMapping("/deleteBoard") public String deleteBoard(@RequestParam(value="boardId") int boardId) { boardService.getDeleteBoard(boardId); return "redirect:/boardList"; } // 보드 수정 @PostMapping("/modifyBoard") public String modifyBoard(Board board) { boardService.getModifyBoard(board); return "redirect:/boardOne?boardId="+board.getBoardId(); } // 보드 수정 페이지 @GetMapping("/modifyBoard") public Board modifyBoardList(Model model, @RequestParam(value="boardId") int boardId) { Board list = boardService.getModifyBoardList(boardId); model.addAttribute("list", list); return list; } } <file_sep>package gdu.test.oraclecrud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import gdu.test.oraclecrud.mapper.BoardMapper; import gdu.test.oraclecrud.vo.Board; @Service @Transactional public class BoardService { @Autowired BoardMapper boardMapper; // 보드 전체 리스트 public List<Board> getBoardList() { return boardMapper.selectboardList(); } // 보드 상세보기 public Board getBoardOne(int boardId) { return boardMapper.selectboardOne(boardId); } // 보드 추가 public int getInsertBoard(Board board) { return boardMapper.insertboard(board); } // 보드 삭제 public int getDeleteBoard(int boardId) { return boardMapper.deleteboard(boardId); } // 보드 수정 public int getModifyBoard(Board board) { return boardMapper.modifyboard(board); } // 보드 수정페이지 public Board getModifyBoardList(int boardId) { return boardMapper.modifyboardList(boardId); } } <file_sep>debug=true logging.level.gdu.test.oraclecrud.mapper=trace server.port=80 spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1521:xe spring.datasource.username=hr spring.datasource.password=<PASSWORD> spring.mvc.view.prefix=/WEB-INF/view/ spring.mvc.view.suffix=.jsp
ec4481e24d549044507c4687a2f418f019336dc0
[ "Java", "INI" ]
4
Java
0464/oraclecrud
17442d2eb852149603266b7cba014fd03a612dad
972d12b88c21c7c25a6c07ba21c7ba9482009f08
refs/heads/master
<file_sep>testCases = int(input()) while testCases > 0: nNumbers, nFriends = list(map(int, input().split())) numbers = list(map(int, input().split())) numbers.sort() friends = list(map(int, input().split())) friends.sort() smallest = 0 biggest = nNumbers - 1 sum = 0 for friend in friends: if friend >= 3: break if friend == 1: sum += 2 * numbers[biggest] biggest -= 1 if friend == 2: sum += numbers[biggest] biggest -= 1 sum += numbers[biggest] biggest -= 1 friends.reverse() for friend in friends: if friend <= 2: break sum += numbers[biggest] + numbers[smallest] biggest -= 1 smallest += friend - 1 print(sum) testCases -= 1; <file_sep>""" Problem: https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/ Input: n s e a b d n -> number of nodes (starting from 0) s -> source node (0 <= s < n) e -> number of edges e next lines with a b d -> edge connecting node a to b with distance d. 0 <= a and b < n """ # # IMPORTS # import math # # CODE # class MinHeap(): def __init__(self): """ I initialize an empty min heap. :returns: nothing """ self.heap = [] def add(self, element): """ I add an elemente to the min heap. :param element: element to be add, tuple of node id and distance. :returns: nothing """ # add element to the heap self.heap.append(element) # get index of added element and parent of added element index = len(self.heap) - 1 parentIndex = (index - 1) // 2 # swap parents and childs while needed while index >= 1 and self.heap[parentIndex][1] > self.heap[index][1]: # swap parent and child swap = self.heap[parentIndex] self.heap[parentIndex] = self.heap[index] self.heap[index] = swap # update parent and child indexes index = parentIndex parentIndex = (index - 1) // 2 def remove(self): """ I remove an elemente of min heap. :returns: removed element or None on empty heap """ # non empty heap: get first element if len(self.heap) > 0: removed = self.heap[0] # empty heap: return None else: return None # heap with one element: remove it and return if len(self.heap) == 1: return self.heap.pop() # put last element on the begining of the heap self.heap[0] = self.heap.pop() # descend new root while needed index = 0 leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 while (leftChild < len(self.heap) and \ self.heap[index][1] > self.heap[leftChild][1]) or \ (rightChild < len(self.heap) and \ self.heap[index][1] > self.heap[rightChild][1]): # swap smallest child with parent if rightChild == len(self.heap) or \ self.heap[leftChild][1] < self.heap[rightChild][1]: # swap with left child swap = self.heap[index] self.heap[index] = self.heap[leftChild] self.heap[leftChild] = swap # update indexes index = leftChild leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 else: # swap with right child swap = self.heap[index] self.heap[index] = self.heap[rightChild] self.heap[rightChild] = swap # update indexes index = rightChild leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 # return removed node return removed def size(self): """ I return the size of the heap. :returns: size of the heap """ return len(self.heap) def top(self): """ I return the top element of the heap. :returns: top element of the heap or None on empty heap """ if len(self.heap) > 0: return self.heap[0] return None def decreaseKey(self, element, cost): """ I decrease the value of an element. :param element: element to have its key decreased :param cost: new element cost :returns: nothing """ # find desired element for node in range(len(self.heap)): # found node: decrease its key if self.heap[node][0] == element: # update its cost self.heap[node] = (element, cost) # get index of added element and parent of added element index = node parentIndex = (index - 1) // 2 # swap parents and childs while needed while index >= 1 and self.heap[parentIndex][1] > self.heap[index][1]: # swap parent and child swap = self.heap[parentIndex] self.heap[parentIndex] = self.heap[index] self.heap[index] = swap # update parent and child indexes index = parentIndex parentIndex = (index - 1) // 2 def relax(distances, parents, heap, source, target, distance): """ I relax a node given an edge. :param distances: array with smallest distances from source to each node :param parents: smallest path tree :param heap: heap with smallest distances to each node from source :param source: source node :param target: target node :param distance: edge cost from source to target :returns: nothing """ # the current edge offers a better path to target: update it if distances[target] > distances[source] + distance: distances[target] = distances[source] + distance parents[target] = source heap.decreaseKey(target, distances[target]) # read input nodes = int(input()) source = int(input()) edges = int(input()) # build empty graph as adjacency list graph = [] for _ in range(nodes): graph.append([]) # populate graph for _ in range(edges): a, b, distance = map(int, input().split()) graph[a].append((b, distance)) graph[b].append((a, distance)) # initialize distances from source list distances = [math.inf] * nodes distances[source] = 0 # initialize parent of shortest path tree list parents = [-1] * nodes parents[source] = None # initialize cut nodes cut = MinHeap() for node in range(nodes): cut.add((node, distances[node])) print(cut.heap) # execute djikstra while cut.size() > 0: # get node with smallest distance to source node = cut.remove() # relax each edge of node for edge in graph[node[0]]: relax(distances, parents, cut, node[0], edge[0], edge[1]) # print distance and parent of each node for node in range(nodes): print('---------------') print(f'Nó {node} - Distancia: {distances[node]}') print(f'Nó {node} - Pai: {parents[node]}') print('---------------') <file_sep>// TLE test 3 #include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <stdlib.h> #include <string> #include <vector> #include <deque> #include <map> #include <queue> using namespace std; typedef long long int lli; typedef vector <lli> vetor; typedef vector <vector <lli> > matriz; int main() { lli i, j, longest, n, x, t, sum; cin >> t; while (t > 0) { cin >> n >> x; vetor elements(n); for (i = 0; i < n; i++) { cin >> elements[i]; } longest = -1; for (i = 0; i < n; i++) { sum = elements[i]; if (sum % x != 0 && longest == -1) { longest = 1; } if (n - i <= longest) { continue; } for (j = i + 1; j < n; j++) { sum += elements[j]; if (sum % x != 0 && (j - i + 1) > longest) { longest = (j - i + 1); } } } cout << longest << endl; t--; } return 0; } <file_sep>#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <stdlib.h> #include <string> #include <vector> #include <deque> #include <map> #include <queue> using namespace std; typedef long long int lli; typedef vector <lli> vetor; typedef vector <vector <lli> > matriz; int main () { lli testCases, size, pos, solutionSize; char str[1000002], solution[100002]; string strAux; bool one, zero; cin >> testCases; while (testCases > 0) { cin >> size; cin >> strAux; for (lli i = size - 1; i >= 0; i--) { str[i] = strAux[i]; } solutionSize = -1; one = false; zero = false; pos = -1; for (lli i = size - 1; i >= 0; i--) { if (str[i] == '1' && one == false && zero == false) { solutionSize++; solution[solutionSize] = '1'; } if (str[i] == '0' && one == false && zero == false) { zero = true; pos = i; } if (str[i] == '1' && one == false && zero == true) { one = true; } if (str[i] == '0' && one == true && zero == true) { str[i + 1] = '0'; pos = i + 1; one = false; } } if (one == false && zero == true) { for (lli i = 0; i <= pos; i++) { cout << str[i]; } for (lli i = solutionSize; i >= 0; i--) { cout << solution[i]; } cout << endl; } else if (one == true && zero == true) { cout << '0'; for (lli i = solutionSize; i >= 0; i--) { cout << solution[i]; } cout << endl; } else if (one == false && zero == false) { for (lli i = solutionSize; i >= 0; i--) { cout << solution[i]; } cout << endl; } testCases--; } return 0; } <file_sep>""" Merge Sort algorithm. Time Complexity: O(n * log(n)) Space Complexity: O(n) """ def mergesort(list, begin, end): # empty sublist: return empty list if begin > end: return [] # one element in sublist: return list with this element if begin == end: return [list[begin]] # divide step middle = (begin + end) // 2 left = mergesort(list, begin, middle) right = mergesort(list, middle + 1, end) # conquer step result = [] i = 0 j = 0 while i < len(left) or j < len(right): # right list already consumed: add left element to result if j == len(right): result.append(left[i]) i += 1 # left list already consumed: add right element to result elif i == len(left): result.append(right[j]) j += 1 # both lists still have elements: add the smaller one elif left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1 return result if __name__ == '__main__': # get input list list = list(map(int, input('Insert list to be ordered\n').split())) # print sorted list print(mergesort(list, 0, len(list) - 1)) <file_sep>""" Bellman-Ford implementation. Application: Graph algorithm to find shortest path from a source node. Time Complexity: O(V * E): We relax all edges V - 1 times Space complexity: O(V + E) Graph is directed and represented by an adjacency list: each node identifier is a key of a dictonary and its value is the adjacency list of that node. Restriction: No cicles with negative cost Algorithm: We relax all edges V - 1 times. With that, on the last time, we guarantee that the shortest path from the source to the furthest target has been relaxed in an optimal mode, and we have the shortest path tree Problem to get input from: https://www.geeksforgeeks.org/bellman-ford-algorithm-dp-23/?ref=leftbar-rightbar Input: n -> number of nodes (starting from 0) s -> source node (0 <= s < n) e -> number of edges e next lines with a b d -> edge connecting node a to b with distance d. 0 <= a and b < n Example (from link): 5 0 8 0 1 -1 0 2 4 1 2 3 1 3 2 1 4 2 3 2 5 3 1 1 4 3 -3 """ # # IMPORTS # import math # # CODE # def relax(distances, parents, source, target, distance): """ I relax a node given an edge. :param distances: array with smallest distances from source to each node :param parents: smallest path tree :param source: source node id :param target: target node id :param distance: edge cost from source to target :returns: nothing """ # the current edge offers a better path to target: update it if distances[target] > distances[source] + distance: distances[target] = distances[source] + distance parents[target] = source if __name__ == '__main__': # read input nodes = int(input()) source = int(input()) edges = int(input()) # build empty graph as adjacency list graph = [] for _ in range(nodes): graph.append([]) # populate graph for _ in range(edges): a, b, distance = map(int, input().split()) graph[a].append((b, distance)) # initialize distances from source list distances = [math.inf] * nodes distances[source] = 0 # initialize parent of shortest path tree list parents = [-1] * nodes parents[source] = None # execute bellman ford for _ in range(nodes - 1): for node in range(nodes): for edge in graph[node]: relax(distances, parents, node, edge[0], edge[1]) # check consistency (negative cicles) for node in range(nodes): for edge in graph[node]: # relax each edge and see if the result changes initialCost = distances[edge[0]] relax(distances, parents, node, edge[0], edge[1]) finalCost = distances[edge[0]] # relax decreased distance: negative cicle, abort if initialCost != finalCost: print('Infinite negative cicle detected. Aborting') exit() # print distance and parent of each node for node in range(nodes): print('---------------') print(f'Nó {node} - Distancia: {distances[node]}') print(f'Nó {node} - Pai: {parents[node]}') print('---------------') <file_sep>""" Topological Sort implementation. Application: Sort events when one event takes precedence over others Time Complexity: O(V * E): We visit each node once and check all edges Space complexity: O(V * E) Graph is unweighted and directed and represented by an adjacency list: each node identifier is a key of a dictonary and its value is the adjacency list of that node. Algorithm: We visit all unvisited neighbours of the current node (starting with the source). For the visited node, we add all of its unvisited neighbours in the end of a queue. The algorithm stops when the queue becomes empty. Problem to get input from: https://www.geeksforgeeks.org/topological-sorting/ Input: n -> number of nodes (starting from 0) e -> number of edges e next lines with a b d -> edge connecting node a to b with distance d. 0 <= a and b < n Example (from link): 6 6 2 3 3 1 4 0 4 1 5 0 5 2 """ # # IMPORTS # import math # # CODE # def dfs(node, graph, visited, allVisited, result): """ I recuservly perform dfs. :param node: current node :param graph: graph :param visited: nodes already visited in this traversal :param allVisited: node visited in any traversal :param result: topological sort result :returns: nothing """ # node already visited in some traversal: cicle detected. abort if visited[node] == True: print('Graph is not acyclic') exit() # node already visited by any older traversal: ignore it if allVisited[node] == True: return # node not visited: set it as visited allVisited[node] = True visited[node] = True # visit each node neighbour for neighbour in graph[node]: dfs(neighbour, graph, visited, allVisited, result) # append node to result result.append(node) if __name__ == '__main__': # read input nodes = int(input()) edges = int(input()) # build empty graph as adjacency list graph = [] for _ in range(nodes): graph.append([]) # populate graph for _ in range(edges): a, b = map(int, input().split()) graph[a].append(b) # initialize all nodes visited by dfs visited = [False] * nodes # initialize topological sort result result = [] # perform topological sort for node in range(nodes): # node not yet visited: dfs it if visited[node] == False: dfs(node, graph, [False] * nodes, visited, result) # print topological sort of nodes result.reverse() print(result) <file_sep># The ideia is, from left to right, find the smallest element in descending # order. After this element, find the biggest in the following ascending order. # If after the ascending order there is a smaller element then him, then just # found the sollution. # get number of test cases testCases = int(input()) # for each test while testCases > 0: # read number of elements in this test case and the elements size = int(input()) elements = list(map(int, input().split())) # initialize indexes i = 0 j = -1 # set flags to each step smallestLeft = False biggestMiddle = False # transverse through array for m in range(size): # smallest left element not found yet if smallestLeft == False: # current element is smallest than the smallest found: update it if elements[m] < elements[i]: i = m # current element is bigger than the smallest: set biggest middle if elements[m] > elements[i]: j = m smallestLeft = True # element used, get next one continue # biggest middle element found if biggestMiddle == False: # current element is bigger than the biggest: set biggest middle if elements[m] > elements[j]: j = m # current element is smaller than the biggest found: print response if elements[m] < elements[j]: print('YES') print(i + 1, j + 1 , m + 1) biggestMiddle = True break # element used, get next one continue # no answer found: print no if biggestMiddle == False: print('NO') # decrement test cases testCases -= 1 <file_sep>""" Problem: https://www.hackerrank.com/challenges/contacts/problem """ # # CODE # class Node: def __init__(self, info): """ I initialize myself. :param info: node info :returns: nothing """ self.info = info self.leaves = 1 self.childs = [] class Trie: def __init__(self): """ I initialize myself. :returns: nothing """ self.childs = [] def addNode(self, name): """ I add a name to the trie. :param name: name to be added :returns: nothing """ # initialize level with root trie node level = self # parse each name letter for letter in name: # check if letter exists in current level found = False for node in level.childs: # letter already present in a node: increment its leaves and descend level if node.info == letter: node.leaves += 1 level = node found = True break # letter not found in this level: create a node for it and descend level if found == False: node = Node(letter) level.childs.append(node) level = node def get(self, name): """ I get ammount of strings in trie starting with name :param name: name to search for in trie :returns: ammount of words starting with name """ level = self for letter in name: found = False for node in level.childs: if node.info == letter: level = node found = True break if found == False: return 0 return level.leaves def realTrie(): """ I solve the problem using a real trie. :returns nothing """ # read number of operations operations = int(input()) # initialize empty trie trie = Trie() # execute each operation for _ in range(operations): # read operation and name operation, name = input().split() # add operation: populate trie if operation == 'add': trie.addNode(name) # find operation: print ammount on trie else: print(trie.get(name)) def fakeTrie(): """ I solve the problem using a hash map. :returns: nothing """ # read number of operations operations = int(input()) # initialize empty fake trie trie = dict() # execute each operation for _ in range(operations): # read operation and name operation, name = input().split() # add operation: populate trie if operation == 'add': # add each substring to trie for i in range(1, len(name) + 1): trie[name[:i]] = trie.get(name[:i], 0) + 1 # find operation: print ammount on trie else: print(trie.get(name, 0)) realTrie() <file_sep># To find the biggest difference, we must retrieve the extremes of each # ascending and descinding sequences # read test cases testCases = int(input()) while testCases > 0: # get size of permutation size = int(input()) # get permutation permutation = list(map(int, input().split())) # start subsequence with first element of permutation subsequence = [permutation[0]] # get if added element of subsequence is bigger then its following element if permutation[0] > permutation[1]: operation = 'bigger' else: operation = 'smaller' # iterate over permutation for i in range(1, size - 1): # operation remains the same -> skip to next element if (operation == 'bigger' and permutation[i] > permutation [i + 1]) or (operation == 'smaller' and permutation[i] < permutation [i + 1]): continue # add element to subsequence since it has biggest diff on ascending or # descinding sequence subsequence.append(permutation[i]) # update next operation if operation == 'bigger': operation = 'smaller' else: operation = 'bigger' # add last element of sequence subsequence.append(permutation[-1]) # print response print(len(subsequence)) for i in range(len(subsequence)): if i == len(subsequence) - 1: print(str(subsequence[i])) else: print(str(subsequence[i]) + ' ', end = '') # decrement test cases testCases -= 1 <file_sep>""" Binary Search implementation. Application: Find an element in a list Time Complexity: 1 - Nonsorted list: O(n * log(n)): We sort the list and perform the search 2 - Sorted list: O(log(n)): We just perform the search Space complexity: O(n) Algorithm: We sort the list, we check if the element is in the middle of the list. If it is, we return it. If not, if the searched element is smaller than the middle we search on the left portion of the list, otherwise we search on the right portion of the list. Input: list elements element to search Example: 10 2 1 5 4 8 7 9 6 3 2 """ # # CODE # def binarySearch(list, start, end, value): """ I recuservly perform dfs. :param list: list to search element on :param start: first index to search on :param end: last index to search on :param value: value to serch on :returns: index of value if it exists. None otherwise """ # start bigger than end: value not found if start > end: return None # start smaller than end: get middle position middle = (start + end) // 2 # value being searched is in the middle: return it if list[middle] == value: return middle # element is bigger than middle position: serach on right portion elif list[middle] < value: return binarySearch(list, middle + 1, end, value) # element is smaller than middle position: serach on left portion else: return binarySearch(list, start, middle - 1, value) if __name__ == '__main__': # read input list = list(map(int, input().split())) value = int(input()) # sort list list.sort() # print result print('Sorted list: ', list) print('Position of element: ', binarySearch(list, 0, len(list) - 1, value)) <file_sep># we must perform a rotation in a first array A in order to obtain the most # number of elements pairing (in the same position) on an array B. # For that matter, we compute how much we need to rotate the array for each # elemnt to match arrays A and B. After that, get the number of rotation that # which will lead to most elements paired. # get size of arrays size = int(input()) # get elements in array A and B A = list(map(int, input().split())) B = list(map(int, input().split())) # add a tuple of element position to each element for i in range(size): A[i] = (A[i], i) B[i] = (B[i], i) # sort both arrays by ther elements A.sort(key = lambda x: x[0]) B.sort(key = lambda x: x[0]) # initilize array of rotations rotations = [0] * size # compute rotations difference for i in range(size): diff = A[i][1] - B[i][1] # rotation is to the left -> turn it to the right if diff < 0: diff = size + diff # increase matching elements on this rotation size rotations[diff] += 1 # print maximum number of elements paired print(max(rotations)) <file_sep># elemnts only of different b can change their position, so in a scenario with # only one b and plenty of a, we can sort all elements of a using the ideia of # selection sort. Using the same ideia, we can sort all elements with b = 1 # afterwards. The only case were isn't possible to sort is when all elements # has the same b, in that case they must be already in ascending order. # get number of test cases testCases = int(input()) # for each test case while testCases > 0: # read array size size = int(input()) # read both arrays elements = list(map(int, input().split())) pairity = list(map(int, input().split())) # check if parity in unique zeroParity = False oneParity = False for b in pairity: if b == 0: zeroParity = True else: oneParity = True # both are true (since size >= 1, at least one will be true, so they can't # be here both false) if zeroParity == oneParity: print('Yes') # array only with 0 or 1 -> elements must be sorted else: ordered = True for i in range(size - 1): if elements[i] > elements[i + 1]: ordered = False break # print response if ordered is True: print('Yes') else: print('No') # decrese test cases testCases -= 1 <file_sep>""" Heap Sort algorithm using heapq from standard library. Time Complexity: O(n * log(n)) Space Complexity: O(n) """ import heapq def heapsort(list): # turn element into a min heap heapq.heapify(list) # remove smallest element from heap and add to result result = [] while len(list) > 0: result.append(heapq.heappop(list)) # return ordered list return result if __name__ == '__main__': # get input list list = list(map(int, input('Insert list to be ordered\n').split())) # print sorted list print(heapsort(list)) <file_sep># The ideia of this code is that an element can only be changed to 1 if its # row and columns only contains 0s, so, when it is changed to one, none of the # elements on this column or row can be changed to 1, thus, it invalidates # both the row and the colum. # # With that said, the ideia then is to count the number of rows and columns with # zeros, and the minumum of those two are the number of plays that can be made. # read number of test cases testCases = int(input()) # apply logic for each test case while testCases > 0: # read number of rows and columns row, column = list(map(int, input().split())) # allocate space for the grid grid = [] for i in range(row): grid.append(list(map(int, input().split()))) # count number of rows with only zeros rowZeros = 0 for i in range(row): found = False for j in range(column): if grid[i][j] == 1: found = True break if found is False: rowZeros += 1 # count number of columns with only zeros columnZeros = 0 for j in range(column): found = False for i in range(row): if grid[i][j] == 1: found = True break if found is False: columnZeros += 1 # get minimum of them minimum = min(rowZeros, columnZeros) # print response based on number of possible plays if minimum % 2 == 0: print('Vivek') else: print('Ashish') testCases -= 1 <file_sep>""" Quick Sort algorithm. Time Complexity: Worst: O(n^2) Average: O(n * log(n)) Space Complexity: O(n) """ def swap(list, i, j): swap = list[j] list[j] = list[i] list[i] = swap def quicksort(list, begin, end): # empty sublist: return if begin > end: return # one element in sublist: return if begin == end: return # quick sort current list i = begin j = begin while i != end: # current element smaller than pivot: put it before pivot if list[i] <= list[end]: swap(list, i, j) j += 1 # move in the list i += 1 # put pivot in right place swap(list, j, end) # divide step quicksort(list, begin, j - 1) quicksort(list, j + 1, end) if __name__ == '__main__': # get input list list = list(map(int, input('Insert list to be ordered\n').split())) # sort list quicksort(list, 0, len(list) - 1) # print sorted list print(list) <file_sep>""" Problem: https://www.hackerrank.com/challenges/swap-nodes-algo/problem """ # # IMPORTS # # needed for recursive solution to work import sys sys.setrecursionlimit(15000) # # CODE # def inorderRecursive(indexes, i): """ I print a binary tree in inorder traversal recursively. :param indexes: binary tree as a list of indexes :param i: current index being visited :return: nothing """ # null node: return if i == -2: return # visit sub-left tree, print node and visit sub-right tree inorder(indexes, indexes[i][0]) print(i + 1, end = ' ') inorder(indexes, indexes[i][1]) def inorderIterative(indexes): """ I print a binary tree in inorder traversal iteratively. :param indexes: binary tree as a list of indexes :return: nothing """ # create pile of nodes and append root to it nodes = [] nodes.append(0) visited = [False] * 1024 # while there is nodes to visit while len(nodes) > 0: # get top of the pile node = nodes[-1] # non null node and unvisited node: visit node and append its left child if indexes[node][0] != -2 and visited[node] == False: visited[node] = True nodes.append(indexes[node][0]) # null node or visited node: print node data and append right child else: print(node + 1, end = ' ') nodes.pop() if indexes[node][1] != -2: nodes.append(indexes[node][1]) def inorderIterative2(indexes): """ I print a binary tree in inorder traversal iteratively without visited list. :param indexes: binary tree as a list of indexes :return: nothing """ # initialize pile of nodes and set current node as root nodes = [] current = 0 # print in order while True: # non null node: enpile current node and move to left child if current != -2: nodes.append(current) current = indexes[current][0] # null node with nodes on pile: remove pile top, print it and visit right child elif len(nodes) > 0: node = nodes.pop() print(node + 1, end = ' ') current = indexes[node][1] # empty pile and null node: stop else: break # read number of nodes in tree n = int(input()) # tree array indexes = [] # heigh of node of index i nodeHeight = [0] * n # nodes in height j heightNodes = [[0]] for i in range(n): heightNodes.append([]) # build tree for i in range(n): childs = list(map(lambda x: int(x) - 1, input().rstrip().split())) indexes.append(childs) for child in childs: if child != -2: nodeHeight[child] = nodeHeight[i] + 1 heightNodes[nodeHeight[child]].append(child) # get ammount of queries queriesCount = int(input()) # execute each query for _ in range(queriesCount): # get query query = int(input()) # find all multiples of the query for i in range(n): # query multiple: swap nodes if (i + 1) % query == 0: for node in heightNodes[i]: indexes[node].reverse() # print answer # inorderRecursive(indexes, 0) # inorderIterative(indexes) inorderIterative2(indexes) print() <file_sep>""" DFS - Depth First Search implementation. Application: Find all nodes reachable by a source. Used for plenty of algorithms like topological sort, finding conected components of a graph and topological sort. Time Complexity: O(V + E): We visit each node once and check all edges Space complexity: O(V + E) Graph is unweighted and directed and represented by an adjacency list: each node identifier is a key of a dictonary and its value is the adjacency list of that node. Algorithm: We visit all unvisited neighbours of the current node (starting with the source). For the visited node, we add all of its unvisited neighbours in the end of a queue. The algorithm stops when the queue becomes empty. Problem to get input from: https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/ Input: n -> number of nodes (starting from 0) s -> source node (0 <= s < n) e -> number of edges e next lines with a b d -> edge connecting node a to b with distance d. 0 <= a and b < n Example (from link): 4 1 6 0 1 0 2 1 2 2 0 2 3 3 3 """ # # IMPORTS # import math # # CODE # def dfs(node, parent, graph, parents, start, end, time): """ I recuservly perform dfs. :param node: current node :param parent: parent node of current nome :param graph: graph :param parents: nodes parents in dfs tree :param start: start time of each node :param end: end time of each node :param time: current time :returns: nothing """ # node already visited: return current time if parents[node] != -1: return time # set start time of current node time += 1 start[node] = time parents[node] = parent # visit each node neighbour for neighbour in graph[node]: time = dfs(neighbour, node, graph, parents, start, end, time) # set end time time += 1 end[node] = time # return time return time if __name__ == '__main__': # read input nodes = int(input()) source = int(input()) edges = int(input()) # build empty graph as adjacency list graph = [] for _ in range(nodes): graph.append([]) # populate graph for _ in range(edges): a, b = map(int, input().split()) graph[a].append(b) # initialize parent of dfs tree list parents = [-1] * nodes # initialize start times start = [-1] * nodes # initialize start times end = [-1] * nodes dfs(source, None, graph, parents, start, end, 0) # print distance and parent of each node for node in range(nodes): print('---------------') print(f'Nó {node} - Inicio: {start[node]}') print(f'Nó {node} - Fim: {end[node]}') print(f'Nó {node} - Pai: {parents[node]}') print('---------------') <file_sep>""" AVL - Balanced Binary Search Tree implementation. Application: Find elements in reasonable time. Time Complexity: Add element: O(log(n)) Delete element: O(log(n)) Update value of en element: O(log(n)) Build: O(n * log(n)) Space complexity: O(n) Algorithm: Build a balanced binary search tree. Binary: each node has at most two childrens. Search: If the value of a node is smaller or equal to its parent, it must be a left child, otherwise a right child. Balanced: The height diference between the left child sub tree and right child sub tree can be at most 1. If it is equal to 2, we must perform rotations to rebalence the tree. Problem to get input from: https://www.geeksforgeeks.org/avl-tree-set-1-insertion/ Input: op -> number of operations to perform elements -> initial tree elements op lines with: 'add' value 'remove' value 'update' value newValue Examples: Updating root on rotations: Simple left rotation: 0 1 2 3 Double left rotation: 0 1 3 2 Simple right rotation: 0 3 2 1 Double right rotation: 0 3 1 2 Updating only childs on rotations: Simple left rotation: 0 2 1 3 4 5 Double left rotation: 0 4 1 5 3 2 Simple right rotation: 0 4 3 5 2 1 Double right rotation: 0 2 1 5 3 4 Two rotations on diferent nodes upon addition: 0 1 2 3 4 5 6 Node removal: Root removal: 3 2 1 3 remove 2 remove 1 remove 3 Subistitute being direct node being removed left child: 1 3 2 4 1 remove 3 Subistitute being direct node being removed right child: 1 2 1 3 4 remove 2 Leaf removal without rotation: 1 2 1 3 remove 1 Leaf removal resulting rotation: 1 2 1 3 4 remove 1 Subistitute on left being a leaf: 1 3 1 4 2 remove 1 Subistitute on left not being a leaf: 1 5 2 6 1 4 7 3 remove 2 Subistitute on right being a leaf: 1 2 1 4 3 remove 4 Subistitute on right not being a leaf: 1 3 2 6 1 4 7 5 remove 6 Geral: 10 1 2 3 4 5 6 7 8 9 10 remove 8 find 8 find 10 update 10 15 find 10 find 15 add 13 find 13 remove 4 add 4 10 10 9 8 7 6 5 4 3 2 1 remove 2 find 2 find 1 update 1 15 find 1 find 15 add 13 find 13 remove 4 add 4 1 5 3 10 2 4 7 11 1 6 9 12 8 remove 10 """ # # CODE # class Node(): """ I am a tree node. """ def __init__(self, value, parent = None): """ I initialize a leaf node. :param value: node value :param parent: parent of the node being created :returns: nothing """ # initialize new node self.value = value self.parent = parent self.left = None self.right = None self.height = 1 @property def balanceFactor(self): """ I compute the balance factor. :returns: balance factor """ leftHeight = self.left.height if self.left != None else 0 rightHeight = self.right.height if self.right != None else 0 return rightHeight - leftHeight def updateHeight(self): """ I update the node height. :returns: nothing """ leftHeight = self.left.height if self.left != None else 0 rightHeight = self.right.height if self.right != None else 0 self.height = max(rightHeight, leftHeight) + 1 class Tree(): """ I am a balanced binary search tree. """ def __init__(self): """ I initialize an empty tree. :returns: nothing """ self.root = None def inorder(self): """ I print the tree in an inorder traversal. :returns: nothing """ # start current node as root current = self.root # start emtpy node stack stack = [] # inform tree height if self.root != None: print('Tree Height: ', self.root.height) else: print('Tree Height: ', 0) print('Inorder traversal: ', end = '') # while there is a current node and stack has nodes: print in order while current != None or len(stack) > 0: # current is not None: add it to stack and go to its left child if current != None: stack.append(current) current = current.left # current is None: print stack top and go to its right child else: node = stack.pop() print(node.value, end = ' ') current = node.right # print new line print() def add(self, value): """ I add a node to the tree. :param value: value to be added :returns: nothing """ # no root node: add node as root if self.root == None: self.root = Node(value, None) return # root already exists: find place of node to be added node = self.root while True: # left child: check if is already a leaf or not if value <= node.value: # current node is a leaf: add new node as left child if node.left == None: node.left = Node(value, node) self.rebalance(node) break # current node is not a leaf: descend to left child node = node.left # right child: check if is already a leaf or not else: # current node is a leaf: add new node as right child if node.right == None: node.right = Node(value, node) self.rebalance(node) break # current node is not a leaf: descend to right child node = node.right def find(self, value): """ I find an element and return its node. :pram value: value to be found :returns: node with value or None on value not found """ # initialize node as root node = self.root # find value while node != None: # value found: return node if node.value == value: return node # value is smaller than node: search in left sub tree elif node.value > value: node = node.left # value is bigger than node: search in right sub tree else: node = node.right # value not found: return None return None def remove(self, value): """ I remove a node from the tree. :param value: value to be removed :returns: nothing """ # find node to be removed node = self.find(value) # value does not exist: abort if node == None: print('Removal failure: Node with value ', value, ' not found') return # value exists: find best substitute candidate # node to be removed is a leaf: remove it if node.left == None and node.right == None: parent = node.parent self.updateNodeParentChild(node, None) # node to be removed has left child: find left child most right node elif node.left != None: # find substitute substitute = node.left while substitute.right != None: substitute = substitute.right # update node value to substitute value node.value = substitute.value # update substitute's parent child, and this child's parent parent = substitute.parent if parent == node: node.left = substitute.left else: parent.right = substitute.left if substitute.left != None: substitute.left.parent = parent # node to be removed has only right child: find right child most left nd else: # find substitute substitute = node.right while substitute.left != None: substitute = substitute.left # update node value to substitute value node.value = substitute.value # update substitute's parent child, and this child's parent parent = substitute.parent if parent == node: node.right = substitute.right else: parent.left = substitute.right if substitute.right != None: substitute.right.parent = parent # value updated and node removed: rebalance tree self.rebalance(parent) def update(self, value, newValue): """ I update the value of a node. :param value: value to be updated :param newValue: node new value :returns: nothing """ # get node to be updated node = self.find(value) # node not found: abort if node == None: print('Node update from ', value, ' to ', newValue, ' failed: ', 'Node with value ', value, ' not found') return # node found: update it self.remove(value) self.add(newValue) def updateNodeParentChild(self, node, newChild): """ I update the parent's child of a node. :pram node: node to have its parent's child node updated :param newChild: parent's node child new node :returns: nothing """ # get node's parent parent = node.parent # node is root: set new child as new root if parent == None: self.root = newChild # node is not root and node is left child of parent: update parent l ch elif parent.left == node: parent.left = newChild # node is not root and node is right child of parent: update parent r ch else: parent.right = newChild def rotateRight(self, node): """ I rotate a node to its right. :param node: node to be rotated :returns: nothing """ # get left child of node child = node.left # update parent's new child self.updateNodeParentChild(node, child) # update parents child.parent = node.parent node.parent = child # update childs node.left = child.right child.right = node if node.left != None: node.left.parent = node # update heights node.updateHeight() child.updateHeight() def rotateLeft(self, node): """ I rotate a node to its left. :param node: node to be rotated :returns: nothing """ # get right child of node child = node.right # update parent's new child self.updateNodeParentChild(node, child) # update parents child.parent = node.parent node.parent = child # update childs node.right = child.left child.left = node if node.right != None: node.right.parent = node # update heights node.updateHeight() child.updateHeight() def rebalance(self, node): """ I rebalance the tree. :param node: node to start rebalance from :returns: nothing """ # perform rebalance until root while node != None: # compute node height node.updateHeight() # store node's parent parent = node.parent # node balance factor is 2: rotate it properly if node.balanceFactor == 2: # right child of node has positive BF: rotate node left if node.right.balanceFactor == 1: self.rotateLeft(node) # right child of node has negative BF: double rotate node left else: self.rotateRight(node.right) self.rotateLeft(node) # node balance factor is -2: rotate it properly elif node.balanceFactor == -2: # left child of node has negative BF: rotate node right if node.left.balanceFactor == -1: self.rotateRight(node) # left child of node has positive BF: double rotate node right else: self.rotateLeft(node.left) self.rotateRight(node) # ascend to parent and rebalance it node = parent if __name__ == '__main__': # read input operations = int(input()) elements = list(map(int, input().split())) # build tree tree = Tree() for element in elements: tree.add(element) # perform operations for _ in range(operations): # read operation input operationInput = input().split() # add operation: add element if operationInput[0] == 'add': tree.add(int(operationInput[1])) # remove operation: remove element elif operationInput[0] == 'remove': tree.remove(int(operationInput[1])) # find operation: find element elif operationInput[0] == 'find': node = tree.find(int(operationInput[1])) print('Found' if node else 'Not found') # update operation: update element elif operationInput[0] == 'update': tree.update(int(operationInput[1]), int(operationInput[2])) # invalid operation: inform else: print('Invalid operation: ', operationInput[0]) # print tree in order tree.inorder() <file_sep>""" Problem: https://www.hackerrank.com/challenges/balanced-brackets/problem """ # # CODE # # read ammount of test cases testCases = int(input()) # solve each test case for _ in range(testCases): # get brackets string text = input() # initialize empty pile to store pile = [] # analyze each brackets string character for i in range(len(text)): # pile non empty: check for a match if len(pile) > 0: # pile top matches with current bracket character: remove pile top if (pile[-1] == '(' and text[i] == ')') or \ (pile[-1] == '{' and text[i] == '}') or \ (pile[-1] == '[' and text[i] == ']'): pile.pop() # pile top does not math with current bracket character: stack up curent bracket chracter else: pile.append(text[i]) # empty pile: stack up curent bracket chracter else: pile.append(text[i]) # empty pile: valid brackets string if (len(pile) == 0): print('YES') # non empty pile: invalid brackets string else: print('NO') <file_sep>""" BFS - Breadth First Search implementation. Application: Find smallest distance from a source node to all nodes. This distance is in means of ammount of edges consumed Time Complexity: O(V + E): We visit each node once and check all edges Space complexity: O(V + E) Graph is unweighted and directed and represented by an adjacency list: each node identifier is a key of a dictonary and its value is the adjacency list of that node. Algorithm: We visit all unvisited neighbours of the current node (starting with the source). For the visited node, we add all of its unvisited neighbours in the end of a queue. The algorithm stops when the queue becomes empty. Problem to get input from: https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/ Input: n -> number of nodes (starting from 0) s -> source node (0 <= s < n) e -> number of edges e next lines with a b d -> edge connecting node a to b with distance d. 0 <= a and b < n Example (from link): 4 2 6 0 11 0 2 1 2 2 0 2 3 3 3 """ # # IMPORTS # import math # # CODE # if __name__ == '__main__': # read input nodes = int(input()) source = int(input()) edges = int(input()) # build empty graph as adjacency list graph = [] for _ in range(nodes): graph.append([]) # populate graph for _ in range(edges): a, b = map(int, input().split()) graph[a].append(b) # initialize distances from source list distances = [math.inf] * nodes distances[source] = 0 # initialize parent of shortest path tree list parents = [-1] * nodes parents[source] = None # initialize queue of nodes to visit queue = [source] # perform bfs until all reacheable nodes are reached while len(queue) > 0: # get first element of queue node = queue.pop() # add each unvisited neighbour to queue for neighbour in graph[node]: # neighbour already visited: skip it if parents[neighbour] != -1: continue # set neighbour as visited distances[neighbour] = distances[node] + 1 parents[neighbour] = node queue.append(neighbour) # print distance and parent of each node for node in range(nodes): print('---------------') print(f'Nó {node} - Distancia: {distances[node]}') print(f'Nó {node} - Pai: {parents[node]}') print('---------------') <file_sep># The ideia is that no bad guys can leave the maze and all good guys must. # Since each person can move in N, E, S, W, we need to "trap" bad guys in # order to not let them escape the maze. Once this is done, if all good guys # can escape, then we're safe, otherwise it does not have solution. To see if # all good guys can escape, we see via dfs if all good guys are reacheable # trough the exit of the maze # # GLOBALS # GOOD = 0 # recursive method to check if someone can escape a maze or not def dfs(maze, row, column, visited, i, j): global GOOD # out of boundary -> return if i == -1 or j == -1 or i == row or j == column: return # already visited place -> return if visited[i][j] == 1: return # reached a wall -> visit and return if maze[i][j] == '#': return # mark the place as visited visited[i][j] = 1 # base case: reached exit -> visit and increase count if maze[i][j] == 'G': GOOD += 1 # dfs north dfs(maze, row, column, visited, i - 1, j) # dfs west dfs(maze, row, column, visited, i, j - 1) # dfs south dfs(maze, row, column, visited, i + 1, j) # dfs east dfs(maze, row, column, visited, i, j + 1) # get number of test cases testCases = int(input()) # for each test case while testCases > 0: # get maze dimensions row, column = list(map(int, input().split())) # read maze maze = [] visited = [] for i in range(row): maze.append(list(map(lambda i:i, input()))) visited.append([0] * column) # trap bad guys and count good guys good = 0 GOOD = 0 fail = False for i in range(row): for j in range(column): # bad guy: trap it if maze[i][j] == 'B': # north block if i > 0 and maze[i - 1][j] == '.': maze[i - 1][j] = '#' # east block if j < column - 1 and maze[i][j + 1] == '.': maze[i][j + 1] = '#' # south block if i < row - 1 and maze[i + 1][j] == '.': maze[i + 1][j] = '#' # west block if j > 0 and maze[i][j - 1] == '.': maze[i][j - 1] = '#' # good guy neighbour: fail if (i > 0 and maze[i - 1][j] == 'G') or\ (j < column - 1 and maze[i][j + 1] == 'G') or\ (i < row - 1 and maze[i + 1][j] == 'G') or\ (j > 0 and maze[i][j - 1] == 'G'): fail = True # good guy -> increase the good guys count elif maze[i][j] == 'G': good += 1 # get number of good guys reachable by exit dfs(maze, row, column, visited, row - 1, column - 1) # print response if fail is True or GOOD != good: print('No') else: print('Yes') # decrease test cases count testCases -= 1 <file_sep>""" Max Heap implementation. Complete (or almost) tree where the parent node is always bigger than its childs. Represented by a list. Given a node in the position i: Parent is in position (i - 1) // 2 Left child is in position (2 * i) + 1 Right child is in position (2 * i) + 2 Operations: Build: O(n * log(n)) Insert element: O(log(n)) Remove min: O(log(n)) Update value: O(n) (find element -> O(n), change key O(log(n))) Space complexity: O(n) Applications: Heap sort Keep track of maximum element of a list """ class MaxHeap(): def __init__(self, list = []): """ I initialize an empty max heap. :param list: list to initialize heap :returns: nothing """ # initialize empty heap self.heap = [] # initialize heap with provided list for element in list: self.add(element) def swap(self, i, j): """ I swap two elements of the heap. :param i: index of first element :param j: index of second element :returns: nothing """ swap = self.heap[i] self.heap[i] = self.heap[j] self.heap[j] = swap def getChilds(self, index): """ I get the index of the childs of a node. :param index: index of the element to get childs from :param j: index of second element :returns: index, left child and right child indexes """ return index, (2 * index) + 1, (2 * index) + 2 def size(self): """ I return the size of the heap. :returns: size of the heap """ return len(self.heap) def top(self): """ I return the top element of the heap. :returns: top element of the heap or None on empty heap """ if len(self.heap) > 0: return self.heap[0] return None def add(self, element): """ I add an elemente to the heap. :param element: element to be add. :returns: nothing """ # add element to the heap self.heap.append(element) # get index of added element and parent of added element index = len(self.heap) - 1 parentIndex = (index - 1) // 2 # swap parents and childs while needed while index >= 1 and self.heap[parentIndex] < self.heap[index]: # swap parent and child self.swap(parentIndex, index) # update parent and child indexes index = parentIndex parentIndex = (index - 1) // 2 def remove(self): """ I remove an elemente of the heap. :returns: removed element or None on empty heap """ # non empty heap: get first element if len(self.heap) > 0: removed = self.heap[0] # empty heap: return None else: return None # heap with one element: remove it and return if len(self.heap) == 1: return self.heap.pop() # put last element on the begining of the heap self.heap[0] = self.heap.pop() # descend new root while needed index, leftChild, rightChild = self.getChilds(0) while (leftChild < self.size() and \ self.heap[index] < self.heap[leftChild]) or \ (rightChild < self.size() and \ self.heap[index] < self.heap[rightChild]): # swap smallest child with parent if rightChild == len(self.heap) or \ self.heap[leftChild] > self.heap[rightChild]: # swap with left child and set current node as left child self.swap(index, leftChild) index, leftChild, rightChild = self.getChilds(leftChild) else: # swap with right child and set current node as right child self.swap(index, rightChild) index, leftChild, rightChild = self.getChilds(rightChild) # return removed node return removed def heapsort(list): # turn list into a max heap heap = MaxHeap(list) # remove biggest element from heap and add to result result = [] while heap.size() > 0: result.append(heap.remove()) # return ordered list return result if __name__ == '__main__': # get input list list = list(map(int, input('Insert list to be ordered\n').split())) # print sorted list print(heapsort(list)) <file_sep>""" Problem: https://www.hackerrank.com/challenges/find-the-running-median/problem """ # # CODE # class MaxHeap(): def __init__(self): """ I initialize an empty max heap. :returns: nothing """ self.heap = [] def add(self, element): """ I add an elemente to the max heap. :param element: element to be add. :returns: nothing """ # add element to the heap self.heap.append(element) # get index of added element and parent of added element index = len(self.heap) - 1 parentIndex = (index - 1) // 2 # swap parents and childs while needed while index >= 1 and self.heap[parentIndex] < self.heap[index]: # swap parent and child swap = self.heap[parentIndex] self.heap[parentIndex] = self.heap[index] self.heap[index] = swap # update parent and child indexes index = parentIndex parentIndex = (index - 1) // 2 def remove(self): """ I remove an elemente of max heap. :returns: removed element or None on empty heap """ # non empty heap: get first element if len(self.heap) > 0: removed = self.heap[0] # empty heap: return None else: return None # heap with one element: remove it and return if len(self.heap) == 1: return self.heap.pop() # put last element on the begining of the heap self.heap[0] = self.heap.pop() # descend new root while needed index = 0 leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 while (leftChild < len(self.heap) and \ self.heap[index] < self.heap[leftChild]) or \ (rightChild < len(self.heap) and \ self.heap[index] < self.heap[rightChild]): # swap smallest child with parent if rightChild == len(self.heap) or \ self.heap[leftChild] > self.heap[rightChild]: # swap with left child swap = self.heap[index] self.heap[index] = self.heap[leftChild] self.heap[leftChild] = swap # update indexes index = leftChild leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 else: # swap with right child swap = self.heap[index] self.heap[index] = self.heap[rightChild] self.heap[rightChild] = swap # update indexes index = rightChild leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 # return removed node return removed def size(self): """ I return the size of the heap. :returns: size of the heap """ return len(self.heap) def top(self): """ I return the top element of the heap. :returns: top element of the heap or None on empty heap """ if len(self.heap) > 0: return self.heap[0] return None class MinHeap(): def __init__(self): """ I initialize an empty min heap. :returns: nothing """ self.heap = [] def add(self, element): """ I add an elemente to the min heap. :param element: element to be add. :returns: nothing """ # add element to the heap self.heap.append(element) # get index of added element and parent of added element index = len(self.heap) - 1 parentIndex = (index - 1) // 2 # swap parents and childs while needed while index >= 1 and self.heap[parentIndex] > self.heap[index]: # swap parent and child swap = self.heap[parentIndex] self.heap[parentIndex] = self.heap[index] self.heap[index] = swap # update parent and child indexes index = parentIndex parentIndex = (index - 1) // 2 def remove(self): """ I remove an elemente of min heap. :returns: removed element or None on empty heap """ # non empty heap: get first element if len(self.heap) > 0: removed = self.heap[0] # empty heap: return None else: return None # heap with one element: remove it and return if len(self.heap) == 1: return self.heap.pop() # put last element on the begining of the heap self.heap[0] = self.heap.pop() # descend new root while needed index = 0 leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 while (leftChild < len(self.heap) and \ self.heap[index] > self.heap[leftChild]) or \ (rightChild < len(self.heap) and \ self.heap[index] > self.heap[rightChild]): # swap smallest child with parent if rightChild == len(self.heap) or \ self.heap[leftChild] < self.heap[rightChild]: # swap with left child swap = self.heap[index] self.heap[index] = self.heap[leftChild] self.heap[leftChild] = swap # update indexes index = leftChild leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 else: # swap with right child swap = self.heap[index] self.heap[index] = self.heap[rightChild] self.heap[rightChild] = swap # update indexes index = rightChild leftChild = (2 * index) + 1 rightChild = (2 * index) + 2 # return removed node return removed def size(self): """ I return the size of the heap. :returns: size of the heap """ return len(self.heap) def top(self): """ I return the top element of the heap. :returns: top element of the heap or None on empty heap """ if len(self.heap) > 0: return self.heap[0] return None # read ammount of elements to be added ammount = int(input()) # initialize maxheap to store "bigger of smallest" elements maxHeap = MaxHeap() # initialize minheap to store "samllest of biggest" elements minHeap = MinHeap() # print('------------') for _ in range(ammount): # get new element element = int(input()) # add element to proper heap smallestOfBiggest = minHeap.top() if smallestOfBiggest != None and element >= smallestOfBiggest: minHeap.add(element) else: maxHeap.add(element) # balance heaps minSize = minHeap.size() maxSize = maxHeap.size() if minSize - maxSize == 2: balance = minHeap.remove() maxHeap.add(balance) print((minHeap.top() + maxHeap.top()) / 2) elif maxSize - minSize == 2: balance = maxHeap.remove() minHeap.add(balance) print((minHeap.top() + maxHeap.top()) / 2) elif minSize - maxSize == 1: print(minHeap.top() / 1) elif maxSize - minSize == 1: print(maxHeap.top() / 1) else: print((minHeap.top() + maxHeap.top()) / 2) # # print('smallest of biggest: ', minHeap.heap) # print('biggest of smallest: ', maxHeap.heap) # print('------------') <file_sep>""" Djikstra implementation. Application: Graph algorithm to find shortest path from a source node. Time Complexity: O(E * log(V)): 1 - We need to build the heap with all vertices -> O(V * log(V)) 2 - We relax all edges -> O(E * log(V)) 3 - We remove each vertex from the heap -> O(V * log(V)) Space complexity: O(V + E) Graph is undirected and represented by an adjacency list: each node identifier is a key of a dictonary and its value is the adjacency list of that node. Restriction: No edges with negative cost Algorithm: We start from the source and relax all the edges that it has. We store the value to reach each node in a min heap. We always remove the smallest element from the heap. It represents the smallest distance to reach that node, as any other path will have a higher value, as any other path already has a higher value and a path can only increase to reach the target node. When the heap is empty, or its top value is infinite, then we have reached all nodes that are reacheable by the source. Problem to get input from: https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-7/ Input: n -> number of nodes (starting from 0) s -> source node (0 <= s < n) e -> number of edges e next lines with a b d -> edge connecting node a to b with distance d. 0 <= a and b < n Example (from link): 9 0 14 0 1 4 0 7 8 1 7 11 1 2 8 7 8 7 7 6 1 2 8 2 8 6 6 6 5 2 2 3 7 2 5 4 3 5 14 3 4 9 5 4 10 """ # # IMPORTS # import math # # CODE # class MinHeap(): def __init__(self, list = []): """ I initialize an empty min heap. Each element is a tuple with (id, shortestdistance) of a node :param list: list to initialize heap :returns: nothing """ # initialize empty heap self.heap = [] # initialize empty dict to store each node's position in heap list self.position = dict() # initialize heap with provided list for element in list: self.add(element) def swap(self, i, j): """ I swap two elements of the heap. :param i: index of first element :param j: index of second element :returns: nothing """ # update their position iId = self.heap[i][0] jId = self.heap[j][0] self.position[iId] = j self.position[jId] = i # swap elements swap = self.heap[i] self.heap[i] = self.heap[j] self.heap[j] = swap def getChilds(self, index): """ I get the index of the childs of a node. :param index: index of the element to get childs from :param j: index of second element :returns: index, left child and right child indexes """ return index, (2 * index) + 1, (2 * index) + 2 def add(self, element): """ I add an elemente to the min heap. :param element: element to be add, tuple of node id and distance. :returns: nothing """ # add element to the heap self.heap.append(element) self.position[element[0]] = len(self.heap) - 1 # get index of added element and parent of added element index = len(self.heap) - 1 parentIndex = (index - 1) // 2 # swap parents and childs while needed while index >= 1 and self.heap[parentIndex][1] > self.heap[index][1]: # swap parent and child self.swap(parentIndex, index) # update parent and child indexes index = parentIndex parentIndex = (index - 1) // 2 def remove(self): """ I remove an elemente of min heap. :returns: removed element or None on empty heap """ # non empty heap: get first element if len(self.heap) > 0: removed = self.heap[0] del self.position[removed[0]] # empty heap: return None else: return None # heap with one element: remove it and return if len(self.heap) == 1: self.heap.pop() return removed # put last element on the begining of the heap self.heap[0] = self.heap.pop() self.position[self.heap[0][0]] = 0 # descend new root while needed index, leftChild, rightChild = self.getChilds(0) while (leftChild < len(self.heap) and \ self.heap[index][1] > self.heap[leftChild][1]) or \ (rightChild < len(self.heap) and \ self.heap[index][1] > self.heap[rightChild][1]): # swap smallest child with parent if rightChild == len(self.heap) or \ self.heap[leftChild][1] < self.heap[rightChild][1]: # swap with left child self.swap(index, leftChild) # update indexes index, leftChild, rightChild = self.getChilds(leftChild) else: # swap with left child self.swap(index, rightChild) # update indexes index, leftChild, rightChild = self.getChilds(rightChild) # return removed node return removed def size(self): """ I return the size of the heap. :returns: size of the heap """ return len(self.heap) def top(self): """ I return the top element of the heap. :returns: top element of the heap or None on empty heap """ if len(self.heap) > 0: return self.heap[0] return None def decreaseKey(self, element, cost): """ I decrease the value of an element. :param element: element to have its key decreased :param cost: new element cost :returns: nothing """ # get element and its parent indexes index = self.position[element] parentIndex = (index - 1) // 2 # update its cost self.heap[index] = (element, cost) # swap parents and childs while needed while index >= 1 and self.heap[parentIndex][1] > self.heap[index][1]: # swap parent and child self.swap(parentIndex, index) # update parent and child indexes index = parentIndex parentIndex = (index - 1) // 2 def relax(distances, parents, heap, source, target, distance): """ I relax a node given an edge. :param distances: array with smallest distances from source to each node :param parents: smallest path tree :param heap: heap with smallest distances to each node from source :param source: source node id :param target: target node id :param distance: edge cost from source to target :returns: nothing """ # the current edge offers a better path to target: update it if distances[target] > distances[source] + distance: distances[target] = distances[source] + distance parents[target] = source heap.decreaseKey(target, distances[target]) if __name__ == '__main__': # read input nodes = int(input()) source = int(input()) edges = int(input()) # build empty graph as adjacency list graph = [] for _ in range(nodes): graph.append([]) # populate graph for _ in range(edges): a, b, distance = map(int, input().split()) graph[a].append((b, distance)) graph[b].append((a, distance)) # initialize distances from source list distances = [math.inf] * nodes distances[source] = 0 # initialize parent of shortest path tree list parents = [-1] * nodes parents[source] = None # initialize cut nodes cut = MinHeap() for node in range(nodes): cut.add((node, distances[node])) # execute djikstra while cut.size() > 0 and cut.top() != math.inf: # get node with smallest distance to source node = cut.remove() # relax each edge of node for edge in graph[node[0]]: relax(distances, parents, cut, node[0], edge[0], edge[1]) # print distance and parent of each node for node in range(nodes): print('---------------') print(f'Nó {node} - Distancia: {distances[node]}') print(f'Nó {node} - Pai: {parents[node]}') print('---------------') <file_sep># TLE -> check cpp version testCases = int(input()) while testCases > 0: size = int(input()) string = input() solution = '' one = False zero = False pos = None for i in range(size - 1, -1, -1): if string[i] == '1' and one == False and zero == False: solution = '1' + solution if string[i] == '0' and one == False and zero == False: zero = True pos = i if string[i] == '1' and one == False and zero == True: one = True if string[i] == '0' and one == True and zero == True: string = string[:i + 1] + '0' + string[i + 2:] pos = i + 1 one = False if one == False and zero == True: solution = string[:pos + 1] + solution elif one == True and zero == True: solution = '0' + solution print(solution) testCases -= 1 <file_sep># TLE test 3 # To find the biggest difference, we must retrieve the extremes of each # ascending and descinding sequences # read test cases testCases = int(input()) while testCases > 0: # get n and x n, x = list(map(int, input().split())) # get array elements = list(map(int, input().split())) # initilize size of longes sub array longest = -1 for i in range(n): sum = elements[i] if sum % x != 0 and longest == -1: longest = 1 if n - i <= longest: continue for j in range(i + 1, n): sum += elements[j] if sum % x != 0 and (j - i + 1) > longest: longest = (j - i + 1) print(longest) # decrement test cases testCases -= 1 <file_sep>#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> #include <stdlib.h> #include <string> #include <vector> #include <deque> #include <map> #include <queue> using namespace std; typedef long long int lli; typedef vector <lli> vetor; typedef vector <vector <lli> > matriz; int main () { lli n_points; matriz points; // initialize matrix for (i = 0; i < n_points; i++) { // create a vector with 2 positions initialized with 0 vetor aux (2, 0); // here we create a matrix with n_points lines and 2 columns points.push_back (aux); } // sort arrays vetor aux (2, 0); sort(aux.begin(), aux.end()); return 0; }
6d4886fdf25aeb9a294bd1a08ecfccb8dd0cc3e7
[ "Python", "C++" ]
28
Python
krautz/programming-marathon
57a9d62df67fb667dde455d0f45b90f7e611de1b
29d4bd3a710fb180742c0f49f599a85314153c8f
refs/heads/master
<repo_name>CaueP/cauep-website<file_sep>/app.js /*eslint-env node*/ //------------------------------------------------------------------------------ // Web Server for <NAME>'s website //------------------------------------------------------------------------------ // This application uses express as its web server // for more info, see: http://expressjs.com var express = require('express'); // package to parse the body of a request into a JSON object var bodyParser = require('body-parser'); // cookie parser to store user information var cookieParser = require ('cookie-parser'); // cfenv provides access to your Cloud Foundry environment // for more info, see: https://www.npmjs.com/package/cfenv var cfenv = require('cfenv'); // create a new express server var app = express(); /* setting up the middleware */ // serve the files out of ./public as our main files app.use(express.static(__dirname + '/public')); // setting the views directory app.set('views', './src/views'); // setting ejs as the view engine app.set('view engine', 'ejs'); // get the app environment from Cloud Foundry var appEnv = cfenv.getAppEnv(); /* setting up the Routes */ // nav bar items var nav = [ { Link: '/resume', Text: 'Resume' } ]; app.get('/', function (req, res) { // rendering the index page, sending a json with the title and navigation items res.render('index', { title: 'Hello from render', nav: nav }); }); // start server on the specified port and binding host app.listen(appEnv.port, '0.0.0.0', function() { // print a message when the server starts listening console.log("Running server on port " + appEnv.url); });
c6372affb2cb86d3d0b524747457d6a35fdd3c5a
[ "JavaScript" ]
1
JavaScript
CaueP/cauep-website
a9d417aad5ba5bb048fd59e94dc3366f26971f6c
6460e4d16bce59657fdb48d13e66965cbc3be83a
refs/heads/master
<file_sep><?php /* * Functions relative to debugging * */ /** * Add a message to the debug log * * When in debug mode ( YOURLS_DEBUG == true ) the debug log is echoed in yourls_html_footer() * Log messages are appended to $ydb->debug_log array, which is instanciated within class ezSQLcore_YOURLS * * @since 1.7 * @param string $msg Message to add to the debug log * @return string The message itself */ function yourls_debug_log( $msg ) { global $ydb; yourls_do_action('debug_log', $msg); $ydb->getProfiler()->log($msg); return $msg; } /** * Get the debug log * * @since 1.7.3 * @return array */ function yourls_get_debug_log() { global $ydb; // Check if we have a profiler registered (will not be the case if the DB hasn't been properly connected to) if ($ydb->getProfiler()) { return $ydb->getProfiler()->get_log(); } return array(); } /** * Debug mode set * * @since 1.7.3 * @param bool $bool Debug on or off */ function yourls_debug_mode($bool) { global $ydb; $bool = (bool)$bool; // log queries if true $ydb->getProfiler()->setActive($bool); // report notices if true if ($bool === true) { error_reporting(-1); } else { error_reporting(E_ERROR | E_PARSE); } } /** * Return YOURLS debug mode * * @since 1.7.7 * @return bool */ function yourls_get_debug_mode() { return ( defined( 'YOURLS_DEBUG' ) && YOURLS_DEBUG == true ); }
7318d90ab10acc3e70a7eaa45bf228f38d08e136
[ "PHP" ]
1
PHP
alaamebrahim/YOURLS
93536c8a936d20ccae7404c69cd028bdac50582b
2d26bf25ad1575edad91856c6e38b8c9abc449c0
refs/heads/master
<repo_name>slushatel/repositories_analysis_db_server<file_sep>/src/main/resources/popularity.view.mysql with `popularity_all` (`metric`,`repository`,`technology`,`report_date`,`value`) as ( SELECT `m`.`name` AS `metric`, `r`.`name` AS `repository`, `t`.`name` AS `technology`, `st`.`report_date` AS `report_date`, ((`st`.`value` / `st_sum`.`sum_value`) * 100) AS `value` FROM ((((`trends`.`statistic` `st` JOIN `trends`.`metrics` `m` ON ((`st`.`metric_id` = `m`.`id`))) JOIN `trends`.`repositories` `r` ON ((`st`.`repository_id` = `r`.`id`))) JOIN `trends`.`technologies` `t` ON ((`st`.`technology_id` = `t`.`id`))) JOIN (SELECT `st`.`metric_id` AS `metric_id`, `st`.`repository_id` AS `repository_id`, `st`.`report_date` AS `report_date`, SUM(`st`.`value`) AS `sum_value` FROM `trends`.`statistic` `st` GROUP BY `st`.`metric_id` , `st`.`repository_id` , `st`.`report_date`) `st_sum` ON (((`st_sum`.`report_date` = `st`.`report_date`) AND (`st_sum`.`repository_id` = `st`.`repository_id`) AND (`st_sum`.`metric_id` = `st`.`metric_id`)))) WHERE (`m`.`name` = 'byte size') AND (`r`.`name` IN ('gitlab' , 'github')) ) SELECT `popularity_all`.`metric` AS `metric`, `popularity_all`.`repository` AS `repository`, `popularity_all`.`technology` AS `technology`, `popularity_all`.`report_date` AS `report_date`, `popularity_all`.`value` AS `value` FROM (`popularity_all` JOIN (SELECT DISTINCT `popularity_all`.`technology` AS `technology` FROM `popularity_all` WHERE (`popularity_all`.`value` >= 3)) `top_tech` ON ((`popularity_all`.`technology` = `top_tech`.`technology`))) ORDER BY `popularity_all`.`technology`<file_sep>/src/main/java/com/example/jpa/repository/MetricRepository.java package com.example.jpa.repository; import com.example.jpa.model.Metric; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface MetricRepository extends JpaRepository<Metric, Long> { Optional<Metric> findByName(String name); } <file_sep>/docker/readme.txt docker exec docker_db_1 sh -c "exec mysqldump --all-databases -uroot -pexample > /dump-all-databases.sql" docker cp docker_db_1:/dump-all-databases.sql dump-all-databases.sql docker cp dump-all-databases.sql docker_db_1:/dump-all-databases.sql docker exec -it docker_db_1 bash mysql -uroot -pexample < /dump-all-databases.sql<file_sep>/src/main/java/com/example/jpa/model/StatisticPK.java package com.example.jpa.model; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.Value; import java.io.Serializable; import java.util.Date; import java.util.Objects; @Data @NoArgsConstructor @AllArgsConstructor public class StatisticPK implements Serializable { private long metric; private long repository; private long technology; private Date reportDate; // public StatisticPK() {} // // public StatisticPK(long metric, long repository, long technology, Date reportDate) { // this.metric = metric; // this.repository = repository; // this.technology = technology; // this.reportDate = reportDate; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // StatisticPK statisticPK = (StatisticPK) o; // return metric == statisticPK.metric && // repository == statisticPK.repository && // technology == statisticPK.technology && // reportDate.equals(statisticPK.reportDate); // } // // @Override // public int hashCode() { // return Objects.hash(metric, repository, technology, reportDate); // } // // public long getMetric() { // return metric; // } // // public void setMetric(long metric) { // this.metric = metric; // } // // public long getRepository() { // return repository; // } // // public void setRepository(long repository) { // this.repository = repository; // } // // public long getTechnology() { // return technology; // } // // public void setTechnology(long technology) { // this.technology = technology; // } // // public Date getReportDate() { // return reportDate; // } // // public void setReportDate(Date reportDate) { // this.reportDate = reportDate; // } } <file_sep>/Readme.md # Hibernate One to Many Mapping Example with Spring Boot and JPA Read the Tutorial - https://www.callicoder.com/hibernate-spring-boot-jpa-one-to-many-mapping-example/ ## Setup the Application 1. Create a database named `hibernate_one_to_many_demo`. 2. Open `src/main/resources/application.properties` and change `spring.datasource.username` and `spring.datasource.password` properties as per your MySQL installation. 3. Type `mvn spring-boot:run` from the root directory of the project to run the application. ////////////// DROP SCHEMA IF EXISTS trends; CREATE SCHEMA trends; USE trends; SET AUTOCOMMIT=1; create table metrics ( id bigint auto_increment PRIMARY KEY, name varchar(100) not null, description varchar(1000) ) ; create table technologies ( id bigint auto_increment PRIMARY KEY, name varchar(100) not null ) ; create table repositories ( id bigint auto_increment PRIMARY KEY, name varchar(100) not null, description varchar(1000) ) ; create table statistic ( metric_id bigint not null, repository_id bigint not null, technology_id bigint not null, report_date date not null, value DECIMAL(12,4) ) ; create index METRIC_IDX on statistic(metric_id); create index REPOSITORY_IDX on statistic(repository_id); create index TECHNOLOGY_IDX on statistic(technology_id); create index REPORT_DATA_IDX on statistic(report_date); alter table statistic add constraint STATISTIC_PK primary key (METRIC_ID, REPOSITORY_ID, TECHNOLOGY_ID, REPORT_DATE); alter table statistic add constraint REPOSITORY_FK foreign key (REPOSITORY_ID) references repositories(ID) on delete RESTRICT; alter table statistic add constraint TECHNOLOGY_FK foreign key (TECHNOLOGY_ID) references technologies(ID) on delete RESTRICT; alter table statistic add constraint METRIC_FK foreign key (METRIC_ID) references metrics(ID) on delete RESTRICT; ///////////////////////////////////// curl -X POST -H 'Content-Type: application/json' -i http://localhost:8080/statistics --data '[{"metric":"metric1", "repository":"repository1", "technology":"technology1", "reportDate":"2015-04-01", "value":"40.345"} , {"metric":"metric1", "repository":"repository1", "technology":"technology1", "reportDate":"2015-05-01", "value":"50.345"}] ' curl -X GET -i 'http://localhost:8080/statistics?metric_id=1&repository_id=1&date_from=2015-02-01&date_to=2015-05-01' --data ' ' <file_sep>/src/main/java/com/example/jpa/controller/StatisticRequestBody.java package com.example.jpa.controller; import lombok.Data; import java.util.Date; @Data public class StatisticRequestBody { private String metric; private String repository; private String technology; private Date reportDate; private Double value; } <file_sep>/src/test/java/com/example/jpa/JpaOneToManyDemoApplicationTests.java package com.example.jpa; import com.example.jpa.model.CodeRepository; import com.example.jpa.model.Statistic; import com.example.jpa.model.StatisticPK; import com.example.jpa.model.Technology; import com.example.jpa.model.Metric; import com.example.jpa.repository.CodeRepositoryRepository; import com.example.jpa.repository.StatisticRepository; import com.example.jpa.repository.TechnologyRepository; import com.example.jpa.repository.MetricRepository; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.transaction.Transactional; import java.math.BigDecimal; import java.util.Date; import java.util.Optional; @RunWith(SpringRunner.class) @SpringBootTest public class JpaOneToManyDemoApplicationTests { @Autowired private StatisticRepository statisticRepository; @Autowired private MetricRepository metricRepository; @Autowired private CodeRepositoryRepository codeRepositoryRepository; @Autowired private TechnologyRepository technologyRepository; @Test @Transactional public void contextLoads() { Technology technology; String langName = "lang1"; Optional<Technology> optLang = technologyRepository.findByName(langName); if (optLang.isPresent()) { technology = optLang.get(); } else { technology = new Technology(); technology.setName(langName); technologyRepository.save(technology); } CodeRepository codeRepository; String repoName = "repo2"; Optional<CodeRepository> optRepo = codeRepositoryRepository.findByName(repoName); if (optRepo.isPresent()) { codeRepository = optRepo.get(); } else { codeRepository = new CodeRepository(); codeRepository.setName(repoName); codeRepositoryRepository.save(codeRepository); } Metric metric; String metricName = "metric1"; Optional<Metric> metricRepo = metricRepository.findByName(metricName); if (metricRepo.isPresent()) { metric = metricRepo.get(); } else { metric = new Metric(); metric.setName(metricName); metricRepository.save(metric); } Statistic statistic = new Statistic(); statistic.setMetric(metric); statistic.setRepository(codeRepository); statistic.setTechnology(technology); statistic.setReportDate(new Date()); statistic.setValue(new BigDecimal(123.45)); statisticRepository.save(statistic); Optional<Technology> foundTechnology = technologyRepository.findByName(langName); if (!foundTechnology.isPresent()) { Assert.fail("technologyRepository error"); } else { Assert.assertEquals(technology, foundTechnology.get()); } Optional<CodeRepository> foundCodeRepository = codeRepositoryRepository.findByName(repoName); if (!foundCodeRepository.isPresent()) { Assert.fail("codeRepositoryRepository error"); } else { Assert.assertEquals(codeRepository, foundCodeRepository.get()); } Optional<Metric> foundMetric = metricRepository.findByName(metricName); if (!foundMetric.isPresent()) { Assert.fail("metricRepository error"); } else { Assert.assertEquals(metric, foundMetric.get()); } StatisticPK statisticPK = new StatisticPK( statistic.getMetric().getId(), statistic.getRepository().getId(), statistic.getTechnology().getId(), statistic.getReportDate()); Optional<Statistic> foundStatistic = statisticRepository.findById(statisticPK); if (!foundStatistic.isPresent()) { Assert.fail("statisticRepository error"); } else { Assert.assertEquals(statistic, foundStatistic.get()); } } } <file_sep>/src/main/java/com/example/jpa/repository/TechnologyRepository.java package com.example.jpa.repository; import com.example.jpa.model.Technology; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.Optional; @Repository public interface TechnologyRepository extends JpaRepository<Technology, Long> { Optional<Technology> findByName(String name); }
93319e1cac16e588582a73adf0cb354f95c3f05a
[ "Java", "SQL", "Text", "Markdown" ]
8
SQL
slushatel/repositories_analysis_db_server
85f77f54bf70b9e80764b6b2c6b82ffaf7232fae
9c85f7ab1a15cb958b074e734fd13f0a0be7a361
refs/heads/master
<file_sep>package com.mitocode.service.impl; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.mitocode.dao.ISignoVitalDAO; import com.mitocode.model.SignoVital; import com.mitocode.service.ISignoVitalService; @Service public class SignoVitalServiceImpl implements ISignoVitalService { @Autowired private ISignoVitalDAO dao; @Override public SignoVital registrar(SignoVital signoVital) { return dao.save(signoVital); } @Override public SignoVital modificar(SignoVital signoVital) { return dao.save(signoVital); } @Override public void eliminar(int idSignoVital) { //INI-CAMBIO PARA SPRING BOOT 2 dao.deleteById(idSignoVital); } @Override public SignoVital listarId(int idPaciente) { //INI-CAMBIO PARA SPRING BOOT 2 Optional<SignoVital> opt = dao.findById(idPaciente); return opt.isPresent() ? opt.get() : new SignoVital(); } @Override public List<SignoVital> listar() { return dao.findAll(); } @Override public Page<SignoVital> listarPageable(Pageable pageable) { return dao.findAll(pageable); } }
8d9fafab606b297736c053bb26943a426977dee9
[ "Java" ]
1
Java
bguamanzara/mediapp-backend
57d4f662ac37c05523afc9dec5f2614872a27157
26ddd413968d1952919f2dc704ab2d9f0b75e8f4
refs/heads/master
<file_sep>// class_recursive.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include "recurs.h" #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include "extract.h" #include"net.h" #include "block.h" #include "create_matrix.h" using namespace std; int main() { /*extern vec_rec rec_val; cout << rec_val.total_numbers << endl;*/ create_matrix vans; //vector<double>x = vans.get_q(38); /*for (int i = 16; i < 50; i++){ vector<double>x = vans.get_q(i); cout << "i=" << i << endl; }*/ //vector<double>line_t=vans.get_q(22); //extern vector<vector<int>>ad; //cout << ad[99][6]; //double w = vans.gsum(23, 4); //cout << w; vans.get_file(); /*extract van; vector<vector<int>>i=van.advanced_return(); cout << i[99][10];*/ /*block van; vector<int>o = van.j_connection(1); cout << o[5];*/ system("pause"); return 0; } <file_sep>#pragma once #include <vector> #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; struct vec_rec{ vector<double>a;//total data vector<double> fixed;//fixed blocks' data int totoal_nets;//otal nets int total_numbers;//total file length int fixed_numbers;//number of fixed blocks data c1=15 int start; }; struct xy{ vector<double>x; vector<double>y; }; class extract { private: public: //int f_size; extract(); ~extract(); vector<int> get_net();//get all moveable blocks in the circuit vec_rec recv();//get all contents vector<double> fixed();//return a vector with only fixed block number xy get_cfile(); vector<vector<int>>advanced_return(); }; <file_sep>//#include "stdafx.h" #include "file_extract.h" file_extract::file_extract() { } file_extract::~file_extract() { } content file_extract::extraction(){ content newfile; vector<vector<int>>temp; int k = 0; temp.resize(1);//do not forget to give an initial length to vector row ifstream infile; infile.open("cct2.txt"); while (!infile.eof()){ int n; //int i = 0; infile >> n; if (n == -1){ k = k + 1; temp.resize(k+2);//k+2 is the new size for vector } else { //cout << k; temp[k].push_back(n); } } cout << "k=" << k <<endl; for (int i = 0; i < k-1; i++){ newfile.file_content.insert(pair<int, vector<int>>(i, temp[i])); } //map<int, vector<int>>::iterator i; int nsize = newfile.file_content.size(); newfile.total_blocks = nsize - 1;//get total blocks vector<int>fanouts; for (int m = 0; m < nsize-1; m++){ int a = 0; a = newfile.file_content[m].size(); fanouts.push_back(a); } cout << "nsize" << nsize << endl; newfile.block_fanout = fanouts; newfile.total_blocks = nsize; return newfile; } map<int, vector<int>> file_extract::get_connection(){ content s = extraction(); map<int, vector<int>>cost_value; for (int i = 0; i < s.total_blocks; i++){ vector<int>temp = s.file_content[i]; vector<int>value; vector<int>final_value; vector<int>store; cout << s.total_blocks << endl; for (int m = i + 1; m < s.total_blocks; m++){ int length = temp.size(); vector<int>compare = s.file_content[m]; int c_length = compare.size(); int cost = 0; for (int y = 1; y < length; y++){ for (int x = 1; x < c_length; x++){ if (temp[y] == compare[x]){ cost = cost + 1; } } } store.push_back(cost); } if (i == 0){ int ss = store.size(); cout << "store size" << ss << endl; value.push_back(0); final_value.insert(final_value.end(), value.begin(), value.end());//½«vec1ѹÈë final_value.insert(final_value.end(), store.begin(), store.end()); cost_value.insert(pair<int, vector<int>>(i, final_value)); } else { for (int x = 0; x < i; x++){ vector < int >c = cost_value[x]; vector<int>temp_store; for (int j = x+1; j < s.total_blocks; j++){ temp_store.push_back(c[j]); } value.push_back(temp_store[i - x - 1]); } value.push_back(0); final_value.insert(final_value.end(), value.begin(), value.end());//½«vec1ѹÈë final_value.insert(final_value.end(), store.begin(), store.end()); cost_value.insert(pair<int, vector<int>>(i, final_value)); } } return cost_value; } <file_sep>grep " 0" vpr_stdout.log >> a1.txt <file_sep>#pragma once #include <vector> #include <iostream> #include "block.h" #include "extract.h" #include "recurs.h" using namespace std; class create_matrix; class spread { block bm; extract em; create_matrix *cd; public: vector<double>get_nb(int x);//x represents if to get x or y value spread(); ~spread(); }; <file_sep>./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --place --pack --place_algorithm bounding_box --nodisp --seed 2 grep " 0" vpr_stdout.log >> s4.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --place --pack --place_algorithm bounding_box --nodisp --seed 3 grep " 0" vpr_stdout.log >> s4.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --place --pack --place_algorithm bounding_box --nodisp --seed 4 grep " 0" vpr_stdout.log >> s4.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --place --pack --place_algorithm bounding_box --nodisp --seed 5 grep " 0" vpr_stdout.log >> s4.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --place --pack --place_algorithm bounding_box --nodisp --seed 6 grep " 0" vpr_stdout.log >> s4.txt <file_sep>sed -i -- 's/ ns//' newb2.txt <file_sep>./vpr k6_frac_N10_mem32K_40nm.xml diffeq1.blif --route_chan_width 56 --nodisp grep "Final critical path" vpr_stdout.log >> B3result.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --route_chan_width 54 --nodisp grep "Final critical path" vpr_stdout.log >> B3result.txt ./vpr k6_frac_N10_mem32K_40nm.xml raygentop.blif --route_chan_width 72 --nodisp grep "Final critical path" vpr_stdout.log >> B3result.txt ./vpr k6_frac_N10_mem32K_40nm.xml or1200.blif --route_chan_width 78 --nodisp grep "Final critical path" vpr_stdout.log >> B3result.txt <file_sep>#include <stdio.h> #include "graphics.h" using namespace std; // Callbacks for event-driven window handling. void delay (void); void drawscreen (void); void act_on_new_button_func (void (*drawscreen_ptr) (void)); void act_on_button_press (float x, float y); void act_on_mouse_move (float x, float y); void act_on_key_press (char c); // For example showing entering lines and rubber banding static bool rubber_band_on = false; static bool have_entered_line, have_rubber_line; static bool line_entering_demo = false; static float x1, y1, x2, y2; static int num_new_button_clicks = 0; int main() { int i; /* initialize display with WHITE background */ printf ("About to start graphics.\n"); init_graphics("Some Example Graphics", WHITE); /* still picture drawing allows user to zoom, etc. */ // Set-up coordinates from (xl,ytop) = (0,0) to // (xr,ybot) = (1000,1000) init_world (0.,0.,1000.,1000.); update_message("Interactive graphics example."); // Pass control to the window handling routine. It will watch for user input // and redraw the screen / pan / zoom / etc. the graphics in response to user // input or windows being moved around the screen. This is done by calling the // four callbacks below. mouse movement and key press (keyboard) events aren't // enabled by default, so they aren't on yet. event_loop(act_on_button_press, NULL, NULL, drawscreen); /* animation section */ clearscreen(); update_message("Non-interactive (animation) graphics example."); setcolor (RED); setlinewidth(1); setlinestyle (DASHED); init_world (0.,0.,1000.,1000.); for (i=0; i<50; i++) { drawline ((float)i,(float)(10.*i),(float)(i+500.),(float)(10.*i+10.)); flushinput(); delay(); } /* Draw an interactive still picture again. I'm also creating one new button. */ init_world (0.,0.,1000.,1000.); update_message("Interactive graphics #2. Click in graphics area to rubber band line."); create_button ("Window", "0 Clicks", act_on_new_button_func); // Enable mouse movement (not just button presses) and key board input. // The appropriate callbacks will be called by event_loop. set_keypress_input (true); set_mouse_move_input (true); line_entering_demo = true; // draw the screen once before calling event loop, so the picture is correct // before we get user input. drawscreen(); event_loop(act_on_button_press, act_on_mouse_move, act_on_key_press, drawscreen); close_graphics (); printf ("Graphics closed down.\n"); return (0); } void drawscreen (void) { /* redrawing routine for still pictures. Graphics package calls * * this routine to do redrawing after the user changes the window * * in any way. */ t_point polypts[3] = {{500.,400.},{450.,480.},{550.,480.}}; t_point polypts2[4] = {{700.,400.},{650.,480.},{750.,480.}, {800.,400.}}; set_draw_mode (DRAW_NORMAL); // Should set this if your program does any XOR drawing in callbacks. clearscreen(); /* Should precede drawing for all drawscreens */ setfontsize (10); setlinestyle (SOLID); setlinewidth (1); setcolor (BLACK); drawtext (110.,55.,"colors",150.); setcolor (LIGHTGREY); fillrect (150.,30.,200.,80.); setcolor (DARKGREY); fillrect (200.,30.,250.,80.); setcolor (WHITE); fillrect (250.,30.,300.,80.); setcolor (BLACK); fillrect (300.,30.,350.,80.); setcolor (BLUE); fillrect (350.,30.,400.,80.); setcolor (GREEN); fillrect (400.,30.,450.,80.); setcolor (YELLOW); fillrect (450.,30.,500.,80.); setcolor (CYAN); fillrect (500.,30.,550.,80.); setcolor (RED); fillrect (550.,30.,600.,80.); setcolor (DARKGREEN); fillrect (600.,30.,650.,80.); setcolor (MAGENTA); fillrect (650.,30.,700.,80.); setcolor (WHITE); drawtext (400.,55.,"fillrect",150.); setcolor (BLACK); drawtext (250.,150.,"drawline",150.); setlinestyle (SOLID); drawline (200.,120.,200.,200.); setlinestyle (DASHED); drawline (300.,120.,300.,200.); setcolor (MAGENTA); drawtext (450, 160, "drawellipticarc", 150); drawellipticarc (550, 160, 30, 60, 90, 270); drawtext (720, 160, "fillellipticarc", 150); fillellipticarc (800, 160, 30, 60, 90, 270); setcolor (BLUE); drawtext (190.,300.,"drawarc",150.); drawarc (190.,300.,50.,0.,270.); drawarc (300.,300.,50.,0.,-180.); fillarc (410.,300.,50.,90., -90.); fillarc (520.,300.,50.,0.,360.); setcolor (BLACK); drawtext (520.,300.,"fillarc",150.); setcolor (BLUE); fillarc (630.,300.,50.,90.,180.); fillarc (740.,300.,50.,90.,270.); fillarc (850.,300.,50.,90.,30.); setcolor (RED); fillpoly(polypts,3); fillpoly(polypts2,4); setcolor (BLACK); drawtext (500.,450.,"fillpoly",150.); setcolor (DARKGREEN); drawtext (500.,610.,"drawrect",150.); drawrect (350.,550.,650.,670.); setcolor (BLACK); setfontsize (8); drawtext (100.,770.,"8 Point Text",800.); setfontsize (12); drawtext (400.,770.,"12 Point Text",800.); setfontsize (15); drawtext (700.,770.,"18 Point Text",800.); setfontsize (24); drawtext (300.,830.,"24 Point Text",800.); setfontsize (32); drawtext (700.,830.,"32 Point Text",800.); setfontsize (10); setlinestyle (SOLID); drawtext (200.,900.,"Thin line (width 1)",800.); setlinewidth (1); drawline (100.,920.,300.,920.); drawtext (500.,900.,"Width 3 Line",800.); setlinewidth (3); drawline (400.,920.,600.,920.); drawtext (800.,900.,"Width 6 Line",800.); setlinewidth (6); drawline (700.,920.,900.,920.); setlinewidth (1); setcolor (GREEN); if (have_entered_line) drawline (x1, y1, x2, y2); // Screen redraw will get rid of a rubber line. have_rubber_line = false; } void delay (void) { /* A simple delay routine for animation. */ int i, j, k, sum; sum = 0; for (i=0;i<100;i++) for (j=0;j<i;j++) for (k=0;k<1000;k++) sum = sum + i+j-k; } void act_on_new_button_func (void (*drawscreen_ptr) (void)) { char old_button_name[200], new_button_name[200]; printf ("You pressed the new button!\n"); setcolor (MAGENTA); setfontsize (12); drawtext (500., 500., "You pressed the new button!", 10000.); sprintf (old_button_name, "%d Clicks", num_new_button_clicks); num_new_button_clicks++; sprintf (new_button_name, "%d Clicks", num_new_button_clicks); change_button_text (old_button_name, new_button_name); } void act_on_button_press (float x, float y) { /* Called whenever event_loop gets a button press in the graphics * * area. Allows the user to do whatever he/she wants with button * * clicks. */ printf("User clicked a button at coordinates (%f, %f)\n", x, y); if (line_entering_demo) { if (rubber_band_on) { rubber_band_on = false; x2 = x; y2 = y; have_entered_line = true; // both endpoints clicked on --> consider entered. // Redraw screen to show the new line. Could do incrementally, but this is easier. drawscreen (); } else { rubber_band_on = true; x1 = x; y1 = y; have_entered_line = false; have_rubber_line = false; } } } void act_on_mouse_move (float x, float y) { // function to handle mouse move event, the current mouse position in the current world coordinate // as defined as MAX_X and MAX_Y in init_world is returned printf ("Mouse move at (%f,%f)\n", x, y); if (rubber_band_on) { // Go into XOR mode. Make sure we set the linestyle etc. for xor mode, since it is // stored in different state than normal mode. set_draw_mode (DRAW_XOR); setlinestyle (SOLID); setcolor (WHITE); setlinewidth (1); if (have_rubber_line) { // Erase old line. drawline (x1, y1, x2, y2); } have_rubber_line = true; x2 = x; y2 = y; drawline (x1, y1, x2, y2); // Draw new line } } void act_on_key_press (char c) { // function to handle keyboard press event, the ASCII character is returned printf ("Key press: %c\n", c); } <file_sep>#!/bin/sh ./abc; read_blif alu4.blif; resyn2; print_stats; <file_sep>for present in 0.1 0.5 1 1.5 do echo "diffeq1.blif initial_pres_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml diffeq1.blif --route_chan_width 56 --initial_pres_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.1 0.5 1 1.5 do echo "sha.blif initial_pres_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --route_chan_width 54 --initial_pres_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.1 0.5 1 1.5 do echo "raygentop.blif initial_pres_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml raygentop.blif --route_chan_width 72 --initial_pres_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.1 0.5 1 1.5 do echo "or1200.blif initial_pres_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml or1200.blif --route_chan_width 78 --initial_pres_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done <file_sep>#pragma once #include <vector> #include <iostream> #include <string> #include <fstream> #include <sstream> #include <map> #include "extern.h" struct final_val{ vector<int>partition_result; int best; }; class calculator; class draw_graph; class branching { draw_graph *DDG; calculator *C; public: branching(); ~branching(); vector<int>fanout_calculation();//calculate fanout of each block vector<int>initial_partition();//get initial best //int getc_cost(int b1, int b2);//calculate cut size for a solution or partial solution final_val branch_result(); final_val branching_recursion(map<int, map<int, vector<int>>>*x1,int n,int b,vector<int>v1); }; <file_sep>./vpr k6_frac_N10_mem32K_40nm.xml or1200.blif --place --pack --place_algorithm bounding_box --nodisp --seed 6 --init_t 0.05 grep " 0" vpr_stdout.log >> A2data/o_6005.txt ./vpr k6_frac_N10_mem32K_40nm.xml or1200.blif --place --pack --place_algorithm bounding_box --nodisp --seed 6 --init_t 0.8 grep " 0" vpr_stdout.log >> A2data/o_6005.txt <file_sep>#pragma once #include <vector> #include "recurs.h" #include <iostream> #include <string> #include <fstream> #include <sstream> #include "extract.h" #include "net.h" #include "block.h" using namespace std; struct linear_parameter{ int m; int n; vector<int>Ap; vector<int>Ai; vector<double>Ax; //vector<double>b; }; class spread; class create_matrix { extract c; net ba; block bbc; spread *sm; public: create_matrix(); ~create_matrix(); void get_file(); vector<vector<double>> matrix_calculation(); vector<double> get_q(int i);//i=0,1 vector<int>get_connections(int i, vector<int>neti);//i=0,1.. double gsum(int x, int y);//x=row ,6,7,8... y=column 6,7,8... vector<double> get_b(int x_y); linear_parameter create_matrix::mat(vector<vector<double>>Atest, vector<double>B_test); }; <file_sep>#include <stdio.h> #include "graphics.h" #include "pathRender.h" #include "a_test.h" #include "router.h" #include <stdio.h> #include <iostream> #include <cstring> #include <vector> #include <fstream> using namespace std; // Callbacks for event-driven window handling. void delay(void); // For example showing entering lines and rubber banding int main() { int m = 0; double num[200]; ifstream file; file.open("circuit.txt"); while (!file.eof()) { file >> num[m++]; } int n = num[0];//need modified to auto extract data from num int w = num[1]; int p = 3; int q = 3; int x = 0; int y = 0; int z = num[19]; int **a = new int*[2 * n + 1]; for (int k = 0; k<2 * n + 1; k++) { a[k] = new int[2 * n + 1]; } for (int i = 0; i < 2 * n + 1; i++){ //cout << i; for (int j = 0; j < 2 * n + 1; j++){ if (i % 2 == 0){ if (j % 2 == 0){ a[i][j] = 0;//switch blocks are 0 } else a[i][j] = 1;//pathes are 1 } else { if (j % 2 == 1){ a[i][j] = 0;//logic blocks are 0 } else a[i][j] = 1;// paths are 1 } } } a[2 * p + 2][2 * q] = 's';//we use the swicth behind source logic to be source a[2 * x + 2][2 * y] = 't';//we use the swicth behind target logic to be target cout << a[2 * x + 2][2 * y] << endl; cout << a[2 * p + 2][2 * q] << endl; int *rng = new int[2]; rng[0] = 2 * p + 2;// need improve to auto assign rng[1] = 2 * q; path recv; recv.n = 0; recv.fifo = a;//bad naming fifo is used to receive 2n+1,2n+1 matrix recv.grid = rng;//used to recive expansion list recv.l = 2; recv.con_num = 2; recv.pl = 0; recv.n_con = 2; recv.w_con = 0; recv.t_con = 0; for (recv.con_num = 0; recv.n == 0; recv.con_num = recv.con_num + 2){ recv = pathRender(recv, n); cout << "finish a loop" << endl; } int source[2] = { 2 * p + 2, 2 * q }; int init_arr[2] = { 2 * x + 2, 2 * y }; cout << recv.pl << endl; int pass_len = recv.pl; int par[3] = { recv.pl, n, z }; printf("About to start graphics.\n"); init_graphics("Some Example Graphics", WHITE); /* still picture drawing allows user to zoom, etc. */ // Set-up coordinates from (xl,ytop) = (0,0) to // (xr,ybot) = (1000,1000) init_world(0., 0., 1000., 1000.); update_message("Interactive graphics example."); for (int y_num = 0; y_num < 4; y_num++){//drawing the logic blocks for (int l_num = 0; l_num < 4; l_num++){ setcolor(DARKGREEN); //drawtext(500., 610., "drawrect", 150.); drawrect(100 * l_num + 50., 100 * y_num + 50., 100 * l_num + 100., 100 * y_num + 100.);//x,y for start and finish, start at 50,50 ,length of square is 50 flushinput(); delay(); } } for (int len_num = 0; len_num < 5; len_num++){ for (int lines = 0; lines < 4; lines++){ for (int row = 0; row < 8; row++){ setlinestyle(SOLID); drawline(100 * lines + 50., 100 * len_num + 1 * row + 5., 100 * lines + 100., 100 * len_num + 1 * row + 5.);//from above to below flushinput(); delay(); } } } for (int len_num = 0; len_num < 4; len_num++){ for (int lines = 0; lines < 5; lines++){ for (int row = 0; row < 8; row++){ setlinestyle(SOLID); drawline(100 * lines + 1 * row + 5., 100 * len_num + 55., 100 * lines + 1 * row + 5., 100 * len_num + 105.);//from left to right flushinput(); delay(); } } } draw(recv.fifo, init_arr, source, par); delay(); delay(); flushinput(); //clearscreen(); update_message("Non-interactive (animation) graphics example."); /* Draw an interactive still picture again. I'm also creating one new button. */ //close_graphics(); printf("Graphics closed down.\n"); //system("pause"); return (0); } <file_sep>ulimit -s 10240 <file_sep>#include "draw_graph.h" draw_graph::draw_graph() { } draw_graph::~draw_graph() { } void draw_graph::draw_depth(map<int, vector<int>>x1){ extern content file_reclaim; extern map<int, vector<int>>order; extern vector<int>branching_o; for (int i = 0; i < x1.size(); i++){ if (x1[i].size() != 0){ vector<int>t = x1[i]; int deviation = 0; double x_coordinate = 500; double y_coordinate = 0; double prex_coordinate = 500; double prey_coordinate = 0; for (int k = 0; k < file_reclaim.total_blocks; k++){ int num = pow(3, k + 1); if (t[k] == 0){ break; } else{ if (t[k] == 1){ x_coordinate = x_coordinate - (1000 / num); } else { if (t[k] == 2){ x_coordinate = x_coordinate; } else{ x_coordinate = x_coordinate + (1000 / num); } } y_coordinate = y_coordinate + 50; } } for (int k = 0; k < file_reclaim.total_blocks; k++){ int num = pow(3, k + 1); if (t[k + 1] == 0){ break; } else{ if (t[k] == 1){ prex_coordinate = prex_coordinate - (1000 / num); } else { if (t[k] == 2){ prex_coordinate = prex_coordinate; } else{ prex_coordinate = prex_coordinate + (1000 / num); } } prey_coordinate = prey_coordinate + 50; } } setcolor(RED); setlinestyle(SOLID); drawline(prex_coordinate, prey_coordinate, x_coordinate, y_coordinate); } } } void draw_graph::draw_lbf(map<int, vector<int>>x2){ extern content file_reclaim; extern map<int, vector<int>>order; extern vector<int>branching_o; for (int i = 0; i < x2.size(); i++){ if (x2[i].size() != 0){ vector<int>t = x2[i]; int deviation = 0; double x_coordinate = 2500; double y_coordinate = 0; double prex_coordinate = 2500; double prey_coordinate = 0; for (int k = 0; k < file_reclaim.total_blocks; k++){ int num = pow(3, k+1); if (t[k] == 0){ break; } else{ if (t[k] == 1){ x_coordinate = x_coordinate - (6000 / num); } else { if (t[k] == 2){ x_coordinate = x_coordinate; } else{ x_coordinate = x_coordinate + (6000 / num); } } y_coordinate = y_coordinate + 200; } } for (int k = 0; k < file_reclaim.total_blocks; k++){ int num = pow(3, k+1); if (t[k+1] == 0){ break; } else{ if (t[k] == 1){ prex_coordinate = prex_coordinate - (6000 / num); } else { if (t[k] == 2){ prex_coordinate = prex_coordinate; } else{ prex_coordinate = prex_coordinate + (6000 / num); } } prey_coordinate = prey_coordinate + 200; } } setcolor(RED); setlinestyle(SOLID); drawline(prex_coordinate, prey_coordinate, x_coordinate, y_coordinate); flushinput(); //cout<<"I draw a line"<<endl; if (prex_coordinate==x_coordinate&&prey_coordinate==y_coordinate){ cout<<"damn"<<endl; } } } } <file_sep>// test.cpp : 定义控制台应用程序的入口点。 // //#include "stdafx.h" #include <iostream> #include <string> #include <fstream> #include <sstream> using namespace std; int length(){ char buffer[256]; int i; ifstream infile; infile.open("circuit.txt"); if (!infile.is_open()) { cout << "cannot open"; } //infile.getline(buffer, 100); //cout << buffer[0] << endl; while (!infile.eof()){ for (i = 1; buffer[0] != '-'; i++) infile.getline(buffer, 20); } return i; infile.close(); } <file_sep>//#include "stdafx.h" #include "low_bound_first.h" low_bound_first::low_bound_first() { } low_bound_first::~low_bound_first() { } void low_bound_first::lbf(){ extern content file_reclaim; extern map<int, vector<int>>order; extern vector<int>branching_o; map<int, vector<int>>p0; vector<int>pl; vector<int>pm; vector<int>pr; for (int k = 0; k < file_reclaim.total_blocks + 4; k++){ if (k == 0){ pl.push_back(1); pm.push_back(2); pr.push_back(3); } else{ pl.push_back(0); pm.push_back(0); pr.push_back(0); } } /*count number of l,m,r;12number of location+3numbers of count and 1bit of lb*/ pl[file_reclaim.total_blocks] = 1; pm[file_reclaim.total_blocks + 1] = 1; pr[file_reclaim.total_blocks + 2] = 1; map < int, map<int, vector<int>>>p1; p0[0] = pl; p0[1] = pm; p0[2] = pr; int best = 0; for (int x = 0; x < file_reclaim.total_blocks / 3; x++){ for (int i = 0; i < file_reclaim.total_blocks / 3; i++){ int n = 0; n = c_sample.getc_cost(branching_o[x], branching_o[i + file_reclaim.total_blocks / 3]); best = best + n; cout << "first is " << branching_o[x] << endl; cout << "second is " << branching_o[i + file_reclaim.total_blocks / 3] << endl; n = c_sample.getc_cost(branching_o[x], branching_o[i + file_reclaim.total_blocks * 2 / 3]); best = best + n; cout <<"initial best" <<best; } } for (int x = 0; x < file_reclaim.total_blocks / 3; x++){ for (int i = 0; i < file_reclaim.total_blocks / 3; i++){ int n = 0; n = c_sample.getc_cost(branching_o[x + file_reclaim.total_blocks / 3], branching_o[i + file_reclaim.total_blocks * 2 / 3]); best = best + n; } } map<int, vector<int>>p; r bi; bi=lbf_recur(&p1, &p0,&p, 0,best,0,0,0); for (int i = 0; i >= 0; i++){ //r goblin; bi = lbf_recur(bi.x1, bi.x2, bi.results, bi.n, bi.b, bi.signal, bi.count, bi.set); if (bi.set == 1){ break; } } } r low_bound_first::lbf_recur(map<int, map<int, vector<int>>>*x1, map<int, vector<int>>*x2, map<int, vector<int>>*results, int n, int b, int signal, int count, int set){ //cout << "number at input" << n << endl; DG.draw_lbf((*x2)); extern content file_reclaim; extern map<int, vector<int>>order; extern vector<int>branching_o; int x1nz = 0; for (int i = 0; i <(*x1).size(); i++){ if ((*x1)[i].size() != 0){ x1nz = x1nz + 1; } } if (x1nz == 0 && (*x2).size() == 0){//no more unprocessed partial solution int best = b; for (int i = 0; i < (*results).size(); i++){ vector<int>temp = (*results)[i]; if (temp[file_reclaim.total_blocks + 3] < best){ best = temp[file_reclaim.total_blocks + 3]; } } cout << "best= " << best << endl; r result; result.b = b; result.count = 0; result.n = n; result.results = results; result.set = 1; result.signal = signal; result.x1 = x1; result.x2 = x2; return result; } else{ if (count == 2000){ r result; result.b = b; result.count = 0; result.n = n; result.results = results; result.set = 0; result.signal = signal; result.x1 = x1; result.x2 = x2; cout << "intermediate return" << endl; return result; } else{ /*have not reached end yet*/ if (signal == 0){ map<int, vector<int>>size_c; map<int, vector<int>>new_primier; size_c = (*x2); int nsize = size_c.size(); int primier = 3 * nsize; int new_count = 0; for (int k = 0; k < nsize; k++){ //for (int i = 0; i < nsize; i++){ vector<int>old_partial_l = size_c[k]; vector<int>old_partial_m = size_c[k]; vector<int>old_partial_r = size_c[k]; old_partial_l[n + 1] = 1; old_partial_l[file_reclaim.total_blocks] = old_partial_l[file_reclaim.total_blocks] + 1; if (old_partial_l[file_reclaim.total_blocks] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_l = old_partial_l; int costl = c_sample.cost_increase(new_partial_l, n + 1); //cout << costl << endl; new_partial_l[file_reclaim.total_blocks + 3] = new_partial_l[file_reclaim.total_blocks + 3] + costl; if (new_partial_l[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_l; new_count = new_count + 1; } } old_partial_m[n + 1] = 2; old_partial_m[file_reclaim.total_blocks + 1] = old_partial_m[file_reclaim.total_blocks + 1] + 1; if (old_partial_m[file_reclaim.total_blocks + 1] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_m = old_partial_m; int costm = c_sample.cost_increase(new_partial_m, n + 1); new_partial_m[file_reclaim.total_blocks + 3] = new_partial_m[file_reclaim.total_blocks + 3] + costm; if (new_partial_m[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_m; new_count = new_count + 1; } } old_partial_r[n + 1] = 3; old_partial_r[file_reclaim.total_blocks + 2] = old_partial_r[file_reclaim.total_blocks + 2] + 1; if (old_partial_r[file_reclaim.total_blocks + 2] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_r = old_partial_r; int costr = c_sample.cost_increase(new_partial_r, n + 1); new_partial_r[file_reclaim.total_blocks + 3] = new_partial_r[file_reclaim.total_blocks + 3] + costr; if (new_partial_r[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_r; new_count = new_count + 1; } } } if (new_primier.size() == 0){//no available vectors for x2(no better or legal solution) if ((*x1)[n].size() != 0){ (*x2) = (*x1)[n]; } else{ n = n - 1; (*x2) = (*x1)[n]; } cout << "doom" << endl; count = count + 1; return lbf_recur(x1, x2, results, n, b, signal,count,set); } else{ map<int, vector<int>>new_x2; int new_x2_length = 0; int lb = 3000; int npsize = new_primier.size(); //cout << "new primier size " << new_primier.size() << endl; //int count_nz_new_primier = new_primier.size(); map<int, vector<int>>temp = new_primier; map<int, vector<int>>reclaim; for (int i = 0; i <npsize; i++){ vector<int>temp; temp = new_primier[i]; if (temp[file_reclaim.total_blocks + 3] < lb){ lb = temp[file_reclaim.total_blocks + 3]; } } //cout << "lb= " << lb << endl; for (int i = 0; i < npsize; i++){ vector<int>temp; temp = new_primier[i]; if (temp[file_reclaim.total_blocks + 3] == lb){ new_x2[new_x2_length] = temp; new_x2_length = new_x2_length + 1; new_primier.erase(i); //cout << "erased number " << i<< endl; } } (*x2) = new_x2; // cout << "x2 size at section1 " << (*x2).size() << endl; map<int, vector<int>>temp2 = *x2; int kkp = new_primier.size(); int count_nz = 0; int *pp; pp = &count_nz; cout << *pp << endl; for (int i = 0; count_nz< kkp; i++){ //vector<int>t = temp[i]; //cout << i; if (new_primier[i].size() != 0){ vector<int>t = new_primier[i]; reclaim[count_nz] = t; count_nz = count_nz + 1; //cout << "count is " << count_nz; } } if (reclaim.size() > 0){ (*x1)[n + 1] = reclaim; //x1.erase(n); } //cout << "x1[n+1] size at section1 " << (*x1)[n + 1].size() << endl; map<int, vector<int>>temp1 = (*x1)[n + 1]; if (n + 1 == file_reclaim.total_blocks - 2){ signal = 1; } count = count + 1; return lbf_recur(x1, x2, results, n + 1, b, signal,count,set); } } else{ /*reach end at this time*/ if (n == file_reclaim.total_blocks - 2){ signal = 1; map<int, vector<int>>size_c; map<int, vector<int>>new_primier; size_c = (*x2); int nsize = size_c.size(); int primier = 3 * nsize; int new_count = 0; for (int k = 0; k < nsize; k++){ //for (int i = 0; i < nsize; i++){ vector<int>old_partial_l = size_c[k]; vector<int>old_partial_m = size_c[k]; vector<int>old_partial_r = size_c[k]; old_partial_l[n + 1] = 1; old_partial_l[file_reclaim.total_blocks] = old_partial_l[file_reclaim.total_blocks] + 1; if (old_partial_l[file_reclaim.total_blocks] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_l = old_partial_l; int costl = c_sample.cost_increase(new_partial_l, n + 1); //cout << costl << endl; new_partial_l[file_reclaim.total_blocks + 3] = new_partial_l[file_reclaim.total_blocks + 3] + costl; if (new_partial_l[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_l; new_count = new_count + 1; b = new_partial_l[file_reclaim.total_blocks + 3]; } } old_partial_m[n + 1] = 2; old_partial_m[file_reclaim.total_blocks + 1] = old_partial_m[file_reclaim.total_blocks + 1] + 1; if (old_partial_m[file_reclaim.total_blocks + 1] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_m = old_partial_m; int costm = c_sample.cost_increase(new_partial_m, n + 1); new_partial_m[file_reclaim.total_blocks + 3] = new_partial_m[file_reclaim.total_blocks + 3] + costm; if (new_partial_m[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_m; new_count = new_count + 1; b = new_partial_m[file_reclaim.total_blocks + 3]; } } old_partial_r[n + 1] = 3; old_partial_r[file_reclaim.total_blocks + 2] = old_partial_r[file_reclaim.total_blocks + 2] + 1; if (old_partial_r[file_reclaim.total_blocks + 2] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_r = old_partial_r; int costr = c_sample.cost_increase(new_partial_r, n + 1); new_partial_r[file_reclaim.total_blocks + 3] = new_partial_r[file_reclaim.total_blocks + 3] + costr; if (new_partial_r[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_r; new_count = new_count + 1; b = new_partial_r[file_reclaim.total_blocks + 3]; } } } int rsize = (*results).size(); for (int i = 0; i < new_primier.size(); i++){ vector<int>temp = new_primier[rsize]; rsize = rsize + 1; } if ((*x1)[n].size() != 0){ //x1.erase(n); int low = 3000; map<int, vector<int>>temp = (*x1)[n]; for (int i = 0; i < (*x1)[n].size(); i++){ vector<int>t = temp[i]; for (int k = 0; k < t.size(); k++){ if (t[file_reclaim.total_blocks + 3] < low){ low = t[file_reclaim.total_blocks + 3]; } } } int x2_count = 0; map<int, vector<int>>temp11 = (*x1)[n]; for (int i = 0; i < (*x1)[n].size(); i++){ vector<int>t = temp[i]; if (t[file_reclaim.total_blocks + 3] == low){ (*x2)[x2_count] = t; x2_count = x2_count + 1; temp11.erase(i); } } int size11 = temp11.size(); map<int, vector<int>>reclaim1; int reclaim1_count = 0; for (int i = 0; reclaim1_count < size11; i++){ if (temp11[i].size() != 0){ reclaim1[reclaim1_count] = temp11[i]; reclaim1_count = reclaim1_count + 1; } } (*x1)[n] = reclaim1; for (int i = 0; i < temp11.size(); i++){ vector<int>().swap(temp11[i]); } for (int i = 0; i < reclaim1.size(); i++){ vector<int>().swap(reclaim1[i]); } for (int i = 0; i < size_c.size(); i++){ vector<int>().swap(size_c[i]); } //cout << "get a solution" << endl; //cout << "size of x1!!!!!!!!!!!!!" << (*x1).size() << endl; count = count + 1; return lbf_recur(x1, x2, results, n, b, signal,count,set); } else{ for (int i = n; i > 0; i--){ if ((*x1)[i].size() != 0){ n = i; break; } } //cout << "n for pick up is " << n << endl; int low = 3000; map<int, vector<int>>temp = (*x1)[n]; for (int i = 0; i < (*x1)[n].size(); i++){ vector<int>t = temp[i]; for (int k = 0; k < t.size(); k++){ if (t[file_reclaim.total_blocks + 3] < low){ low = t[file_reclaim.total_blocks + 3]; } } } int x2_count = 0; map<int, vector<int>>temp11 = (*x1)[n]; map<int, vector<int>>x2_temp; for (int i = 0; i < (*x1)[n].size(); i++){ vector<int>t = temp11[i]; if (t[file_reclaim.total_blocks + 3] == low){ x2_temp[x2_count] = t; x2_count = x2_count + 1; temp11.erase(i); } } (*x2) = x2_temp; //cout << "x2 length" << x2_count << endl; int size11 = temp11.size(); map<int, vector<int>>reclaim1; int reclaim1_count = 0; for (int i = 0; reclaim1_count < size11; i++){ if (temp11[i].size() != 0){ reclaim1[reclaim1_count] = temp11[i]; reclaim1_count = reclaim1_count + 1; } } (*x1)[n] = reclaim1; for (int i = 0; i < temp11.size(); i++){ vector<int>().swap(temp11[i]); } for (int i = 0; i < reclaim1.size(); i++){ vector<int>().swap(reclaim1[i]); } for (int i = 0; i < size_c.size(); i++){ vector<int>().swap(size_c[i]); } count = count + 1; return lbf_recur(x1, x2, results, n, b, signal,count,set); } } else{ map<int, vector<int>>size_c; map<int, vector<int>>size_temp; map<int, vector<int>>new_primier; size_temp = (*x2); vector<int> nz; int nz_size = 0; int sz = size_temp.size(); for (int i = 0; nz_size <sz; i++){ if (nz_size == size_temp.size()){ break; } if (size_temp[i].size() != 0){ nz.push_back(i); nz_size = nz_size + 1; } } for (int i = 0; i < nz_size; i++){ size_c[i] = size_temp[nz[i]]; } //cout << "x2 size" << x2.size() << endl; int nsize = size_c.size(); int primier = 3 * nsize; int new_count = 0; for (int k = 0; k < nsize; k++){ //for (int i = 0; i < nsize; i++){ vector<int>old_partial_l = size_c[k]; //cout << "left size" << old_partial_l.size() << endl; vector<int>old_partial_m = size_c[k]; vector<int>old_partial_r = size_c[k]; old_partial_l[n + 1] = 1; old_partial_l[file_reclaim.total_blocks] = old_partial_l[file_reclaim.total_blocks] + 1; if (old_partial_l[file_reclaim.total_blocks] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_l = old_partial_l; int costl = c_sample.cost_increase(new_partial_l, n + 1); //cout << costl << endl; new_partial_l[file_reclaim.total_blocks + 3] = new_partial_l[file_reclaim.total_blocks + 3] + costl; if (new_partial_l[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_l; new_count = new_count + 1; } } old_partial_m[n + 1] = 2; old_partial_m[file_reclaim.total_blocks + 1] = old_partial_m[file_reclaim.total_blocks + 1] + 1; if (old_partial_m[file_reclaim.total_blocks + 1] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_m = old_partial_m; int costm = c_sample.cost_increase(new_partial_m, n + 1); new_partial_m[file_reclaim.total_blocks + 3] = new_partial_m[file_reclaim.total_blocks + 3] + costm; if (new_partial_m[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_m; new_count = new_count + 1; } } old_partial_r[n + 1] = 3; old_partial_r[file_reclaim.total_blocks + 2] = old_partial_r[file_reclaim.total_blocks + 2] + 1; if (old_partial_r[file_reclaim.total_blocks + 2] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_r = old_partial_r; int costr = c_sample.cost_increase(new_partial_r, n + 1); new_partial_r[file_reclaim.total_blocks + 3] = new_partial_r[file_reclaim.total_blocks + 3] + costr; if (new_partial_r[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_r; new_count = new_count + 1; } } } //x1[n] = x1[n].erase(); if (new_primier.size() == 0){ //cout << "dead n= " << n << endl; (*x1).erase(n);//no subbranchs can have a better solution for (int i = n - 1; i >= 0; i--){ if ((*x1)[i].size() != 0){ n = i; break; } } map<int, vector<int>>new_x2; int new_x2_length = 0; int lb = 3000; int npsize = (*x1)[n].size(); for (int i = 0; i < npsize; i++){ vector<int>temp; temp = (*x1)[n][i]; if (temp[file_reclaim.total_blocks + 3] < lb){ lb = temp[file_reclaim.total_blocks + 3]; } } for (int i = 0; i <npsize; i++){ vector<int>temp; temp = (*x1)[n][i]; if (temp[file_reclaim.total_blocks + 3] == lb){ new_x2[new_x2_length] = temp; new_x2_length = new_x2_length + 1; (*x1)[n].erase(i); } } (*x2) = new_x2; //cout << "new x2 size is " << x2.size() << endl; int kkp = (*x1)[n].size(); int count_nz = 0; int *pp; pp = &count_nz; map<int, vector<int>>reclaim2; //cout << "new primier size is " << kkp << endl; for (int i = 0; count_nz< kkp; i++){ if ((*x1)[n][i].size() != 0){ vector<int>t = (*x1)[n][i]; reclaim2[count_nz] = t; count_nz = count_nz + 1; //cout << "count is " << count_nz; } } (*x1)[n] = reclaim2; //x1.erase(n); for (int i = 0; i < new_x2.size(); i++){ vector<int>().swap(new_x2[i]); } for (int i = 0; i < reclaim2.size(); i++){ vector<int>().swap(reclaim2[i]); } count = count + 1; return lbf_recur(x1, x2, results, n, b, signal,count,set); } else{ map<int, vector<int>>new_x2; int new_x2_length = 0; int lb = 3000; int npsize = new_primier.size(); for (int i = 0; i < npsize; i++){ vector<int>temp; temp = new_primier[i]; if (temp[file_reclaim.total_blocks + 3] < lb){ lb = temp[file_reclaim.total_blocks + 3]; } } for (int i = 0; i <npsize; i++){ vector<int>temp; temp = new_primier[i]; if (temp[file_reclaim.total_blocks + 3] == lb){ new_x2[new_x2_length] = temp; new_x2_length = new_x2_length + 1; new_primier.erase(i); } } (*x2) = new_x2; //cout << "new x2 size is " << x2.size() << endl; int kkp = new_primier.size(); int count_nz = 0; int *pp; pp = &count_nz; map<int, vector<int>>reclaim2; //cout << "new primier size is " << kkp << endl; for (int i = 0; count_nz< kkp; i++){ //vector<int>t = temp[i]; //cout << i; if (new_primier[i].size() != 0){ vector<int>t = new_primier[i]; reclaim2[count_nz] = t; count_nz = count_nz + 1; //cout << "count is " << count_nz; } } if (reclaim2.size() > 0){ (*x1)[n + 1] = reclaim2; //x1.erase(n); } for (int i = 0; i < new_x2.size(); i++){ vector<int>().swap(new_x2[i]); } for (int i = 0; i < reclaim2.size(); i++){ vector<int>().swap(reclaim2[i]); } count = count + 1; return lbf_recur(x1, x2, results, n + 1, b, signal,count,set); } } } } } } <file_sep>//#include "stdafx.h" #include "extern.h" file_extract a; branching b; content file_reclaim = a.extraction(); map<int, vector<int>>order = a.get_connection(); vector<int>branching_o = b.initial_partition();<file_sep>for file in diffeq1.blif sha.blif raygentop.blif or1200.blif do <file_sep>#!/bin/sh read_blif alu4.blif;resyn2;print_stats; <file_sep>struct path{ int *grid; int **fifo; int n, l, con_num, pl, n_con, w_con, t_con; }; path pathRender(path f_in, int n);<file_sep>#include "stdafx.h" #include "block.h" block::block() { } block::~block() { } vector<int> block::get_net(){//get all moveable blocks in the circuit extern vec_rec rec_val; vec_rec globalVector = rec_val; vector<int>connection; //vector<int>j_connection; extern vector<double>fget; vector<double>f = fget; int fix_size = f.size(); //cout << fix_size << endl; int count = 0; for (int x = 0; x <globalVector.total_numbers; x++){ if (globalVector.a[x] == -1){ if (globalVector.a[x + 1] == -1){//end of moveable break; } else{ count = count + 1;//line + 1 if (count >= fix_size){ connection.push_back(globalVector.a[x + 1]);//store moveable block } } } } return connection; } vector<int>block::get_connections(int i){// get connection between block i and the rest of the circuit, i=0,1.... //vec_rec g_recv = b.recv();// get circuit info vector<int>g_connection;//return extern vector<int> nget; vector<int>netl = nget;//get all moveable blocks in the circuit vector<int>neti = j_connection(netl[i]);//get all net that connects to block i int i_size = neti.size(); int n = netl.size(); for (int k = 0; k < n; k++){ if (netl[k] == netl[i]){//find itself continue; } else{ vector<int>g = j_connection(netl[k]);//get all net that connects to block j int g_size = g.size(); int set = 0; for (int b = 0; b < g_size; b++){ for (int c = 0; c < i_size; c++){ if (g[b] == neti[c]){//match connection g_connection.push_back(netl[k]); set = 1; break; } } if (set == 1){ break; } } } } return g_connection; } vector<int> block::j_connection(int j){//get all net that connects to block j extern vec_rec rec_val; extern vector<vector<int>>ad; vec_rec v = rec_val; vector<int>j1;//return int cont = 0; int v_length = ad[j - 1].size(); for (int k = 2; k < v_length; k++){ j1.push_back(ad[j - 1][k]); } return j1; } bound block::get_boundary(){ extern vec_rec rec_val; vec_rec g_r = rec_val; double X_max = 0; double X_min = 10; double Y_min = 0; double Y_max =10; for (int i = 0; i < g_r.fixed_numbers; i = i + 3){ if (g_r.fixed[i + 1]>X_max){ X_max = g_r.fixed[i + 1]; } if (g_r.fixed[i + 1] < X_min){ X_min = g_r.fixed[i + 1]; } if (g_r.fixed[i + 2]>Y_max){ Y_max = g_r.fixed[i + 2]; } if (g_r.fixed[i + 2]<Y_min){ Y_min = g_r.fixed[i + 2]; } } bound res_boundary; res_boundary.x_max = X_max; res_boundary.x_min = X_min; res_boundary.y_max = Y_max; res_boundary.y_min = Y_min; return res_boundary; }<file_sep>for file in diffeq1.blif sha.blif raygentop.blif or1200.blif do for seed in 2 20 45 90 150 do #echo "$file -1.0 $temp $seed" >> A3result.txt ./vpr --place --pack --place_algorithm bounding_box k6_frac_N10_mem32K_40nm.xml $file \ --nodisp --seed $seed #--init_t $temp grep "Placement cost: " vpr_stdout.log >> A4result.txt sed -i -- 's/Placement cost://' A4result.txt sed -i -- 's/bb_cost://' A4result.txt sed -i -- 's/td_cost://' A4result.txt sed -i -- 's/delay_cost://' A4result.txt done done <file_sep>//#include "stdafx.h" #include "calculator.h" calculator::calculator() { } calculator::~calculator() { } int calculator::getc_cost(int b1, int b2){//b1, b2 are blocks to calculate extern map<int, vector<int>>order; vector<int>b = order[b1]; int r_value = b[b2]; return r_value; } int calculator::cost_increase(vector<int>x,int n){//n is the location of newly added value in vector extern content file_reclaim; extern map<int, vector<int>>order; extern vector<int>branching_o; int cost_increase = 0; for (int i = 0; i < n; i++){ int new_cost = 0; if (x[i] == x[n]){ new_cost = 0; //cout << "match" << endl; } else{ new_cost = getc_cost(branching_o[n], branching_o[i]); cost_increase = cost_increase + new_cost; } } return cost_increase; }<file_sep>#pragma once #include <vector> #include "extract.h" #include "net.h" #include "recurs.h" using namespace std; struct bound{ double x_min; double x_max; double y_min; double y_max; }; class block { //int k; extract b; net nb; public: vector<int> block::get_net(); vector<int>get_connections(int i); vector<int>j_connection(int j);//get all net that connects to block j bound get_boundary(); block(); ~block(); }; <file_sep>#include "stdafx.h" #include "create_matrix.h" #include "spread.h" using namespace std; create_matrix::create_matrix() { } create_matrix::~create_matrix() { } void create_matrix::get_file() { int coordinate = 0; cout << "X coordinate input 1, Y coordinate input 0" << endl; cin >> coordinate; vector<vector<double>>r_q = matrix_calculation(); vector<double>r_b = get_b(coordinate); linear_parameter matl = mat(r_q, r_b); int row = matl.m; cout << "row number=" << row << endl; int column = matl.n; int x = matl.Ap.size(); int *AP = new int[x]; int y = matl.Ai.size(); int *AI = new int[y]; int z = matl.Ax.size(); double *AX = new double[z]; //int b_length = 15; vector<double>B; cout << "below is the matlab form" << endl; cout << "row = " << matl.m << endl; cout << "column is =" << matl.n << endl; cout << "Ap = " << endl; for (int p = 0; p < matl.Ap.size(); p++){ AP[p] = matl.Ap[p]; cout << AP[p] << endl; } cout << "Ai = " << endl; for (int p = 0; p < matl.Ai.size(); p++){ AI[p] = matl.Ai[p]; cout << AI[p] << endl; } cout << "Ax = " << endl; for (int p = 0; p < matl.Ax.size(); p++){ AX[p] = matl.Ax[p]; cout << AX[p] << endl; } spread dd; sm = &dd; cout << "B=" << endl; /*for (int p = 0; p < 15; p++){ B[p] = sm.get_nb[p]; cout << B[p] << endl; }*/ //B = sm->get_nb(coordinate);//new b values after introducing new fixed blocks in the quarter B = r_b;//get b values without adding new fixed blocks ofstream outfile_b; if (coordinate == 1){ outfile_b.open("C:\\Users\\ThinkPad\\Desktop\\b_x.txt"); } else { outfile_b.open("C:\\Users\\ThinkPad\\Desktop\\b_y.txt"); } //outfile_b.open("C:\\Users\\ThinkPad\\Desktop\\b.txt"); for (int p = 0; p < r_b.size(); p++){ outfile_b << B[p] << " "; } outfile_b.close(); ofstream outfile_Ap; outfile_Ap.open("C:\\Users\\ThinkPad\\Desktop\\Ap.txt"); for (int p = 0; p <matl.Ap.size(); p++){ outfile_Ap << matl.Ap[p] << " "; } outfile_Ap.close(); ofstream outfile_Ai; outfile_Ai.open("C:\\Users\\ThinkPad\\Desktop\\Ai.txt"); for (int p = 0; p <matl.Ai.size(); p++){ outfile_Ai << matl.Ai[p] << " "; } outfile_Ai.close(); ofstream outfile_Ax; outfile_Ax.open("C:\\Users\\ThinkPad\\Desktop\\Ax.txt"); for (int p = 0; p <matl.Ax.size(); p++){ outfile_Ax << matl.Ax[p] << " "; } outfile_Ax.close(); } vector<vector<double>> create_matrix::matrix_calculation(){//return Q vector<vector<double>>q; //q.resize(15, vector<double>(15)); //vec_rec n_recv = c.recv();// get circuit info extern vector<int> nget; vector<int>netlist = nget;//get all moveable blocks in the circuit int n_size = netlist.size(); for (int i = 0; i < n_size; i++){//loop all blocks vector<double>line_t = get_q(netlist[i]);//a line prepare to add to Q q.push_back(line_t); } return q; } vector<double> create_matrix::get_q(int i){//i=0,1,..... //vec_rec n_recv = c.recv();// get circuit info extern vec_rec rec_val; vec_rec n_recv = rec_val; extern vector<int> nget; vector<int>netlist = nget;;//get all moveable blocks in the circuit int n_size = netlist.size(); vector<double>line(n_size);//a line prepare to add to Q cout << n_recv.fixed_numbers; int nx = n_recv.fixed_numbers / 3; vector<int>j_connect = bbc.j_connection(netlist[i - nx - 1]);//get all net that connects to block j int j_size = j_connect.size(); double q_sum = 0; for (int x = 0; x < j_size; x++){//loop all net that connects to j double w = ba.get_weight(j_connect[x]);//get weight for a net //cout << "get net's weight" << j_connect[x] << endl; vector<int>p = ba.get_num(j_connect[x]);//j_connect[x]is the net number int num = p.size() - 1; q_sum = q_sum + w*num; } line[i - nx - 1] = q_sum;// // get off diag cout << n_size << endl; for (int z = 0; z < n_size; z++){ if (netlist[z] == netlist[i - nx - 1]){ continue; } else{ double sum = 0; vector<int>off_diag = get_connections(i - nx - 1, j_connect); int o_diag = off_diag.size(); for (int y = 0; y < o_diag; y++){ double w2 = gsum(i, off_diag[y]); line[off_diag[y] - nx - 1] = -w2; //cout << "finish a point" << endl; } } } return line; } vector<int>create_matrix::get_connections(int i, vector<int>neti){// get connection between block i and the rest of the circuit, i=0,1.... //vec_rec g_recv = c.recv();// get circuit info vector<int>g_connection;//return extern vector<int> nget; vector<int>netl = nget;//get all moveable blocks in the circuit //vector<int>neti = bbc.j_connection(netl[i]);//get all net that connects to block i int i_size = neti.size(); int n = netl.size(); for (int k = 0; k < n; k++){ if (netl[k] == netl[i]){//find itself continue; } else{ vector<int>g = bbc.j_connection(netl[k]);//get all net that connects to block j int g_size = g.size(); int set = 0; for (int b = 0; b < g_size; b++){ for (int c = 0; c < i_size; c++){ if (g[b] == neti[c]){//match connection g_connection.push_back(netl[k]); set = 1; break; } } if (set == 1){ break; } } } } return g_connection; } double create_matrix::gsum(int x, int y){//get sum of off diag value for a block,x is the row , y is the column double s = 0; extern vec_rec rec_val; vec_rec s_recv = rec_val; int ss = s_recv.fixed_numbers / 3; extern vector<int> nget; extern vector<vector<int>>ad; for (int i = 2; i < ad[x-1].size(); i++){ for (int k = 2; k < ad[y-1].size(); k++){ if (ad[x-1][i] == ad[y-1][k]){ double w1 = ba.get_weight(ad[x-1][i]); s = s + w1; } } } return s; } vector<double> create_matrix::get_b(int x_y){ vector<double>b; extern vec_rec rec_val; vec_rec b_recv = rec_val; extern vector<int> nget; vector<int>b_mov = nget; extern vector<double>fget; vector<double>b_fix = fget; int b_fsize = b_fix.size(); for (int i = 0; i < b_mov.size(); i++){//loop through each moveable block vector<int>b_connect = bbc.j_connection(b_mov[i]);//get all net that connects to block j double b_sum = 0; int b_size = b_connect.size(); for (int k = 0; k < b_size; k++){//the code below is to find if there is a fixed block in that net vector<int>b_content = ba.get_num(b_connect[k]);//net b_connect[k]'s content mov b_r = ba.moveable(b_connect[k]); //cout << "fixed block number in net" << b_connect[k] << "is" << b_r.m_num << endl; if (b_r.m_num == 0){//that net has no connection to fix blocks continue; } else{ for (int h = 0; h < b_r.mv.size(); h++){//fix double W = ba.get_weight(b_connect[k]);//weight for net //cout << "weight is =" << W << endl; if (x_y == 1){ for (int c = 0; c < b_recv.fixed.size(); c = c + 3){//get x coordinate if (b_recv.fixed[c] == b_r.mv[h]){ b_sum = b_sum + W*b_recv.fixed[c + 1]; break; } } } else{ for (int c = 0; c < b_recv.fixed.size(); c = c + 3){//get y coordinate if (b_recv.fixed[c] == b_r.mv[h]){ b_sum = b_sum + W*b_recv.fixed[c + 2]; break; } } } } } } b.push_back(b_sum); } return b; } linear_parameter create_matrix::mat(vector<vector<double>>Atest, vector<double>B_test){ vector<int>Ap_re(1);//make one room for the first zero vector<int>Ai_re; vector<double>Ax_re; vector<double>b_re; int nz = 0;//number of non-zero item in a column int m = Atest.size();//get m for a m*n matrix //cout << m; int n = Atest[0].size();//get n for a m*n matrix cout << n; for (int i = 0; i < n; i++){//loop each column search for non-zero //nz = 0; for (int x = 0; x < m; x++){ if (Atest[x][i] != 0){ nz = nz + 1;//find a nz //cout << nz << endl; Ai_re.push_back(x);//add nz's row coordinate to a vector Ax_re.push_back(Atest[x][i]);//store nz's value } } Ap_re.push_back(nz);//add the number of nz in a column } linear_parameter para_return; para_return.Ai = Ai_re; para_return.Ap = Ap_re; para_return.Ax = Ax_re; para_return.m = m; para_return.n = n; return para_return; }<file_sep>for present in 0.5 1 2 10 do echo "diffeq1.blif acc_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml diffeq1.blif --route_chan_width 56 --acc_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.5 1 2 10 do echo "sha.blif acc_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --route_chan_width 54 --acc_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.5 1 2 10 do echo "raygentop.blif acc_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml raygentop.blif --route_chan_width 72 --acc_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.5 1 2 10 do echo "or1200.blif acc_fac $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml or1200.blif --route_chan_width 78 --acc_fac $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done <file_sep>// w.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <cstring> #include <vector> #include <fstream> using namespace std; int length(); int main() { int m=0; double num[3000]; ifstream file; file.open("C:\\Users\\ThinkPad\\Desktop\\circuit.txt"); while (!file.eof()) { file >> num[m++]; } int n = num[1]; cout << num[1] << endl; int *cont = new int[n]; for (int i = 0; i < n; i++){ cont[i] = 0; } int line_num = length(); cout << line_num<< endl; int mini_w=0; for (int f = 0; f < line_num-5; f++){ int mark = 0; for (int k = 0; k < n; k++){ if (cont[k] == num[7 + 6 * f]){ //cont[k] = num[7 + 6 * f]; //cout << num[7 + 6 * f] << endl; mark = 0; //cout << mark << endl; } else{ mark = mark+1; //cout << mark << endl; } } if (mark == n){ cont[mini_w] = num[7 + 6 * f]; cout << "w="<<cont[mini_w] << endl; mini_w = mini_w + 1; //cout << mini_w << endl; } } cout << mini_w << endl; system("pause"); return 0; } int length(){ char buffer[256]; int i; ifstream infile; infile.open("C:\\Users\\ThinkPad\\Desktop\\circuit.txt"); if (!infile.is_open()) { cout << "cannot open"; } //infile.getline(buffer, 100); //cout << buffer[0] << endl; while (!infile.eof()){ for (i = 1; buffer[0] != '-'; i++) infile.getline(buffer, 20); } return i; infile.close(); } //cout << num[7 + 6 * f] << endl; //cout << mini_w << endl; //continue;<file_sep>for file in diffeq1.blif sha.blif raygentop.blif or1200.blif do for temp in 900 50 5 0.8 0.05 do for seed in 2 20 45 90 150 do #echo "$file -1.0 $temp $seed" >> A3result.txt ./vpr --place --pack --place_algorithm bounding_box k6_frac_N10_mem32K_40nm.xml $file \ --nodisp --seed $seed --init_t $temp grep "Placement cost: " vpr_stdout.log >> A3result.txt sed -i -- 's/Placement cost://' A3result.txt sed -i -- 's/bb_cost://' A3result.txt sed -i -- 's/td_cost://' A3result.txt sed -i -- 's/delay_cost://' A3result.txt done done done <file_sep>int length();<file_sep>// a_test.cpp : 定义控制台应用程序的入口点。 // //#include "stdafx.h" #include <stdio.h> #include <iostream> #include <string> #include <fstream> #include <sstream> #include "router.h" #include "graphics.h" #include "pathRender.h" #include "easygl_constants.h" using namespace std; void delay(void); void draw(int **matrix, int *init, int *source, int *par); void draw(int **matrix, int *init,int *source,int *par){ int num = par[1]; int row = par[2]; int rec_len = par[0]; int mark = 0;//mark for the source //cout << "mark=0" << endl; int *rec_init; //int *rec_source; rec_init = init;//recive target coordinate //rec_source = source; while (mark == 0){ cout << source[0] << endl; if (rec_init[0] - 2 >= 0 && rec_init[1] >= 0){//target has a point in the left if (rec_init[0] - 2 == source[0] && rec_init[1] == source[1]){//left is the source? cout << "find target left" << endl;//furthur replaced by drawing red line cout << "drawline from" << rec_init[0] << rec_init[1] << "to" << rec_init[0] - 2 << rec_init[1] << endl; setlinestyle(SOLID); setcolor(RED); drawline(100 * (rec_init[0] - 2) / 2 + 100., 100 * (num - rec_init[1] / 2) + 1 * row + 5., (rec_init[0] - 2) / 2 + 150., 100 * (num - rec_init[1] / 2) + 1 * row + 5.); flushinput(); delay(); delay(); mark = 1; continue; } } //left point is not the target try right if (rec_init[0] + 2 <= 2 * num && rec_init[1] >= 0){//target has a point in the right if (rec_init[0] + 2 == source[0] && rec_init[1] == source[1]){//right is the source? cout << "find target right" << endl;//furthur replaced by drawing red line setlinestyle(SOLID); setcolor(RED); drawline(100 * (rec_init[0]) / 2 + 50., 100 * (num - rec_init[1] / 2) + 1 * row + 5., 100 * (rec_init[0]) / 2 + 100., 100 * (num - rec_init[1] / 2) + 1 * row + 5.); flushinput(); delay(); delay(); mark = 1; continue; } } if (rec_init[0] >= 0 && rec_init[1] + 2 <= 2 * num){//target has a point in the above if (rec_init[0] == source[0] && rec_init[1] + 2 == source[1]){//above is the source? cout << "find target above" << endl;//furthur replaced by drawing red line setlinestyle(SOLID); setcolor(RED); drawline((100 * ((rec_init[0])) / 2) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2 - 1) + 55., (100 * ((rec_init[0])) / 2) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2 - 1) + 105.); flushinput(); delay(); delay(); mark = 1; continue; } } if (rec_init[0] >= 0 && rec_init[1] - 2 >= 0){//target has a point in the below if (rec_init[0] == source[0] && rec_init[1] - 2 == source[1]){//below is the source? cout << "find target below" << endl;//furthur replaced by drawing red line setlinestyle(SOLID); setcolor(RED); drawline((100 * ((rec_init[0])) / 2 + 1) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2 - 1) + 155., (100 * ((rec_init[0])) / 2 + 1) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2 - 1) + 205.); flushinput(); delay(); delay(); mark = 1; continue; } } //none of the four is the target if (rec_init[0] - 1>=0){ if (matrix[rec_init[0] - 1][rec_init[1]] == rec_len){//left value==current value? rec_len = rec_len - 1;//change current wire value rec_init[0] = rec_init[0] - 2;//change source to new coordinate rec_init[1] = rec_init[1]; setlinestyle(SOLID); setcolor(RED); drawline((100 * (rec_init[0])) / 2 + 50., 100 * (num - (rec_init[1]) / 2) + 1 * row + 5., (100 * (rec_init[0])) / 2 + 100., 100 * (num - (rec_init[1]) / 2) + 1 * row + 5.); flushinput(); delay(); delay(); cout << "mark the path left" << endl; continue;//find the next target finish this loop to next } } if (rec_init[0] + 1<=2*num){ if (matrix[rec_init[0] + 1][rec_init[1]] == rec_len){//right value==current value? rec_len = rec_len - 1;//change current wire value rec_init[0] = rec_init[0] + 2;//change source to new coordinate cout << "rec_init=" << rec_init[0] << endl; rec_init[1] = rec_init[1]; setlinestyle(SOLID); setcolor(RED); drawline((100 * (rec_init[0] - 2) / 2) + 50., 100 * (num - (rec_init[1]) / 2) + 1 * row + 5., (100 * (rec_init[0] - 2) / 2) + 100., 100 * (num - (rec_init[1]) / 2) + 1 * row + 5.); flushinput(); delay(); delay(); cout << "mark the path right" << endl; continue;//find the next target finish this loop to next } } if (rec_init[1] + 1<=2*num){ if (matrix[rec_init[0]][rec_init[1] + 1] == rec_len){//above value==current value? rec_len = rec_len - 1;//change current wire value rec_init[0] = rec_init[0];//change source to new coordinate rec_init[1] = rec_init[1] + 2; setlinestyle(SOLID); setcolor(RED); drawline((100 * ((rec_init[0])) / 2) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2-1) + 155., (100 * ((rec_init[0])) / 2) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2-1) + 205.); flushinput(); delay(); delay(); cout << "mark the path above" << endl; continue;//find the next target finish this loop to next } } if (rec_init[1] - 1>=0){ if (matrix[rec_init[0]][rec_init[1] - 1] == rec_len){//below value==current value? rec_len = rec_len - 1;//change current wire value rec_init[0] = rec_init[0];//change source to new coordinate rec_init[1] = rec_init[1] - 2; setlinestyle(SOLID); setcolor(RED); drawline((100 * ((rec_init[0])) / 2 + 1) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2-1) + 55., (100 * ((rec_init[0])) / 2 + 1) + 1 * row + 5., 100 * (num - (rec_init[1]) / 2-1) + 105.); flushinput(); delay(); delay(); cout << "mark the path below" << endl; continue;//find the next target finish this loop to next } } }//while } void delay(void) { /* A simple delay routine for animation. */ int i, j, k, sum; sum = 0; for (i = 0; i<100; i++) for (j = 0; j<i; j++) for (k = 0; k<1000; k++) sum = sum + i + j - k; } <file_sep> #include "branching.h" #include "calculator.h" #include "draw_graph.h" branching::branching() { } branching::~branching() { } vector<int>branching::fanout_calculation(){ extern map<int, vector<int>>order; vector<int>fanout; int o_size = order.size(); for (int i = 0; i < o_size; i++){ int number = 0; vector<int>temp = order[i]; for (int k = 0; k < temp.size();k++){ number = number + temp[k]; } fanout.push_back(number); } return fanout; } vector<int>branching::initial_partition(){ extern map<int, vector<int>>order; vector<int>f_result = fanout_calculation(); vector<int>block; for (int i = 0; i < f_result.size(); i++){ block.push_back(i); } for (int i = 0; i < f_result.size(); i++){ int temp = 0; for (int x = i + 1; x < f_result.size(); x++){ if (f_result[i] < f_result[x]){ temp = f_result[i]; f_result[i] = f_result[x]; f_result[x] = temp; temp = block[i]; block[i] = block[x]; block[x] = temp; } //cout<<"van"; } } return block; } final_val branching::branch_result(){ extern content file_reclaim; extern map<int, vector<int>>order; extern vector<int>branching_o; vector<int>initial_fanout = initial_partition();//get first partition map<int, vector<int>>p0; vector<int>pl; vector<int>pm; vector<int>pr; /*each vector represents a partial solution last member of vector is partial solution's cost*/ for (int k = 0; k < file_reclaim.total_blocks + 4; k++){ if (k == 0){ pl.push_back(1); pm.push_back(2); pr.push_back(3); } else{ pl.push_back(0); pm.push_back(0); pr.push_back(0); } } /*count number of l,m,r;12number of location+3numbers of count and 1bit of lb*/ pl[file_reclaim.total_blocks] = 1; pm[file_reclaim.total_blocks + 1] = 1; pr[file_reclaim.total_blocks + 2] = 1; map < int, map<int, vector<int>>>p1; p0[0] = pl; p0[1] = pm; p0[2] = pr; p1[0] = p0; /*get initial best*/ calculator ccc; C = &ccc; int best = 0; for (int x = 0; x < file_reclaim.total_blocks / 3; x++){ for (int i = 0; i < file_reclaim.total_blocks / 3; i++){ int n = 0; n = C->getc_cost(branching_o[x], branching_o[i + file_reclaim.total_blocks / 3]); best = best + n; cout << "first is " << branching_o[x] << endl; cout << "second is " << branching_o[i + file_reclaim.total_blocks / 3] << endl; cout << best; n = C->getc_cost(branching_o[x], branching_o[i + file_reclaim.total_blocks * 2 / 3]); best = best + n; } } for (int x = 0; x < file_reclaim.total_blocks / 3; x++){ for (int i = 0; i < file_reclaim.total_blocks / 3; i++){ int n = 0; n = C->getc_cost(branching_o[x + file_reclaim.total_blocks / 3], branching_o[i + file_reclaim.total_blocks*2 / 3]); best = best + n; } } cout << best << endl; final_val xx = branching_recursion(&p1, 0, best, initial_fanout); return xx; } final_val branching::branching_recursion(map<int, map<int, vector<int>>>*x1, int n, int b, vector<int>v1){ calculator ccc; C = &ccc; extern content file_reclaim; extern map<int, vector<int>>order; if (n == file_reclaim.total_blocks-1){ final_val x; map<int, vector<int>>new_primier; new_primier = (*x1)[file_reclaim.total_blocks - 1]; int psize = new_primier.size(); int best = b; cout << "first best is" << best << endl; cout << "vector length" << file_reclaim.total_blocks; cout << "i=" << psize << endl; for (int i = 0; i < psize; i++){ vector<int>temp; temp = new_primier[i]; cout << "cost " << temp[file_reclaim.total_blocks + 3] << endl; if (temp[file_reclaim.total_blocks + 3] < best){ best = temp[file_reclaim.total_blocks + 3]; x.partition_result = temp; } } x.best = best; for (int y = 0; y < x.partition_result.size(); y++){ cout << x.partition_result[y]; } cout << "best should be" << best << endl; draw_graph xxx; DDG = &xxx; for (int i = 0; i < (*x1).size(); i++){ DDG->draw_depth((*x1)[i]); } return x; } else { /* get */ map<int, vector<int>>size_c; map<int, vector<int>>new_primier; size_c = (*x1)[n]; int nsize = size_c.size(); int primier = 3 * nsize; int new_count = 0; for (int k = 0; k < nsize; k++){ //for (int i = 0; i < nsize; i++){ vector<int>old_partial_l = size_c[k]; vector<int>old_partial_m = size_c[k]; vector<int>old_partial_r = size_c[k]; old_partial_l[n + 1] = 1; old_partial_l[file_reclaim.total_blocks] = old_partial_l[file_reclaim.total_blocks] + 1; /*cout << "old"; for (int m = 0; m < old_partial_l.size(); m++){ cout << old_partial_l[m]; } cout << ""<<endl;*/ if (old_partial_l[file_reclaim.total_blocks] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_l = old_partial_l; int costl = C->cost_increase(new_partial_l,n+1); //cout << costl << endl; new_partial_l[file_reclaim.total_blocks + 3] = new_partial_l[file_reclaim.total_blocks + 3] + costl; if (new_partial_l[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_l; new_count = new_count + 1; } //cout << "" <<endl; /*for (int m = 0; m < new_partial_l.size(); m++){ cout << new_partial_l[m]; }*/ } old_partial_m[n + 1] = 2; old_partial_m[file_reclaim.total_blocks + 1] = old_partial_m[file_reclaim.total_blocks + 1] + 1; if (old_partial_m[file_reclaim.total_blocks + 1] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_m = old_partial_m; int costm = C->cost_increase(new_partial_m, n + 1); new_partial_m[file_reclaim.total_blocks + 3] = new_partial_m[file_reclaim.total_blocks + 3] + costm; if (new_partial_m[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_m; new_count = new_count + 1; } /*cout << "new"; for (int m = 0; m < new_partial_m.size(); m++){ cout << new_partial_m[m]; } cout << "" << endl;*/ } old_partial_r[n + 1] = 3; old_partial_r[file_reclaim.total_blocks + 2] = old_partial_r[file_reclaim.total_blocks + 2] + 1; if (old_partial_r[file_reclaim.total_blocks + 2] <= file_reclaim.total_blocks / 3){ vector<int>new_partial_r = old_partial_r; int costr = C->cost_increase(new_partial_r, n + 1); new_partial_r[file_reclaim.total_blocks + 3] = new_partial_r[file_reclaim.total_blocks + 3] + costr; if (new_partial_r[file_reclaim.total_blocks + 3] <= b){ new_primier[new_count] = new_partial_r; new_count = new_count + 1; } } /*need a function to calculate the cost increase*/ /*need a function to calculate number of 1,2,3*/ } (*x1)[n + 1] = new_primier; cout << "n is " << n << endl; cout << "map size"<<new_primier.size() << endl; return branching_recursion(x1, n + 1, b, v1); } } <file_sep>for present in 0.5 2 5 8 do echo "diffeq1.blif pres_fac_mult $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml diffeq1.blif --route_chan_width 56 --pres_fac_mult $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.5 2 5 8 do echo "sha.blif pres_fac_mult $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --route_chan_width 54 --pres_fac_mult $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.5 2 5 8 do echo "raygentop.blif pres_fac_mult $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml raygentop.blif --route_chan_width 72 --pres_fac_mult $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 0.5 2 5 8 do echo "or1200.blif pres_fac_mult $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml or1200.blif --route_chan_width 78 --pres_fac_mult $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done <file_sep>//#include "stdafx.h" #include <vector> #include "extract.h" using namespace std; //extern vector<int>b; //extern int van; extern vector<int> nget; extern vector<double>fget; extern vec_rec rec_val; extern vector<vector<int>>ad; //void sample();<file_sep>// bound_branch.cpp : 定义控制台应用程序的入口点。 // #include "stdio.h" #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <map> #include "file_extract.h" #include "extern.h" #include "branching.h" #include "calculator.h" #include "low_bound_first.h" #include "graphics.h" #include <math.h> using namespace std; int main() { printf("About to start graphics.\n"); init_graphics("Some Example Graphics", WHITE); /* still picture drawing allows user to zoom, etc. */ // Set-up coordinates from (xl,ytop) = (0,0) to // (xr,ybot) = (1000,1000) init_world(0., 0., 1000., 1000.); update_message("Interactive graphics example."); file_extract x; map<int, vector<int>>cost; cost = x.get_connection(); cout << cost.size() << endl; for (int i = 0; i < cost.size(); i++){ vector<int>y = cost[i]; for (int c = 0; c < y.size(); c++){ if (c == y.size()-1){ cout << y[c] << endl; } else{ cout << y[c]; } } } branching a; vector<int>q = a.initial_partition(); final_val ivan = a.branch_result(); for (int x = 0; x < q.size(); x++){ cout << q[x] << endl; } /*low_bound_first l; l.lbf();*/ //vector<int>sample = {1,1,2,2,3,0}; //calculator C; //int c = C.cost_increase(sample, 4); //cout << "increase is " << c << endl; //final_val d = a.branch_result(); //cout << "best is" << d.best << endl; /*map<int, vector<int>>xtest; cout << xtest.size() << endl; vector<int>y = { 1, 2, 3, 4 }; xtest[1] = y; xtest[0] = y; cout << xtest.size(); xtest.erase(1); cout << xtest.size(); xtest[1] = y; cout << xtest.size();*/ /*map<int, map<int, vector<int>>>x; map<int, vector<int>>y; map<int, vector<int>>ytest; vector<int>z; vector<int>x_test = { 1 }; x[0] = ytest; x[1] = y; y[0] = x_test; cout << "x size before erase"<<x.size() << endl; y.erase(0); cout << "x size after erase" << x.size() << endl;*/ /*vector<int>x(20, 40); cout << "x size before swap " << x.size() << endl; vector<int>().swap(x); cout << "x size after swap " << x.size() << endl;*/ /*map<int, map<int, vector<int>>>*x; map<int, map<int, vector<int>>>y; map<int, vector<int>>z; y[0] = z; x = &y; cout << (*x).size() << endl; cout << (x[0]).size() << endl; //cout << x.size() << endl;*/ //system("pause"); return 0; } <file_sep>for present in 2 5 8 15 do echo "diffeq1.blif bb_factor $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml diffeq1.blif --route_chan_width 56 --bb_factor $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 2 5 8 15 do echo "sha.blif bb_factor $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml sha.blif --route_chan_width 54 --bb_factor $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 2 5 8 15 do echo "raygentop.blif bb_factor $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml raygentop.blif --route_chan_width 72 --bb_factor $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done for present in 2 5 8 15 do echo "or1200.blif bb_factor $present" >> B2result.txt ./vpr k6_frac_N10_mem32K_40nm.xml or1200.blif --route_chan_width 78 --bb_factor $present --nodisp grep "Final critical path" vpr_stdout.log >> B2result.txt done <file_sep>#include "stdafx.h" #include "net.h" net::net()//get net number { //net_number = i; } net::~net() { } mov net:: moveable(int i){//return the number of fixed blocks in a net, also return the number of fixed blocks in that net int net = i; //extern vec_rec rec_val; vector<int>rec = get_num(net);//get the net and its content extern vector<double>fget; vector<double>f_rec = fget;//vector that only contain block number vector<int>mv; int m_num = 0; int n = rec.size();//get size of the net vector //cout << "net size=" << n << endl; int m = f_rec.size();//get size of fixed block number //cout << "fix size=" << m << endl; for (int x = 0; x < n; x++){//loop over all contents in net for (int y = 0; y < m; y++){//loop over all content in block vector if (rec[x] == f_rec[y]){//find fixed block m_num = m_num + 1; //cout << m_num; mv.push_back(rec[x]); break; } else{ continue; } } } mov m_return; if (m_num == 0){//the net has no connection to fixed block m_return.mv.push_back(1); m_return.m_num = m_num; } else{ m_return.mv = mv; m_return.m_num = m_num; } //cout << "number of fixed" << m_num << endl; return m_return; } vector<int> net::get_num(int i){ int net = i;// net number for search int block = 0;//store the value of block number extern vec_rec rec_val; vec_rec globalVector = rec_val; vector<int>net_content;//return the net i's content in a vector int stop = globalVector.total_numbers - globalVector.fixed_numbers - 2;//count stop when finished cheking all blocks int begin = 1;//tell the for loop the number is node or net for (int i = 0; i < stop; i++){ if (globalVector.a[i] == -1){//judge if is the end of line begin = 1; continue;//move to next line } else{ if (begin == 1){//if the number is the block? block = globalVector.a[i];//assign the block number to store begin = 0;//start searching for net i i = i + 1; continue; } else{//number is for a net if (globalVector.a[i] == net){ net_content.push_back(block); } } } } return net_content; } double net::get_weight(int net_number){// get net i's weight vector<int>net_recv = get_num(net_number);//get net i's content int net_size = net_recv.size(); //cout << "net i'"<<i<<"s size is= " <<net_size << endl; double weight = 2.0 / net_size; //cout << "net i'" << i << "s weight is= " << weight << endl; return weight; } double net::get_wl(int i){//must take special care about net:: function is to get wl of a net, take input of net number i vector<int>mb = get_mv(i); extern vec_rec rec_val; vec_rec w = rec_val; int f_size = w.fixed_numbers / 3; //mov n_wl = moveable(i); xy wl_recv = vans.get_cfile();//get moveable blocks and x,y coordiante //cout << n_wl.mv[0] - f_size - 1; int m_length = mb.size(); double Xmax = 0; double Xmin = 100; double Ymax = 0; double Ymin = 100; //cout << mb[1] << endl; //cout << wl_recv.y[mb[0] - f_size - 1] << endl; for (int x = 0; x < m_length; x++){//loop all moveable blocks if (wl_recv.x[mb[x] - f_size-1]>Xmax){ Xmax = wl_recv.x[mb[x] - f_size - 1]; } if (wl_recv.x[mb[x] - f_size - 1] < Xmin){ Xmin = wl_recv.x[mb[x] - f_size - 1]; } if (wl_recv.y[mb[x] - f_size - 1]>Ymax){ Ymax = wl_recv.y[mb[x] - f_size - 1]; } if (wl_recv.y[mb[x] - f_size - 1] < Ymin){ Ymin = wl_recv.y[mb[x] - f_size - 1]; } } double x_l = Xmax - Xmin; double y_l = Ymax - Ymin; double r_value=0; r_value = x_l + y_l; return r_value; } vector<int>net::get_mv(int i){ mov g_mv = moveable(i); vector<int>con = get_num(i); vector<int>move_b; for (int d = 0; d < con.size(); d++){ int set = 0; for (int c = 0; c < g_mv.m_num; c++){ if (con[d] == g_mv.mv[c]){ set = 1; break; } } if (set == 0){ move_b.push_back(con[d]); } } return move_b; }<file_sep>//#include "stdafx.h" #include <stdio.h> #include <iostream> #include <cstring> #include <vector> #include <fstream> #include"router.h" using namespace std; //static int t_con = 0; struct path{ int *grid; int **fifo; int n, l, con_num, pl, n_con, w_con, t_con; }; path pathRender(path f_in, int n){// z has not been used, add later path tempPath; tempPath = f_in; tempPath.t_con = f_in.t_con; int l_con = 0; int mark = 0; int loop = 1; int length = 1;//path number int pd = 0; for (int i = 0; i < tempPath.n_con; i = i + 2){ if (tempPath.grid[tempPath.con_num] - 2 == tempPath.grid[i] && tempPath.grid[tempPath.con_num + 1] == tempPath.grid[i + 1]){ pd = 1; } } if (tempPath.grid[tempPath.con_num] - 2 >= 0&&pd==0){//source has a swtich block on the left cout << "source has a swtich block on the left" << endl; if (tempPath.fifo[tempPath.grid[tempPath.con_num] - 2][tempPath.grid[tempPath.con_num + 1]] == 116){ mark = 1; cout << "find target left" << endl; tempPath.n = 1; tempPath.fifo[tempPath.grid[tempPath.con_num] - 1][tempPath.grid[tempPath.con_num + 1]] = tempPath.l; tempPath.pl = tempPath.fifo[tempPath.grid[tempPath.con_num] - 1][tempPath.grid[tempPath.con_num + 1]]; return tempPath; } else {//not the target l_con = l_con + 1; tempPath.n_con = tempPath.n_con + 2; cout << tempPath.n_con << endl; int *fifo = new int[tempPath.n_con];//make one more room in the expansion list ::memcpy(fifo, tempPath.grid, 4 * tempPath.n_con);//copy the original expansion list into fifo int n = sizeof(tempPath.grid); //cout << "length=" << n << endl; fifo[tempPath.n_con - 2] = tempPath.grid[tempPath.con_num] - 2;//store the new coordinate into expansion list fifo[tempPath.n_con - 1] = tempPath.grid[tempPath.con_num + 1]; tempPath.grid = fifo; if (tempPath.fifo[tempPath.grid[tempPath.con_num] - 1][tempPath.grid[tempPath.con_num + 1]] == 1){ tempPath.fifo[tempPath.grid[tempPath.con_num] - 1][tempPath.grid[tempPath.con_num + 1]] = tempPath.l;//mark the path between two swtich blocks } } } int pr = 0; for (int i = 0; i < tempPath.n_con; i = i + 2){ if (tempPath.grid[tempPath.con_num] + 2 == tempPath.grid[i] && tempPath.grid[tempPath.con_num + 1] == tempPath.grid[i + 1]){ pr = 1; } } if (tempPath.grid[tempPath.con_num] + 2 <= 2 * n + 1&&pr==0){//source has a swtich block on the right cout << "source has a swtich block on the right" << endl; if (tempPath.fifo[tempPath.grid[tempPath.con_num] + 2][tempPath.grid[tempPath.con_num + 1]] == 116){ mark = 1; tempPath.n = 1; tempPath.fifo[tempPath.grid[tempPath.con_num] + 1][tempPath.grid[tempPath.con_num + 1]] = tempPath.l; tempPath.pl = tempPath.fifo[tempPath.grid[tempPath.con_num] + 1][tempPath.grid[tempPath.con_num + 1]]; return tempPath;//should be replaced by return } else { l_con = l_con + 1; tempPath.n_con = tempPath.n_con + 2; cout << tempPath.n_con << endl; int *fifo = new int[tempPath.n_con]; ::memcpy(fifo, tempPath.grid, 4 * tempPath.n_con); fifo[tempPath.n_con - 2] = tempPath.grid[tempPath.con_num] + 2;//store the new coordinate into expansion list fifo[tempPath.n_con - 1] = tempPath.grid[tempPath.con_num + 1]; tempPath.grid = fifo; if (tempPath.fifo[tempPath.grid[tempPath.con_num] + 1][tempPath.grid[tempPath.con_num + 1]] == 1){ tempPath.fifo[tempPath.grid[tempPath.con_num] + 1][tempPath.grid[tempPath.con_num + 1]] = tempPath.l; } } } int pc = 0; for (int i = 0; i < tempPath.n_con; i = i + 2){ if (tempPath.grid[tempPath.con_num] == tempPath.grid[i] && tempPath.grid[tempPath.con_num + 1] + 2 == tempPath.grid[i + 1]){ pc = 1; } } if (tempPath.grid[tempPath.con_num + 1] + 2 <= 2 * n + 1&&pc==0){//source has a swtich block on the above cout << "source has a swtich block on the above" << endl; if (tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] + 2] == 116){ //cout << slv.fifo[slv.grid[slv.con_num]][slv.grid[slv.con_num + 1] + 2]; mark = 1; cout << "find target above" << endl; tempPath.n = 1; tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] + 1] = tempPath.l; tempPath.pl = tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] + 1]; return tempPath; } else { l_con = l_con + 1; tempPath.n_con = tempPath.n_con + 2; //cout << slv.n_con << endl; int *fifo = new int[tempPath.n_con]; ::memcpy(fifo, tempPath.grid, 4 * tempPath.n_con); fifo[tempPath.n_con - 2] = tempPath.grid[tempPath.con_num];//store the new coordinate into expansion list fifo[tempPath.n_con - 1] = tempPath.grid[tempPath.con_num + 1] + 2; tempPath.grid = fifo; if (tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] + 1] == 1){ tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] + 1] = tempPath.l; } } } int pa = 0; for (int i = 0; i < tempPath.n_con; i = i + 2){ if (tempPath.grid[tempPath.con_num] == tempPath.grid[i] && tempPath.grid[tempPath.con_num + 1] - 2 == tempPath.grid[i + 1]){ pa = 1; } } //cout << slv.grid[slv.con_num + 1]; if (tempPath.grid[tempPath.con_num + 1] - 2 >= 0&&pa==0){//source has a swtich block on the below cout << "source has a swtich block on the below" << endl; l_con = l_con + 1; cout << "l_con=" << l_con << endl; if (tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] - 2] == 116){ mark = 1; cout << "find target below" << endl; tempPath.n = 1; tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] - 1] = tempPath.l; tempPath.pl = tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] - 1];//return the value of the path between slv.fifo[slv.grid[slv.con_num]][slv.grid[slv.con_num + 1] - 2] and source return tempPath; } else { tempPath.n_con = tempPath.n_con + 2; cout << tempPath.n_con << endl; if (tempPath.l == 2){ tempPath.l = tempPath.l + 1; tempPath.w_con = l_con + 1; cout << "next=" << tempPath.w_con << endl; cout << "total=" << tempPath.t_con << endl; } else{ //cout << num << endl; if (tempPath.con_num/2+1== tempPath.w_con){ tempPath.t_con = l_con + tempPath.t_con; tempPath.w_con = tempPath.w_con + tempPath.t_con; cout << "next="<<tempPath.w_con << endl; tempPath.t_con = 0; tempPath.l = tempPath.l + 1; cout << "length=" << tempPath.l << endl; } else{ tempPath.t_con = l_con + tempPath.t_con; cout << "total=" << tempPath.t_con << endl; } } int *fifo = new int[tempPath.n_con];//creat new array to store the expansion numbers ::memcpy(fifo, tempPath.grid, 4 * tempPath.n_con); fifo[tempPath.n_con - 2] = tempPath.grid[tempPath.con_num];//store the new coordinate into expansion list fifo[tempPath.n_con - 1] = tempPath.grid[tempPath.con_num + 1] - 2; tempPath.grid = fifo; //num = num + 2; if (tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] - 1] == 1){ tempPath.fifo[tempPath.grid[tempPath.con_num]][tempPath.grid[tempPath.con_num + 1] - 1] = tempPath.l;//first surronding has no target } path r_value; r_value.n_con = tempPath.n_con; r_value.w_con = tempPath.w_con; r_value.con_num = tempPath.con_num; r_value.t_con = tempPath.t_con; r_value.l = tempPath.l; r_value.n = mark; r_value.fifo = tempPath.fifo; r_value.grid = fifo; return r_value; } } else { if (tempPath.l == 2){ tempPath.l = tempPath.l + 1; tempPath.w_con = l_con + 1; } else{ if (tempPath.con_num/2+1== tempPath.w_con){ tempPath.w_con = tempPath.w_con + tempPath.t_con; cout << "next=" << tempPath.w_con << endl; tempPath.t_con = 0; tempPath.l = tempPath.l + 1; cout << "length=" << tempPath.l << endl; } else{ tempPath.t_con = l_con + tempPath.t_con; cout << "total=" << tempPath.t_con << endl; } } int *fifo = new int[tempPath.n_con];//creat new array to store the expansion numbers ::memcpy(fifo, tempPath.grid, 4 * tempPath.n_con); path r_value; r_value.con_num = tempPath.con_num; r_value.t_con = tempPath.t_con; r_value.n_con = tempPath.n_con; r_value.w_con = tempPath.w_con; r_value.l = tempPath.l; r_value.n = mark; r_value.fifo = tempPath.fifo; r_value.grid = tempPath.grid; return r_value; } }<file_sep>grep "0.000000" deviation.txt >>r/deviation.txt grep "0.000000" mean.txt >>r/mean.txt <file_sep>#pragma once //#include "stdafx.h" #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include <map> #include "file_extract.h" #include "extern.h" #include "branching.h" #include "calculator.h" #include "draw_graph.h" using namespace std; struct r{ map<int, map<int, vector<int>>>*x1; map<int, vector<int>>*x2; map<int, vector<int>>*results; int n; int b; int signal; int set; int count; }; class low_bound_first { calculator c_sample; draw_graph DG; public: low_bound_first(); ~low_bound_first(); void lbf(); r lbf_recur(map<int, map<int, vector<int>>>*x1, map<int, vector<int>>*x2, map<int, vector<int>>*results, int n, int b,int signal,int count,int set); }; <file_sep>#include "stdafx.h" #include <iostream> #include <string> #include <fstream> #include <sstream> #include <vector> #include "extract.h" using namespace std; extract::extract() { }; extract::~extract() { } vec_rec extract::recv(){//get all contents vector<double> a;//creat vector to reveive data vector<double> fixed; ifstream file; file.open("C:\\Users\\ThinkPad\\Desktop\\ECE1387\\project2\\c1.txt");//open file while (!file.eof()) { double n;//varaible to receive data file >> n; //cout << n; a.push_back(n); } int v_size = a.size();//size of the whole file int n = 0; int f_start = 0; for (n = 0; n < v_size; n++){//locate the start of fix pins if (a[n] == -1){ if (a[n + 1] == -1){ f_start = n + 2; break; } } } for (n = f_start; n < v_size - 1; n++){//put fixed pins data into fixed vector double i = a[n]; fixed.push_back(i); } int f_size = fixed.size(); vector<int>nodes; for (int m = 0; m < f_size; m = m + 3){//get the nodes that are fixed nodes.push_back(fixed[m]); } //calculate the number of total nets int net_num = 0;//number of nets for (int i = 2; i < f_start - 2; i++){//count stop at the beginning of fixed blocks if (a[i] == -1){//end of a line i = i + 2; //cout << "next line begins" << a[i+1] << endl; continue; } else{ if (a[i] >= net_num){ net_num = a[i]; } } } vec_rec van; van.a = a; van.fixed = fixed; van.totoal_nets = net_num; van.total_numbers = v_size; van.fixed_numbers = f_size; van.start = f_start; //cout << "net number is" << net_num << endl; //cout << fixed[1] << endl; //cout << f_size << "van" << endl; //cout << v_size << "van" << endl; return van; } vector<int> extract::get_net(){//get all moveable blocks in the circuit extern vec_rec rec_val; vec_rec vans = rec_val; vector<int>connection; //vector<int>j_connection; vector<double>f = fixed(); int fix_size = f.size(); //cout << fix_size << endl; int count = 0; for (int x = 0; x <vans.total_numbers; x++){ if (vans.a[x] == -1){ if (vans.a[x + 1] == -1){//end of moveable break; } else{ count = count + 1;//line + 1 if (count >= fix_size){ connection.push_back(vans.a[x + 1]);//store moveable block /*int i = x + 3; while (vans.a[i]!=-1){ j_connection.push_back(vans.a[i]); i++; }*/ } } } } /*for (int f = 0; f < connection.size(); f++){ cout << connection[f]; } cout << "total finish"<<endl; /*for (int y = 0; y < j_connection.size(); y++){ cout << j_connection[y]; }*/ return connection; } vector<double> extract::fixed(){//return a vector with only fixed block number extern vec_rec rec_val; vec_rec vans = rec_val; vector<double>fix; int n = vans.fixed.size(); for (int i = 0; i < n; i = i + 3){ fix.push_back(vans.fixed[i]); } //cout << "content fix" << fix[0] << fix[1] << fix.back() << endl; return fix; } xy extract::get_cfile(){ vector<double>x_co; vector<double>y_co; int c0 = 0; ifstream inputfile; inputfile.open("C:\\Users\\ThinkPad\\Desktop\\coordinate.txt"); while (!inputfile.eof()){ double n = 0; inputfile >> n; if (c0 < 15){ x_co.push_back(n); } else { y_co.push_back(n); } c0 = c0 + 1; } xy vans; vans.x=x_co; vans.y=y_co; return vans; } vector<vector<int>>extract::advanced_return(){ extern vec_rec rec_val; vector<vector<int>>ar; //int alength = rec_val.a.size(); int v_row;//row number of vector for (int i = rec_val.start-3; i > 0; i--){ if (rec_val.a[i] == -1){ v_row = rec_val.a[i + 1]; break; } } ar.resize(v_row);//v_row rows //cout << v_row; int count = 0; for (int c = 0; c < v_row; c++){//store data to each line in vector for (int x = 0; x < 30; x++){ if (rec_val.a[count] == -1){ count = count + 1; break; } else{ ar[c].push_back(rec_val.a[count]); count = count + 1; } } } return ar; } <file_sep>======================================================================== 控制台应用程序:class_recursive 项目概述 ======================================================================== 应用程序向导已为您创建了此 class_recursive 应用程序。 本文件概要介绍组成 class_recursive 应用程序的每个文件的内容。 class_recursive.vcxproj 这是使用应用程序向导生成的 VC++ 项目的主项目文件,其中包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。 class_recursive.vcxproj.filters 这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。 class_recursive.cpp 这是主应用程序源文件。 ///////////////////////////////////////////////////////////////////////////// 其他标准文件: StdAfx.h, StdAfx.cpp 这些文件用于生成名为 class_recursive.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。 ///////////////////////////////////////////////////////////////////////////// 其他注释: 应用程序向导使用“TODO:”注释来指示应添加或自定义的源代码部分。 ///////////////////////////////////////////////////////////////////////////// <file_sep>#pragma once #include <vector> #include "extract.h" #include "recurs.h" using namespace std; struct mov{ vector<int>mv;//moveable content int m_num;//number of moveable blocks }; class net { extract vans; //int net_number; public: net(); ~net(); mov moveable(int i);//i=6,7... vector<int> get_num(int i);//i=6,7.... double get_weight(int net_number);//i=6,7... double get_wl(int i);//get net number i vector<int>net::get_mv(int i); }; <file_sep>#include "stdafx.h" #include "spread.h" #include "create_matrix.h" spread::spread() { } spread::~spread() { } vector<double>spread::get_nb(int x){ create_matrix cc; cd = &cc; vector<double>bValues = cd->get_b(x); bound b = bm.get_boundary(); double x0 = (b.x_max + b.x_min) / 2; cout << "x0= " << x0 << endl; double y0 = (b.y_max + b.y_min) / 2; double x1 = (b.x_min + x0) / 2; double x2 = (b.x_max + x0) / 2; double y1 = (b.y_max + y0) / 2; double y2 = (b.y_min + y0) / 2; xy e_get = em.get_cfile(); cout << "sb size is= " << bValues.size() << endl; for (int i = 0; i < bValues.size(); i++){ double n = bValues[i]; cout << "sb[i] value is =" << n << endl; cout << "eget is " << e_get.x[i] << endl; if (x == 1){ if (e_get.x[i] <= x0){//left upper bValues[i] = n + x1;//weight =1 cout << "eget is " << e_get.x[i] << endl; continue; } else{ bValues[i] = n + x2;//weight =1 continue; } } else{ if (e_get.x[i]<=y0){ bValues[i] = n + y1;//weight =1 continue; } else{ bValues[i] = n + y2;//weight =1 continue; } } } cout << "start showing b" << endl; for (int i = 0; i < bValues.size(); i++){ cout << bValues[i] << endl; } return bValues; }<file_sep>//s#include "stdafx.h" #include <vector> #include <iostream> #include <string> #include <fstream> #include <sstream> #include <map> #include "file_extract.h" #include "branching.h" using namespace std; extern content file_reclaim; extern map<int, vector<int>>order; extern vector<int>branching_o;<file_sep>void draw(int **matrix, int *init, int *source, int *par); void delay(void); <file_sep>#include "stdafx.h" #include "recurs.h" #include <iostream> using namespace std; extract c; vec_rec rec_val = c.recv(); vector<int> nget=c.get_net(); extern vector<double>fget=c.fixed(); extern vector<vector<int>>ad = c.advanced_return();
16eba36824f690c52b95ed24468b435583eaffe9
[ "C", "Text", "C++", "Shell" ]
49
C++
DavidRen1996/ECE1387
af8e1ab91395be015bf4b1572429d0e33971ef0b
ad0bdbd4c9b7a8c640f306d1c3ffaafe380d0825
refs/heads/master
<repo_name>Gruuler/minions<file_sep>/elements/authenticate.php <?php $valid = false; ?><file_sep>/index.php <head> <?php include 'elements/master.php'; include 'elements/authenticate.php'; ?> </head> <body> <?php include 'elements/header.php'; ?> <?php if($valid) { echo "Please <a href='login.php'>Log In</a> to coninue."; } ?> <?php include 'elements/footer.php'; ?> </body>
6d0db2312ee45064190c3a09db3c6dd0227a1ee4
[ "PHP" ]
2
PHP
Gruuler/minions
0b99c94abf2ce84ab6cf568311a5f821ed767c00
906cdd94d6521e1acad35201deb6b53bbdce12dd
refs/heads/master
<file_sep># 0. Installing Meteor # 1. Creating an app $> meteor create toppoll [view source](https://github.com/rizafahmi/toppoll/commit/b412652050614dc36696dbaf2ab68cdfd307af97) Run meteor $> cd toppoll $> meteor # 2. Templates Add listing template that iterates through polls. <head> <title>Toppoll</title> </head> <body> <h1>Top Poll</h1> <ul> {{> poll}} </ul> </body> <template name="poll"> {{#each polls}} <li>{{question}}</li> {{/each}} </template> Remove placeholder code and binding dummy polls in javascript file. if (Meteor.isClient) { Template.poll.helpers({ 'polls': [ { question: "Bagaimana menurut kamu Meteor itu?", answer: [ { a: "Keren" }, { b: "Bagus" }, { c: "Biasa aja" } ] }, { question: "Apakah belajar Meteor menyenangkan?", answer: [ { a: "Tentu saja" }, { b: "Pastinya" }, { c: "Hmmm..." } ] }, ] }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } [View Source](https://github.com/rizafahmi/toppoll/commit/f96670e21d177fd0b65e4b1462e50c25f07840e1) # 3. Collections Add new polls collection, and change dummy polls into Polls.find() Polls = new Mongo.Collection("polls"); if (Meteor.isClient) { Template.poll.helpers({ polls: function () { return Polls.find(); } }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } Now, let's try insert one or more data from the database. $> meteor mongo meteor:PRIMARY> db.polls.insert({question: "Apakah Meteor keren?", answers: [{a: "Pastinya"}, {b: "Keren dong"}, {c: "Keren sih"}], dateCreated: new Date()}) # 4. Forms and Events Sekarang kita akan buat form untuk add poll baru. <head> <title>Toppoll</title> </head> <body> <h1>Top Poll</h1> <form class="new-poll" action=""> <textarea id="" name="question" cols="30" rows="10" placeholder="Enter your poll question here"></textarea> <input type="text" name="answer_a" placeholder="First poll answer"> <input type="text" name="answer_b" placeholder="Second poll answer"> <input type="text" name="answer_c" placeholder="third poll answer"> <button type="submit">Save</button> </form> <ul> {{> poll}} </ul> </body> <template name="poll"> {{#each polls}} <li>{{question}}</li> {{/each}} </template> Kok jelek ya... Time to use bootstrap! Buka `https://atmospherejs.com/` search bootstrap. Tambahkan paket bootstrap pilihan kita ke project. $> meteor add mizzao:bootstrap-3 Masih keliatan kurang ok sih, mari kita benarkan desain-nya. <head> <title>Toppoll</title> </head> <body> <div class="container"> <div class="row"> <h1>Top Poll</h1> <div class="col-md-8"> <h3> &gt; New Poll</h3> {{> newPoll}} </div> </div> <div class="row"> <div class="col-md-8"> <h3> &gt; List of Polls</h3> <ul> {{> poll}} </ul> </div> </div> </div> </body> <template name="poll"> {{#each polls}} <li>{{question}}</li> {{/each}} </template> <template name="newPoll"> <form class="form-horizontal new-poll" action=""> <div class="form-group"> <textarea id="" class="form-control" name="question" placeholder="Enter your poll question here"></textarea> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_a" placeholder="First poll answer"> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_b" placeholder="Second poll answer"> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_c" placeholder="third poll answer"> </div> <div class="form-group"> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </template> Sudah kelihatan better, kan?! Sekarang mari kita bikin form polling baru berfungsi. Buka javascript file. Polls = new Mongo.Collection("polls"); PollAnswers = new Mongo.Collection("pollAnswer"); if (Meteor.isClient) { Template.poll.helpers({ polls: function () { return Polls.find(); } }); Template.newPoll.events({ 'submit .new-poll': function (e) { var question = e.target.question.value; var answer_a = e.target.answer_a.value; var answer_b = e.target.answer_b.value; var answer_c = e.target.answer_c.value; Polls.insert({ question: question, answer_a: answer_a, answer_b: answer_b, answer_c: answer_c, createdAt: new Date() }); e.target.question.value = ""; e.target.answer_a.value = ""; var answer_b = e.target.answer_b.value; var answer_c = e.target.answer_c.value; Polls.insert({ question: question, answer_a: answer_a, answer_b: answer_b, answer_c: answer_c, createdAt: new Date() }); PollAnswers.insert({ pollId: poll, answer: answer_a }); PollAnswers.insert({ pollId: poll, answer: answer_b }); PollAnswers.insert({ pollId: poll, answer: answer_c }); e.target.question.value = ""; e.target.answer_a.value = ""; e.target.answer_b.value = ""; e.target.answer_c.value = ""; return false; } }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); } Mari kita coba form kita. Yes! It works! Ok, selesai sudah workshop kita hari ini sampai bertemu di episode berikutnya :) Biar daftar polling-nya ter sorting sesuai tanggal (yg terbaru diatas), kita ubah dikit di bagian query-nya. return Polls.find({}, {sort: {createdAt: -1}}); # 5. Remove a Poll Ok, sekarang kita mau coba buat supaya bisa hapus polling yg udah kita buat. Pertama-tama kita tambah tombol delete-nya dulu di template html. <head> <title>Toppoll</title> </head> <body> <div class="container"> <div class="row"> <h1>Top Poll</h1> <div class="col-md-8"> <h3> &gt; New Poll</h3> {{> newPoll}} </div> </div> <div class="row"> <div class="col-md-8"> <h3> &gt; List of Polls</h3> <ul> {{> poll}} </ul> </div> </div> </div> </body> <template name="poll"> {{#each polls}} <li> {{question}} <button class="btn btn-danger btn-delete btn-xs" type="button">&times;</button> </li> {{/each}} </template> <template name="newPoll"> <form class="form-horizontal new-poll" action=""> <div class="form-group"> <textarea id="" class="form-control" name="question" placeholder="Enter your poll question here"></textarea> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_a" placeholder="First poll answer"> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_b" placeholder="Second poll answer"> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_c" placeholder="third poll answer"> </div> <div class="form-group"> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </template> Ok, sekarang mari kita buat delete button berfungsi. if (Meteor.isClient) { ... Template.poll.events({ 'click .btn-delete': function () { Polls.remove(this._id); } }); } Sekarang yuk kita coba mendelete beberapa polling yg kita buat sebelumnya. Tuh, keren kan? # 6. Enhanced List of Polls Sekarang yuk kita bikin list of polls lebih bagus dan lebih terstruktur. Seperti menggunakan table, terus bisa diklik untuk menuju ke poll yg bisa kita vote rame-rame. Buka html file dan bikin tabel untuk list of poll. <head> <title>Toppoll</title> </head> <body> <div class="container"> <div class="row"> <h1>Top Poll</h1> <div class="col-md-8"> <h3> &gt; New Poll</h3> {{> newPoll}} </div> </div> <div class="row"> <div class="col-md-10"> <h3> &gt; List of Polls</h3> <ul> {{> poll}} </ul> </div> </div> </div> </body> <template name="poll"> <table class="table table-striped"> <thead> <tr> <th>Questions</th> <th>Actions</th> </tr> </thead> <tbody> {{#each polls}} <tr> <td>{{question}}</td> <td> <button class="btn btn-warning btn-vote btn-sm" type="button">Vote Now</button> <button class="btn btn-danger btn-delete btn-sm" type="button">Delete</button> </td> </tr> {{/each}} </tbody> </table> </template> <template name="newPoll"> <form class="form-horizontal new-poll" action=""> <div class="form-group"> <textarea id="" class="form-control" name="question" placeholder="Enter your poll question here"></textarea> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_a" placeholder="First poll answer"> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_b" placeholder="Second poll answer"> </div> <div class="form-group"> <input class="form-control" type="text" name="answer_c" placeholder="third poll answer"> </div> <div class="form-group"> <button class="btn btn-primary" type="submit">Save</button> </div> </form> </template> Nah, sekarang terlihat lebih bagus, bukan?! # 7. Voting Time! Nah sekarang kita mau bikin kalo user klik tombol 'Vote Now' akan buka semacam modal untuk voting. Yuk kita bikin modal di html file kita. {{# if selectedVote}} <!-- MODAL --> <div id="voteModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button> <h4 class="modal-title">{{selectedVote.question}}</h4> </div> <div class="modal-body"> <table class="table table-striped"> <tbody> {{#each pollAnswers}} <tr> <td>{{answer}}</td> <td><strong>{{count}}</strong></td> <td><button class="btn btn-sm btn-vote-count btn-success">Vote!</button></td> </tr> {{/each}} </tbody> </table> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal --> {{/if}} Jangan lupa kalo kita klik button 'Vote Now' men-trigger modal-nya. <button class="btn btn-warning btn-vote btn-sm" data-toggle="modal" data-target="#voteModal" type="button">Vote Now</button> Sekarang ke javascript file. Pertama, kalo button 'Vote Now' di klik, kita akan set session yg menyimpan vote id. Template.poll.events({ 'click .btn-delete': function () { Polls.remove(this._id); }, 'click .btn-vote': function () { Session.set('selectedVote', this._id); } }); Begitu vote id tersedia, kita select di database dan ditampilkan di modal. Termasuk kita select semua answer yg terkait dengan vote question tadi. Template.poll.helpers({ polls: function () { return Polls.find({}, {sort: {createdAt: -1}}); }, selectedVote: function () { var vote = Polls.findOne(Session.get("selectedVote")); return vote ; }, pollAnswers: function () { var answers = PollAnswers.find({pollId: Session.get("selectedVote")}, {sort: {count: -1}}); return answers; } }); Sekarang kita tampilkan di html. Kita pake if untuk cek kalo data sudah tersedia maka modal akan dimunculkan. Kalo ngga ada data, modal tidak akan muncul. Kita taro modal ini didalam template poll supaya masih didalam satu konteks. {{# if selectedVote}} <!-- MODAL --> <div id="voteModal" class="modal fade"> ... </div><!-- /.modal --> {{/if}} Selanjutnya kita bikin tiga button vote itu berfungsi. Setiap kali klik kita dapat id-nya, terus count-nya di increment. Template.poll.events({ 'click .btn-delete': function () { Polls.remove(this._id); }, 'click .btn-vote': function () { Session.set('selectedVote', this._id); }, 'click .btn-vote-count': function () { var id = this._id; PollAnswers.update({_id: id}, {$inc: { count: 1 }}); }, }); Sekarang yuk kita coba. Keren kan?! Coba lihat di database, beneran nambah ngga datanya di database. # Reset Vote # Edit Vote <file_sep>Polls = new Mongo.Collection("polls"); PollAnswers = new Mongo.Collection("pollAnswer"); if (Meteor.isClient) { Template.poll.helpers({ polls: function () { return Polls.find({}, {sort: {createdAt: -1}}); }, selectedVote: function () { var vote = Polls.findOne(Session.get("selectedVote")); return vote ; }, pollAnswers: function () { var answers = PollAnswers.find({pollId: Session.get("selectedVote")}, {sort: {count: -1}}); return answers; } }); Template.poll.events({ 'click .btn-delete': function () { Polls.remove(this._id); }, 'click .btn-vote': function () { Session.set('selectedVote', this._id); }, 'click .btn-vote-count': function () { var id = this._id; PollAnswers.update({_id: id}, {$inc: { count: 1 }}); }, }); Template.newPoll.events({ 'submit .new-poll': function (e) { var question = e.target.question.value; var answer_a = e.target.answer_a.value; var answer_b = e.target.answer_b.value; var answer_c = e.target.answer_c.value; var poll = Polls.insert({ question: question, createdAt: new Date() }); console.log(poll); PollAnswers.insert({ pollId: poll, answer: answer_a }); PollAnswers.insert({ pollId: poll, answer: answer_b }); PollAnswers.insert({ pollId: poll, answer: answer_c }); e.target.question.value = ""; e.target.answer_a.value = ""; e.target.answer_b.value = ""; e.target.answer_c.value = ""; return false; } }); } if (Meteor.isServer) { Meteor.startup(function () { // code to run on server at startup }); }
721792d8022b9515080bf2049778cb66514992c6
[ "Markdown", "JavaScript" ]
2
Markdown
rizafahmi/toppoll
5092ffee51b5bd767694881a9b1e8ccfc4d3dff7
e7d4dc02c64b608f5ddc0f3e0e5661779a60b1ce
refs/heads/master
<repo_name>nighthary/rn-cnodejs<file_sep>/app/view/home/movie/index-view.js import React, { Component } from 'react' import { PanResponder, StyleSheet, View, Dimensions, LayoutAnimation } from 'react-native' const {width, height} = Dimensions.get('window') const MIN_SIZE = 50; const MAX_SIZE = width / 2 + 50; class MovieIndex extends Component { static navigationOptions = ({navigation}) => { return { headerTitle: '我', headerStyle: { backgroundColor:'#000', paddingRight:10, }, headerTitleStyle: { color: '#FFF' } } } // 构造 constructor (props) { super(props) // 初始状态 this.state = { cWidth: 50, cHeight: 50 } _panResponder = {} _previousLeft = 0 _previousTop = 0 _circleStyles = {} circle = (null: ?{ setNativeProps(props: Object): void }) startX1 = 0; startY1 = 0; startX2 = 0; startY2 = 0; endX1 = 0; endY1 = 0; endX2 = 0; endY2 = 0; CIRCLE_SIZE = width / 4; nowLength = 0; console.log(CIRCLE_SIZE) } componentWillMount () { this._panResponder = PanResponder.create({ onStartShouldSetPanResponder: this._handleStartShouldSetPanResponder.bind(this), onMoveShouldSetPanResponder: this._handleMoveShouldSetPanResponder.bind(this), onPanResponderGrant: this._handlePanResponderGrant.bind(this), onPanResponderMove: this._handlePanResponderMove.bind(this), onPanResponderRelease: this._handlePanResponderEnd.bind(this), onPanResponderTerminate: this._handlePanResponderEnd.bind(this), onPanResponderStart: this._onPanResponderStart.bind(this), }) this._previousLeft = 20 this._previousTop = 84 this._circleStyles = { style: { left: this._previousLeft, top: this._previousTop, backgroundColor: 'green', } } } componentDidMount () { this._updateNativeStyles() } _highlight () { // this._circleStyles.style.backgroundColor = 'blue' CIRCLE_SIZE = CIRCLE_SIZE - 5; CIRCLE_SIZE = CIRCLE_SIZE <= 50 ? 50 : CIRCLE_SIZE; this._circleStyles.style.width = CIRCLE_SIZE; this._circleStyles.style.height = CIRCLE_SIZE; this._updateNativeStyles() // this.startAnimation(CIRCLE_SIZE) } _unHighlight () { // this._circleStyles.style.backgroundColor = 'red' CIRCLE_SIZE = CIRCLE_SIZE + 5; CIRCLE_SIZE = MAX_SIZE <= CIRCLE_SIZE ? MAX_SIZE : CIRCLE_SIZE; console.log(`CIRCLE_SIZE: ${CIRCLE_SIZE}`); this._circleStyles.style.width = CIRCLE_SIZE; this._circleStyles.style.height = CIRCLE_SIZE; this._updateNativeStyles() // this.startAnimation(CIRCLE_SIZE) } _updateNativeStyles () { this.circle && this.circle.setNativeProps(this._circleStyles) } _handleStartShouldSetPanResponder (e: Object, gestureState: Object): boolean { // Should we become active when the user presses down on the circle? return true } _handleMoveShouldSetPanResponder (e: Object, gestureState: Object): boolean { // Should we become active when the user moves a touch over the circle? return true } _handlePanResponderGrant (e: Object, gestureState: Object) { // this._highlight() } _onPanResponderStart (e:Object, gestureState: Object){ if(gestureState.numberActiveTouches === 2) { let {touches} = e.nativeEvent; startX1 = touches[0].locationX; startY1 = touches[0].locationY; startX2 = touches[1].locationX; startY2 = touches[1].locationY; } } _handlePanResponderMove (e: Object, gestureState: Object) { // this._circleStyles.style.left = this._previousLeft + gestureState.dx // this._circleStyles.style.top = this._previousTop + gestureState.dy // this._updateNativeStyles() if(gestureState.numberActiveTouches === 2){ let {touches} = e.nativeEvent; endX1 = touches[0].locationX; endY1 = touches[0].locationY; endX2 = touches[1].locationX; endY2 = touches[1].locationY; let {dx, dy} = gestureState // console.log(`dx:${dx}====dy:${dy}`); let moveX = Math.abs(endX2 - endX1) let moveY = Math.abs(endY2 - endY1) move1 = Math.sqrt(Math.pow(moveX, 2) + Math.pow(moveY, 2) , 2) if(nowLength !== 0 && move1 > nowLength && (moveX> 100 || moveY > 100)){ this._unHighlight() }else if(nowLength !== 0 && move1 <= nowLength && (moveX> 100 || moveY > 100)){ this._highlight() } console.log(`move1:${move1}====nowLength:${nowLength}===moveX:${moveX}====moveY:${moveY}`) nowLength = move1 } } _handlePanResponderEnd (e: Object, gestureState: Object) { // this._unHighlight() // this._previousLeft += gestureState.dx // this._previousTop += gestureState.dy CIRCLE_SIZE = CIRCLE_SIZE < 100 ? 100: CIRCLE_SIZE; CIRCLE_SIZE = CIRCLE_SIZE > width / 2 ? width / 2: CIRCLE_SIZE; console.log(`CIRCLE_SIZE:${CIRCLE_SIZE}`) this.startAnimation(CIRCLE_SIZE) } async startAnimation(value) { LayoutAnimation.configureNext(LayoutAnimation.create(700, LayoutAnimation.Types.spring, LayoutAnimation.Properties.scaleXY)); await this.setState({cWidth: value, cHeight: value}); this._circleStyles.style.width = CIRCLE_SIZE; this._circleStyles.style.height = CIRCLE_SIZE; this._updateNativeStyles() } render () { let {cWidth,cHeight} = this.state; return ( <View style={styles.container} {...this._panResponder.panHandlers} > <View style={styles.scaleView}> <View ref={(circle) => { this.circle = circle }} style={{width: cWidth, height: cHeight}} /> </View> </View> ) } } const styles = StyleSheet.create({ round: { width: 50, height: 50, marginLeft: -40 }, container: { flex: 1, // alignItems:'center', // justifyContent:'center' }, scaleView: { width, height, backgroundColor: '#eee', alignItems:'center', justifyContent:'flex-start' } }) export default MovieIndex<file_sep>/app/view/info/styles.js import { StyleSheet, Dimensions } from 'react-native'; const {width, height} = Dimensions.get('window') export const styles = StyleSheet.create({ icon: { width: 25, }, container: { flex: 1 }, info: { height: 80, backgroundColor: '#FFF', paddingHorizontal: 20, flexDirection: 'row', alignItems: 'center' }, avator: { width: 50, height: 50, borderRadius: 25 }, detail: { marginLeft:20, }, name: { color: '#333', fontSize: 16 }, time: { fontSize: 12, color: '#999', paddingTop: 5, paddingBottom: 5, }, rowList: { marginTop: 10, backgroundColor:'#FFF' }, row: { height: 50, flexDirection: 'row', alignItems:'center', paddingLeft: 20 }, img: { width: 20, height: 20, marginRight: 15 }, rowInner: { flex: 1, paddingTop: 20, paddingBottom: 20, flexDirection: 'row', paddingRight: 20, justifyContent: 'space-between', borderBottomWidth: 0.5, borderColor: '#F1F1F1', }, title: { fontSize: 14, color: '#333' }, txt: { fontSize: 12, color: '#999', } })<file_sep>/app/navigator/Navigator.js import { StackNavigator } from 'react-navigation'; import Home from '../view/Home'; import Second from '../view/Second'; import TabView from './MyTabNavigator'; import AnimateView from '../view/Animate'; import MyList from '../view/MyList'; const AppNavigator = StackNavigator( { // 页面跳转的钩子 Home: { screen: Home , key: 'Home'}, Second: {screen: Second, key: 'Second'}, TabView: { screen: TabView, key: 'TabView'}, animate: {screen: AnimateView, key: 'animate'}, myList: {screen: MyList, key: 'myList'} }); export default AppNavigator; <file_sep>/app/view/home/ImageShow.js import React, { Component } from 'react' import { Dimensions, Image } from 'react-native' import ImageZoom from 'react-native-image-pan-zoom' class ImageShow extends React.Component { render () { return ( <ImageZoom cropWidth={Dimensions.get('window').width} cropHeight={Dimensions.get('window').height} imageWidth={200} imageHeight={200}> <Image style={{width: 200, height: 200}} source={{uri: 'http://v1.qzone.cc/avatar/201407/07/00/24/53b9782c444ca987.jpg!200x200.jpg'}}/> </ImageZoom> ) } } export default ImageShow<file_sep>/app/navigator/MyNavigator.js import { TabNavigator, StackNavigator } from 'react-navigation' import React from 'react' import HomeIndex from '../view/home/'; import InfoIndex from '../view/info/'; import Detail from '../view/home/detail/'; import Movie from '../view/home/movie/'; import ImageShow from '../view/home/ImageShow'; import Login from '../view/info/login/'; import MyInfo from '../view/info/myInfo/'; const Tabs = TabNavigator({ home: { screen: HomeIndex, }, info: { screen: InfoIndex, } }, { animationEnabled: false, swipeEnabled: true, tabBarOptions: { activeTintColor: '#e25800', showIcon: true, mode: 'card', indicatorStyle: { height: 0 }, style: { backgroundColor: '#fff', }, }, tabBarPosition: 'bottom' }) const Navigator = StackNavigator({ tabs: {screen: Tabs}, detail: {screen: Detail}, login: {screen: Login}, myInfo: {screen: MyInfo}, movie: {screen: Movie}, img: {screen: ImageShow}, }, { initialRouteName: 'tabs', cardStyle: { backgroundColor: '#F1F1F1' }, headerMode: 'screen' }) export default Navigator<file_sep>/app/navigator/MyTabNavigator.js import { TabNavigator } from 'react-navigation'; import React from 'react'; import { Image, StyleSheet } from 'react-native'; import TabIndex from '../view/tab/TabIndex'; import Mine from '../view/tab/MineNavigator'; const MyTabNavigator = TabNavigator({ TabIndex: { screen: TabIndex, key: 'TabIndex', options: { tabBar: { label: '首页', icon: ({tintColor}) => ( <Image source={require('../assets/imgs/home.png')} style={[{tintColor: tintColor},styles.icon]} /> ), }, } }, Mine: { screen: Mine, key: 'Mine', options: { tabBar: { label: '我', icon: ({tintColor}) => ( <Image source={require('../assets/imgs/mine.png')} style={[{tintColor: tintColor},styles.icon]} /> ), }, } } }, { animationEnabled: false, tabBarPosition: 'bottom', swipeEnabled: false, backBehavior: 'none', tabBarOptions: { activeTintColor: '#0F9C00', // 文字和图片选中颜色 inactiveTintColor: '#999', // 文字和图片默认颜色 showIcon: true, // android 默认不显示 icon, 需要设置为 true 才会显示 indicatorStyle: {height: 0}, // android 中TabBar下面会显示一条线,高度设为 0 后就不显示线了, 不知道还有没有其它方法隐藏??? style: { backgroundColor: '#fff', // TabBar 背景色 }, labelStyle: { fontSize: 12, // 文字大小 }, } }) const styles = StyleSheet.create({ icon: { height: 22, width: 22, resizeMode: 'contain' } }); export default MyTabNavigator<file_sep>/app/redux/middleware.js import promiseMiddleware from 'redux-promise'; import thunkMiddleware from 'redux-thunk'; import loggerMiddleware from './middleware/loggerMiddleware'; export default [ promiseMiddleware, thunkMiddleware, loggerMiddleware ];<file_sep>/app/view/Second.js import React, { Component } from 'react' import { Text, View, Button, TouchableHighlight, Image, StyleSheet, } from 'react-native' class Second extends Component { static navigationOptions = { title: 'Second', } constructor (props) { super(props) } render () { const {params} = this.props.navigation.state return ( <View> <TouchableHighlight> <Text onPress={() => { this.props.navigation.goBack() }}> Hello, {params.name}! </Text> </TouchableHighlight> <Text> Hello, {params.name}! </Text> <Button title="去TabView" onPress={() => { this.props.navigation.navigate('TabView')}}/> <Button title="去动画View" onPress={() => { this.props.navigation.navigate('animate')}}/> <Button title="去列表" onPress={() => { this.props.navigation.navigate('myList')}}/> <Image source={{ uri: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1035436093,3470577695&fm=27&gp=0.jpg', cache: 'only-if-cached' }} style={styles.img}/> </View> ) } } const styles = StyleSheet.create({ img: { width: 200, height: 100, margin: 20 } }) export default Second<file_sep>/app/view/info/index-view.js import React, { Component } from 'react' import { View, Text, Image, TouchableOpacity, } from 'react-native' import Header from './components/Header' import { styles } from './styles' class InfoIndex extends Component { static navigationOptions = ({navigation}) => { return { tabBarLabel: '我', tabBarIcon: ({focused, tintColor}) => { return ( <Image source={require('../../assets/imgs/mine.png')} style={[styles.icon, {tintColor: tintColor}]} /> ) }, headerTitle: '我', headerStyle: { backgroundColor: '#000', paddingRight: 10 }, headerTitleStyle: { color: '#FFF' } } } render = () => { const { navigate } = this.props.navigation; const data = { }; const headerProps = { data, navigate } return ( <View style={styles.container}> <Header {...headerProps} /> <View style={styles.rowList}> <TouchableOpacity> <View style={styles.row}> <Image source={require('../../assets/imgs/integral.png')} style={styles.img} /> <View style={styles.rowInner}> <Text style={styles.title}>论坛积分</Text> <Text style={styles.txt}>280</Text> </View> </View> </TouchableOpacity> <TouchableOpacity> <View style={styles.row}> <Image source={require('../../assets/imgs/github.png')} style={styles.img} /> <View style={styles.rowInner}> <Text style={styles.title}>代码仓库</Text> <Text style={styles.txt}>NightHary</Text> </View> </View> </TouchableOpacity> </View> <View style={styles.rowList}> <TouchableOpacity> <View style={styles.row}> <Image source={require('../../assets/imgs/comment.png')} style={styles.img} /> <View style={styles.rowInner}> <Text style={styles.title}>最近回复</Text> <Text style={styles.txt}>5</Text> </View> </View> </TouchableOpacity> <TouchableOpacity> <View style={styles.row}> <Image source={require('../../assets/imgs/post.png')} style={styles.img} /> <View style={styles.rowInner}> <Text style={styles.title}>最新发布</Text> <Text style={styles.txt}>3</Text> </View> </View> </TouchableOpacity> <TouchableOpacity> <View style={styles.row}> <Image source={require('../../assets/imgs/post.png')} style={styles.img} /> <View style={styles.rowInner}> <Text style={styles.title}>话题收藏</Text> {/*<Text style={styles.txt}>3</Text>*/} </View> </View> </TouchableOpacity> </View> <View style={styles.rowList}> <TouchableOpacity> <View style={styles.row}> <Image source={require('../../assets/imgs/setting.png')} style={styles.img} /> <View style={styles.rowInner}> <Text style={styles.title}>设置</Text> </View> </View> </TouchableOpacity> </View> </View> ) } componentDidMount () { } } export default InfoIndex<file_sep>/app/navigator/index.js import React, { Component } from 'react'; import AppNavigator from './Navigator'; export default class NavigatorView extends Component { static displayName = 'NavigationView'; render() { return ( <AppNavigator /> ); } } <file_sep>/app/view/tab/Info.js import React, { Component } from 'react'; import { Text, View, Button } from 'react-native'; class Info extends Component { static navigationOptions = { headerTitle: '个人信息' } constructor (props, context) { super(props, context); this.gotoTabIndex = this.gotoTabIndex.bind(this); this.gotoStackIndex = this.gotoStackIndex.bind(this); } render () { const { navigate } = this.props.navigation; return ( <View> <Button title="回到Stack首页" onPress={ this.gotoStackIndex } /> <Button title="回到Tab首页" onPress={ this.gotoTabIndex } /> <Button title="返回" onPress={() => this.props.navigation.goBack()} /> </View> ) } gotoTabIndex () { this.props.navigation.navigate('TabIndex') } gotoStackIndex () { this.props.navigation.goBack('Home') } } export default Info;<file_sep>/app/view/home/index-view.js import React, { Component } from 'react' import { View, Text, Image, FlatList, TouchableOpacity, ActivityIndicator, ProgressBar, } from 'react-native' import { getHomeList } from '../../service/apis'; import {formatDate} from '../../util/tools'; import {baseStyle, styles, tabStyles, listStyles} from './styles'; const tabs = [{key: 'all', value: '全部'}, {key: 'good', value: '精华'}, {key: 'share', value: '分享'}, {key: 'ask', value: '问答'}] const tabsObj = { 'top': '置顶', 'ask': '问答', 'good': '精华', 'share': '分享', 'job': '招聘', 'dev': '测试', 'default': '暂无' } class HomeIndex extends Component { static navigationOptions = ({navigation}) => { return { tabBarLabel: '首页', tabBarIcon: ({tintColor}) => { return ( <Image source={require('../../assets/imgs/home.png')} style={[styles.icon, {tintColor: tintColor}]} /> ) }, headerLeft: ( <Image style={styles.headerLeft} source={require('../../assets/imgs/logo.png')} resizeMode='contain' /> ), headerRight: ( <View style={styles.headerRight}> <TouchableOpacity style={styles.headerTouch} onPress={() => { navigation.navigate('img') }}> <Image style={styles.headerBtn} source={require('../../assets/imgs/icon-search.png')} resizeMode='contain' /> </TouchableOpacity> </View> ), headerStyle: { backgroundColor:'#000', paddingRight:10 } } } constructor (props) { super(props) this.state = { lists: [], isLoading: false, isShowLoading: false, limit: 10, page: 1, isDataEnd: false, refreshing: true, failed: false, } } componentWillMount () { this.getList() } getList () { let {page, limit} = this.state; let {activeTab} = this.props; let _isDataEnd = false; if(!this.state.isLoading){ this.setState({isLoading: true}) getHomeList(page, limit, activeTab).then((result) => { if (result.success) { let _data = result.data; this.convertData(_data); const newData = this.state.lists.concat(_data); this.setState({isLoading: false, lists: newData, refreshing: false, isDataEnd: _isDataEnd, isShowLoading: false}) } }).catch(err => { this.setState({failed: true}) }) } } convertData (data) { data.map((elem, index) => { let obj = data[index]; obj.create_at = formatDate(obj.create_at); obj.last_reply_at = formatDate(obj.last_reply_at); obj.tabTxt = tabsObj[data[index].tab]; let avatar_url = obj.author.avatar_url; if (avatar_url && !avatar_url.startsWith('https')){ obj.author.avatar_url = 'https:' + avatar_url } }) } refresh () { this.setState({page: 1, lists: [],isDataEnd: false, refreshing: false, failed: false}) this.getList() } loadMore () { if(!this.state.isDataEnd){ this.setState({page: this.state.page++ }) this.getList() } } async switchTab (tab) { this.setState({isShowLoading: true}); const {changeTab} = this.props; this.setState({ lists: []}); await changeTab(tab); this.getList(); } render () { const {activeTab} = this.props; const {navigate} = this.props.navigation; let {isShowLoading} = this.state; return ( <View style={styles.container}> <View style={tabStyles.tabView}> { tabs.map((item, index) => ( <TouchableOpacity key={index} onPress={() => {this.switchTab(item.key)}}> <View style={[tabStyles.item, activeTab === item.key ? tabStyles.itemActive : null]} key={index}> <Text style={[tabStyles.txt, activeTab === item.key ? tabStyles.txtActive : null]}>{item.value}</Text> </View> </TouchableOpacity> )) } </View> <FlatList refreshing={this.state.refreshing} data={this.state.lists} keyExtractor={(item, index) => index} renderItem={this._renderListItem} onRefresh={this.refresh.bind(this)} onEndReached={this.loadMore.bind(this)} onEndReachedThreshold={0.1} getItemLayout={(data, index) => ({length: 270.5, offset: 270.5 * index, index})} /> <TouchableOpacity onPress={() => { navigate('detail') }}> <Image style={styles.pubilsh} source={require('../../assets/imgs/add.png')} resizeMode='contain' /> </TouchableOpacity> <View style={styles.loading}> <ActivityIndicator animating={isShowLoading} size="large" /> </View> </View> ) } _renderListItem = ({item}) => { return ( <TouchableOpacity onPress={() => (this.props.navigation.navigate('movie'))} activeOpacity={0.6}> <View style={listStyles.item}> <View style={listStyles.header}> <View style={[listStyles[item.tab], listStyles.tab]}> <Text style={listStyles.headerTxt}>{item.tabTxt}</Text> </View> <Text numberOfLines={1} style={listStyles.title}>{item.title}</Text> </View> <View style={listStyles.content}> <TouchableOpacity> <Image source={{ uri: item.author.avatar_url}} style={listStyles.avatar} /> </TouchableOpacity> <View style={listStyles.info}> <Text style={listStyles.name}>{item.author.loginname}</Text> <Text style={listStyles.time}>{item.create_at}</Text> </View> <View style={listStyles.replyInfo}> <View style={listStyles.count}> <Text style={listStyles.replyCount}>{item.reply_count} / </Text> <Text style={listStyles.visitCount}>{item.visit_count}</Text> </View> <Text style={listStyles.replyTime}>{item.last_reply_at}</Text> </View> </View> </View> </TouchableOpacity> ) } } export default HomeIndex <file_sep>/app/service/apis.js import {get, post} from '../util/request' // let rootPath = `http://malldev.goodsogood.com` let rootPath = `https://cnodejs.org` export function buildParams(obj) { let result = []; for(var key in obj){ result.push(`${key}=${obj[key]}`) } return result.join('&') } export function getHomeList(page, limit, tab){ // const path = `${rootPath}/app/commodity/recommendList?openId=f0a9c82b1f07ea88f52d5b314be037f0`; const path = `${rootPath}/api/v1/topics?` + buildParams({ limit, page, tab}); console.log(`${path}`) return get(path) } export function getDetail(id){ const path = `${rootPath}`; return get(path, buildParams(id)) } export function login(accesstoken){ const path = `${rootPath}/accesstoken`; return post(path, buildParams({accesstoken})) }<file_sep>/app/util/resource.js const resources = { } export default function getResource(key) { return resources[key]; }<file_sep>/app/view/info/myInfo/index.js import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as MyInfoActions from './state'; import IndexView from './index-view'; const mapStateToProps = ( state ) => ({ test: state.getIn( [ 'homeState', 'test' ] ), nowCount: state.getIn( ['homeState', 'nowCount']) }); const mapDispathToProps = ( dispath ) => ({ MyInfoActions: bindActionCreators( MyInfoActions, dispath ) }); export default connect( mapStateToProps, mapDispathToProps )( IndexView ); <file_sep>/app/view/info/state.js import { Map } from 'immutable'; const initState = Map( { // test variable test : '个人中心', } ); // 设置loading状态 export default function InfoReducer( state = initState, action = {} ) { switch ( action.type ) { default: return state } }<file_sep>/app/view/Animate.js import React, { Component } from 'react'; import { NativeModules, View, Text, StyleSheet, TouchableOpacity, LayoutAnimation } from 'react-native'; const { UIManager } = NativeModules; UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true) class Home extends Component { static navigationOptions = { title: 'Animate-View' } constructor (props){ super(props); this.state = { w: 100, h: 100, }; } render () { return ( <View style={styles.container}> <View style={[styles.box, {width: this.state.w, height: this.state.h}]} /> <TouchableOpacity onPress={ this._onBig }> <View style={styles.button}> <Text style={styles.buttonText}> Big!</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={ this._onSmall }> <View style={styles.button}> <Text style={styles.buttonText}> Small!</Text> </View> </TouchableOpacity> </View> ) } _onBig = () => { LayoutAnimation.spring(); this.setState({w: this.state.w + 15, h: this.state.h + 15}) } _onSmall = () => { LayoutAnimation.spring(); this.setState({w: this.state.w - 15, h: this.state.h - 15}) } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, box: { width: 200, height: 200, backgroundColor: 'red' }, button: { backgroundColor: 'black', paddingHorizontal: 20, paddingVertical: 15, marginTop: 15 }, buttonText: { color: '#fff', fontWeight: 'bold' } }) export default Home;<file_sep>/app/view/home/styles.js import { StyleSheet, Dimensions } from 'react-native'; const {width, height} = Dimensions.get('window') export const baseStyle = StyleSheet.create({ center: { flex: 1, alignItems: 'center', justifyContent: 'center', minHeight: 200, } }) export const styles = StyleSheet.create({ container: { flex: 1, backgroundColor:'#FFF' }, headerLeft: { height: 25, width: 100, marginLeft: 15 }, headerRight: { flex: 1, flexDirection: 'row', alignItems: 'center' }, headerImg: { width, height: 150 }, pubilsh: { position: 'absolute', bottom: -60, right: 20, width: 40, }, loading: { position: 'absolute', top: 80, flex: 1, width, flexDirection: 'row', justifyContent: 'center', alignItems: 'center' } }) export const tabStyles = StyleSheet.create({ tabView: { flexDirection: 'row', backgroundColor: '#FFF', justifyContent: 'space-around', borderBottomWidth: 0.5, borderColor: '#F5F5F5' }, item: { padding: 15, alignItems: 'center', justifyContent: 'center' }, itemActive:{ borderBottomWidth: 1.5, borderColor: '#4181DE', }, txt: { color: '#000' }, txtActive: { color: '#4181DE' } }) export const listStyles = StyleSheet.create({ item: { padding: 10, borderBottomWidth: 0.5, borderColor: '#f1f1f1' }, header: { flexDirection: 'row', alignItems: 'center', flexWrap: 'wrap', }, tab: { marginRight: 10, paddingTop: 5, paddingLeft: 6, paddingBottom: 5, paddingRight: 6, borderRadius: 3, }, all: { backgroundColor: '#e74c3c', }, ask: { backgroundColor: '#3498db', }, good: { backgroundColor: '#e67e22', }, share: { backgroundColor: '#1abc9c', }, headerTxt: { color: '#000', fontSize: 12 }, title: { flex: 1, fontSize: 16 }, content: { marginTop: 10, flex: 1, flexDirection: 'row' }, avatar: { width: 50, height: 50, borderRadius: 25, marginRight: 10 }, info: { flex: 1, paddingVertical: 5, justifyContent: 'space-between', }, name: { fontSize: 12 }, time: { fontSize: 12, }, replyInfo: { paddingVertical: 5, justifyContent: 'space-between', alignItems: 'flex-end' }, replyCount: { fontSize: 12, color: '#42b983', }, visitCount: { fontSize: 12 }, replyTime: { fontSize: 12 }, count: { flexDirection: 'row' } }) <file_sep>/app/view/info/components/Header.js import React, { Component } from 'react' import { View, Text, Image, TouchableOpacity, StyleSheet, } from 'react-native' class Header extends Component { render = () => { const {data, navigate} = this.props return ( Object.keys(data).length ? <TouchableOpacity onPress={() => { navigate('myInfo')}}> <View style={styles.info}> <Image resizeMode='cover' source={require('../../../assets/imgs/header.png')} style={styles.avator} /> <View style={styles.detail}> <Text style={styles.name}>NightHary</Text> <Text style={styles.time}>注册于:8天前</Text> </View> </View> </TouchableOpacity> : <TouchableOpacity onPress={() => { navigate('login')}}> <View style={styles.info}> <Image resizeMode='cover' source={require('../../../assets/imgs/header.png')} style={styles.avator} /> <View style={styles.detail}> <Text style={styles.name}>未注册</Text> </View> </View> </TouchableOpacity> ) } } const styles = StyleSheet.create({ info: { height: 80, backgroundColor: '#FFF', paddingHorizontal: 20, flexDirection: 'row', alignItems: 'center' }, avator: { width: 50, height: 50, borderRadius: 25 }, detail: { marginLeft: 20, }, name: { color: '#333', fontSize: 14 }, time: { fontSize: 12, color: '#999', paddingTop: 5, paddingBottom: 5, } }) export default Header<file_sep>/app/view/MyList.js import React, { Component } from 'react' import { Text, FlatList, View, Image, StyleSheet } from 'react-native' import Mock from 'mockjs' class Home extends Component { constructor (props){ super(props) Mock.Random.image('200x100', '#FF6600') this.data = Mock.mock({ // 属性 list 的值是一个数组,其中含有 1 到 10 个元素 'list|1-10': [{ // 属性 id 是一个自增数,起始值为 1,每次增 1 'id|+1': 1, 'text': '@ctitle(5)', 'key': '@string("aeiou",5)', 'img': '@image' }] }) console.log(this.data) } static navigationOptions = { title: 'FatList' } render = () => ( <FlatList data={ this.data.list} renderItem={({item}) => this._renderItem(item)} /> ) _renderItem = (item) => ( <View style={styles.container}> <Text style={styles.txt} numberOfLines={2}>{item.text}</Text> <Image source={{ uri: item.img }} style={styles.img}/> </View> ) } const styles = StyleSheet.create({ container: { borderWidth: 1, borderColor: 'aqua', alignItems:'center', }, img: { width: 200, height:100 }, txt: { width: 200, color: 'red', fontSize: 20 } }) export default Home<file_sep>/README.md # rn-cnodejs react native cnodejs <file_sep>/app/view/info/login/index-view.js import React, { Component } from 'react' import { View, Text, Image, StyleSheet, TextInput, TouchableOpacity, AsyncStorage, ActivityIndicator, } from 'react-native' import {login} from '../../../service/apis'; class HomeIndex extends Component { static navigationOptions = ({navigation}) => { return { headerTitle: '登录', mode: 'card', headerMode: 'float', headerStyle: { backgroundColor:'#000', paddingRight:10, }, headerTitleStyle: { color: '#FFF' } } } constructor (props) { super(props) this.state = { text: '', isShowLoading: false } } componentWillMount () { } _onLogin = (accesstoken) => { if (!accesstoken) return this.setState({ isShowLoading }) login({accesstoken}).then((result) => { if(Number(result.code) === 0){ consoloe.log(result) consoloe.log(JSON.stringify(result)) AsyncStorage.setItem('accesstoken', accesstoken) this.props.navigation.goBack() } }) } render () { let {isShowLoading} = this.state; return ( <View style={styles.container}> <View style={styles.logoView}> <Image style={styles.logo} source={require('../../../assets/imgs/logo.png')} resizeMode='contain' /> </View> <View style={styles.inputView}> <TextInput style={styles.input} value={this.state.text} placeholder='输入 Access Token' underlineColorAndroid="transparent" onChangeText={(text) => { this.setState({ text }) }} /> </View> <TouchableOpacity style={styles.loginBtn} onPress={() => { this._onLogin(this.state.text) }}> <Text style={styles.login}>登录</Text> </TouchableOpacity> <ActivityIndicator animating={isShowLoading} size="large" color="#4876FF" /> </View> ) } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#FFFFFF', }, bgImageWrapper: { position: 'absolute', top: 0, bottom: 0, left: 0, right: 0 }, bgImage: { flex: 1, resizeMode: "stretch" }, logoView: { alignItems: 'center', margin: 15, marginBottom: 0, borderRadius: 5, backgroundColor: '#282828', }, logo: { width: 200, }, inputView: { height: 44, margin: 15, marginBottom: 0, borderRadius: 5, borderWidth: 1, borderColor: '#FFFFFF', justifyContent: 'center', backgroundColor: '#F8F8F8', }, input: { fontSize: 14, paddingLeft: 15, paddingRight: 15, }, loginBtn: { padding: 15, margin: 15, borderRadius: 5, alignItems: 'center', justifyContent: 'center', backgroundColor: '#0079FD', }, login: { color: '#FFF', fontSize: 16, fontWeight: 'bold', } }) export default HomeIndex<file_sep>/app/view/tab/MineNavigator.js import { StackNavigator } from 'react-navigation'; import MineIndex from './MineIndex'; import Info from './Info'; const MineNavigator = StackNavigator( { // 页面跳转的钩子 MineIndex: { screen: MineIndex, key: 'MineIndex' }, info: {screen: Info, key: 'info'}, }); const defaultGetStateForAction = MineNavigator.router.getStateForAction; MineNavigator.router.getStateForAction = (action, state) => { if (state && action.type === 'PushTwoProfiles') { const routes = [ ...state.routes, {key: 'MineIndex', routeName: 'MineIndex'}, {key: 'info', routeName: 'info'}, ]; return { ...state, routes, index: routes.length - 1, }; } return defaultGetStateForAction(action, state); }; export default MineNavigator; <file_sep>/ios/build/Build/Intermediates/testRn.build/Debug-iphonesimulator/testRn.build/DerivedSources/testRn_vers.c extern const unsigned char testRnVersionString[]; extern const double testRnVersionNumber; const unsigned char testRnVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:testRn PROJECT:testRn-1" "\n"; const double testRnVersionNumber __attribute__ ((used)) = (double)1.; <file_sep>/app/view/home/state.js import { Map } from 'immutable'; const initState = Map( { // test variable test : '首页', nowCount: 999, activeTab: 'all' } ); // 设置loading状态 const NOW_COUNT_ADD = 'home/NOW_COUNT_ADD'; const NOW_ACTIVE_TAB = 'home/NOW_ACTIVE_TAB'; export default function HomeReducer( state = initState, action = {} ) { switch ( action.type ) { case NOW_COUNT_ADD: return state.set('nowCount', action.payload) break; case NOW_ACTIVE_TAB: return state.set('activeTab', action.payload) break; default: return state } } export const setNowCount = (count) => { return (dispatch) => dispatch({ type: NOW_COUNT_ADD, payload: count }); }; export const changeTab = (tab) => { return (dispatch) => dispatch({ type: NOW_ACTIVE_TAB, payload: tab }); }<file_sep>/app/view/tab/MineIndex.js import React, { Component } from 'react' import { Text, View, Button } from 'react-native' class Mine extends Component { static navigationOptions = { headerTitle: '个人中心' } constructor (props, context) { super(props, context); this.gotoTabIndex = this.gotoTabIndex.bind(this); this.gotoStackIndex = this.gotoStackIndex.bind(this); this.gotoInfo = this.gotoInfo.bind(this); } render () { return ( <View> <Button title="回到Stack首页" onPress={this.gotoStackIndex}/> <Button title="回到Tab首页" onPress={this.gotoTabIndex}/> <Button title="去个人信息" onPress={ this.gotoInfo }/> <Button title="返回" onPress={() => this.props.navigation.goBack()}/> </View> ) } gotoTabIndex () { this.props.navigation.goBack('TabIndex') } gotoStackIndex () { debugger this.props.navigation.goBack('Home') } gotoInfo() { this.props.navigation.navigate('info') } } export default Mine<file_sep>/app/redux/reducer.js import { loop, combineReducers } from 'redux-loop-symbol-ponyfill'; import { Map, fromJS } from 'immutable'; import NavigatorReducer from '../navigator/NavigatorState'; import HomeReducer from '../view/home/state'; import InfoReducer from '../view/info/state'; import DetailReducer from '../view/home/detail/state'; import LoginReducer from '../view/info/login/state'; import MyInfoReducer from '../view/info/myInfo/state'; const reducers = { navigatorState: NavigatorReducer, homeState: HomeReducer, infoState: InfoReducer, detailState: DetailReducer, loginState: LoginReducer, myInfoState: MyInfoReducer, }; const immutableStateContainer = Map(); const getImmutable = (child, key) => child ? child.get(key) : void 0; const setImmutable = (child, key, value) => child.set(key, value); const namespacedReducer = combineReducers( reducers, immutableStateContainer, getImmutable, setImmutable ); export default function mainReducer(state, action) { const [nextState, effects] = namespacedReducer(state || void 0, action); return loop(fromJS(nextState), effects); }
8b367d5e55ae6a47f617a033f60a5237ca25114e
[ "JavaScript", "C", "Markdown" ]
27
JavaScript
nighthary/rn-cnodejs
d9c095a2b93716a5482b313f8f5148c800c0e379
e261ef1088f51de9ce962dc310711ad16ee760b9
refs/heads/main
<repo_name>jeremi420/projektowanie-serwisow-www-21686-185<file_sep>/lab2/assets/scripts/main.js "use strict"; const rows = 3; const columns = 3; const initialState = { squares: Array(rows * columns).fill(null), xIsNext: true, }; var state = initialState; let main = document.getElementsByTagName("main")[0]; main.style.margin = "auto"; main.style.backgroundColor = "#212121"; main.style.height = "100vh"; main.style.width = "100vw"; main.style.position = "relative"; main.style.textAlign = "center"; main.style.color = "white"; let modal = document.createElement("div"); modal.style.position = "absolute"; modal.style.top = "50%"; modal.style.left = "50%"; modal.style.transform = "translate(-50%, -50%)"; modal.style.minHeight = "260px"; main.append(modal); let title = document.createElement("h4"); title.textContent = "Kółko i krzyżyk"; modal.append(title); let status = document.createElement("div"); status.textContent = "Następny gracz: X"; modal.append(status); const onClick = (value) => (e) => { let squares = state.squares.slice(); if (state.squares[value] || calculateWinner(squares)) return; const newValue = state.xIsNext ? "X" : "O"; squares[value] = newValue; e.target.textContent = newValue; state = { ...state, squares, xIsNext: !state.xIsNext, }; const winner = calculateWinner(squares); if (winner || state.squares.indexOf(null) === -1) { if (winner) { status.innerHTML = "Wygrywa: " + winner; } else { status.innerHTML = "Remis"; } let reset = document.createElement("button"); reset.textContent = "reset"; reset.className = "btn btn-info"; reset.onclick = () => { state = { ...state, squares: Array(rows * columns).fill(null), xIsNext: true, }; let buttons = document.getElementsByClassName("btn btn-dark"); for (let i = 0; i < buttons.length; i++) { buttons[i].textContent = null; } status.innerHTML = "Następny gracz: X"; modal.removeChild(reset); }; modal.append(reset); } else { status.innerHTML = "Następny gracz: " + (state.xIsNext ? "X" : "O"); } }; function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if ( squares[a] && squares[a] === squares[b] && squares[a] === squares[c] ) { return squares[a]; } } return null; } for (let i = 0; i < rows; i++) { let row = document.createElement("div"); row.style.display = "inline-block"; for (let j = 0; j < columns; j++) { let square = document.createElement("button"); square.className = "btn btn-dark"; square.style.minHeight = "38px"; square.style.minWidth = "38px"; square.style.margin = "5px"; square.style.float = "left"; square.onclick = onClick(i * columns + j); row.append(square); } modal.append(row); modal.append(document.createElement("br")); } <file_sep>/lab7_i_8/src/App.js import React from "react"; import { Switch, Route, Link, useParams } from "react-router-dom"; import AppBar from "./AppBar"; import Drawer from "./Drawer"; import Home from "./Home"; import Products from "./Products"; import Cart from "./Cart"; import ProductDetails from "./ProductDetails"; export default function App() { const [open, setOpen] = React.useState(false); const toggleDrawer = (open) => (event) => { if ( event.type === "keydown" && (event.key === "Tab" || event.key === "Shift") ) { return; } setOpen(open); }; return ( <React.Fragment> <AppBar handleMenuClick={toggleDrawer(true)} /> <Drawer open={open} handleClose={toggleDrawer(false)} /> <Switch> <Route path="/" exact> <Home /> </Route> <Route path="/products/:id"> <ProductDetails /> </Route> <Route path="/products"> <Products /> </Route> <Route path="/cart"> <Cart /> </Route> </Switch> </React.Fragment> ); } <file_sep>/lab5/README.md # projektowanie-serwisow-www-jw-185 ## laboratorium piąte ## Autor <NAME> ### wykonanie zadań ćwiczeniowych ![wykonanie zadań](./screenshot.png) _wykonanie zadań_ <file_sep>/lab7_i_8/README.md # projektowanie-serwisow-www-jw-185 ## <NAME> ## laboratorium ósme ### laboratorium ósme w tym laboratorium dodałem implemenetację prostego koszyka w reactcie. Wykorzystałem object assign oraz spread operator. Przykład na ktorym się wzorowałem https://github.com/arnab-datta/counter-app. ![koszyk](./screenshots/cart.png) Korzystam z rozszerzenia git do visual studio code które pozwala mi osiągnąć podobne efekety co git difftool ![difftool](./screenshots/difftool.png) Powyższy przykład pokazuje różnicę pomiędzy ostatnim commitem wprowadzone w pojedynczym pliku. ![difftool2](./screenshots/difftool2.png) tutaj możemy zobaczyć jak zmieniła się struktura całego katalogu. ## laboratorium siódme Projekt strony napisanej w reactcie, wykorzystującej biblioteki material ui, oraz react router Dostępne ścieżki: - / - strona domowa - /products - katalog produktów - /products/:id - strona szczegółów produktu ### Strona glówna ![strona główna](./screenshots/home.png) ### Nawigacja Nawigacja na stronie odbywa się za pomocą drawera. Na liście dostępnych ścieżek, podświetla się ta, która została wybrana. ![nawigacja](./screenshots/navbar.png) ### katalog produktów Prosty katalog produktów z wykorzystaniem komponentów Grid oraz Paper. Zdjęcia stanowią odnośniki do strony szczegółów produktu. ![katalog produktów](./screenshots/products.png) ### szczegóły produktu Nie dodałem obsługi stanu globalnego, dlatego wyświetlane jest jedynie id produktu przekazanego w parametrach url. ![szczegóły produktu](./screenshots/product_details.png) <file_sep>/lab6/README.md # projektowanie-serwisow-www-jw-185 ## laboratorium szóste ## Autor <NAME> ### wykonanie zadań ćwiczeniowych prosta aplikacja w reactcie. Stan jest przekazywany do dwóch komponentów TodoList oraz TodoListItem. ![wykonanie zadań](./screenshot.png) _wykonanie zadań_ <file_sep>/README.md ### projektowanie-serwisow-www-jw-185 ### Autor <NAME> ![Strona główna](./Lab1/screenshots/main.png) ![list](./Lab1/screenshots/letter.png) ![podręcznik](./Lab1/screenshots/textbook.png) ![kontakt](./Lab1/screenshots/form.png) <file_sep>/lab7_i_8/src/ProductDetails.js import React from "react"; import { useParams } from "react-router-dom"; export default function ProductDetails() { const { id } = useParams(); return <div>{`product id ${id}`}</div>; } <file_sep>/lab7_i_8/src/Products.js import React from "react"; import Container from "@material-ui/core/Container"; import Paper from "@material-ui/core/Paper"; import Typography from "@material-ui/core/Typography"; import Grid from "@material-ui/core/Grid"; import { Switch, Route, Link, useParams } from "react-router-dom"; export default function Products() { const [products, setProducts] = React.useState([ { id: 1, image: "https://lp2.hm.com/hmgoepprod?set=source[/1b/7a/1b7aa9a9ba44ffc2221bdbba17134fe3c0a9e0be.jpg],origin[dam],category[men_hoodiessweatshirts_hoodies],type[LOOKBOOK],res[z],hmver[1]&call=url[file:/product/main]", title: "Bluza z kapturem Relaxed Fit", }, { id: 2, image: "https://lp2.hm.com/hmgoepprod?set=source[/5e/90/5e90db8dfffe1a2b023908fa6270fa85b0e53d86.jpg],origin[dam],category[men_tshirtstanks_shortsleeve],type[DESCRIPTIVESTILLLIFE],res[y],hmver[1]&call=url[file:/product/main]", title: "T-shirt Slim Fit 5-pak", }, { id: 3, image: "https://lp2.hm.com/hmgoepprod?set=source[/a9/5f/a95ff9affce0818feba6ef91ffa9118ff484ab25.jpg],origin[dam],category[men_underwearloungewear_underwear],type[LOOKBOOK],res[y],hmver[1]&call=url[file:/product/main]", title: "Krótkie bokserki 5-pak", }, ]); return ( <Container maxWidth="md"> <Grid container spacing={2}> {products.map((product) => ( <Grid item xs={6} sm={4} md={3}> <Link to={`/products/${product.id}`}> <Paper style={{ width: "100%", position: "relative", paddingTop: "143%", textDecoration: "none", overflow: "hidden", backgroundSize: "cover", backgroundRepeat: "no-repeat", backgroundPosition: "center", backgroundImage: `url(${product.image})`, }} ></Paper> </Link> <Typography>{product.title}</Typography> </Grid> ))} </Grid> </Container> ); } <file_sep>/lab3/README.md # projektowanie-serwisow-www-jw-185 ## laboratorium drugie ## Autor <NAME> ### wykonanie zadań ćwiczeniowych ![zadania ćwiczeniowe](./images/2.png) wyniki napisanych funkcji wyświetlają się na konsoli ### dodanie obsługi zdarzeń ![obsługa zdarzeń](./images/1.png) <file_sep>/lab3/js/app.js function zadanie1(txt) { return "Liczba liter: " + txt.length; } function zadanie2(arr) { return arr.reduce((acc, val) => acc + val, 0); } function zadanie3(txt) { return Array.from(txt) .map((val, idx) => idx % 2 == 0 ? val.toUpperCase() : val.toLowerCase() ) .join(""); } function zadanie4(a, b) { return typeof a === "number" && typeof b === "number" ? a * b : false; } function zadanie5(imie, miesiac) { let akcja = ""; miesiac = miesiac.toLowerCase(); switch (miesiac) { case "grudzien": case "styczen": case "luty": akcja = "jezdzi na sankach"; break; case "marzec": case "kwiecien": case "maj": akcja = "chodzi po kaluzach"; break; case "czerwiec": case "lipiec": case "sierpien": akcja = "sie opala"; break; case "wrzesien": case "pazdziernik": case "listopad": akcja = "zbiera liscie"; break; } return imie + " " + akcja; } function zadanie6(txt, del) { return txt.split(del).sort().join(del); } function zadanie7a(arr) { return arr.map((val) => val.toUpperCase()); } function zadanie7b(arr) { return arr.map(zadanie3); } function zadanie8(imie) { return imie[imie.length - 1] === "a" ? true : false; } function zadanie9() { const users = [ "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", ]; return users .map((val) => val.split(" ")[0]) .filter(zadanie8) .reduce((acc) => acc + 1, 0); } console.info('zadanie1("ala ma kota") :' + zadanie1("ala ma kota")); console.info("zadanie2([1, 2, 3, 4, 5]) :" + zadanie2([1, 2, 3, 4, 5])); console.info('zadanie3("Ala ma kota") :' + zadanie3("Ala ma kota")); console.info("zadanie4(2, 3) :" + zadanie4(2, 3)); console.info('zadanie5("Ala", "Grudzien") :' + zadanie5("Ala", "Grudzien")); console.info( 'zadanie6("Ania|Marcin|Bartek|Piotr|Kuba|Beata|Agnieszka", "|") :' + zadanie6("Ania|Marcin|Bartek|Piotr|Kuba|Beata|Agnieszka", "|") ); console.info( 'zadanie7a(["Ania", "Marcin", "Bartek", "Piotr"]) :' + zadanie7a(["Ania", "Marcin", "Bartek", "Piotr"]) ); console.info( 'zadanie7b(["Ania", "Marcin", "Bartek", "Piotr"]) :' + zadanie7b(["Ania", "Marcin", "Bartek", "Piotr"]) ); console.info('zadanie8("Ala") :' + zadanie8("Ala")); console.info("zadanie9() :" + zadanie9()); <file_sep>/lab7_i_8/src/Counter.js import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Chip from "@material-ui/core/Chip"; import IconButton from "@material-ui/core/IconButton"; import AddIcon from "@material-ui/icons/Add"; import RemoveIcon from "@material-ui/icons/Remove"; import DeleteIcon from "@material-ui/icons/Delete"; const useStyles = makeStyles((theme) => ({ root: { display: "flex", justifyContent: "center", flexWrap: "wrap", "& > *": { margin: theme.spacing(1), }, }, })); function Counter({ onIncrement, onDecrement, onDelete, amount }) { const classes = useStyles(); return ( <div className={classes.root}> <Chip label={amount} /> <IconButton onClick={onIncrement} color="secondary"> <AddIcon /> </IconButton> <IconButton onClick={onDecrement} color="secondary"> <RemoveIcon /> </IconButton> <IconButton onClick={onDelete} color="secondary"> <DeleteIcon /> </IconButton> </div> ); } export default Counter; <file_sep>/lab7_i_8/src/Drawer.js import React from "react"; import clsx from "clsx"; import { makeStyles } from "@material-ui/core/styles"; import Drawer from "@material-ui/core/Drawer"; import Button from "@material-ui/core/Button"; import List from "@material-ui/core/List"; import Divider from "@material-ui/core/Divider"; import ListItem from "@material-ui/core/ListItem"; import ListItemIcon from "@material-ui/core/ListItemIcon"; import ListItemText from "@material-ui/core/ListItemText"; import InboxIcon from "@material-ui/icons/MoveToInbox"; import MailIcon from "@material-ui/icons/Mail"; import { NavLink } from "react-router-dom"; import HomeIcon from "@material-ui/icons/Home"; import ListIcon from "@material-ui/icons/List"; const useStyles = makeStyles({ list: { width: 250, }, fullList: { width: "auto", }, }); export default function TemporaryDrawer({ open, handleClose }) { const classes = useStyles(); return ( <div> <React.Fragment> <Drawer open={open} onClose={handleClose}> <div className={clsx(classes.list, { [classes.fullList]: true, })} role="presentation" onClick={handleClose} onKeyDown={handleClose} > <List> <ListItem button key="/" component={NavLink} to="/" activeClassName="Mui-selected" exact={true} > <ListItemIcon> <HomeIcon /> </ListItemIcon> <ListItemText primary="Strona główna" /> </ListItem> <ListItem button key="/products" component={NavLink} to="/products" activeClassName="Mui-selected" exact={true} > <ListItemIcon> <ListIcon /> </ListItemIcon> <ListItemText primary="Produkty" /> </ListItem> </List> </div> </Drawer> </React.Fragment> </div> ); } <file_sep>/lab7_i_8/src/Cart.js import React from "react"; import Chip from "@material-ui/core/Chip"; import Button from "@material-ui/core/Button"; import Counter from "./Counter"; function Cart() { const [state, setState] = React.useState({ counters: [ { id: 1, value: 0 }, { id: 2, value: 0 }, { id: 3, value: 0 }, { id: 4, value: 0 }, ], }); const handleIncrement = (counter) => () => { const counters = [...state.counters]; const index = counters.indexOf(counter); setState({ ...state, counters: counters.map((counter, i) => { if (i === index) { return { ...counter, value: counter.value + 1, }; } return counter; }), }); }; const handleDecrement = (counter) => () => { const counters = [...state.counters]; const index = counters.indexOf(counter); setState({ ...state, counters: counters.map((counter, i) => { if (i === index) { return { ...counter, value: counter.value === 0 ? 0 : counter.value - 1, }; } return counter; }), }); }; const handleReset = () => { setState({ ...state, counters: state.counters.map((counter) => ({ ...counter, value: 0, })), }); }; const handleDelete = (counterId) => () => { setState({ ...state, counters: state.counters.filter( (counter) => counter.id !== counterId ), }); }; const handleRestart = () => { window.location.reload(); }; return ( <React.Fragment> <Chip label={state.counters.filter((c) => c.value !== 0).length} /> <Button onClick={handleReset}>reset</Button> <Button onClick={handleRestart}>restart</Button> <div> {state.counters.map((counter) => ( <Counter onIncrement={handleIncrement(counter)} onDecrement={handleDecrement(counter)} onDelete={handleDelete(counter.id)} amount={counter.value} /> ))} </div> </React.Fragment> ); } export default Cart; <file_sep>/lab4/assets/scripts/main.js var canvas = document.getElementById("myCanvas"); var score = document.getElementById("score"); var bestScore = document.getElementById("bestScore"); var ctx = canvas.getContext("2d"); // var x = 0; // var y = 0; var ballRadius = 10; var cw = 10; var direction = "right" var initLength = 4; var snake = []; var food = null; var interval = null; var points = 0; var bestPoints = 0; var delay = 100; function generateFood() { food = { x: Math.floor(Math.random() * (canvas.width / cw)), y: Math.floor(Math.random() * (canvas.height / cw)), }; } function initSnake() { snake = []; for(var i = initLength-1; i >=0 ; i--) { snake.push({ x: i, y: 0 }) } } function drawCell(x,y) { ctx.beginPath(); ctx.fillStyle = "rgb(170, 170, 170)"; ctx.arc( x * cw + 6, y * cw + 6, 4, 0, 2 * Math.PI, false ); ctx.fill(); ctx.closePath(); } function drawFood() { ctx.beginPath(); ctx.fillStyle = "rgb(0, 0, 0)"; ctx.arc(food.x * cw + 6, food.y * cw + 6, 4, 0, 2 * Math.PI, false); ctx.fill(); ctx.closePath(); } function drawBorder() { ctx.beginPath(); ctx.rect(0, 0, canvas.width, canvas.height); ctx.strokeStyle = "rgba(0, 0, 255, 0.5)"; ctx.stroke(); ctx.closePath(); } function collisionOccured(x, y) { if(x === -1 || y === -1 || x == (canvas.width / cw) || y == (canvas.height / cw)) return true; return false; } function clear() { ctx.clearRect(0, 0, canvas.width, canvas.height); } function gameOver() { clearInterval(interval); score.innerHTML = "Wynik: 0"; if(points > bestPoints) { bestPoints = points; bestScore.innerHTML = "Najlepszy wynik: " + bestPoints; } alert(`koniec gry\ntwoje punkty: ${points}\n najlepszy wynik: ${bestPoints}`); newGame(); } function tick() { clear(); drawBorder(); var { x, y } = snake[0]; switch (direction) { case "up": y = y - 1; break; case "down": y = y + 1; break; case "right": x = x + 1; break; case "left": x = x - 1; break; } var tail = {}; if ( collisionOccured(x, y) || snake.filter((el) => el.x === x && el.y === y).length ) { return gameOver(); } if(x === food.x && y === food.y) { generateFood(); points = points + 1; score.innerHTML = "Wynik: " + points; } else { tail = snake.pop(); } tail.x = x; tail.y = y; snake.unshift(tail); drawSnake(); drawFood(); } function drawSnake() { for (i = 0; i < snake.length; i++) { drawCell(snake[i].x, snake[i].y); } } function newGame() { direction = "right"; points = 0; initSnake(); generateFood(); drawSnake(); drawFood(); drawBorder(); interval = setInterval(tick, delay); } function handleKeyDown(e) { switch(e.keyCode) { case 37: if(direction !== "right") direction = "left"; break; case 38: if (direction !== "down") direction = "up"; break; case 39: if (direction !== "left") direction = "right"; break; case 40: if (direction !== "up") direction = "down"; break; } } document.addEventListener("keydown", handleKeyDown); newGame(); // initSnake(); // generateFood(); // tick();<file_sep>/lab4/README.md # projektowanie-serwisow-www-jw-185 ## laboratorium czwarte ## Autor <NAME> ### wykonanie zadań ćwiczeniowych Snake napisany w js Sterowanie strzałkami ![snake](./assets/images/snake.png) *snake* ![koniec gry](./assets/images/game_over.png) *koniec gry*
fb775f5ea6794cb111612e48a110db1612dfcf4d
[ "JavaScript", "Markdown" ]
15
JavaScript
jeremi420/projektowanie-serwisow-www-21686-185
aa8f12390f3a73adb08b4e26fc311a2e3e0ac4c7
70fae371876a89e87ae0e0d501c19dd971b6a499
refs/heads/master
<file_sep># 1. make two dictionaries with four items # 2. print both dictionaries; hint - convert 'dict' to 'str' type # 1. make two dictionaries with four items friend1 = { 'name': 'Gunu', 'height': 3, 'age': 5, 'city': 'Corona'} friend2 = { 'name': 'Simrat', 'height': 4, 'age': 7, 'city': 'Corona'} # 2. print both dictionaries; hint - convert 'dict' to 'str' type print('My friend 1 details:' + str(friend1)) print('My friend 2 details:' + str(friend2)) print('===============**********===============')
c97ce4d95d3c14be45cc9891f0d2a83e36ecabfd
[ "Python" ]
1
Python
kulvirvirk/python_dictionary_2
3976acde730404edbed58281f87b4b4d306ebf87
4a1d2b24c849e9c27a44c5f24bedddebb4227c42
refs/heads/master
<file_sep>import React from 'react'; class Houses extends React.Component { render (){ return ( <div className="BigLogosBox"> <div className="housesBig"> <img className="imgHousesBig gryfindor" src= "https://andreitalguero.files.wordpress.com/2011/02/gryfindor.jpg?w=240g" /> </div> <div className="housesBig" > <img className="imgHousesBig hufflepuff" src="https://andreitalguero.files.wordpress.com/2011/02/hupelpuff.jpg" /> </div> <div className="housesBig"> <img className="imgHousesBig ravenclaw" src="https://andreitalguero.files.wordpress.com/2011/02/ravenclaw.jpg"/> </div> <div className="housesBig" > <img className="imgHousesBig slytherin" src="https://i.ebayimg.com/images/g/AEkAAOSwZjJVADTu/s-l300.jpg"/> </div> </div> ) } } export default Houses; <file_sep>import React, { Component } from 'react'; import './App.css'; import Houses from './components/Houses'; class App extends Component { constructor(props) { super(props) this.handleChange = this.handleChange.bind(this); this.state = { characters: [], almacen:'' } } componentDidMount() { fetch('http://hp-api.herokuapp.com/api/characters') .then(response => response.json()) .then(json => { this.setState({ characters: json }); }); } paintCharacters () { const variableParaFiltrarLuego= this.state.characters.filter((personajeFiltrado)=> { return personajeFiltrado.name.toLowerCase().includes(this.state.almacen); }) return variableParaFiltrarLuego.map((personaje)=>{ return <div className="characterBox"><li className="characters"> <h3>{ personaje.name }</h3> <div className="imgBox"> <img className="imagen" src={ personaje.image } /> </div> <div className="iconLife"> <div className={`icons house_${personaje.house.toLowerCase()}`}></div> <div className={`icons state_${personaje.alive? 'vivo':'muerto'.toLowerCase()}`}> </div> </div> </li></div>; }); }; handleChange (event) { const valorRecogido = event.target.value this.setState ({ almacen: valorRecogido.toLowerCase() }) }; render() { console.log(this.state.almacen) return ( <div className="todo"> <header className="App-header"> </header> <main className="container"> <div className="input"> <input onChange={this.handleChange} placeholder="Escribe tu personaje favorito"/> </div> <div className="AllCharactersBox"> <ul className="personajes"> {this.paintCharacters()} </ul> <Houses /> </div> </main> </div> ); } } export default App; // <header className="App-header"> // <img src={logo} className="App-logo" alt="logo" /> // <h1 className="App-title">Welcome to React</h1> // </header> // <p className="App-intro"> // To get started, edit <code>src/App.js</code> and save to reload. // </p>
c534fbfa79f5ef7711f12daca519a735644d3d55
[ "JavaScript" ]
2
JavaScript
Celia19C/clarke-s4-eval-mnn-Celia19C
16995f0798a72c7792e926231f6a692d75a1b5e5
2602d191e382b3e58b28c44ab8b9a46b60a3620b
refs/heads/master
<repo_name>arnoldstoba/dot-files<file_sep>/dotfiles/hyper.js module.exports = { config: { fontSize: 13, fontFamily: 'Hasklig, Menlo, monospace', cursorColor: '#F81CE5', foregroundColor: '#fff', backgroundColor: '#222', borderColor: '#333', padding: '12px 14px', css: '', termCSS: ` x-screen x-row { font-variant-ligatures: initial; } `, colors: [ '#000000', '#ff0000', '#33ff00', '#ffff00', '#0066ff', '#cc00ff', '#00ffff', '#d0d0d0', '#808080', '#ff0000', '#33ff00', '#ffff00', '#0066ff', '#cc00ff', '#00ffff', '#ffffff' ] }, plugins: [ "hypercwd", "hyperlinks", "hyperterm-paste", "hyperterm-alternatescroll", "hyperterm-tabs", "hyper-statusline" ], localPlugins: [] }; <file_sep>/dotfiles/functions/whois #!/usr/bin/env bash # Whois # get whois from an url # from: github.com/paulirish/dotfiles # # usage: # whos https://www.google.de # => whois information/ function whois() { local domain=$(echo "$1" | awk -F/ '{print $3}') # get domain from URL if [ -z $domain ] ; then domain=$1 fi echo "Getting whois record for: $domain …" /usr/bin/whois -h whois.internic.net $domain | sed '/NOTICE:/q' }<file_sep>/dotfiles/zshrc #!/usr/bin/env bash # .zshrc file # contains all function/alias imports # bashrc version of the zsh shell # to provide a better overview, the files are included "manually" # (prob at cost of some performance) # include `rupa/z` shell script # requires `brew install z` . /usr/local/Cellar/z/1.9/etc/profile.d/z.sh # function imports . ~/.functions/extract . ~/.functions/localip . ~/.functions/server . ~/.functions/whois . ~/.functions/mkdir # configuration imports . ~/.conf/zsh . ~/.conf/path # alias imports . ~/.aliases/aliases <file_sep>/ellipsis.sh #!/usr/bin/env bash # ellipsis configuration file # link all files from inside the dotfiles folder # this file sets up the linking to the ~ dir. # @todo: do not link setup files / or remove after pkg.link() { fs.link_files dotfiles } <file_sep>/dotfiles/functions/mkdir #!/usr/bin/env bash # md function shortcut # Create a new directory and enter it # from: github.com/paulirish/dotfiles # # usage: # md lorem # => entrs /lorem function md() { mkdir -p "$@" && cd "$@" }<file_sep>/dotfiles/aliases/aliases #!/usr/bin/env bash # base aliases # basic bash aliases (using osx) # from: paulirish/dotfiles # from: holman/dotfiles # tree/ls shortcuts # requires `brew install tree` alias l="tree -l -L 1 -a -C --dirsfirst" alias ll="tree -l -L 1 -a -C -u -p --si -D --dirsfirst" alias ld="tree -l -L 1 -a -D -r -C" # editor shortcuts alias a="atom" alias v="vim" # general terminal shortcuts alias o="open" alias qq="exit" <file_sep>/dotfiles/functions/extract #!/usr/bin/env bash # Archive extract function # from: github.com/paulirish/dotfiles # # usage: # extract filename.zip # => filename/ # # Works with most of the popular # archive types including zip and multiple # tar compression formats. function extract() { if [ -f "$1" ] ; then local filename=$(basename "$1") local foldername="${filename%%.*}" local fullpath=`perl -e 'use Cwd "abs_path";print abs_path(shift)' "$1"` local didfolderexist=false if [ -d "$foldername" ]; then didfolderexist=true read -p "$foldername already exists, do you want to overwrite it? (y/n) " -n 1 echo if [[ $REPLY =~ ^[Nn]$ ]]; then return fi fi mkdir -p "$foldername" && cd "$foldername" case $1 in *.tar.bz2) tar xjf "$fullpath" ;; *.tar.gz) tar xzf "$fullpath" ;; *.tar.xz) tar Jxvf "$fullpath" ;; *.tar.Z) tar xzf "$fullpath" ;; *.tar) tar xf "$fullpath" ;; *.taz) tar xzf "$fullpath" ;; *.tb2) tar xjf "$fullpath" ;; *.tbz) tar xjf "$fullpath" ;; *.tbz2) tar xjf "$fullpath" ;; *.tgz) tar xzf "$fullpath" ;; *.txz) tar Jxvf "$fullpath" ;; *.zip) unzip "$fullpath" ;; *) echo "'$1' cannot be extracted via extract()" && cd .. && ! $didfolderexist && rm -r "$foldername" ;; esac else echo "'$1' is not a valid file" fi } <file_sep>/dotfiles/functions/localip #!/usr/bin/env bash # localip # prints the local ip information # from: github.com/paulirish/dotfiles # # usage: localip # => ip info function localip(){ function _localip(){ echo "📶 "$(ipconfig getifaddr "$1"); } export -f _localip local purple="\x1B\[35m" reset="\x1B\[m" networksetup -listallhardwareports | \ sed -r "s/Hardware Port: (.*)/${purple}\1${reset}/g" | \ sed -r "s/Device: (en.*)$/_localip \1/e" | \ sed -r "s/Ethernet Address:/📘 /g" | \ sed -r "s/(VLAN Configurations)|==*//g" }<file_sep>/dotfiles/conf/path #!/usr/bin/env bash # add ellipsis package manager to $PATH export PATH=~/.ellipsis/bin:$PATH # rupa/z brew installation path # required: `brew install z` . `brew --prefix`/etc/profile.d/z.sh # add MAMP bin/php to $PATH # required: mamp installation with global php PATH="/Applications/MAMP/Library/bin:$PATH" PATH="/Applications/MAMP/bin/php/php5.6.10/bin:$PATH"
abed41c2abd0495a8fc63d622bcd5b571bdff425
[ "JavaScript", "Shell" ]
9
JavaScript
arnoldstoba/dot-files
ab8525e481d627dfef1d427b5284c9bd0a4506ec
ae8a344068148288339767e3d2e78b2c9416cb83
refs/heads/master
<file_sep><?php namespace AppBundle\Solution; use AppBundle\Solver\AdventSolverInterface; use AppBundle\Solver\DaySolver; class Day18 extends DaySolver implements AdventSolverInterface { private $lights = []; public function getSolution1() { $row = 0; foreach ($this->input as $line) { $this->parseLine($line, $row); $row++; } $animation_times = 100; $new_lights = $this->changeLights($this->lights); for ($i=1; $i < $animation_times; $i++) { $new_lights = $this->changeLights($new_lights); } $result = $this->countOn($new_lights); echo "{$result} lights are on after animating the lights {$animation_times} times<Br>"; } public function getSolution2() { if (empty($this->lights)) { $row = 0; foreach ($this->input as $line) { $this->parseLine($line, $row); $row++; } } $this->turnOnCorners($this->lights); $animation_times = 100; $new_lights = $this->changeLights($this->lights, true); for ($i=1; $i < $animation_times; $i++) { $new_lights = $this->changeLights($new_lights, true); } $result = $this->countOn($new_lights); echo "If corner lights are broken and always stay on {$result} lights are ON after animating the lights {$animation_times} times"; } private function turnOnCorners(&$lights) { //Every corner's light always stay ON $max_rows = count($lights) - 1; $max_cols = count($lights[0]) - 1; $lights[0][0] = true; $lights[0][$max_cols] = true; $lights[$max_rows][$max_cols] = true; $lights[$max_rows][0] = true; } private function countOn($lights) { $on = 0; foreach ($lights as $row => $row_lights) { foreach ($row_lights as $col => $signal) { if ($signal == true) { $on++; } } } return $on; } private function changeLights($prev_lights, $sol2 = false) { $new_lights = []; foreach ($prev_lights as $row => $row_lights) { foreach ($row_lights as $col => $signal) { $new_lights[$row][$col] = $this->getNextSignal($row, $col, $signal, $prev_lights, $sol2); } } return $new_lights; } private function getNextSignal($row, $col, $current_signal, $prev_lights, $sol2) { if ($sol2 == true) { //Every corner's light alway stay ON $max_rows = count($prev_lights) - 1; $max_cols = count($prev_lights[0]) - 1; if (($row == 0 && $col == 0) || ($row == 0 && $col == $max_cols) || ($row == $max_rows && $col == $max_cols) || ($row == $max_rows && $col == 0) ) { return true; } } $neighs_on = $this->getNeighboursOn($row, $col, $prev_lights); $next_signal = ''; if ($current_signal == true) { if ($neighs_on == 2 || $neighs_on == 3) { $next_signal = true; } else { $next_signal = false; } } else { if ($neighs_on == 3) { $next_signal = true; } else { $next_signal = false; } } return $next_signal; } private function getNeighboursOn($row, $col, $prev_lights) { $neghs_on = 0; $neighs = $this->getNeighbours($row, $col); foreach ($neighs as $neigh) { $n_row = $neigh['row']; $n_col = $neigh['col']; if (isset($prev_lights[$n_row][$n_col]) && $prev_lights[$n_row][$n_col] == true) { $neghs_on++; } } return $neghs_on; } private function getNeighbours($row, $col) { return [ ['row' => $row-1, 'col' => $col -1], ['row' => $row-1, 'col' => $col], ['row' => $row-1, 'col' => $col + 1], ['row' => $row, 'col' => $col - 1], ['row' => $row, 'col' => $col + 1], ['row' => $row+1, 'col' => $col - 1], ['row' => $row+1, 'col' => $col], ['row' => $row+1, 'col' => $col + 1] ]; } private function parseLine($line, $row) { $col = 0; for ($i = 0; $i < strlen($line); $i++) { if ($line[$i] == "#") { $this->lights[$row][$col] = true; } elseif ($line[$i] == ".") { $this->lights[$row][$col] = false; } $col++; } } }<file_sep><?php namespace AppBundle\Solver; interface AdventSolverInterface { public function getSolution1(); public function getSolution2(); }<file_sep><?php namespace AppBundle\Solver; class SolverFactory { protected $entity; public function create($dayNo) { $class = "\\AppBundle\\Solution\\Day". $dayNo; if (class_exists($class)) { $this->entity = new $class($dayNo); } else { throw new \Exception("No class found called {$class}"); } return $this->entity; } } <file_sep><?php namespace AppBundle\Solver; class DaySolver { protected $input; public function __construct($dayNo) { $this->input = $this->getInput($dayNo); } private function getInput($dayNo) { $input_path = __DIR__ . "/../../../app/Resources/input/day{$dayNo}_input.txt"; if (file_exists($input_path)) { return file($input_path); } else { return ''; } } } <file_sep><?php namespace AppBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use AppBundle\Solver\SolverFactory; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Response; /** * Class SolutionController * @package AppBundle\Controller */ class SolutionController extends Controller { /** * @Route("/day/{day}", name="day_number") * * @param $day int - the day for the solution */ public function dayAction($day) { $factory = new SolverFactory(); $daySolver = $factory->create($day); $daySolver->getSolution1(); $daySolver->getSolution2(); exit(); } } <file_sep>advent_of_code_sym ================== A Symfony project created on December 6, 2015, 1:39 pm.
50d23696fcb5129f4878f4ad5e0ebf1fda02b7ba
[ "Markdown", "PHP" ]
6
PHP
prafed/advent_of_code_symfony
222ac4d351169776e6572410b39c2e9135c7c9a7
ba1d7841f085f6bd597adcac79559eb6eadcc36d
refs/heads/main
<repo_name>forkclone/TripAdvisor-Python-Scraper-Restaurants-2021<file_sep>/Scraper.py import requests from bs4 import BeautifulSoup import csv from selenium import webdriver import time import sys import argparse pathToReviews = "TripReviews.csv" pathToStoreInfo = "TripStoresInfo.csv" #webDriver init def scrapeRestaurantsUrls(tripURLs): urls =[] for url in tripURLs: page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') results = soup.find('div', class_='_1kXteagE') stores = results.find_all('div', class_='wQjYiB7z') for store in stores: unModifiedUrl = str(store.find('a', href=True)['href']) urls.append('https://www.tripadvisor.com'+unModifiedUrl) return urls def scrapeRestaurantInfo(url): print(url) page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') storeName = soup.find('h1', class_='_3a1XQ88S').text avgRating = soup.find('span', class_='r2Cf69qf').text.strip() storeAddress = soup.find('div', class_= '_2vbD36Hr _36TL14Jn').find('span', class_='_2saB_OSe').text.strip() noReviews = soup.find('a', class_='_10Iv7dOs').text.strip().split()[0] with open(pathToStoreInfo, mode='a', encoding="utf-8") as trip: data_writer = csv.writer(trip, delimiter = ',', quotechar = '"', quoting = csv.QUOTE_MINIMAL) data_writer.writerow([storeName, storeAddress, avgRating, noReviews]) parser = argparse.ArgumentParser() parser.add_argument('--url', required=True, help ='need starting url') parser.add_argument('-i', '--info', action='store_true', help="Collects restaurant's info") parser.add_argument('-m', '--many', action='store_true', help="Collects whole area info") args = parser.parse_args() startingUrl = args.url if args.info: info = True else: info = False if args.many: urls = scrapeRestaurantsUrls([startingUrl]) else: urls = [startingUrl] driver = webdriver.Chrome('chromedriver.exe') for url in urls: print(url) #if you want to scrape restaurants info if info == True: scrapeRestaurantInfo(url) nextPage = True while nextPage: #Requests driver.get(url) time.sleep(1) #Click More button more = driver.find_elements_by_xpath("//span[contains(text(),'More')]") for x in range(0,len(more)): try: driver.execute_script("arguments[0].click();", more[x]) time.sleep(3) except: pass soup = BeautifulSoup(driver.page_source, 'html.parser') #Store name storeName = soup.find('h1', class_='_3a1XQ88S').text #Reviews results = soup.find('div', class_='listContainer hide-more-mobile') try: reviews = results.find_all('div', class_='prw_rup prw_reviews_review_resp') except Exception: continue #Export to csv try: with open(pathToReviews, mode='a', encoding="utf-8") as trip_data: data_writer = csv.writer(trip_data, delimiter = ',', quotechar = '"', quoting = csv.QUOTE_MINIMAL) for review in reviews: ratingDate = review.find('span', class_='ratingDate').get('title') text_review = review.find('p', class_='partial_entry') if len(text_review.contents) > 2: reviewText = str(text_review.contents[0][:-3]) + ' ' + str(text_review.contents[1].text) else: reviewText = text_review.text reviewerUsername = review.find('div', class_='info_text pointer_cursor') reviewerUsername = reviewerUsername.select('div > div')[0].get_text(strip=True) rating = review.find('div', class_='ui_column is-9').findChildren('span') rating = str(rating[0]).split('_')[3].split('0')[0] data_writer.writerow([storeName, reviewerUsername, ratingDate, reviewText, rating]) except: pass #Go to next page if exists try: unModifiedUrl = str(soup.find('a', class_ = 'nav next ui_button primary',href=True)['href']) url = 'https://www.tripadvisor.com' + unModifiedUrl except: nextPage = False
78fe459b65e190fc497240518ac2b26a79b29df4
[ "Python" ]
1
Python
forkclone/TripAdvisor-Python-Scraper-Restaurants-2021
818a142d63817cd56fb308743466677652db1789
c31ef8f15bc3ddf550802629b0946034e02fc427
refs/heads/master
<repo_name>hiradbaba/Star-Wars<file_sep>/PRO.cpp #include<stdio.h> #include<stdlib.h> #include<Windows.h> #include<conio.h> #include<time.h> #include<string.h> #include "myMusic.h" // defining space and arrow keys----------------------------------------------------- #define UP 72 #define DOWN 80 #define LEFT 75 #define RIGHT 77 #define SPACE 32 //defining colors-------------------------------------------------------------------- #define RED FOREGROUND_RED | FOREGROUND_INTENSITY #define GREEN FOREGROUND_GREEN | FOREGROUND_INTENSITY #define BLUE FOREGROUND_BLUE | FOREGROUND_INTENSITY #define YELLOW FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY #define CYAN FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY #define MAGNETA FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY #define WHITE FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY //--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------- /* PROGRAM PARTS: -MENU -reading highscore and position file(find_highscore,readP) -enemy type 1: killed - income_generate() - count() -hit -enemy type 2: killed - sp_random() - count()-hit -bullet type A: shot -bullet type B: spshot -bullet type RPG: nRPG - Rshot */ //---------------------------------------------------------------------------------------- // SCORE: BASED ON SHOOTING ENEMIES --- LEVEL:BASED ON SCORE------------------------ int score; int level; int killed; char Nname[20]; char Cname[20]; char Hname[20]; //---------------------------------------------------------------------------------- // Point structure which includes the coordination --------------------------------- struct point{ int x; int y; }; //---------------------------------------------------------------------------------- //Income structure which includes the NUMBER of enemies coming and Their positions-- struct income{ int n; point enemy[1000]; }; //---------------------------------------------------------------------------------- struct bull{ int n; point bullet[10000]; }; //GLOBALS-------------------------------------------------------------------------- point me; income en; income spen; int nRPG; //GOXY function changes the cursors postion to print in different areas-------------- void goxy(int x,int y){ COORD coord={x,y}; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),coord); } //COLOR function changes the color--------------------------------------------------- void color(int a){ HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hConsole,a); } //----------------------------------------------------------------------------------- //this function geneterates the special enemy which dies with special weapon--------------- int sp_random(){ int i=0; time_t t; srand((unsigned) time(&t)); int conflict = 1; while(conflict == 1 ){ conflict = 0; for(i=0;i<spen.n;i++){ spen.enemy[i].x=rand()%40; spen.enemy[i].y=-1*(rand()%(spen.n*2)); if(spen.enemy[i].x == 0){ spen.enemy[i].x = 1; } if(spen.enemy[i].y == 0){ spen.enemy[i].y = 1; } } for(i=0;i<spen.n;i++){ for(int j=0; j<spen.n; j++){ if( i != j){ if((abs(spen.enemy[j].x-spen.enemy[i].x)<3) && (abs(spen.enemy[j].y-spen.enemy[i].y)<3) ){ conflict = 1; } } } } for(i=0;i<spen.n;i++){ for(int j=0; j<en.n; j++){ if((abs(en.enemy[j].x-spen.enemy[i].x)<6 && abs(spen.enemy[i].y-en.enemy[j].y)<4) ){ conflict = 1; } } } } // income temp = spen; int minx=spen.enemy[0].y; int minp=0; for(i=1; i<spen.n; i++){ if(spen.enemy[i].y<minx){ minx=spen.enemy[i].y; minp=i; } } return minp; } //--------------------------------------------------------------------- /*Income_Generate: This function generates enemies' posittions randomly based on the max size of x and the number of enemies after generating it will find the last enemy who comes from the top of the screen and returns it position in the array-----*/ int income_generate(){ time_t t; srand((unsigned) time(&t)); int i=0; int conflict = 1; while(conflict == 1 ){ conflict = 0; for(i=0;i<en.n;i++){ en.enemy[i].x=rand()%40; en.enemy[i].y=-1*(rand()%(en.n*2)); if(en.enemy[i].x == 0){ en.enemy[i].x = 1; } if(en.enemy[i].y == 0){ en.enemy[i].y = 1; } } for(i=0;i<en.n;i++){ for(int j=0; j<en.n; j++){ if( i != j){ if((abs(en.enemy[j].x-en.enemy[i].x)<3) && (abs(en.enemy[j].y-en.enemy[i].y)<3) ){ conflict = 1; } } } } } //income temp = en; int minx=en.enemy[0].y; int minp=0; for(i=1; i<en.n; i++){ if(en.enemy[i].y<minx){ minx=en.enemy[i].y; minp=i; } } return minp; } //------------------------------------------------------------- //this fuctions reads the highscore file----------------------- int find_score(FILE* p){ char y[4]; fscanf(p,"%s %s",Hname,y); int i; i=atoi(y); return i; } //this function reads the saved the data used for the game------ void readP(){ FILE*pr=fopen("position.txt","r"); char posx[4],posy[4],posen[4],posscore[4],posNrpg[4],pospen[4]; fscanf(pr,"%s %s %s %s %s %s %s",posx,posy,posen,posscore,posNrpg,pospen,Cname); score=atoi(posscore); me.y=atoi(posy); me.x=atoi(posx); en.n=atoi(posen); nRPG=atoi(posNrpg); spen.n=atoi(pospen); fclose(pr); } //this function counts the number of enemies in the screen---------- int count(){ int i,counter=0; for(i=0;i<en.n;i++){ if((en.enemy[i].y<=30 && en.enemy[i].y>0) || (spen.enemy[i].y<=30 && spen.enemy[i].y>0)) counter++; } return counter; } //------------------------------------------------------------------ // this function prints the MENU of the game------------------------ void MENU(int i){ goxy(20,12); color(YELLOW); printf("STAR WARS"); goxy(20,15); color(CYAN); printf("New Game"); goxy(20,16); printf("Continue"); goxy(20,17); printf("High Score"); goxy(20,18); printf("EXIT"); goxy(18,i); printf("%c",1); } //-------------------------------------------------------------------------------------------- int mode=0; //MAIN function------------------------------------------------------------------------------- int main(){ //Menu----------------------------------------------------------------------------------- while(1){ if(mode==0){ int i=15; int a,ci; MENU(i); while(1){ ci=i; if(_kbhit()){ a=_getch(); if(a==UP && i>15){ Beep(300, 200); i--; } else if(a==DOWN && i<18){ Beep(300, 200); i++; } else if(a==13){ Beep(500,200); if(i==15){ mode=1; system("cls"); break; } else if(i==16){ mode=2; system("cls"); break; } else if(i==18){ exit(0); } else if(i==17){ mode=3; system("cls"); break; } MENU(i); } } if(ci!=i){ goxy(18,ci); printf(" "); goxy(18,i); printf("%c",1); } } } //-------------------------------------------------------------------------------------- //defining & initializing variables------------------------------------------------------ if(mode==1 || mode==2){ //data----------------------------- int min,mins; int time=100; point copy; bull B; bull SP; point RPG; B.n=0; SP.n=0; int spshot=0; int Rshot=0; spen.n=2; int hitx=0; //---------------------------------- if(mode==1){ goxy(15,10); color(13); printf("Please The Pilot's Name: "); scanf("%s",Nname); system("cls"); //---------------------------------- //starting data--------------------- me.x=20; me.y=20; en.n=6; score=0; level=0; nRPG=3; } if(mode==2){ readP(); level=score/10; } FILE* fp=fopen("highscore.txt","r"); int highscore=find_score(fp); fclose(fp); //----------------------------------- min=income_generate(); mins=sp_random(); // a: the character which we receive from keyboard shot:a flag which is 1 if we have shoot---- int a; int shot=0,hit=0; while(1){ // copy would be the previous position of me or in other words our ship--------------- copy=me; killed = 0; hitx=0; if(_kbhit()){ a=_getch(); //The keys we use in the game---------------------------------------------------- if(a==UP && me.y>0){ me.y--; } else if(a==DOWN && me.y<30){ me.y++; } else if(a==LEFT && me.x>0) me.x--; else if(a==RIGHT && me.x<40) me.x++; else if(a==SPACE){ shot=1; B.n+=1; B.bullet[B.n-1].x=copy.x+2; B.bullet[B.n-1].y=copy.y; Beep(250, 20); } else if(a=='c'){ spshot=1; SP.n+=1; SP.bullet[SP.n-1].x=copy.x+2; SP.bullet[SP.n-1].y=copy.y; Beep(350, 20); } else if(a=='e'){ goxy(15,15); color(YELLOW); printf("ARE YOU SURE YOU WANT TO EXIT? (Y/N)"); a=getch(); //Saving and ending the game-------------------- if(a=='y'){ FILE* x=fopen("position.txt","w"); if(mode==1) fprintf(x,"%d %d %d %d %d %d %s",me.x,me.y,en.n,score,nRPG,spen.n,Nname); else if (mode==2) fprintf(x,"%d %d %d %d %d %d %s",me.x,me.y,en.n,score,nRPG,spen.n,Cname); fclose(x); system("cls"); mode=0; break; } else{ goxy(15,15); printf(" "); continue; } } //RPG button-------------------------------------- else if(a=='x' && Rshot==0){ Beep(2000,50); RPG.x=me.x+2; RPG.y=me.y; Rshot=1; } goxy(copy.x,copy.y); printf(" "); continue; } //printing our ship, bullets, enemy ships------------------------ //ship,space,score and level-------------- goxy(copy.x,copy.y); printf(" "); goxy(me.x,me.y); color(CYAN); printf("[%c%c%c]",205,234,205); goxy(20,35); color(YELLOW); printf("SCORE:%d",score); goxy(20,37); printf("LEVEl:%d",level); goxy(10,35); printf("RPG:%d",nRPG); //----------------------------------------- //normal bullet----------------------------------- if(shot){ for(int k=0;k<B.n;k++){ if(B.bullet[k].y>0){ goxy(B.bullet[k].x,B.bullet[k].y-1); color(WHITE); printf("|"); if(B.bullet[k].y!=copy.y){ goxy(B.bullet[k].x,B.bullet[k].y); printf(" "); } B.bullet[k].y--; } if(B.bullet[k].y==0){ goxy(B.bullet[k].x,0); printf(" "); B.bullet[k].x=NULL; B.bullet[k].y=NULL; } } } //special bullet------------------------------------- if(spshot){ for(int k=0;k<SP.n;k++){ if(SP.bullet[k].y>0){ goxy(SP.bullet[k].x,SP.bullet[k].y-1); color(RED); printf("%c",186); if(SP.bullet[k].y!=copy.y){ goxy(SP.bullet[k].x,SP.bullet[k].y); printf(" "); } SP.bullet[k].y--; } if(SP.bullet[k].y==0){ goxy(SP.bullet[k].x,0); printf(" "); SP.bullet[k].x=NULL; SP.bullet[k].y=NULL; } } } //RPG SHOT which kills all the enemies-------------------- if(Rshot && nRPG){ if(RPG.y>0){ goxy(RPG.x,RPG.y-1); color(YELLOW); printf("%c",254); } if(RPG.y!=copy.y){ goxy(RPG.x,RPG.y); printf(" "); } RPG.y--; if(RPG.y<=10){ for(int k=0;k<en.n;k++){ goxy(en.enemy[k].x,en.enemy[k].y-1); printf(" "); goxy(en.enemy[k].x,en.enemy[k].y); printf(" "); goxy(RPG.x,RPG.y); printf(" "); if(level>=2){ goxy(spen.enemy[k].x,spen.enemy[k].y-1); printf(" "); goxy(spen.enemy[k].x,spen.enemy[k].y); printf(" "); } } hitx=1; for(int k=0;k<en.n;k++){ en.enemy[k].x=NULL; en.enemy[k].y=NULL; spen.enemy[k].x=NULL; spen.enemy[k].y=NULL; } nRPG--; Rshot=0; } } //------------------------------------------- //enemy-------------------------------------- for(int j=0;j<en.n;j++){ if(en.enemy[j].y>0 && en.enemy[j].y<31 && en.enemy[j].x!=NULL){ goxy(en.enemy[j].x,en.enemy[j].y); color(GREEN); printf("%c%c%c",195,15,180); goxy(en.enemy[j].x,en.enemy[j].y-1); printf(" "); if(en.enemy[j].y==30){ goxy(en.enemy[j].x,en.enemy[j].y); printf(" "); } } //Enemy hits me-------------------------------- if((en.enemy[j].x<=me.x+4 && en.enemy[j].x>=me.x-2) && en.enemy[j].y==me.y){ hit=1; break; } //enemy shot------------------------------------------- for(int k=0;k<B.n;k++){ if(B.bullet[k].x!=0 && B.bullet[k].y!=0){ if(en.enemy[j].x-B.bullet[k].x<=0 && en.enemy[j].x-B.bullet[k].x>=-2 && ( B.bullet[k].y==en.enemy[j].y || B.bullet[k].y==en.enemy[j].y+1)){ goxy(en.enemy[j].x,en.enemy[j].y); printf(" "); en.enemy[j].x=NULL; en.enemy[j].y=NULL; goxy(B.bullet[k].x,B.bullet[k].y); printf(" "); // goxy(B.bullet[k].x,B.bullet[k].y-1); // printf(" "); B.bullet[k].x=NULL; B.bullet[k].y=NULL; //score++; killed = 1; } } } en.enemy[j].y++; } //special enemies-------------------------------------------------------- if(level>=2){ for(int j=0;j<en.n;j++){ if(spen.enemy[j].y>0 && spen.enemy[j].y<31 && spen.enemy[j].x!=NULL){ goxy(spen.enemy[j].x,spen.enemy[j].y); color(13); printf("%c%c%c",204,207,185); goxy(spen.enemy[j].x,spen.enemy[j].y-1); printf(" "); if(spen.enemy[j].y==30){ goxy(spen.enemy[j].x,spen.enemy[j].y); printf(" "); } } //special enemy hits me-------------------------------- if((spen.enemy[j].x<=me.x+4 && spen.enemy[j].x>=me.x-2) && spen.enemy[j].y==me.y){ hit=1; break; } //special enemy shot------------------------------------------- for(int k=0;k<SP.n;k++){ if(SP.bullet[k].x!=0 && SP.bullet[k].y!=0){ if(abs(SP.bullet[k].x-spen.enemy[j].x)<=2 && ( SP.bullet[k].y==spen.enemy[j].y || SP.bullet[k].y==spen.enemy[j].y+1)){ goxy(spen.enemy[j].x,spen.enemy[j].y); printf(" "); spen.enemy[j].x=NULL; spen.enemy[j].y=NULL; goxy(SP.bullet[k].x,SP.bullet[k].y); printf(" "); // goxy(SP.bullet[k].x,SP.bullet[k].y-1); // printf(" "); SP.bullet[k].x=NULL; SP.bullet[k].y=NULL; //score++; killed = 1; } } } spen.enemy[j].y++; } } //when the last enemy reaches to the bottom we have to generate positions again if(en.enemy[min].y==32){ min=income_generate(); } if(spen.enemy[mins].y==32){ mins=sp_random(); } if (killed == 1){ score++; int plevel=level; level=score/10; if(level-plevel!=0){ en.n+=2; if(level%3==0) time-=20; if(level%2==0){ spen.n+=2; } } } if(hitx==1){ score+=count(); int plevel=level; level=score/10; if(level-plevel!=0){ en.n+=2; if(level%3==0) time-=20; if(level%2==0){ spen.n+=2; } } } //the end of the story------------------------------------------ if(hit!=0){ if(score>highscore){ fp=fopen("highscore.txt","w"); if(mode==1) fprintf(fp,"%s %d",Nname,score); else if(mode==2) fprintf(fp,"%s %d",Cname,score); fclose(fp); } system("cls"); goxy(15,10); color(RED); Beep(1000,500); printf("GAME OVER!\n"); goxy(10,12); if(mode==1) printf("Captain %s ... You Did Well",Nname); else if(mode==2) printf("Captain %s ... You Did Well",Cname); goxy(10,14); printf("Out There But Unfortunately"); goxy(10,16); printf("The DARK SIDE Took Over The Galaxy"); goxy(10,18); printf("Come Back And Rule The Galaxy"); goxy(10,20); printf("Before Darth Vader Finds Luke Skywalker"); goxy(10,22); printf("And Kills Every Last One Of JEDIs"); music(); system("cls"); mode=0; break; } Sleep(time); } } //HIGH SCORE PREVIEW--------------------------------------------------------------- if(mode==3){ char x[20]; FILE* f=fopen("highscore.txt","r"); fgets(x,20,f); goxy(15,10); color(CYAN); printf("And The Top Player Is:"); goxy(15,13); color(YELLOW); printf("%s",x); fclose(f); if(_kbhit()){ system("cls"); mode=0; } } } return 0; } <file_sep>/myMusic.h #include<windows.h> #define DO Beep(261,400); #define RE Beep(293,200); #define MI Beep(329,400); #define FA Beep(349,200); #define SO Beep(392,400); #define LA Beep(440,400); #define TI Beep(493,200); #define SOL Beep(523,1000); void music(){ SO; SO; SO; DO; SO; FA; MI; RE; SOL; SO; FA; MI; RE; SOL; SO; FA; MI; FA; RE; //SO; SO; SO; DO; SO; FA; MI; RE; SOL; SO; FA; MI; RE; SOL; SO; FA; MI; FA; RE; }
2721ec644a7147ae00f8d3e4b9508ea72e9055f4
[ "C", "C++" ]
2
C++
hiradbaba/Star-Wars
b3d03e574b8cc843f8b12dfb074e6e1b4fce7f64
7d037a6153b03bfd6e288d8fb7cd637443ee170b
refs/heads/master
<repo_name>arooons/Music<file_sep>/src/Song.java /** * Created by Connor on 1/20/16. */ public class Song extends Media implements Information { private String title; private String artist; private String genre; private int length; //constructors public Song() { this.title = genString(); this.artist = genString(); this.length = (int) ((Math.random() * 90) + 60); this.genre = genString(); } public Song(String title, String artist, int length, String genre) { this.title = title; this.artist = artist; this.length = length; this.genre = genre; super.addSong(this); } public Song(String name1, String artist1) { this.title = name1; this.artist = artist1; this.length = (int) ((Math.random() * 90) + 60); this.genre = genString(); } @Override public String toString(){ return "Title: " + title + " Artist: " + artist + " Genre: " + genre + " Length: " + length + "\n"; } //getters and setters public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } @Override public int getLength() { return length; } public void setLength(int length) { this.length = length; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } @Override public String getName(){ return title; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Song song = (Song) o; if (length != song.length) return false; if (title != null ? !title.equals(song.title) : song.title != null) return false; if (artist != null ? !artist.equals(song.artist) : song.artist != null) return false; return genre != null ? genre.equals(song.genre) : song.genre == null; } public static boolean testSongGettersAndSetters() { int pass = 0; Song song1 = new Song(); song1.setTitle("<NAME>"); if ("<NAME>".equals(song1.getTitle())){ pass++; } song1.setArtist("konswela"); if ("konswela".equals(song1.getArtist())){ pass++; } song1.setGenre("Rock n Roll"); if ("Rock n Roll".equals(song1.getGenre())){ pass++; } song1.setLength(166); if (166 == song1.getLength()){ pass++; } return pass == 4; } public static void testSongEquals(){ boolean result1 = false, result2 = false, result3 = true; Song song1 = new Song("<NAME>","konswela",166,"Rock n Roll"); Song song2 = new Song("<NAME>","konswela",166,"Rock n Roll"); if(song1.equals(song2)) { result1 = true; } Song song3 = new Song("Soem song","idk even",2342332,"Roll and Rock"); Song song4 = new Song("Soem song","idk even",2342332,"Roll and Rock"); if(song3.equals(song4)){ result2 = true; } if(!song3.equals(song1)){ result3 = false; } System.out.println ("\nTesting Song Equals..."); System.out.println ("r1: "+ (result1) + " (Expected: true)"); // true System.out.println ("r2: " + (result2) + " (Expected: true)"); // true System.out.println ("r3: " + (result3)+ " (Expected: false)"); // false System.out.print("Completed. Result: "); System.out.println ((result1) && (result2) && (!result3)); // want: true, true, false } }<file_sep>/src/Information.java /** * Created by Connor on 1/21/16. */ public interface Information { int getLength(); String getName(); int comparable(Media m); }
abbf6d1d84fcd98bd8a935209db534b540598b2b
[ "Java" ]
2
Java
arooons/Music
c5f10dc789f99067a0ada3adb958a093cd6f66fa
352787e216586eb785f4f34eb818d86390e44dd6
refs/heads/main
<file_sep>const reverseInt = require("./index"); test("Reverse input = 0", () => { expect(reverseInt(0)).toEqual(0); }); test("Reverse positive input", () => { expect(reverseInt(1)).toEqual(1); expect(reverseInt(123)).toEqual(321); expect(reverseInt(6969)).toEqual(9696); expect(reverseInt(720)).toEqual(27); }); test("Reverse negative input", () => { expect(reverseInt(-1)).toEqual(-1); expect(reverseInt(-69)).toEqual(-96); expect(reverseInt(-887)).toEqual(-788); expect(reverseInt(-90)).toEqual(-9); }); <file_sep>// Given a string, return a new string with the reversed // order of characters // --- Examples // reverse('apple') === 'leppa' // reverse('hello') === 'olleh' // reverse('Greetings!') === '!sgniteerG' function reverseString(str) { let reversedString = ""; for (let i = str.length - 1; i >= 0; i--) { reversedString = reversedString + str[i]; } return reversedString; } function reverseStringTwo(str) { return str.split("").reduce((rev, char) => { return char + rev; }, ""); } module.exports = { reverseString, reverseStringTwo, }; <file_sep>const palindrome = require("./index"); test("'aba' is a palindrome", () => { expect(palindrome("aba")).toBeTruthy(); }); test("' aba' is not a palindrome", () => { expect(palindrome(" aba")).toBeFalsy(); }); test("'kodok' is a palindrome", () => { expect(palindrome("kodok")).toBeTruthy(); }); <file_sep>const { maxChar, maxCharTwo } = require("./index"); test("Finds the most frequently used char", () => { expect(maxChar("b")).toEqual("b"); expect(maxChar("a")).toEqual("a"); expect(maxCharTwo("a")).toEqual("a"); expect(maxChar("fjbsojklnavwsepokdsjknrpoisaldmsshisssssssssdas")).toEqual( "s" ); expect(maxCharTwo("fjbsojklnavwsepokdsjknrpoisaldmsshisssssssssdas")).toEqual( "s" ); }); test("Works with numbers in the string", () => { expect(maxChar("ab1c1d1e1f1g1")).toEqual("1"); expect(maxCharTwo("ab1c2d1e1f1g1")).toEqual("1"); }); <file_sep># data-structures Learning algorithms and data structures # Installation Install jest for testing: `npm install -g jest` # Testing Run `jest folder-name --watch` e.g. `jest palindrome --watch`
cd17eebe9005682ecd5a4e12e6dd7b6823ade9b8
[ "JavaScript", "Markdown" ]
5
JavaScript
luthfynur/data-structures
2d5618692300c643f66767a08339491b15b3fc65
0d194c991c8452a5b3d133dbb0f7f4f84affa45c
refs/heads/master
<repo_name>AndyVuGit/mob<file_sep>/README.md # cipher Please refer to the 2017 version of the files as that was made using the latest version of Visual Studios. <file_sep>/2017 version/mobTest/mobTest/main.cpp #include "f0700.h" #include <iostream> int main() { //Sample Input int a1 = 128; int a2[1408]; for (int i = 0; i < 1408; i++) { a2[i] = i; } a2[20] = -400; a2[30] = 400; a2[500] = 0; int a3 = 4; int a4[116]; for (int a = 0; a < 116; a++) { a4[a] = 0; } int test = f0700(a1, a2, a3, a4); int prev = f0700Original(a1, a2, a3, a4); std::cout << "test = " << test << std::endl; std::cout << "prev = " << prev << std::endl; return 0; }<file_sep>/2017 version/mobTest/mobTest/f0700.cpp #include "f0700.h" signed int __cdecl f0700(int a1, int *a2, int a3, int *a4) { // Pre-Condition: // a1: possible input value = [64, 128, 256] // a2: is an int[1408] array // possible input value for each element = [-4095 ... 4095] // a3: possible input value = [2, 3, 4, 5, 6] // a4: is an int[116] array // possible input value for each element = [0] // // Post-Condition: // a1: value shouldn't change // a2: value shouldn't change // a3: value shouldn't changed // a4: value can changed int index, count, negative; int *current, *next; index = 0; count = 0; negative = -1; a2[a1 - 1] = 10000; //Limit used to break out of the loop a2[a1] = -10000; //Limit used to break out of the loop do { current = &a2[index]; //points to the first index of v4cx ++index; next = &a2[index]; //points to the 2nd index of v4 int diffCheck = negative * (*current - *next); if (a3 > diffCheck) { do { int currentIndex = negative * (*current); int nextIndex = negative * (*next); if (nextIndex > currentIndex) current = next; next += 1; //Points next to the next index ++index; diffCheck = negative * (*current - *next); } while (a3 > diffCheck); } negative = -negative; count += 1; } while (index < a1); return count; } signed int __cdecl f0700Original(int a1, int *a2, int a3, int *a4) { // Pre-Condition: // a1: possible input value = [64, 128, 256] // a2: is an int[1408] array // possible input value for each element = [-4095 ... 4095] // a3: possible input value = [2, 3, 4, 5, 6] // a4: is an int[116] array // possible input value for each element = [0] // // Post-Condition: // a1: value shouldn't change // a2: value shouldn't change // a3: value shouldn't changed // a4: value can changed int *v4; int v5; int v6; int v7; int o1; int v9; int *v10; int v11; int v12; int v13; int v14; int v15; int a2a; v4 = a2; v5 = a1; v6 = 0; v7 = a2[a1]; v14 = a2[a1 - 1]; o1 = 0; v9 = -1; a2[a1 - 1] = 10000; v15 = v7; a2[a1] = -10000; a2a = 0; if (a1 > 0) { v10 = a4; do { v11 = (int)&v4[v6++]; *v10 = v11; v12 = (int)&v4[v6]; if (v9 * (*(int *)v11 - *(int *)v12) < a3) { do { if (v9 * *(int *)v12 > v9 * *(int *)*v10) *v10 = v12; v13 = *(int *)(v12 + 4); v12 += 4; ++v6; } while (v9 * (*(int *)*v10 - v13) < a3); v5 = a1; } ++v10; v9 = -v9; o1 = a2a++ + 1; } while (v6 < v5); } if (o1 % 2) --o1; v4[v5 - 1] = v14; v4[v5] = v15; return o1; }
eb253f6ad437f61b355e088471c7bfbbd71f16a7
[ "Markdown", "C++" ]
3
Markdown
AndyVuGit/mob
07a66f683b4712d6674c04f4a0dd38f77642f628
bf56a658ea430b49dea243fcdc08b246adf4b59f
refs/heads/master
<repo_name>cancerhermit/createdb.py<file_sep>/README.md Installing ---------- from [pypi.python.org](https://pypi.python.org/pypi/createdb) sudo pip install createdb from [github](https://github.com/cancerhermit/createdb.py) Usage ---------- from createdb import createdb createdb(host="127.0.0.1",port=5432,user="username",dbname="new") PostgreSQL Documentation ---------- PostgreSQL [createdb](http://www.postgresql.org/docs/9.2/static/app-createdb.html)<file_sep>/py_modules/createdb.py #!/usr/bin/env python # -*- coding: utf-8 -* from os.path import * from subprocess import PIPE, Popen from public import * @public def createdb(args=[],host=None,port=None,dbname=None,username=None,description=None,echo=False,bin="/usr/bin/createdb"): """Execute PostgreSQL createdb command Args: dbname (str): database name host (str): server host (optional) port (int): server host (optional) username (str): username (optional) description (str): database comment (optional) bin (str): createdb binary filename (optional) Returns: string with createdb shell output Raises: IOError: createdb binary not exists ValueError: invalid port OSError: createdb shell error """ if not exists(bin): err = "%s not exists" % bin raise IOError(err) if isinstance(args,(str,unicode)): args = args.split(" ") args = [bin] + args process = Popen(args,stdout=PIPE,stderr=PIPE) stdout,stderr = process.communicate() if process.returncode==0: return stdout else: raise OSError(stderr) #print createdb(["-h","127.0.0.1","test"])
3a641f3d331f06c0aac7a850a19e8bcdb5f04044
[ "Markdown", "Python" ]
2
Markdown
cancerhermit/createdb.py
42eea8f5f705eb0aacea8cd16ed22feb08e4ebc3
5db1f11f84aee6ff3ae1f528028b702e15254c5f
refs/heads/master
<file_sep>package com.example.self_servicefood; import android.app.SearchManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.SearchView; import java.util.List; import controller.UserSharedPrefs; import controller.Utilities; import model.Business; import model.DbConnect; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class SearchActivity extends AppCompatActivity implements OnItemClick, Callback<List<Business>> { public RecyclerView orderLayout; public SearchAdapter nAdapter; protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_main); orderLayout = findViewById(R.id.businesslist); orderLayout.setLayoutManager(new LinearLayoutManager(this)); orderLayout.setItemAnimator(new DefaultItemAnimator()); orderLayout.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL)); DbConnect dbConnect = DbConnect.getDbCon(); //// Conduct the Search here // Fill adapter with business items List<Business> businessList = dbConnect.getBusinesses(); nAdapter = new SearchAdapter(SearchActivity.this, R.layout.activity_each_business, businessList, this); // Get the intent, verify the action and get the query // Intent intent = getIntent(); // if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // String query = intent.getStringExtra(SearchManager.QUERY); // doMySearch(query); // } // } // // // private void doMySearch(String query) { //// Get businesses //// Filter them // } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); ComponentName componentName = new ComponentName(this, SearchActivity.class); assert searchManager != null; searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName)); return true; } @Override public void itemClick(View view, int position) { switch (view.getId()){ case R.id.each_business_name: UserSharedPrefs.saveBusiness(this,nAdapter.getItemint(position)); Intent intent = new Intent(SearchActivity.this,CategoryList.class); startActivity(intent); finish(); } } @Override public boolean itemLongClick(View view, int position) { return false; } @Override public void onResponse(Call<List<Business>> call, Response<List<Business>> response) { } @Override public void onFailure(Call<List<Business>> call, Throwable t) { } } <file_sep>//package com.example.self_servicefood; // //import android.support.v7.widget.RecyclerView; //import android.view.View; //import android.widget.TextView; // //public class CategoryHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { // // private OnItemClick onItemClick; // public TextView textView; // // // public CategoryHolder(View itemView, OnItemClick onItemClick) { // super(itemView); // this.onItemClick = onItemClick; // // textView = itemView.findViewById(R.id.each_catergory_text); // // textView.setOnClickListener(this); // // textView.setOnLongClickListener(this); // } // // @Override // public void onClick(View view) { // onItemClick.itemClick(view, getAdapterPosition()); // } // // @Override // public boolean onLongClick(View view) { // return onItemClick.itemLongClick(view, getAdapterPosition()); // } //}<file_sep>package com.example.self_servicefood; import android.content.Context; import android.graphics.Typeface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.TextView; import java.util.HashMap; import java.util.List; import model.Category; import model.Item; public class ExpandableListAdapter extends BaseExpandableListAdapter { private Context context; private List<String> list; private HashMap<String, List<Item>> hashMap; public ExpandableListAdapter(Context context, List<String> list, HashMap<String, List<Item>> hashMap) { this.context = context; this.list = list; this.hashMap = hashMap; } @Override public int getGroupCount() { return list.size(); } @Override public int getChildrenCount(int i) { return hashMap.get(list.get(i)).size(); } @Override public Object getGroup(int i) { return list.get(i); } @Override public Object getChild(int i, int i1) { return hashMap.get(list.get(i)).get(i1); } @Override public long getGroupId(int i) { return i; } @Override public long getChildId(int i, int i1) { return i1; } @Override public boolean hasStableIds() { return false; } @Override public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) { String header = (String) getGroup(i); if (view == null) { LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.activity_categories, null); } TextView listHeader = (TextView) view.findViewById(R.id.categorylist); listHeader.setTypeface(null, Typeface.BOLD); listHeader.setText(header); return view; } @Override public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) { final String txt = (String)getChild(i,i1); if (view == null) { LayoutInflater inflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.activity_menu, null); } TextView txtList = (TextView) view.findViewById(R.id.itemlist); txtList.setText(txt); return view; } @Override public boolean isChildSelectable(int i, int i1) { return true; } } <file_sep>package model; public class User { private int id; private String email; private String name; private String surname; private String password; private int type; /* TODO: Discuss whether to save type as int or char or String? User types: 1- manager 2- staff 3- customer */ private String picture; private int business_id; public User(int id,String email, String name, String surname, String password, int type, String picture, int business_id) { this.email = email; this.name = name; this.surname = surname; this.password = <PASSWORD>; this.type = type; this.picture = picture; this.business_id = business_id; this.id = id; } public int getId() { return id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public int getBusiness_id() { return business_id; } public void setBusiness_id(int business_id) { this.business_id = business_id; } } <file_sep>package com.example.self_servicefood; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import controller.UserSharedPrefs; import controller.Utilities; import model.DbConnect; import model.User; public class MainActivity extends AppCompatActivity { public Button signinbutton, signup; public EditText enterEmail, enterPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); // if (UserSharedPrefs.getUser(this) == null){ signinbutton = findViewById(R.id.login_button); enterEmail = findViewById(R.id.email_signin); enterPassword = findViewById(R.id.password_signin); signup = findViewById(R.id.register_button); DbConnect dbConnect = DbConnect.getDbCon(); // User user = dbConnect.authenticateUser(enterEmail.getText().toString(), enterPassword.getText().toString()); signinbutton.setOnClickListener(v -> { // if (Utilities.isOnline(MainActivity.this)) { // //// Request Data // change to SearchActivity if (user != null) { UserSharedPrefs.saveUser(this, user); if (user.getType() == 3) { Intent intent = new Intent(MainActivity.this, SearchActivity.class); startActivity(intent); finish(); } else if (user.getType() == 2) { Intent intent = new Intent(MainActivity.this, orderStaff.class); startActivity(intent); finish(); } } else { Toast.makeText(MainActivity.this, "Login failed!", Toast.LENGTH_LONG).show(); } }); // // } // else Toast.makeText(MainActivity.this,"Network isn't available!", Toast.LENGTH_LONG).show(); // }); signup.setOnClickListener(v -> { Intent intent = new Intent(MainActivity.this, RegisterActivity.class); startActivity(intent); finish(); }); } } <file_sep>package model; public class Item { private int id; private int business_id; private String name; private int stock_left; private double price; private String description; private String picture; private int category_id; public Item(int id, int business_id, String name, int stock_left, double price, String description, String picture, int category_id) { this.id = id; this.business_id = business_id; this.name = name; this.stock_left = stock_left; this.price = price; this.description = description; this.picture = picture; this.category_id = category_id; } public int getId() { return id; } public int getBusiness_id() { return business_id; } public void setBusiness_id(int business_id) { this.business_id = business_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getStock_left() { return stock_left; } public void setStock_left(int stock_left) { this.stock_left = stock_left; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } public int getCategory_id() { return category_id; } public void setCategory_id(int category_id) { this.category_id = category_id; } } <file_sep>package model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Driver; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.transform.Result; /** * @desc A singleton database access class for MySQL */ public final class DbConnect { public Connection conn; private Statement statement; public static DbConnect db; private DbConnect() { String url= "jdbc:mysql://172.16.31.10:3306/"; //String url = "jdbc:mysql://mysql.itu.dk:3306/"; String dbName = "SelfService2000"; String driver = "com.mysql.jdbc.Driver"; String userName = "mcjorgel"; String password = "<PASSWORD>"; try { Class.forName(driver).newInstance(); this.conn = (Connection) DriverManager.getConnection(url + dbName, userName, password); } catch (Exception sqle) { sqle.printStackTrace(); } } /** * @return MysqlConnect Database connection object */ public static synchronized DbConnect getDbCon() { if (db == null) { db = new DbConnect(); } return db; } //Data fetching methods public void testConn() { try { statement = db.conn.createStatement(); int result = statement.executeUpdate("insert into users values" + " (null,'<EMAIL>', 'mr test', 'abdc', 'pass', 1, 'apisdf',null);"); System.out.println(result); } catch (SQLException ex){ System.out.println(ex); } } public static void main(String[] args){ DbConnect db = DbConnect.getDbCon(); db.testConn(); } public ResultSet query(String query) throws SQLException{ statement = db.conn.createStatement(); ResultSet res = statement.executeQuery(query); return res; } public int insert(String insertQuery) throws SQLException { statement = db.conn.createStatement(); int result = statement.executeUpdate(insertQuery); return result; //nr of rows affected } public String sanitize(String string){ //TODO: Figure out sanitizing return string; } public String hashPassword(String password){ // TODO: Figure out hashing return password; } public User authenticateUser (String email, String password){ String query = "Select * from users where email='" +email +"';"; //TODO: include hashing String hashedPassword = hashPassword(password); try { ResultSet resultSet = query(query); while (resultSet.next()){ String dbPassword = resultSet.getString("password"); if(!hashedPassword.equals(dbPassword)) return null; int id = Integer.parseInt(resultSet.getString("id")); String name = resultSet.getString("name"); String surname = resultSet.getString("surname"); String picture = resultSet.getString("picture"); int type = Integer.parseInt(resultSet.getString("type")); int business_id = Integer.parseInt(resultSet.getString("business_id")); return new User(id, email, name, surname, dbPassword, type, picture, business_id); } } catch (SQLException e) { e.printStackTrace(); } return null; } // TODO: maybe it's ok public User createUser(String name, String surname, String email, String password, int type, int business_id){ // check if email is taken List<User> existingUser = getUsersByEmail(email); if (!existingUser.isEmpty()) return null; String query = "Insert into users (email, name, surname, password, type, picture, business_id) " + "values('" + email + "','" + name + "','" + surname + "', '" + hashPassword(password) + "', " + type + ",'default.jpg', " + business_id +")"; try { int rowsAffected = insert(query); if (rowsAffected==1){ /* Erida says: There is a smarter way of getting the id of the new user (hint: Statement.RETURN_GENERATED_KEYS) but it requires a new insert method and it might turn out to not be supported so I'm choosing the easy(lazy) way of doing it. If sb improves this code I won't mind :) */ List<User> userlist = getUsersByEmail(email); // TODO: idk if this is okay? if(userlist.size()==1) return userlist.get(0); //else you either did not insert (?????) // or you have more than 1 user with the same email (?????) } } catch (SQLException e) { e.printStackTrace(); } return null; } public List<User> getUsersByEmail(String email){ List<User> users = new ArrayList<>(); String newEmail = sanitize(email); String query= "Select * from users where email='" + newEmail + "';"; try { ResultSet result = query(query); while (result.next()){ int id = Integer.parseInt(result.getString("id")); email = result.getString("email"); String name = result.getString("name"); String surname = result.getString("surname"); String password = <PASSWORD>.getString("<PASSWORD>"); int type = Integer.parseInt(result.getString("type")); String picture = result.getString("picture"); int business_id = Integer.parseInt(result.getString("id")); users.add(new User(id, email, name, surname, password, type, picture, business_id)); } } catch (SQLException e) { e.printStackTrace(); } return users; } public List<Business> getBusinesses(){ List<Business> businesses = new ArrayList<>(); String query= "Select * from businesses;"; try { ResultSet result = query(query); while (result.next()){ int id = Integer.parseInt(result.getString("id")); String name = result.getString("name"); String address = result.getString("address"); String city = result.getString("city"); String country = result.getString("country"); String cvr = result.getString("cvr"); String bankaccount = result.getString("bankaccount"); String mobilepay = result.getString("mobilepay"); String phonenumber = result.getString("phonenumber"); String logo = result.getString("logo"); businesses.add(new Business(id, name, address, city, country, cvr, bankaccount, mobilepay, phonenumber, logo)); } } catch (SQLException e) { e.printStackTrace(); } return businesses; } public HashMap<String, List<Item>> getMenuByBusinessId(int business_id){ //maps category to items in that category HashMap<String, List<Item>> menu = new HashMap<>(); String query= "Select items.*, categories.name as category_name from items, categories where" + " items.category_id = category.id and items.business_id=" + business_id + ";"; try { ResultSet result = query(query); while (result.next()){ int id = Integer.parseInt(result.getString("id")); int bus_id = Integer.parseInt(result.getString("business_id")); String name = result.getString("name"); int quantity = Integer.parseInt(result.getString("quantity")); double price = Double.parseDouble(result.getString("price")); String description = result.getString("description"); String picture = result.getString("picture"); int category_id = Integer.parseInt(result.getString("category_id")); String category_name = result.getString("category_name"); Item item = new Item(id, business_id, name, quantity, price, description, picture, category_id); List<Item> items = new ArrayList<>(); if(menu.containsKey(category_name)) { items = menu.get(category_name); } items.add(item); menu.put(category_name, items); } } catch (SQLException e) { e.printStackTrace(); } return menu; } public Map<Order, List<OrderItem>> getOrdersByCustomerId(int customer_id){ Map<Order, List<OrderItem>> orders = new HashMap<>(); String query= "Select * from orders where user_id=" + customer_id + ";"; try { ResultSet result = query(query); while (result.next()){ int id = Integer.parseInt(result.getString("id")); Timestamp time = Timestamp.valueOf(result.getString("time")); int user_id = Integer.parseInt(result.getString("user_id")); int business_id = Integer.parseInt(result.getString("business_id")); double total = Double.parseDouble(result.getString("total")); int state = Integer.parseInt(result.getString("state")); Order order = new Order(id, time, user_id, business_id, total,state); query = "Select orderitems.*,items.* from orderitems, items" + " where orderitems.order_id= " + id + "' and " + "orderitems.item_id = items.id"; ResultSet orderItemsResult = query(query); List<OrderItem> orderItems = new ArrayList<>(); while (orderItemsResult.next()){ int order_id = Integer.parseInt(result.getString("order_id")); int item_id = Integer.parseInt(result.getString("item_id")); int quantity = Integer.parseInt(result.getString("quantity")); // We already have the business_id // int business_id = Integer.parseInt(result.getString("business_id")); String name = result.getString("name"); int stock_left = Integer.parseInt(result.getString("stock_left")); double price = Integer.parseInt(result.getString("price")); String description = result.getString("description"); String picture = result.getString("picture"); int category_id = Integer.parseInt(result.getString("category_id")); Item item = new Item(item_id, business_id, name, stock_left, price, description, picture, category_id); OrderItem orderItem = new OrderItem(order_id, item_id, item, quantity); orderItems.add(orderItem); } orders.put(order, orderItems); } } catch (SQLException e) { e.printStackTrace(); } return orders; } public boolean updateOrderState(int order_id, int loggedIn_id, int loggedIn_business_id, int newState){ String query = "Select * from orders where id=" + order_id + ";"; try { ResultSet resultSet = query(query); while (resultSet.next()){ int id = Integer.parseInt(resultSet.getString("id")); Timestamp time = Timestamp.valueOf(resultSet.getString("time")); int user_id = Integer.parseInt(resultSet.getString("user_id")); int bus_id = Integer.parseInt(resultSet.getString("bus_id")); double total = Double.parseDouble(resultSet.getString("total")); int state = Integer.parseInt(resultSet.getString("state")); //An order can be cancelled by the customer who made it // only if it still pending (state 1) if(user_id == loggedIn_id && state == 1 && newState == 4){ query = "Update orders set state=4 where id="+ order_id +";"; int rowsAffected= insert(query); if(rowsAffected==1) return true; } //The order status can be changed by staff only if they're // working in the business the order was made to else if(bus_id == loggedIn_business_id){ //TODO: Discuss if staff can cancel order at any state //Transition from pending to processing if(state == 1 && newState == 2){ query = "Update orders set state=2 where id="+ order_id +";"; int rowsAffected= insert(query); if(rowsAffected==1) return true; } //Transition from pending to cancelled else if(state == 1 && newState == 4){ query = "Update orders set state=4 where id="+ order_id +";"; int rowsAffected= insert(query); if(rowsAffected==1) return true; } //Transition from processing to ready else if(state == 2 && newState == 3){ query = "Update orders set state=3 where id="+ order_id +";"; int rowsAffected= insert(query); if(rowsAffected==1) return true; } } } } catch (SQLException e) { e.printStackTrace(); } return false; } public Map<Order, List<OrderItem>> getOrdersByBusinessId(int business_id) { Map<Order, List<OrderItem>> orders = new HashMap<>(); String query = "Select * from orders where business_id=" + business_id + ";"; try { ResultSet result = query(query); while (result.next()) { int id = Integer.parseInt(result.getString("id")); Timestamp time = Timestamp.valueOf(result.getString("time")); int user_id = Integer.parseInt(result.getString("user_id")); // Given as a parameter // int business_id = Integer.parseInt(result.getString("business_id")); double total = Double.parseDouble(result.getString("total")); int state = Integer.parseInt(result.getString("state")); Order order = new Order(id, time, user_id, business_id, total, state); query = "Select orderitems.*,items.* from orderitems, items" + " where orderitems.order_id= " + id + "' and " + "orderitems.item_id = items.id"; ResultSet orderItemsResult = query(query); List<OrderItem> orderItems = new ArrayList<>(); while (orderItemsResult.next()) { int order_id = Integer.parseInt(result.getString("order_id")); int item_id = Integer.parseInt(result.getString("item_id")); int quantity = Integer.parseInt(result.getString("quantity")); // We already have the business_id // int business_id = Integer.parseInt(result.getString("business_id")); String name = result.getString("name"); int stock_left = Integer.parseInt(result.getString("stock_left")); double price = Integer.parseInt(result.getString("price")); String description = result.getString("description"); String picture = result.getString("picture"); int category_id = Integer.parseInt(result.getString("category_id")); Item item = new Item(item_id, business_id, name, stock_left, price, description, picture, category_id); OrderItem orderItem = new OrderItem(order_id, item_id, item, quantity); orderItems.add(orderItem); } orders.put(order, orderItems); } } catch (SQLException e) { e.printStackTrace(); } return orders; } public boolean createOrder(int user_id, int business_id, Map<Integer, Integer> item_idToQuantity){ double total = 0; String query; int id; //query price of each item to calculate total for (Map.Entry<Integer, Integer> entry : item_idToQuantity.entrySet()) { int item_id = entry.getKey(); int quantity = entry.getValue(); query = "Select * from items where id=" + item_id + ";"; try { ResultSet result = query(query); while (result.next()) { int stock_left = Integer.parseInt(result.getString("stock_left")); //if not enough items in stock order fails if(stock_left<quantity) return false; double price = Double.parseDouble(result.getString("price")); total += price * quantity; } } catch (SQLException e) { e.printStackTrace(); //if an item fails to be retrieved then the order cannot be completed return false; } } Date date = new Date(); Timestamp time = new Timestamp(date.getTime()); query= "Insert into orders(time, user_id, business_id, total, state)" + "values(" + time + ", " + user_id + ", " + business_id +", " + total + ", 1);"; try { int rowsAffected = insert(query); //if order was inserted you have to insert order items if(rowsAffected == 1) { //get order_id query = "Select * from orders where time=" + time + " and user_id =" + user_id + " and business_id=" + business_id + ";"; try { ResultSet result = query(query); // while (result.next()) { id = Integer.parseInt(result.getString("id")); // } for (Map.Entry<Integer, Integer> entry : item_idToQuantity.entrySet()) { int item_id = entry.getKey(); int quantity = entry.getValue(); query = "Insert into orderitems(order_id, item_id, quantity) " + "values (" + id + ", " + item_id + ", " + quantity + ";"; rowsAffected = insert(query); //I'm ignoring the case when the insertion fails because then we would //have to undo so many insertions and we don't have enough time for that } return true; } catch (SQLException e) { e.printStackTrace(); //if an item fails to be retrieved then the order cannot be completed return false; } } } catch (SQLException e) { e.printStackTrace(); return false; } return false; } } <file_sep>//package com.example.self_servicefood; // //class OrderActivity { //} <file_sep>package model; public class OrderItem { private int order_id; private int item_id; private Item item; private int quantity; public OrderItem(int order_id, int item_id, Item item, int quantity) { this.order_id = order_id; this.item_id = item_id; this.item = item; this.quantity = quantity; } public OrderItem(int order_id, int item_id, int quantity) { this.order_id = order_id; this.item_id = item_id; this.quantity = quantity; } public int getOrder_id() { return order_id; } public void setOrder_id(int order_id) { this.order_id = order_id; } public int getItem_id() { return item_id; } public void setItem_id(int item_id) { this.item_id = item_id; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } } <file_sep>package com.example.self_servicefood; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import java.util.List; import model.Item; public class ItemAdapter extends RecyclerView.Adapter<ItemHolder> { private OnItemClick onItemClick; private Context context; private List<Item> objects; private int resource; public ItemAdapter(OnItemClick onItemClick, Context context, List<Item> objects, int resource) { this.onItemClick = onItemClick; this.context = context; this.objects = objects; this.resource = resource; } @NonNull @Override public ItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return new ItemHolder(LayoutInflater.from(context).inflate(resource, parent, false), onItemClick); } @Override public void onBindViewHolder(@NonNull ItemHolder holder, int position) { Item item = objects.get(position); holder.textView.setText(item.getId()); } @Override public int getItemCount() { return objects.size(); } public Item getItem(int position) { return objects.get(position); } public void remove(Item notes) { objects.remove(notes); notifyDataSetChanged(); } } <file_sep>package com.example.self_servicefood; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import java.util.List; import model.Order; public class OrderAdapter extends RecyclerView.Adapter<OrderHolder> { private OnItemClick onItemClick; private Context context; private List<Order> objects; private int resource; public OrderAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Order> objects, OnItemClick onItemClick) { this.context = context; this.objects = objects; this.resource = resource; this.onItemClick = onItemClick; } @Override public OrderHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); return new OrderHolder(LayoutInflater.from(context).inflate(resource, parent, false), onItemClick); } @Override public void onBindViewHolder(OrderHolder holder, int position) { Order order = objects.get(position); holder.textView.setText(order.getId()); } @Override public int getItemCount() { return objects.size(); } public Order getItem(int position) { return objects.get(position); } public void remove(Order notes) { objects.remove(notes); notifyDataSetChanged(); } } <file_sep>package model; import java.sql.Timestamp; public class Order { private int id; private Timestamp time; private int user_id; private int business_id; private double total; private int state; /* TODO: Discuss whether to save state as int or char or String? Order states: 1- pending 2- processing 3- ready 4- cancelled */ public Order(int id, Timestamp time, int user_id, int business_id, double total, int state) { this.id = id; this.time = time; this.user_id = user_id; this.business_id = business_id; this.total = total; this.state = state; } public int getId() { return id; } public Timestamp getTime() { return time; } public void setTime(Timestamp time) { this.time = time; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public int getBusiness_id() { return business_id; } public void setBusiness_id(int business_id) { this.business_id = business_id; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } public int getState() { return state; } public void setState(int state) { this.state = state; } } <file_sep>package model; public class Category{ private int id; private int business_id; private String name; public Category(int id, int business_id, String name) { this.id = id; this.business_id = business_id; this.name = name; } public int getId() { return id; } public int getBusiness_id() { return business_id; } public void setBusiness_id(int business_id) { this.business_id = business_id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
38dd843f4c3c76d76df41ba28fff4675e580642f
[ "Java" ]
13
Java
jkeci15/Self-ServiceFood
0e3ab29be0a770bad145fcb772fc6123ddfeae1c
0a59b58577ffe230150d7ed4348c71e35d025d14
refs/heads/master
<repo_name>StrikeBhack/GSB<file_sep>/gsb_php/vues/v_info.php <div class ="info"> <?php echo $info; ?> </div><file_sep>/gsb_java/src/com/metier/Region.java package com.metier; import javax.persistence.*; @Entity @Table(name = "region") public class Region { // ########## PROPRIETES ##########// @Id @GeneratedValue @Column(name = "idR") private int idR; @Column(name = "nomRegion") private String nomRegion; // ################################// // ########## CONSTRUCTEURS ##########// /** * Constructeur d'une région * * @param idR * @param nomRegion */ public Region(int idR, String nomRegion) { super(); this.idR = idR; this.nomRegion = nomRegion; } /** * Constructeur vide d'une région */ public Region() { super(); // TODO Auto-generated constructor stub } // ###################################// // ########## METHODES ##########// /** * Accesseur de idR * * @return idR */ public int getIdR() { return idR; } /** * Mutateurs de l'idR * * @param idR */ public void setIdR(int idR) { this.idR = idR; } /** * Accesseur de nomRegion * * @return nomRegion */ public String getNomRegion() { return nomRegion; } /** * Mutateurs de nomRegion * * @param nomRegion */ public void setNomRegion(String nomRegion) { this.nomRegion = nomRegion; } /** * Méthode toString * * @return idR, nomRegion */ @Override public String toString() { return "Region [idR=" + idR + ", nomRegion=" + nomRegion + "]"; } // ##############################// } <file_sep>/gsb_java/src/com/modele/ModeleConsultationVisiteur.java package com.modele; import java.util.List; import java.util.Locale; import javax.swing.table.AbstractTableModel; import com.metier.Utilisateur; import com.persistance.AccesData; public class ModeleConsultationVisiteur extends AbstractTableModel { private final String[] entetes = { "Nom", "Pr�nom"}; private List<Utilisateur> listeVisiteur; public ModeleConsultationVisiteur() { super(); } public ModeleConsultationVisiteur(List<Utilisateur> listeVisiteur) { super(); this.listeVisiteur = listeVisiteur; } @Override public int getColumnCount() { return entetes.length; } @Override public int getRowCount() { return listeVisiteur.size(); } @Override public String getColumnName(int columnIndex) { return entetes[columnIndex]; } @Override public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: // Nom return listeVisiteur.get(rowIndex).getNom(); case 1: // Pr�nom return listeVisiteur.get(rowIndex).getPrenom(); default: throw new IllegalArgumentException(); } } } <file_sep>/gsb_java/src/com/metier/FraisForfait.java package com.metier; import java.math.BigDecimal; import java.util.List; import javax.persistence.*; @Entity @Table(name = "fraisforfait") public class FraisForfait { // ########## PROPRIETES ##########// @Id @Column(name = "id") private String id; @Column(name = "libelle") private String libelle; @Column(name = "montant", columnDefinition = "decimal", precision = 2, scale = 3) private BigDecimal montant; // ################################// // ########## CONSTRUCTEURS ##########// /** * Constructeur d'une fiche de frais * * @param id * @param libelle * @param montant */ public FraisForfait(String id, String libelle, BigDecimal montant) { super(); this.id = id; this.libelle = libelle; this.montant = montant; } /** * Constructeur vide d'une fiche de frais */ public FraisForfait() { super(); // TODO Auto-generated constructor stub } // ###################################// // ########## METHODES ##########// /** * Accesseur de l'id * * @return id */ public String getId() { return id; } /** * Mutateurs de l'id * * @param id */ public void setId(String id) { this.id = id; } /** * Accesseur du libelle * * @return libelle */ public String getLibelle() { return libelle; } /** * Mutateurs du libelle * * @param libelle */ public void setLibelle(String libelle) { this.libelle = libelle; } /** * Accesseur de montant * * @return montant */ public BigDecimal getMontant() { return montant; } /** * Mutateurs de montant * * @param montant */ public void setMontant(BigDecimal montant) { this.montant = montant; } /** * Méthode toString * * @return id, libelle, montant */ @Override public String toString() { return "FraisForfait [id=" + id + ", libelle=" + libelle + ", montant=" + montant + "]"; } // ##############################// } <file_sep>/gsb_php/controleurs/c_gererFraisComptable.php <?php include("vues/v_sommaire.php"); $action = $_REQUEST['action']; $idVisiteur = $_SESSION['idVisiteur']; $titre = "Validation fiche frais"; $idEtat = 'CL'; include("vues/v_entete_contenu.php"); switch($action){ case 'selectionnerUtilisateurMois':{ $lesInfos=$pdo->getFichesVisiteurEtat($idEtat); $moisASelectionner=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $idVisiteur=$lesInfos[0]["id"]; $mois=$lesInfos[0]["mois"]; break; } case 'voirRemboursement':{ $lesInfos=$pdo->getFichesVisiteurEtat('CL'); $lesInfosUtilisateur = $_REQUEST['lstMois']; $moisASelectionner = $lesInfosUtilisateur; $arrayInfos= explode("-",$lesInfosUtilisateur); $mois = $arrayInfos[1]; $idVisiteur = $arrayInfos[0]; break; } case 'supprimer':{ $lesInfos=$pdo->getFichesVisiteurEtat($idEtat); $lesInfosUtilisateur = $_REQUEST['idVisiteurMois']; $moisASelectionner = $lesInfosUtilisateur; $array = explode("-", $lesInfosUtilisateur); $mois = $array[1]; $idVisiteur = $array[0]; $idFrais = $_REQUEST['idFrais']; //TODO : Function qui rajoute 'REFUSE' devant le libelle à créer $pdo->supprimerFraisHorsForfait($idFrais); /*$leMois=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $moisASelectionner=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $leMoisU[0]=$lesInfos[0]["id"]; $leMoisU[1]=$lesInfos[0]["mois"];*/ break; } case 'reporteFrais':{ $lesInfos = $pdo->getFichesVisiteurEtat ( $idEtat ); // gére la sélection dasn la liste d�roulante $idFrais = $_REQUEST ['idFrais']; $infos = $_REQUEST ['idVisiteurMois']; $moisASelectionner = $infos; $array = explode ( "-", $infos ); $mois = $array [1]; $idVisiteur = $array [0]; // le mois suivant $moisSuivant = $mois + 1; $listeMoisDispo = $pdo->getLesMoisDisponibles ( $idVisiteur ); // récupère les infos d'une ligne hors forfait $unHorsForfait = $pdo->getUneLigneHorsForfait ( $idFrais ); $dernierMois = $pdo->dernierMoisSaisi ( $idVisiteur ); $libelle = $unHorsForfait ['libelle']; $dateFrais = $unHorsForfait ['date']; $montant = $unHorsForfait ['montant']; if ($moisSuivant == $dernierMois) { $pdo->supprimerFraisHorsForfait ( $idFrais ); } else { $pdo->supprimerFraisHorsForfait ( $idFrais ); $pdo->creeNouvellesLignesFrais ( $idVisiteur, $moisSuivant ); } $pdo->creeNouveauFraisHorsForfait ( $idVisiteur, $moisSuivant, $libelle, $dateFrais, $montant ); $lesInfos = $pdo->getFichesVisiteurEtat ( $idEtat); // Charger idMois et idVisiteur $infos = $_REQUEST ['idVisiteurMois']; $moisASelectionner = $infos; $array = explode ( "-", $infos ); $mois = $array [1]; $idVisiteur = $array [0]; /*$lesInfos=$pdo->getFichesVisiteurEtat('CL'); $leMois=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $moisASelectionner=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $leMoisU[0]=$lesInfos[0]["id"]; //print_r($leMoisU[0]); $leMoisU[1]=$lesInfos[0]["mois"];*/ break; } case 'ValiderRemboursement':{ $leMois = $_REQUEST['lstMois']; $moisASelectionner = $leMois; $leMoisU= $leMois; $leMoisU= explode("-",$leMoisU); $lesInfos=$pdo->get_LesMoisValides(); $info = 'Fiche validée !'; include("vues/v_info.php"); $pdo->majEtatFicheFrais($leMoisU[0],$leMoisU[1],"VA"); $lesInfos=$pdo->getFichesVisiteurEtat('CL'); $leMois=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $moisASelectionner=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $leMoisU[0]=$lesInfos[0]["id"]; $leMoisU[1]=$lesInfos[0]["mois"]; break; } } /*if (nbErreurs() != 0 ){ include("vues/v_erreurs.php"); } else{*/ $lesFraisHorsForfait = $pdo->getLesFraisHorsForfait($idVisiteur,$mois); $lesFraisForfait= $pdo->getLesFraisForfait($idVisiteur,$mois); $lesInfosFicheFrais = $pdo->getLesInfosFicheFrais($idVisiteur,$mois); $numAnnee = substr( $mois,0,4); $numMois = substr( $mois,4,2); $libEtat = $lesInfosFicheFrais['libEtat']; $idEtat = $lesInfosFicheFrais['idEtat']; $montantValide = $lesInfosFicheFrais['montantValide']; $nbJustificatifs = $lesInfosFicheFrais['nbJustificatifs']; $dateModif = $lesInfosFicheFrais['dateModif']; $dateModif = convertirDateAnglaisVersFrancais($dateModif); include("vues/v_listeVisiteursMois2.php"); include("vues/v_listeFraisForfaitComptable.php"); include("vues/v_gererFraisComptable.php"); //} ?><file_sep>/gsb_java/src/com/vue/JPanelStatsMoyenneFF.java package com.vue; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JLabel; import javax.swing.JComboBox; import javax.swing.JScrollPane; import javax.swing.JTable; import com.metier.Region; import com.metier.Utilisateur; import com.modele.ModeleMoyenneFF; import com.modele.ModeleMoyenneFHF; import com.modele.ModeleStatistiquesFF; import com.modele.ModeleStatistiquesFFHF; import com.persistance.AccesData; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.Calendar; import java.util.List; import javax.swing.SwingConstants; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.Font; import javax.swing.JCheckBox; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; public class JPanelStatsMoyenneFF extends JPanel { private JScrollPane scrollPane; private JTable table; private List<Region> listeRegion = AccesData.getListeRegion(); private JLabel lblMois; private JComboBox comboBoxMois; private ModeleMoyenneFF modeleFF=null; private ModeleMoyenneFHF modeleFHF=null; Calendar cal = Calendar.getInstance(); private String[] listeMois = {"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"}; private JLabel lblTitre; private Checkbox chckbxMoyenneFraisForfait; private Checkbox chckbxMoyenneFraisHors; private List<Utilisateur> listeVisiteur; String mois; /** * Create the panel. */ public JPanelStatsMoyenneFF() { setLayout(null); add(getScrollPane()); add(getLblMois()); add(getComboBox_1()); add(getLblTitre()); add(getChckbxMoyenneFraisForfait()); add(getChckbxMoyenneFraisHors()); chargerJTable(); } private JScrollPane getScrollPane() { if (scrollPane == null) { scrollPane = new JScrollPane(); scrollPane.setBounds(473, 136, 598, 409); scrollPane.setViewportView(getTable()); } return scrollPane; } private JTable getTable() { if (table == null) { table = new JTable(); } return table; } private JLabel getLblMois() { if (lblMois == null) { lblMois = new JLabel("Mois : "); lblMois.setHorizontalAlignment(SwingConstants.CENTER); lblMois.setBounds(63, 174, 69, 20); } return lblMois; } private JComboBox getComboBox_1() { if (comboBoxMois == null) { comboBoxMois = new JComboBox(); // permet de r�cup�rer la date du jour int i; for(i = 0; i < listeMois.length; i++) { // compare l'index en cours avec le mois actuel // permet de ne pas afficher le mois en cours if (cal.get(Calendar.MONTH) != i) { comboBoxMois.addItem(listeMois[i]); } } comboBoxMois.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { chargerJTable(); } }); comboBoxMois.setBounds(167, 171, 143, 26); } return comboBoxMois; } final CheckboxGroup groupe = new CheckboxGroup(); // cr�ation du CheckboxGroup private Checkbox getChckbxMoyenneFraisForfait() { if (chckbxMoyenneFraisForfait == null) { chckbxMoyenneFraisForfait = new Checkbox("Moyenne des Frais Forfait par R�gion", groupe, true); chckbxMoyenneFraisForfait.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { lblTitre.setText("Moyenne des Frais Forfait par R�gion"); comboBoxMois.setSelectedIndex(0); chargerJTable(); modeleFF(); } }); chckbxMoyenneFraisForfait.setBounds(63, 57, 247, 23); } return chckbxMoyenneFraisForfait; } private Checkbox getChckbxMoyenneFraisHors() { if (chckbxMoyenneFraisHors == null) { chckbxMoyenneFraisHors = new Checkbox("Moyenne des Frais Hors Forfait par R�gion", groupe, false); chckbxMoyenneFraisHors.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent e) { lblTitre.setText("Moyenne des Frais Hors Forfait par R�gion"); comboBoxMois.setSelectedIndex(0); chargerJTable(); modeleFHF(); } }); chckbxMoyenneFraisHors.setBounds(63, 93, 247, 23); } return chckbxMoyenneFraisHors; } private JLabel getLblTitre() { if (lblTitre == null) { lblTitre = new JLabel("Moyenne des Frais Hors Forfait"); lblTitre.setFont(new Font("Tahoma", Font.BOLD, 18)); lblTitre.setBounds(473, 94, 598, 20); } return lblTitre; } public void chargerJTable() { // chargement des donn�es du tableau listeVisiteur = AccesData.getListeVisiteur(listeRegion.get(comboBoxMois.getSelectedIndex()).getIdR()); //met le mois au format de la base int idMois = comboBoxMois.getSelectedIndex()+1; if(idMois >= 10) { mois = "2014" + idMois; } else { mois = "20140" + idMois; } //charge la jtable en fonctionn de la checkbox s�lectionn� if(groupe.getSelectedCheckbox().equals(chckbxMoyenneFraisForfait)) { modeleFF(); } else { modeleFHF(); } } public void modeleFF() { // affectation du mod�le � la Jtable modeleFF = new ModeleMoyenneFF(listeRegion, mois); table.setModel(modeleFF); table.revalidate(); } public void modeleFHF() { // affectation du mod�le � la Jtable modeleFHF = new ModeleMoyenneFHF(listeRegion, mois); table.setModel(modeleFHF); table.revalidate(); } } <file_sep>/gsb_java/src/com/vue/TestMapping.java package com.vue; import org.hibernate.Session; import java.util.*; import com.util.HibernateSession; import com.metier.*; public class TestMapping { public static void main(String[] args) { // TODO Auto-generated method stub Session s = HibernateSession.getSession(); /*//##### test récupération etat ##### List<Etat> listeEtat = s.createQuery("from Etat").list(); for (Etat e : listeEtat) { System.out.println(e.toString()); } // récupération 1 ligne Etat e = (Etat)s.get(Etat.class, "CL"); System.out.println("\n\n"); System.out.println(e.toString());*/ //##### test récupération ficheFrais ##### /*List<FicheFrais> listeFicheFrais = s.createQuery("from FicheFrais").list(); for (FicheFrais ff : listeFicheFrais) { //System.out.println(ff.getIdEtat().getLibelle()); System.out.println(ff.toString()); } //##### test récupération 1 ficheFrais ##### FicheFraisPK ffpk = new FicheFraisPK("f4", "201406"); FicheFrais ff = (FicheFrais)s.get(FicheFrais.class, ffpk); System.out.println("\n\n"); System.out.println(ff.toString()); //##### test récupération selon idVisiteur ##### List<FicheFrais> listeFicheFrais = s.createQuery("from FicheFrais").list(); for(FicheFrais f : listeFicheFrais) { if(f.getId().getIdVisiteur().equals("f4")) { System.out.println(f); } }*/ /*//##### typeUtilisateur ##### List<TypeUtilisateur> listeTU = s.createQuery("from TypeUtilisateur").list(); for (TypeUtilisateur tu : listeTU) { //System.out.println(ff.getIdEtat().getLibelle()); System.out.println(tu.toString()); } // récupération 1 ligne TypeUtilisateur t = (TypeUtilisateur)s.get(TypeUtilisateur.class, 'c'); System.out.println("\n\n"); System.out.println(t.toString()); //##### REGION ##### List<Region> listeRegion = s.createQuery("from Region").list(); for (Region r : listeRegion) { //System.out.println(ff.getIdEtat().getLibelle()); System.out.println(r.toString()); } // récupération 1 ligne Region r = (Region)s.get(Region.class, 23); System.out.println("\n\n"); System.out.println(r.toString());*/ /*//##### UTILISATEUR ##### List<Utilisateur> listeUtil = s.createQuery("from Utilisateur").list(); for (Utilisateur util : listeUtil) { //System.out.println(ff.getIdEtat().getLibelle()); System.out.println(util.toString()); } Utilisateur u = (Utilisateur)s.get(Utilisateur.class, "a131"); System.out.println("\n\n"); System.out.println(u.toString());*/ //##### LigneFraisHorsForfait ##### /*List<LigneFraisHorsForfait> listeLHF = s.createQuery("from LigneFraisHorsForfait").list(); for (LigneFraisHorsForfait lhf : listeLHF) { System.out.println(lhf.toString()); } LigneFraisHorsForfait l = (LigneFraisHorsForfait)s.get(LigneFraisHorsForfait.class, 1933); System.out.println("\n\n"); System.out.println(l.toString()); //##### FraisForfait ##### List<FraisForfait> ligneFF = s.createQuery("from FraisForfait").list(); for (FraisForfait ff : ligneFF) { System.out.println(ff.toString()); } FraisForfait f = (FraisForfait)s.get(FraisForfait.class, "REP"); System.out.println("\n\n"); System.out.println(f.toString());*/ //##### LigneFraisForfait ##### /*List<LigneFraisForfait> ligneFF = s.createQuery("from LigneFraisForfait").list(); for (LigneFraisForfait ff : ligneFF) { System.out.println(ff.toString()); } LigneFraisForfait lf = (LigneFraisForfait)s.get(LigneFraisForfait.class, "REP"); System.out.println("\n\n"); System.out.println(lf.toString()); //##### Recup 1 LigneFraisForfait ##### FicheFraisPK ffpk = new FicheFraisPK("f4", "201406"); LigneFraisForfaitPK lffpk = new LigneFraisForfaitPK(ffpk, "ETP"); LigneFraisForfait ff = (LigneFraisForfait)s.get(LigneFraisForfait.class, lffpk); System.out.println(ff);*/ } } <file_sep>/gsb_php/vues/v_gererFraisComptable.php <div id="sousContenu"> <h3>Fiche de frais de <?php echo $nom." ".$prenom?> du mois de <?php echo obtenirLibelleMois($numMois)." ".$numAnnee?> :</h3> <form method="POST" action="index.php?uc=gererFraisComptable&action=rembourser"> <h4>Descriptif des éléments hors forfait -<?php echo $nbJustificatifs ?> justificatifs reçus -</h4> <table class="listeLegere"> <tr> <th class="date">Date</th> <th class="libelle">Libellé</th> <th class="montant">Montant</th> <th class="reporter">Reporter</th> <th class="supprimer">supprimer</th> </tr> <?php $info = ""; if (isset($_REQUEST['lstMois'])) { $info = $_REQUEST['lstMois']; } foreach ( $lesFraisHorsForfait as $unFraisHorsForfait ) { $id = $unFraisHorsForfait['id']; $date = $unFraisHorsForfait['date']; $libelle = $unFraisHorsForfait['libelle']; $montant = $unFraisHorsForfait['montant']; ?> <tr> <td><?php echo $date ?></td> <td class="libelle"><?php echo $libelle ?></td> <td class="montant"><?php echo $montant ?></td> <td><a href="index.php?uc=gererFraisComptable&action=reporteFrais&idFrais=<?php echo $id ?>&idVisiteurMois=<?php echo $info?>" onmouseover="style.cursor='pointer'" onclick="return confirm('Voulez-vous vraiment reporter ce frais?');"><img src="images/redo.png" /></a></td> <td><a href="index.php?uc=gererFraisComptable&action=supprimer&idFrais=<?php echo $id ?>&idVisiteurMois=<?php echo $info?>" onmouseover="style.cursor='pointer'" onclick="return confirm('Voulez-vous vraiment supprimer ce frais?');"><img src="images/delete.png" /></a></td> </tr> <?php } /* $info = ""; if (isset($_REQUEST['lstMois'])) { $info = $_REQUEST['lstMois']; } */ ?> </table> &nbsp; <center><input style="width:20%" id="Remboursement" type="submit" class ="bouton" value="Validation" size="20" /></center> <input type="hidden" id="valRemb" name="lstMois" value="<?php echo $info ?>" > </div> </form> <script> var remb = document.getElementById("lstMois").value; document.getElementById("valRemb").value = remb; </script> </div><file_sep>/gsb_php/vues/v_listeMois.php  <div id="sousContenu"> <h3>Mois à sélectionner : </h3> <form action="index.php?uc=etatFrais&action=voirEtatFrais" method="post"> <div class="corpsForm"> <p> <label for="lstMois" accesskey="n">Mois : </label> <select id="lstMois" name="lstMois" title="Sélectionnez le mois souhaité pour la fiche de frais"> <?php foreach ($lesMois as $unMois) { $mois = $unMois['mois']; $numAnnee = $unMois['numAnnee']; $numMois = $unMois['numMois']; $selected = ($mois == $moisASelectionner)?("selected"):(""); ?> <option <?php echo $selected ?> value="<?php echo $mois ?>"><?php echo obtenirLibelleMois($numMois) . " " . $numAnnee ?> </option> <?php } ?> </select> </p> </div> <div class="piedForm"> <p> <input id="ok" type="submit" class="bouton" value="Valider" size="20" /> <input id="annuler" type="reset" class="bouton" value="Effacer" size="20" /> </p> </div> </form> </div> <file_sep>/gsb_java/src/com/vue/JPanelConsultationVisiteur.java package com.vue; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.CheckboxGroup; import java.awt.Font; import javax.swing.JOptionPane; import javax.swing.SwingConstants; import javax.swing.JCheckBox; import javax.swing.JList; import javax.swing.JComboBox; import javax.swing.JTextField; import javax.swing.JSeparator; import javax.swing.JButton; import javax.swing.JTable; import javax.swing.JScrollPane; import com.metier.Region; import com.metier.Utilisateur; import com.modele.ModeleConsultationVisiteur; import com.persistance.AccesData; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.util.List; import java.awt.Checkbox; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeEvent; public class JPanelConsultationVisiteur extends JPanel { private JTextField txtNom; private JTextField txtPrnom; private JTextField txtId; private JTable tableConsultation; private ModeleConsultationVisiteur modele=null; private List<Region> listeRegion; private JLabel lblNom; private JLabel lblPrnom; private JLabel lblIdVisiteur; private List<Utilisateur> listeVisiteur; /** * Create the panel. */ public JPanelConsultationVisiteur() { setLayout(null); JLabel lblSlectionnerUneRgion = new JLabel("Recherche d'un visiteur"); lblSlectionnerUneRgion.setHorizontalAlignment(SwingConstants.CENTER); lblSlectionnerUneRgion.setFont(new Font("Tahoma", Font.PLAIN, 25)); lblSlectionnerUneRgion.setBounds(488, 16, 276, 41); add(lblSlectionnerUneRgion); final JComboBox comboBox = new JComboBox(); comboBox.setBounds(70, 203, 203, 26); add(comboBox); listeRegion = AccesData.getListeRegion(); for(Region r : listeRegion) { comboBox.addItem(r.getNomRegion()); } final CheckboxGroup groupe = new CheckboxGroup(); // cr�ation du CheckboxGroup final Checkbox chckbxSlectionnerRgion = new Checkbox("S\u00E9lectionner une r\u00E9gion", groupe, true); // cr�ation du checkbox et ajout dans un CheckboxGroup chckbxSlectionnerRgion.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { txtNom.setEditable(false); txtPrnom.setEditable(false); txtId.setEditable(false); comboBox.setEnabled(true); } }); chckbxSlectionnerRgion.setFont(new Font("Tahoma", Font.PLAIN, 20)); chckbxSlectionnerRgion.setBounds(44, 148, 255, 29); add(chckbxSlectionnerRgion); final Checkbox chckbxSaisirNomEt = new Checkbox("Saisir nom et pr\u00E9nom", groupe, false); chckbxSaisirNomEt.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { comboBox.setEnabled(false); txtId.setEditable(false); txtNom.setText(""); txtNom.setEditable(true); txtPrnom.setText(""); txtPrnom.setEditable(true); } }); chckbxSaisirNomEt.setFont(new Font("Tahoma", Font.PLAIN, 20)); chckbxSaisirNomEt.setBounds(44, 295, 238, 29); add(chckbxSaisirNomEt); final Checkbox chckbxSaisirIdentifiantDu = new Checkbox("Saisir identifiant", groupe, false); chckbxSaisirIdentifiantDu.addFocusListener(new FocusAdapter() { @Override public void focusGained(FocusEvent arg0) { comboBox.setEnabled(false); txtId.setText(""); txtId.setEditable(true); txtNom.setEditable(false); txtPrnom.setEditable(false); } }); chckbxSaisirIdentifiantDu.setFont(new Font("Tahoma", Font.PLAIN, 20)); chckbxSaisirIdentifiantDu.setBounds(44, 493, 184, 29); add(chckbxSaisirIdentifiantDu); txtNom = new JTextField(); txtNom.setBounds(127, 348, 146, 26); add(txtNom); txtNom.setColumns(10); txtNom.setEditable(false); txtPrnom = new JTextField(); txtPrnom.setBounds(127, 385, 146, 26); add(txtPrnom); txtPrnom.setColumns(10); txtPrnom.setEditable(false); txtId = new JTextField(); txtId.setBounds(127, 541, 93, 26); add(txtId); txtId.setColumns(10); txtId.setEditable(false); JButton btnRechercher = new JButton("Rechercher"); btnRechercher.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { // instanciation d'un objet Modele //modele = new ModeleConsultationVisiteur(); if(groupe.getSelectedCheckbox().equals(chckbxSlectionnerRgion)) { // recherche en fonction de l'id r�gion listeVisiteur = AccesData.getListeVisiteur(listeRegion.get(comboBox.getSelectedIndex()).getIdR()); modele = new ModeleConsultationVisiteur(listeVisiteur); } else if (groupe.getSelectedCheckbox().equals(chckbxSaisirNomEt)) { if(txtNom.getText().equals("") || txtPrnom.getText().equals("")) { JOptionPane.showMessageDialog(null, "Nom ou pr�nom non renseign� !", "Erreur", JOptionPane.ERROR_MESSAGE); } else if (AccesData.getListeVisiteur(txtNom.getText(), txtPrnom.getText()).isEmpty()) { JOptionPane.showMessageDialog(null, "Aucun visiteur correspondant !", "Information", JOptionPane.INFORMATION_MESSAGE); } else { listeVisiteur = AccesData.getListeVisiteur(txtNom.getText(), txtPrnom.getText()); modele = new ModeleConsultationVisiteur(listeVisiteur); } // en fonction du nom et prenom } else { if(txtId.getText().equals("")) { JOptionPane.showMessageDialog(null, "Identifiant non saisie !", "Erreur", JOptionPane.ERROR_MESSAGE); } else if(AccesData.getListeVisiteur(txtId.getText()).isEmpty()) { JOptionPane.showMessageDialog(null, "Aucun visiteur correspondant !", "Information", JOptionPane.INFORMATION_MESSAGE); } else { listeVisiteur = AccesData.getListeVisiteur(txtId.getText()); modele = new ModeleConsultationVisiteur(listeVisiteur); } // en fonction de l'id } // affectation du mod�le � la Jtable tableConsultation.setModel(modele); // rafraichissement tableConsultation.revalidate(); } }); btnRechercher.setFont(new Font("Tahoma", Font.PLAIN, 20)); btnRechercher.setBounds(98, 599, 146, 29); add(btnRechercher); JScrollPane scrollPaneConsultation = new JScrollPane(); scrollPaneConsultation.setBounds(378, 103, 791, 577); add(scrollPaneConsultation); tableConsultation = new JTable(); tableConsultation.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(e.getClickCount() == 2) { int row = tableConsultation.getSelectedRow(); String nom = tableConsultation.getValueAt(row, 0).toString(); String prenom = tableConsultation.getValueAt(row, 1).toString(); Utilisateur visiteurClic = AccesData.getListeVisiteur(nom, prenom).get(0); JDialogInfoVisiteur infoVisiteur = new JDialogInfoVisiteur(visiteurClic); } } }); scrollPaneConsultation.setViewportView(tableConsultation); add(getLblNom()); add(getLblPrnom()); add(getLblIdVisiteur()); } private JLabel getLblNom() { if (lblNom == null) { lblNom = new JLabel("Nom : "); lblNom.setBounds(59, 354, 31, 14); } return lblNom; } private JLabel getLblPrnom() { if (lblPrnom == null) { lblPrnom = new JLabel("Pr\u00E9nom : "); lblPrnom.setBounds(44, 391, 46, 14); } return lblPrnom; } private JLabel getLblIdVisiteur() { if (lblIdVisiteur == null) { lblIdVisiteur = new JLabel("Id Visiteur : "); lblIdVisiteur.setBounds(31, 547, 59, 14); } return lblIdVisiteur; } } <file_sep>/gsb_php/vues/v_etatFraisComptable.php <div id="sousContenu"> <h3>Fiche de frais de <?php echo $nom." ".$prenom?> du mois de <?php echo obtenirLibelleMois($numMois)." ".$numAnnee?> :</h3> <form method="POST" action="index.php?uc=voirEtatRemboursement&action=rembourser"> <div id="etatMontant"> <div id="etat" class="<?php echo $idEtat;?>"> Date dernière modification depuis le <?php echo $dateModif?> </div> <div id="montantValide"> Montant Valide : <div><?php echo $montantValide?></div> </div> </div> <h4>Eléments forfaitisés :</h4> <table class="listeLegere"> <tr> <?php foreach ( $lesFraisForfait as $unFraisForfait ) { $libelle = $unFraisForfait['libelle']; ?> <th> <?php echo $libelle?></th> <?php } ?> </tr> <tr> <?php foreach ( $lesFraisForfait as $unFraisForfait ) { $quantite = $unFraisForfait['quantite']; ?> <td class="qteForfait"><?php echo $quantite?> </td> <?php } ?> </tr> </table> <h4>Descriptif des éléments hors forfait -<?php echo $nbJustificatifs ?> justificatifs reçus -</h4> <table class="listeLegere"> <tr> <th class="date">Date</th> <th class="libelle">Libellé</th> <th class="montant">Montant</th> </tr> <?php foreach ( $lesFraisHorsForfait as $unFraisHorsForfait ) { $date = $unFraisHorsForfait['date']; $libelle = $unFraisHorsForfait['libelle']; $montant = $unFraisHorsForfait['montant']; ?> <tr> <td><?php echo $date ?></td> <td class="libelle"><?php echo $libelle ?></td> <td class="montant"><?php echo $montant ?></td> </tr> <?php } $info = ""; if (isset($_REQUEST['lstMois'])) { $info = $_REQUEST['lstMois']; } ?> </table> &nbsp; <center><input style="width:20%" id="Remboursement" type="submit" class ="bouton" value="Remboursement" size="20" /></center> <input type="hidden" id="valRemb" name="lstMois" value="<?php echo $info ?>" > </div> </form> <script> var remb = document.getElementById("lstMois").value; document.getElementById("valRemb").value = remb; </script> </div><file_sep>/gsb_php/vues/v_sommaire.php <div id="menuGauche"> <div id="infosUtil"> <h2></h2> <div id="user"> <img src="images/UserIcon.png" /> </div> <div id="infos"> <h2> <?php echo $_SESSION['prenom']." ".$_SESSION['nom'] ?> </h2> <h3><?php echo $_SESSION['libelleType'] ?></h3> </div> <ul class="menuList"> <li class="smenu"> <a href="index.php?uc=connexion&action=deconnexion" title="Se déconnecter" >Déconnexion</a> </li> </ul> </div> <ul id="menuPrincipal" class="menuList"> <?php foreach($_SESSION['menu'] as $ligneMenu){?> <li class="smenu"> <a href="index.php?uc=<?php echo $ligneMenu["lien"];?>" title="<?php echo $ligneMenu["titre"];?>"><?php echo $ligneMenu["texte"]; ?></a> </li> <?php } ?> </ul> </div> <!-- <ul id="menuPrincipal" class="menuList"> <li class="smenu"> <a href="index.php?uc=accueil" title="Accueil"><?php ?></a> </li> <li class="smenu"> <a href="index.php?uc=gererFrais&action=saisirFrais" title="Saisie fiche de frais "><?php ?></a> </li> <li class="smenu"> <a href="index.php?uc=etatFrais&action=selectionnerMois" title="Consultation de mes fiches de frais"><?php ?></a> </li> </ul> </div> --> <file_sep>/gsb_java/ressources/readme.txt ########## CAS D'UTILISATION ############# - connexion => OK - Consulter fiche visiteur => OK - Modifier coordonées visiteur => OK - Enregistrer nouveau visiteur => OK => rajouter une colonne email dans la table utilisateur => OK => rajouter une propriété email dans la classe utilisateur => OK - Suppression d'un visiteur => OK - Statistiques : 5 stats => 2/5 ########## NOTE ########### Connexion: secrétaire = sfelicity/sfelicity responsable suivi frais = jjean/jjean <======== utilisateur tester pour l'instant DRH = jmichel/jmichel comptable = rjack/rjack visiteur = ex: dandre/oppg5 Connexion BDD: => dans fichier hibernate.cfg.xml Pour lancer l'appli: => JFrameGSB.java<file_sep>/gsb_php/vues/v_listeVisiteursMois2.php <div id="sousContenu"> <h3>Sélection Fiche : </h3> <form action="index.php?uc=gererFraisComptable&action=voirRemboursement" method="post"> <div class="corpsForm"> <p> <label for="lstMois" accesskey="n">Utilisateur et Mois : </label> <select id="lstMois" name="lstMois" title="Séléctionnez le mois et l'utilisateur souhaité pour la fiche de frais" onchange="submit()"> <?php foreach ($lesInfos as $unMois) { $id = $unMois["id"]; $nom = $unMois["nom"]; $prenom = $unMois["prenom"]; $mois = $unMois['mois']; //TODO : FAIRE UN SUBstring sur le $mois pour l'annee $selected = ($id."-".$mois == $moisASelectionner)?("selected"):(""); $leMois = $unMois['mois']; ?> <option <?php echo $selected ?> value="<?php echo $id."-".$mois ?>"><?php echo $prenom." ".$nom." - ".obtenirLibelleMois(substr($mois,4,2)) ?> </option> <?php } ?> </select> </p> </div> </form> </div> <file_sep>/gsb_java/ressources/gsb_modifier.sql -- phpMyAdmin SQL Dump -- version 4.1.4 -- http://www.phpmyadmin.net -- -- Client : 127.0.0.1 -- Généré le : Mer 04 Mars 2015 à 21:34 -- Version du serveur : 5.6.15-log -- Version de PHP : 5.5.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de données : `gsb_intranet` -- -- -------------------------------------------------------- -- -- Structure de la table `etat` -- CREATE TABLE IF NOT EXISTS `etat` ( `id` varchar(2) NOT NULL, `libelle` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `etat` -- INSERT INTO `etat` (`id`, `libelle`) VALUES ('CL', 'Saisie clôturée'), ('CR', 'Fiche créée, saisie en cours'), ('RB', 'Remboursée'), ('VA', 'Validée et mise en paiement'); -- -------------------------------------------------------- -- -- Structure de la table `fichefrais` -- CREATE TABLE IF NOT EXISTS `fichefrais` ( `idVisiteur` varchar(4) NOT NULL, `mois` varchar(6) NOT NULL, `nbJustificatifs` int(11) DEFAULT NULL, `montantValide` decimal(10,2) DEFAULT NULL, `dateModif` date DEFAULT NULL, `idEtat` varchar(2) DEFAULT 'CR', PRIMARY KEY (`idVisiteur`,`mois`), KEY `idEtat` (`idEtat`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `fichefrais` -- INSERT INTO `fichefrais` (`idVisiteur`, `mois`, `nbJustificatifs`, `montantValide`, `dateModif`, `idEtat`) VALUES ('4569', '201411', 0, '0.00', '2014-11-14', 'CR'), ('4569', '201501', 0, '0.00', '2015-02-02', 'CL'), ('4569', '201502', 0, '0.00', '2015-02-02', 'CR'), ('a131', '201401', 7, '4634.84', '2014-03-07', 'RB'), ('a131', '201402', 4, '4723.96', '2014-04-06', 'RB'), ('a131', '201403', 6, '6006.68', '2014-05-01', 'RB'), ('a131', '201404', 7, '3946.62', '2014-06-02', 'RB'), ('a131', '201405', 5, '3786.02', '2014-07-06', 'RB'), ('a131', '201406', 10, '4585.22', '2014-08-07', 'RB'), ('a131', '201407', 4, '1516.60', '2014-09-06', 'RB'), ('a131', '201408', 12, '5821.88', '2015-02-02', 'RB'), ('a131', '201409', 11, '0.00', '2014-09-07', 'CR'), ('a17', '201401', 3, '4350.72', '2014-03-06', 'RB'), ('a17', '201402', 10, '3629.00', '2014-04-01', 'RB'), ('a17', '201403', 3, '3085.62', '2014-05-02', 'RB'), ('a17', '201404', 0, '2183.82', '2014-06-06', 'RB'), ('a17', '201405', 12, '5552.08', '2014-07-08', 'RB'), ('a17', '201406', 2, '2935.26', '2014-08-08', 'RB'), ('a17', '201407', 7, '4555.84', '2014-09-03', 'RB'), ('a17', '201408', 2, '2460.82', '2015-02-02', 'RB'), ('a17', '201409', 12, '0.00', '2014-09-01', 'CR'), ('a17', '201410', 0, '0.00', '2014-10-10', 'CR'), ('a17', '201411', 0, '0.00', '2015-02-02', 'CL'), ('a17', '201502', 0, '0.00', '2015-02-02', 'CR'), ('a55', '201401', 8, '5921.00', '2014-03-05', 'RB'), ('a55', '201402', 9, '5305.30', '2014-04-03', 'RB'), ('a55', '201403', 6, '5661.68', '2014-05-06', 'RB'), ('a55', '201404', 11, '4149.62', '2014-06-03', 'RB'), ('a55', '201405', 7, '4100.98', '2014-07-02', 'RB'), ('a55', '201406', 7, '4039.62', '2014-08-08', 'RB'), ('a55', '201407', 4, '3786.40', '2014-09-06', 'RB'), ('a55', '201408', 1, '3033.18', '2015-02-02', 'RB'), ('a55', '201409', 12, '0.00', '2014-09-04', 'CR'), ('a93', '201401', 3, '2409.80', '2014-03-03', 'RB'), ('a93', '201402', 5, '2985.98', '2014-04-05', 'RB'), ('a93', '201403', 5, '4675.22', '2014-05-02', 'RB'), ('a93', '201404', 8, '5903.76', '2014-06-06', 'RB'), ('a93', '201405', 2, '2351.46', '2014-07-01', 'RB'), ('a93', '201406', 0, '3306.42', '2014-08-04', 'RB'), ('a93', '201407', 5, '2886.88', '2014-09-08', 'RB'), ('a93', '201408', 0, '2559.32', '2015-02-02', 'RB'), ('a93', '201409', 4, '0.00', '2014-09-01', 'CR'), ('b13', '201401', 10, '4253.34', '2014-03-07', 'RB'), ('b13', '201402', 11, '7178.02', '2014-04-02', 'RB'), ('b13', '201403', 0, '1932.36', '2014-05-04', 'RB'), ('b13', '201404', 4, '3828.74', '2014-06-01', 'RB'), ('b13', '201405', 3, '2915.50', '2014-07-08', 'RB'), ('b13', '201406', 3, '4563.64', '2014-08-04', 'RB'), ('b13', '201407', 6, '5914.26', '2014-09-06', 'RB'), ('b13', '201408', 6, '4928.60', '2015-02-02', 'RB'), ('b13', '201409', 2, '0.00', '2014-09-01', 'CR'), ('b16', '201401', 2, '3308.50', '2014-03-04', 'RB'), ('b16', '201402', 10, '5816.02', '2014-04-08', 'RB'), ('b16', '201403', 3, '3317.70', '2014-05-05', 'RB'), ('b16', '201404', 9, '4717.02', '2014-06-01', 'RB'), ('b16', '201405', 5, '3022.84', '2014-07-01', 'RB'), ('b16', '201406', 4, '2869.64', '2014-08-05', 'RB'), ('b16', '201407', 0, '2293.66', '2014-09-03', 'RB'), ('b16', '201408', 11, '5446.38', '2015-02-02', 'RB'), ('b16', '201409', 9, '0.00', '2014-09-02', 'CR'), ('b19', '201401', 7, '2590.74', '2014-03-02', 'RB'), ('b19', '201402', 12, '4909.10', '2014-04-07', 'RB'), ('b19', '201403', 5, '4181.98', '2014-05-03', 'RB'), ('b19', '201404', 4, '4545.10', '2014-06-06', 'RB'), ('b19', '201405', 4, '3584.08', '2014-07-05', 'RB'), ('b19', '201406', 10, '6326.78', '2014-08-02', 'RB'), ('b19', '201407', 12, '4969.68', '2014-09-05', 'RB'), ('b19', '201408', 6, '5234.02', '2015-02-04', 'RB'), ('b19', '201409', 3, '0.00', '2014-09-04', 'CR'), ('b25', '201401', 8, '4301.32', '2014-03-05', 'RB'), ('b25', '201402', 12, '5395.62', '2014-04-06', 'RB'), ('b25', '201403', 11, '3778.80', '2014-05-03', 'RB'), ('b25', '201404', 5, '4042.96', '2014-06-01', 'RB'), ('b25', '201405', 2, '2033.34', '2014-07-03', 'RB'), ('b25', '201406', 11, '4650.42', '2014-08-08', 'RB'), ('b25', '201407', 4, '4587.06', '2014-09-03', 'RB'), ('b25', '201408', 12, '4465.50', '2015-02-04', 'RB'), ('b25', '201409', 9, '0.00', '2014-09-08', 'CR'), ('b28', '201401', 5, '3066.08', '2014-03-06', 'RB'), ('b28', '201402', 3, '3589.56', '2014-04-07', 'RB'), ('b28', '201403', 2, '4891.90', '2014-05-01', 'RB'), ('b28', '201404', 0, '1896.96', '2014-06-08', 'RB'), ('b28', '201405', 11, '4248.22', '2014-07-02', 'RB'), ('b28', '201406', 9, '4370.92', '2014-08-05', 'RB'), ('b28', '201407', 5, '5205.16', '2014-09-02', 'RB'), ('b28', '201408', 2, '2415.18', '2015-02-04', 'RB'), ('b28', '201409', 5, '0.00', '2014-09-05', 'CR'), ('b34', '201401', 5, '5032.76', '2014-03-04', 'RB'), ('b34', '201402', 11, '5578.28', '2014-04-08', 'RB'), ('b34', '201403', 8, '5696.64', '2014-05-06', 'RB'), ('b34', '201404', 6, '4008.46', '2014-06-03', 'RB'), ('b34', '201405', 4, '4801.46', '2014-07-05', 'RB'), ('b34', '201406', 10, '4528.26', '2014-08-06', 'RB'), ('b34', '201407', 12, '5408.96', '2014-09-03', 'RB'), ('b34', '201408', 12, '5814.18', '2015-02-04', 'RB'), ('b34', '201409', 2, '0.00', '2014-09-08', 'CR'), ('b4', '201401', 11, '5238.72', '2014-03-07', 'RB'), ('b4', '201402', 10, '4796.14', '2014-04-08', 'RB'), ('b4', '201403', 9, '4337.38', '2014-05-06', 'RB'), ('b4', '201404', 9, '5663.44', '2014-06-02', 'RB'), ('b4', '201405', 8, '5408.04', '2014-07-03', 'RB'), ('b4', '201406', 12, '6300.80', '2014-08-03', 'RB'), ('b4', '201407', 3, '3879.82', '2014-09-04', 'RB'), ('b4', '201408', 12, '4954.72', '2015-02-04', 'RB'), ('b4', '201409', 5, '0.00', '2014-09-01', 'CR'), ('b50', '201401', 0, '3190.32', '2014-03-03', 'RB'), ('b50', '201402', 4, '2409.12', '2014-04-04', 'RB'), ('b50', '201403', 6, '3716.86', '2014-05-05', 'RB'), ('b50', '201404', 1, '3570.64', '2014-06-07', 'RB'), ('b50', '201405', 6, '3022.70', '2014-07-02', 'RB'), ('b50', '201406', 11, '4244.28', '2014-08-03', 'RB'), ('b50', '201407', 10, '5336.48', '2014-09-02', 'RB'), ('b50', '201408', 1, '3145.54', '2015-02-02', 'RB'), ('b50', '201409', 8, '0.00', '2014-09-07', 'CR'), ('b59', '201401', 4, '3744.92', '2014-03-07', 'RB'), ('b59', '201402', 2, '2485.96', '2014-04-05', 'RB'), ('b59', '201403', 9, '4321.30', '2014-05-07', 'RB'), ('b59', '201404', 5, '4395.04', '2014-06-03', 'RB'), ('b59', '201405', 12, '4748.80', '2014-07-02', 'RB'), ('b59', '201406', 0, '2377.68', '2014-08-08', 'RB'), ('b59', '201407', 0, '4176.92', '2014-09-01', 'RB'), ('b59', '201408', 10, '5367.00', '2015-02-05', 'RB'), ('b59', '201409', 6, '0.00', '2014-09-01', 'CR'), ('c14', '201401', 6, '4852.88', '2014-03-03', 'RB'), ('c14', '201402', 7, '3980.02', '2014-04-01', 'RB'), ('c14', '201403', 0, '2823.82', '2014-05-03', 'RB'), ('c14', '201404', 1, '3702.00', '2014-06-01', 'RB'), ('c14', '201405', 6, '2480.94', '2014-07-02', 'RB'), ('c14', '201406', 3, '3123.98', '2014-08-08', 'RB'), ('c14', '201407', 3, '3488.12', '2014-09-02', 'RB'), ('c14', '201408', 2, '3685.08', '2015-02-26', 'RB'), ('c14', '201409', 0, '0.00', '2014-09-02', 'CR'), ('c3', '201401', 4, '4163.18', '2014-03-03', 'RB'), ('c3', '201402', 2, '2984.28', '2014-04-04', 'RB'), ('c3', '201403', 4, '3059.40', '2014-05-05', 'RB'), ('c3', '201404', 7, '4364.26', '2014-06-07', 'RB'), ('c3', '201405', 5, '4221.86', '2014-07-02', 'RB'), ('c3', '201406', 10, '4768.68', '2014-08-01', 'RB'), ('c3', '201407', 0, '3192.82', '2014-09-08', 'RB'), ('c3', '201408', 2, '4679.90', '2014-09-08', 'VA'), ('c3', '201409', 3, '0.00', '2014-09-01', 'CR'), ('c54', '201401', 3, '5070.56', '2014-03-04', 'RB'), ('c54', '201402', 4, '3084.48', '2014-04-04', 'RB'), ('c54', '201403', 0, '2128.40', '2014-05-07', 'RB'), ('c54', '201404', 7, '4082.18', '2014-06-04', 'RB'), ('c54', '201405', 10, '5211.30', '2014-07-06', 'RB'), ('c54', '201406', 9, '4689.62', '2014-08-02', 'RB'), ('c54', '201407', 4, '3448.38', '2014-09-02', 'RB'), ('c54', '201408', 3, '3082.44', '2015-02-26', 'RB'), ('c54', '201409', 11, '0.00', '2014-09-04', 'CR'), ('d13', '201401', 2, '1638.00', '2014-03-03', 'RB'), ('d13', '201402', 4, '2148.60', '2014-04-01', 'RB'), ('d13', '201403', 4, '2635.18', '2014-05-04', 'RB'), ('d13', '201404', 2, '3651.36', '2014-06-02', 'RB'), ('d13', '201405', 3, '4483.86', '2014-07-05', 'RB'), ('d13', '201406', 10, '5215.92', '2014-08-03', 'RB'), ('d13', '201407', 12, '5124.16', '2014-09-08', 'RB'), ('d13', '201408', 1, '3271.30', '2015-02-26', 'RB'), ('d13', '201409', 0, '0.00', '2014-09-02', 'CR'), ('d51', '201401', 3, '4057.48', '2014-03-07', 'RB'), ('d51', '201402', 10, '3505.00', '2014-04-07', 'RB'), ('d51', '201403', 2, '3606.10', '2014-05-03', 'RB'), ('d51', '201404', 4, '5103.16', '2014-06-02', 'RB'), ('d51', '201405', 6, '4762.28', '2014-07-06', 'RB'), ('d51', '201406', 5, '3366.94', '2014-08-02', 'RB'), ('d51', '201407', 7, '3054.76', '2014-09-04', 'RB'), ('d51', '201408', 3, '3498.60', '2014-09-05', 'VA'), ('d51', '201409', 1, '0.00', '2014-09-04', 'CR'), ('e22', '201401', 7, '5112.50', '2014-03-04', 'RB'), ('e22', '201402', 8, '4381.66', '2014-04-02', 'RB'), ('e22', '201403', 12, '5608.90', '2014-05-05', 'RB'), ('e22', '201404', 9, '3887.32', '2014-06-01', 'RB'), ('e22', '201405', 3, '3995.54', '2014-07-08', 'RB'), ('e22', '201406', 1, '2681.04', '2014-08-03', 'RB'), ('e22', '201407', 1, '2118.68', '2014-09-01', 'RB'), ('e22', '201408', 0, '3332.32', '2014-09-02', 'VA'), ('e22', '201409', 5, '0.00', '2014-09-01', 'CR'), ('e24', '201401', 0, '3381.28', '2014-03-05', 'RB'), ('e24', '201402', 9, '5629.32', '2014-04-05', 'RB'), ('e24', '201403', 4, '2370.80', '2014-05-06', 'RB'), ('e24', '201404', 7, '3581.20', '2014-06-06', 'RB'), ('e24', '201405', 0, '1919.38', '2014-07-05', 'RB'), ('e24', '201406', 2, '2037.82', '2014-08-04', 'RB'), ('e24', '201407', 11, '4263.14', '2014-09-01', 'RB'), ('e24', '201408', 2, '3167.82', '2014-09-02', 'VA'), ('e24', '201409', 2, '0.00', '2014-09-05', 'CR'), ('e39', '201401', 10, '7416.56', '2014-03-06', 'RB'), ('e39', '201402', 8, '6167.72', '2014-04-01', 'RB'), ('e39', '201403', 11, '5656.92', '2014-05-05', 'RB'), ('e39', '201404', 2, '3501.16', '2014-06-02', 'RB'), ('e39', '201405', 7, '4829.78', '2014-07-02', 'RB'), ('e39', '201406', 12, '6454.78', '2014-08-04', 'RB'), ('e39', '201407', 0, '1806.26', '2014-09-06', 'RB'), ('e39', '201408', 11, '7392.08', '2014-09-07', 'VA'), ('e39', '201409', 10, '0.00', '2014-09-07', 'CR'), ('e49', '201401', 6, '3273.70', '2014-03-06', 'RB'), ('e49', '201402', 4, '5348.08', '2014-04-08', 'RB'), ('e49', '201403', 12, '6112.62', '2014-05-02', 'RB'), ('e49', '201404', 12, '5285.80', '2014-06-04', 'RB'), ('e49', '201405', 3, '3527.48', '2014-07-08', 'RB'), ('e49', '201406', 1, '4216.14', '2014-08-01', 'RB'), ('e49', '201407', 8, '5471.64', '2014-09-01', 'RB'), ('e49', '201408', 11, '5830.22', '2014-09-08', 'VA'), ('e49', '201409', 0, '0.00', '2014-09-06', 'CR'), ('e5', '201401', 6, '5308.68', '2014-03-07', 'RB'), ('e5', '201402', 1, '2424.90', '2014-04-06', 'RB'), ('e5', '201403', 4, '3480.88', '2014-05-05', 'RB'), ('e5', '201404', 12, '6462.24', '2014-06-08', 'RB'), ('e5', '201405', 0, '1418.08', '2014-07-02', 'RB'), ('e5', '201406', 6, '4117.26', '2014-08-06', 'RB'), ('e5', '201407', 1, '3676.40', '2014-09-03', 'RB'), ('e5', '201408', 1, '2665.22', '2014-09-03', 'VA'), ('e5', '201409', 9, '0.00', '2014-09-08', 'CR'), ('e52', '201401', 1, '3040.86', '2014-03-04', 'RB'), ('e52', '201402', 3, '1742.40', '2014-04-05', 'RB'), ('e52', '201403', 0, '2998.06', '2014-05-08', 'RB'), ('e52', '201404', 9, '6614.46', '2014-06-05', 'RB'), ('e52', '201405', 9, '6966.32', '2014-07-03', 'RB'), ('e52', '201406', 0, '2622.26', '2014-08-06', 'RB'), ('e52', '201407', 0, '1888.76', '2014-09-05', 'RB'), ('e52', '201408', 7, '2982.44', '2014-09-07', 'VA'), ('e52', '201409', 3, '0.00', '2014-09-01', 'CR'), ('f21', '201401', 12, '5076.98', '2014-03-07', 'RB'), ('f21', '201402', 8, '5853.70', '2014-04-04', 'RB'), ('f21', '201403', 12, '7810.90', '2014-05-02', 'RB'), ('f21', '201404', 1, '2968.82', '2014-06-02', 'RB'), ('f21', '201405', 8, '5327.94', '2014-07-07', 'RB'), ('f21', '201406', 2, '2404.12', '2014-08-02', 'RB'), ('f21', '201407', 0, '2303.22', '2014-09-01', 'RB'), ('f21', '201408', 9, '5788.48', '2014-09-05', 'VA'), ('f21', '201409', 6, '0.00', '2014-09-06', 'CR'), ('f39', '201401', 11, '6107.40', '2014-03-06', 'RB'), ('f39', '201402', 10, '4499.40', '2014-04-04', 'RB'), ('f39', '201403', 12, '5238.00', '2014-05-08', 'RB'), ('f39', '201404', 8, '6170.30', '2014-06-05', 'RB'), ('f39', '201405', 5, '2551.16', '2014-07-04', 'RB'), ('f39', '201406', 0, '4131.82', '2014-08-04', 'RB'), ('f39', '201407', 4, '3723.38', '2014-09-06', 'RB'), ('f39', '201408', 12, '5130.08', '2014-09-03', 'VA'), ('f39', '201409', 9, '0.00', '2014-09-05', 'CR'), ('f4', '201401', 10, '4450.72', '2014-03-03', 'RB'), ('f4', '201402', 3, '1913.00', '2014-04-08', 'RB'), ('f4', '201403', 1, '2992.10', '2014-05-03', 'RB'), ('f4', '201404', 12, '4560.64', '2014-06-01', 'RB'), ('f4', '201405', 4, '4171.48', '2014-07-07', 'RB'), ('f4', '201406', 11, '7482.72', '2014-08-08', 'RB'), ('f4', '201407', 11, '3509.60', '2014-09-04', 'RB'), ('f4', '201408', 3, '3145.36', '2014-09-07', 'VA'), ('f4', '201409', 11, '0.00', '2014-09-04', 'CR'); -- -------------------------------------------------------- -- -- Structure de la table `fraisforfait` -- CREATE TABLE IF NOT EXISTS `fraisforfait` ( `id` varchar(3) NOT NULL, `libelle` varchar(20) NOT NULL, `montant` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `fraisforfait` -- INSERT INTO `fraisforfait` (`id`, `libelle`, `montant`) VALUES ('ETP', 'Forfait Etape', '110.00'), ('KM', 'Frais Kilométrique', '0.62'), ('NUI', 'Nuitée Hôtel', '80.00'), ('REP', 'Repas Restaurant', '25.00'); -- -------------------------------------------------------- -- -- Structure de la table `lignefraisforfait` -- CREATE TABLE IF NOT EXISTS `lignefraisforfait` ( `idVisiteur` varchar(4) NOT NULL, `mois` varchar(6) NOT NULL, `idFraisForfait` varchar(3) NOT NULL, `quantite` int(11) DEFAULT NULL, PRIMARY KEY (`idVisiteur`,`mois`,`idFraisForfait`), KEY `idFraisForfait` (`idFraisForfait`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `lignefraisforfait` -- INSERT INTO `lignefraisforfait` (`idVisiteur`, `mois`, `idFraisForfait`, `quantite`) VALUES ('4569', '201411', 'ETP', 0), ('4569', '201411', 'KM', 0), ('4569', '201411', 'NUI', 0), ('4569', '201411', 'REP', 0), ('4569', '201501', 'ETP', 0), ('4569', '201501', 'KM', 0), ('4569', '201501', 'NUI', 0), ('4569', '201501', 'REP', 0), ('4569', '201502', 'ETP', 0), ('4569', '201502', 'KM', 0), ('4569', '201502', 'NUI', 0), ('4569', '201502', 'REP', 0), ('a131', '201401', 'ETP', 12), ('a131', '201401', 'KM', 932), ('a131', '201401', 'NUI', 16), ('a131', '201401', 'REP', 6), ('a131', '201402', 'ETP', 10), ('a131', '201402', 'KM', 758), ('a131', '201402', 'NUI', 18), ('a131', '201402', 'REP', 20), ('a131', '201403', 'ETP', 18), ('a131', '201403', 'KM', 814), ('a131', '201403', 'NUI', 12), ('a131', '201403', 'REP', 20), ('a131', '201404', 'ETP', 7), ('a131', '201404', 'KM', 901), ('a131', '201404', 'NUI', 4), ('a131', '201404', 'REP', 14), ('a131', '201405', 'ETP', 17), ('a131', '201405', 'KM', 471), ('a131', '201405', 'NUI', 10), ('a131', '201405', 'REP', 2), ('a131', '201406', 'ETP', 3), ('a131', '201406', 'KM', 731), ('a131', '201406', 'NUI', 17), ('a131', '201406', 'REP', 12), ('a131', '201407', 'ETP', 5), ('a131', '201407', 'KM', 430), ('a131', '201407', 'NUI', 4), ('a131', '201407', 'REP', 6), ('a131', '201408', 'ETP', 15), ('a131', '201408', 'KM', 774), ('a131', '201408', 'NUI', 15), ('a131', '201408', 'REP', 11), ('a131', '201409', 'ETP', 15), ('a131', '201409', 'KM', 515), ('a131', '201409', 'NUI', 10), ('a131', '201409', 'REP', 7), ('a17', '201401', 'ETP', 17), ('a17', '201401', 'KM', 856), ('a17', '201401', 'NUI', 13), ('a17', '201401', 'REP', 4), ('a17', '201402', 'ETP', 4), ('a17', '201402', 'KM', 550), ('a17', '201402', 'NUI', 3), ('a17', '201402', 'REP', 20), ('a17', '201403', 'ETP', 6), ('a17', '201403', 'KM', 801), ('a17', '201403', 'NUI', 5), ('a17', '201403', 'REP', 7), ('a17', '201404', 'ETP', 5), ('a17', '201404', 'KM', 361), ('a17', '201404', 'NUI', 17), ('a17', '201404', 'REP', 2), ('a17', '201405', 'ETP', 14), ('a17', '201405', 'KM', 434), ('a17', '201405', 'NUI', 6), ('a17', '201405', 'REP', 14), ('a17', '201406', 'ETP', 14), ('a17', '201406', 'KM', 473), ('a17', '201406', 'NUI', 8), ('a17', '201406', 'REP', 5), ('a17', '201407', 'ETP', 17), ('a17', '201407', 'KM', 982), ('a17', '201407', 'NUI', 11), ('a17', '201407', 'REP', 2), ('a17', '201408', 'ETP', 7), ('a17', '201408', 'KM', 711), ('a17', '201408', 'NUI', 11), ('a17', '201408', 'REP', 6), ('a17', '201409', 'ETP', 12), ('a17', '201409', 'KM', 867), ('a17', '201409', 'NUI', 15), ('a17', '201409', 'REP', 5), ('a17', '201410', 'ETP', 0), ('a17', '201410', 'KM', 0), ('a17', '201410', 'NUI', 0), ('a17', '201410', 'REP', 0), ('a17', '201411', 'ETP', 0), ('a17', '201411', 'KM', 0), ('a17', '201411', 'NUI', 0), ('a17', '201411', 'REP', 0), ('a17', '201502', 'ETP', 0), ('a17', '201502', 'KM', 0), ('a17', '201502', 'NUI', 0), ('a17', '201502', 'REP', 0), ('a55', '201401', 'ETP', 16), ('a55', '201401', 'KM', 900), ('a55', '201401', 'NUI', 20), ('a55', '201401', 'REP', 18), ('a55', '201402', 'ETP', 12), ('a55', '201402', 'KM', 615), ('a55', '201402', 'NUI', 13), ('a55', '201402', 'REP', 16), ('a55', '201403', 'ETP', 19), ('a55', '201403', 'KM', 864), ('a55', '201403', 'NUI', 12), ('a55', '201403', 'REP', 18), ('a55', '201404', 'ETP', 12), ('a55', '201404', 'KM', 751), ('a55', '201404', 'NUI', 2), ('a55', '201404', 'REP', 14), ('a55', '201405', 'ETP', 11), ('a55', '201405', 'KM', 429), ('a55', '201405', 'NUI', 19), ('a55', '201405', 'REP', 2), ('a55', '201406', 'ETP', 8), ('a55', '201406', 'KM', 401), ('a55', '201406', 'NUI', 13), ('a55', '201406', 'REP', 11), ('a55', '201407', 'ETP', 5), ('a55', '201407', 'KM', 820), ('a55', '201407', 'NUI', 19), ('a55', '201407', 'REP', 2), ('a55', '201408', 'ETP', 14), ('a55', '201408', 'KM', 789), ('a55', '201408', 'NUI', 5), ('a55', '201408', 'REP', 3), ('a55', '201409', 'ETP', 17), ('a55', '201409', 'KM', 461), ('a55', '201409', 'NUI', 6), ('a55', '201409', 'REP', 14), ('a93', '201401', 'ETP', 6), ('a93', '201401', 'KM', 340), ('a93', '201401', 'NUI', 10), ('a93', '201401', 'REP', 5), ('a93', '201402', 'ETP', 3), ('a93', '201402', 'KM', 579), ('a93', '201402', 'NUI', 14), ('a93', '201402', 'REP', 13), ('a93', '201403', 'ETP', 18), ('a93', '201403', 'KM', 981), ('a93', '201403', 'NUI', 5), ('a93', '201403', 'REP', 11), ('a93', '201404', 'ETP', 15), ('a93', '201404', 'KM', 998), ('a93', '201404', 'NUI', 18), ('a93', '201404', 'REP', 15), ('a93', '201405', 'ETP', 6), ('a93', '201405', 'KM', 433), ('a93', '201405', 'NUI', 4), ('a93', '201405', 'REP', 17), ('a93', '201406', 'ETP', 11), ('a93', '201406', 'KM', 841), ('a93', '201406', 'NUI', 15), ('a93', '201406', 'REP', 15), ('a93', '201407', 'ETP', 4), ('a93', '201407', 'KM', 624), ('a93', '201407', 'NUI', 2), ('a93', '201407', 'REP', 18), ('a93', '201408', 'ETP', 5), ('a93', '201408', 'KM', 636), ('a93', '201408', 'NUI', 18), ('a93', '201408', 'REP', 7), ('a93', '201409', 'ETP', 8), ('a93', '201409', 'KM', 679), ('a93', '201409', 'NUI', 14), ('a93', '201409', 'REP', 10), ('b13', '201401', 'ETP', 12), ('b13', '201401', 'KM', 907), ('b13', '201401', 'NUI', 4), ('b13', '201401', 'REP', 6), ('b13', '201402', 'ETP', 11), ('b13', '201402', 'KM', 421), ('b13', '201402', 'NUI', 15), ('b13', '201402', 'REP', 6), ('b13', '201403', 'ETP', 7), ('b13', '201403', 'KM', 778), ('b13', '201403', 'NUI', 6), ('b13', '201403', 'REP', 8), ('b13', '201404', 'ETP', 11), ('b13', '201404', 'KM', 377), ('b13', '201404', 'NUI', 20), ('b13', '201404', 'REP', 2), ('b13', '201405', 'ETP', 5), ('b13', '201405', 'KM', 775), ('b13', '201405', 'NUI', 18), ('b13', '201405', 'REP', 6), ('b13', '201406', 'ETP', 20), ('b13', '201406', 'KM', 372), ('b13', '201406', 'NUI', 6), ('b13', '201406', 'REP', 12), ('b13', '201407', 'ETP', 20), ('b13', '201407', 'KM', 723), ('b13', '201407', 'NUI', 19), ('b13', '201407', 'REP', 17), ('b13', '201408', 'ETP', 16), ('b13', '201408', 'KM', 930), ('b13', '201408', 'NUI', 5), ('b13', '201408', 'REP', 12), ('b13', '201409', 'ETP', 10), ('b13', '201409', 'KM', 446), ('b13', '201409', 'NUI', 20), ('b13', '201409', 'REP', 16), ('b16', '201401', 'ETP', 12), ('b16', '201401', 'KM', 475), ('b16', '201401', 'NUI', 13), ('b16', '201401', 'REP', 17), ('b16', '201402', 'ETP', 7), ('b16', '201402', 'KM', 471), ('b16', '201402', 'NUI', 19), ('b16', '201402', 'REP', 16), ('b16', '201403', 'ETP', 4), ('b16', '201403', 'KM', 935), ('b16', '201403', 'NUI', 6), ('b16', '201403', 'REP', 3), ('b16', '201404', 'ETP', 6), ('b16', '201404', 'KM', 621), ('b16', '201404', 'NUI', 10), ('b16', '201404', 'REP', 15), ('b16', '201405', 'ETP', 6), ('b16', '201405', 'KM', 732), ('b16', '201405', 'NUI', 17), ('b16', '201405', 'REP', 3), ('b16', '201406', 'ETP', 4), ('b16', '201406', 'KM', 722), ('b16', '201406', 'NUI', 7), ('b16', '201406', 'REP', 6), ('b16', '201407', 'ETP', 13), ('b16', '201407', 'KM', 393), ('b16', '201407', 'NUI', 4), ('b16', '201407', 'REP', 12), ('b16', '201408', 'ETP', 14), ('b16', '201408', 'KM', 599), ('b16', '201408', 'NUI', 6), ('b16', '201408', 'REP', 3), ('b16', '201409', 'ETP', 20), ('b16', '201409', 'KM', 442), ('b16', '201409', 'NUI', 19), ('b16', '201409', 'REP', 7), ('b19', '201401', 'ETP', 13), ('b19', '201401', 'KM', 777), ('b19', '201401', 'NUI', 2), ('b19', '201401', 'REP', 4), ('b19', '201402', 'ETP', 4), ('b19', '201402', 'KM', 705), ('b19', '201402', 'NUI', 18), ('b19', '201402', 'REP', 2), ('b19', '201403', 'ETP', 14), ('b19', '201403', 'KM', 379), ('b19', '201403', 'NUI', 8), ('b19', '201403', 'REP', 20), ('b19', '201404', 'ETP', 17), ('b19', '201404', 'KM', 305), ('b19', '201404', 'NUI', 17), ('b19', '201404', 'REP', 11), ('b19', '201405', 'ETP', 14), ('b19', '201405', 'KM', 634), ('b19', '201405', 'NUI', 3), ('b19', '201405', 'REP', 11), ('b19', '201406', 'ETP', 16), ('b19', '201406', 'KM', 469), ('b19', '201406', 'NUI', 10), ('b19', '201406', 'REP', 10), ('b19', '201407', 'ETP', 7), ('b19', '201407', 'KM', 664), ('b19', '201407', 'NUI', 18), ('b19', '201407', 'REP', 8), ('b19', '201408', 'ETP', 16), ('b19', '201408', 'KM', 321), ('b19', '201408', 'NUI', 12), ('b19', '201408', 'REP', 14), ('b19', '201409', 'ETP', 8), ('b19', '201409', 'KM', 995), ('b19', '201409', 'NUI', 10), ('b19', '201409', 'REP', 8), ('b25', '201401', 'ETP', 11), ('b25', '201401', 'KM', 386), ('b25', '201401', 'NUI', 18), ('b25', '201401', 'REP', 17), ('b25', '201402', 'ETP', 11), ('b25', '201402', 'KM', 751), ('b25', '201402', 'NUI', 14), ('b25', '201402', 'REP', 5), ('b25', '201403', 'ETP', 17), ('b25', '201403', 'KM', 490), ('b25', '201403', 'NUI', 5), ('b25', '201403', 'REP', 16), ('b25', '201404', 'ETP', 12), ('b25', '201404', 'KM', 458), ('b25', '201404', 'NUI', 5), ('b25', '201404', 'REP', 14), ('b25', '201405', 'ETP', 8), ('b25', '201405', 'KM', 457), ('b25', '201405', 'NUI', 4), ('b25', '201405', 'REP', 5), ('b25', '201406', 'ETP', 7), ('b25', '201406', 'KM', 641), ('b25', '201406', 'NUI', 17), ('b25', '201406', 'REP', 10), ('b25', '201407', 'ETP', 19), ('b25', '201407', 'KM', 813), ('b25', '201407', 'NUI', 13), ('b25', '201407', 'REP', 18), ('b25', '201408', 'ETP', 9), ('b25', '201408', 'KM', 425), ('b25', '201408', 'NUI', 7), ('b25', '201408', 'REP', 9), ('b25', '201409', 'ETP', 7), ('b25', '201409', 'KM', 681), ('b25', '201409', 'NUI', 6), ('b25', '201409', 'REP', 12), ('b28', '201401', 'ETP', 14), ('b28', '201401', 'KM', 334), ('b28', '201401', 'NUI', 8), ('b28', '201401', 'REP', 6), ('b28', '201402', 'ETP', 5), ('b28', '201402', 'KM', 588), ('b28', '201402', 'NUI', 18), ('b28', '201402', 'REP', 19), ('b28', '201403', 'ETP', 17), ('b28', '201403', 'KM', 895), ('b28', '201403', 'NUI', 15), ('b28', '201403', 'REP', 14), ('b28', '201404', 'ETP', 7), ('b28', '201404', 'KM', 358), ('b28', '201404', 'NUI', 6), ('b28', '201404', 'REP', 17), ('b28', '201405', 'ETP', 14), ('b28', '201405', 'KM', 531), ('b28', '201405', 'NUI', 5), ('b28', '201405', 'REP', 10), ('b28', '201406', 'ETP', 11), ('b28', '201406', 'KM', 516), ('b28', '201406', 'NUI', 2), ('b28', '201406', 'REP', 20), ('b28', '201407', 'ETP', 18), ('b28', '201407', 'KM', 468), ('b28', '201407', 'NUI', 11), ('b28', '201407', 'REP', 9), ('b28', '201408', 'ETP', 10), ('b28', '201408', 'KM', 889), ('b28', '201408', 'NUI', 2), ('b28', '201408', 'REP', 3), ('b28', '201409', 'ETP', 6), ('b28', '201409', 'KM', 531), ('b28', '201409', 'NUI', 9), ('b28', '201409', 'REP', 4), ('b34', '201401', 'ETP', 18), ('b34', '201401', 'KM', 598), ('b34', '201401', 'NUI', 20), ('b34', '201401', 'REP', 20), ('b34', '201402', 'ETP', 11), ('b34', '201402', 'KM', 544), ('b34', '201402', 'NUI', 13), ('b34', '201402', 'REP', 12), ('b34', '201403', 'ETP', 13), ('b34', '201403', 'KM', 872), ('b34', '201403', 'NUI', 14), ('b34', '201403', 'REP', 8), ('b34', '201404', 'ETP', 9), ('b34', '201404', 'KM', 333), ('b34', '201404', 'NUI', 19), ('b34', '201404', 'REP', 8), ('b34', '201405', 'ETP', 9), ('b34', '201405', 'KM', 833), ('b34', '201405', 'NUI', 17), ('b34', '201405', 'REP', 20), ('b34', '201406', 'ETP', 15), ('b34', '201406', 'KM', 423), ('b34', '201406', 'NUI', 3), ('b34', '201406', 'REP', 5), ('b34', '201407', 'ETP', 19), ('b34', '201407', 'KM', 308), ('b34', '201407', 'NUI', 4), ('b34', '201407', 'REP', 12), ('b34', '201408', 'ETP', 5), ('b34', '201408', 'KM', 639), ('b34', '201408', 'NUI', 17), ('b34', '201408', 'REP', 20), ('b34', '201409', 'ETP', 20), ('b34', '201409', 'KM', 521), ('b34', '201409', 'NUI', 10), ('b34', '201409', 'REP', 18), ('b4', '201401', 'ETP', 11), ('b4', '201401', 'KM', 806), ('b4', '201401', 'NUI', 18), ('b4', '201401', 'REP', 8), ('b4', '201402', 'ETP', 8), ('b4', '201402', 'KM', 597), ('b4', '201402', 'NUI', 10), ('b4', '201402', 'REP', 15), ('b4', '201403', 'ETP', 11), ('b4', '201403', 'KM', 749), ('b4', '201403', 'NUI', 2), ('b4', '201403', 'REP', 3), ('b4', '201404', 'ETP', 15), ('b4', '201404', 'KM', 362), ('b4', '201404', 'NUI', 20), ('b4', '201404', 'REP', 17), ('b4', '201405', 'ETP', 19), ('b4', '201405', 'KM', 992), ('b4', '201405', 'NUI', 2), ('b4', '201405', 'REP', 19), ('b4', '201406', 'ETP', 17), ('b4', '201406', 'KM', 340), ('b4', '201406', 'NUI', 14), ('b4', '201406', 'REP', 18), ('b4', '201407', 'ETP', 10), ('b4', '201407', 'KM', 661), ('b4', '201407', 'NUI', 13), ('b4', '201407', 'REP', 14), ('b4', '201408', 'ETP', 11), ('b4', '201408', 'KM', 356), ('b4', '201408', 'NUI', 7), ('b4', '201408', 'REP', 14), ('b4', '201409', 'ETP', 19), ('b4', '201409', 'KM', 981), ('b4', '201409', 'NUI', 12), ('b4', '201409', 'REP', 20), ('b50', '201401', 'ETP', 9), ('b50', '201401', 'KM', 936), ('b50', '201401', 'NUI', 14), ('b50', '201401', 'REP', 20), ('b50', '201402', 'ETP', 2), ('b50', '201402', 'KM', 376), ('b50', '201402', 'NUI', 12), ('b50', '201402', 'REP', 14), ('b50', '201403', 'ETP', 8), ('b50', '201403', 'KM', 503), ('b50', '201403', 'NUI', 11), ('b50', '201403', 'REP', 11), ('b50', '201404', 'ETP', 11), ('b50', '201404', 'KM', 772), ('b50', '201404', 'NUI', 8), ('b50', '201404', 'REP', 11), ('b50', '201405', 'ETP', 3), ('b50', '201405', 'KM', 985), ('b50', '201405', 'NUI', 11), ('b50', '201405', 'REP', 3), ('b50', '201406', 'ETP', 4), ('b50', '201406', 'KM', 594), ('b50', '201406', 'NUI', 17), ('b50', '201406', 'REP', 5), ('b50', '201407', 'ETP', 8), ('b50', '201407', 'KM', 804), ('b50', '201407', 'NUI', 11), ('b50', '201407', 'REP', 8), ('b50', '201408', 'ETP', 15), ('b50', '201408', 'KM', 367), ('b50', '201408', 'NUI', 12), ('b50', '201408', 'REP', 11), ('b50', '201409', 'ETP', 18), ('b50', '201409', 'KM', 487), ('b50', '201409', 'NUI', 6), ('b50', '201409', 'REP', 4), ('b59', '201401', 'ETP', 18), ('b59', '201401', 'KM', 616), ('b59', '201401', 'NUI', 9), ('b59', '201401', 'REP', 5), ('b59', '201402', 'ETP', 9), ('b59', '201402', 'KM', 558), ('b59', '201402', 'NUI', 9), ('b59', '201402', 'REP', 4), ('b59', '201403', 'ETP', 11), ('b59', '201403', 'KM', 465), ('b59', '201403', 'NUI', 3), ('b59', '201403', 'REP', 20), ('b59', '201404', 'ETP', 15), ('b59', '201404', 'KM', 842), ('b59', '201404', 'NUI', 16), ('b59', '201404', 'REP', 4), ('b59', '201405', 'ETP', 6), ('b59', '201405', 'KM', 440), ('b59', '201405', 'NUI', 8), ('b59', '201405', 'REP', 13), ('b59', '201406', 'ETP', 12), ('b59', '201406', 'KM', 464), ('b59', '201406', 'NUI', 4), ('b59', '201406', 'REP', 18), ('b59', '201407', 'ETP', 18), ('b59', '201407', 'KM', 366), ('b59', '201407', 'NUI', 19), ('b59', '201407', 'REP', 18), ('b59', '201408', 'ETP', 14), ('b59', '201408', 'KM', 650), ('b59', '201408', 'NUI', 5), ('b59', '201408', 'REP', 4), ('b59', '201409', 'ETP', 4), ('b59', '201409', 'KM', 768), ('b59', '201409', 'NUI', 13), ('b59', '201409', 'REP', 12), ('c14', '201401', 'ETP', 17), ('c14', '201401', 'KM', 524), ('c14', '201401', 'NUI', 14), ('c14', '201401', 'REP', 13), ('c14', '201402', 'ETP', 17), ('c14', '201402', 'KM', 771), ('c14', '201402', 'NUI', 4), ('c14', '201402', 'REP', 7), ('c14', '201403', 'ETP', 15), ('c14', '201403', 'KM', 611), ('c14', '201403', 'NUI', 9), ('c14', '201403', 'REP', 3), ('c14', '201404', 'ETP', 14), ('c14', '201404', 'KM', 900), ('c14', '201404', 'NUI', 7), ('c14', '201404', 'REP', 19), ('c14', '201405', 'ETP', 5), ('c14', '201405', 'KM', 737), ('c14', '201405', 'NUI', 3), ('c14', '201405', 'REP', 7), ('c14', '201406', 'ETP', 9), ('c14', '201406', 'KM', 979), ('c14', '201406', 'NUI', 15), ('c14', '201406', 'REP', 5), ('c14', '201407', 'ETP', 18), ('c14', '201407', 'KM', 726), ('c14', '201407', 'NUI', 11), ('c14', '201407', 'REP', 2), ('c14', '201408', 'ETP', 16), ('c14', '201408', 'KM', 834), ('c14', '201408', 'NUI', 6), ('c14', '201408', 'REP', 16), ('c14', '201409', 'ETP', 13), ('c14', '201409', 'KM', 403), ('c14', '201409', 'NUI', 8), ('c14', '201409', 'REP', 20), ('c3', '201401', 'ETP', 12), ('c3', '201401', 'KM', 989), ('c3', '201401', 'NUI', 13), ('c3', '201401', 'REP', 11), ('c3', '201402', 'ETP', 4), ('c3', '201402', 'KM', 994), ('c3', '201402', 'NUI', 9), ('c3', '201402', 'REP', 19), ('c3', '201403', 'ETP', 10), ('c3', '201403', 'KM', 570), ('c3', '201403', 'NUI', 12), ('c3', '201403', 'REP', 3), ('c3', '201404', 'ETP', 4), ('c3', '201404', 'KM', 923), ('c3', '201404', 'NUI', 10), ('c3', '201404', 'REP', 13), ('c3', '201405', 'ETP', 7), ('c3', '201405', 'KM', 803), ('c3', '201405', 'NUI', 18), ('c3', '201405', 'REP', 7), ('c3', '201406', 'ETP', 10), ('c3', '201406', 'KM', 714), ('c3', '201406', 'NUI', 5), ('c3', '201406', 'REP', 16), ('c3', '201407', 'ETP', 16), ('c3', '201407', 'KM', 811), ('c3', '201407', 'NUI', 6), ('c3', '201407', 'REP', 18), ('c3', '201408', 'ETP', 16), ('c3', '201408', 'KM', 895), ('c3', '201408', 'NUI', 9), ('c3', '201408', 'REP', 5), ('c3', '201409', 'ETP', 13), ('c3', '201409', 'KM', 419), ('c3', '201409', 'NUI', 10), ('c3', '201409', 'REP', 13), ('c54', '201401', 'ETP', 18), ('c54', '201401', 'KM', 588), ('c54', '201401', 'NUI', 16), ('c54', '201401', 'REP', 13), ('c54', '201402', 'ETP', 14), ('c54', '201402', 'KM', 854), ('c54', '201402', 'NUI', 6), ('c54', '201402', 'REP', 4), ('c54', '201403', 'ETP', 11), ('c54', '201403', 'KM', 320), ('c54', '201403', 'NUI', 4), ('c54', '201403', 'REP', 16), ('c54', '201404', 'ETP', 12), ('c54', '201404', 'KM', 539), ('c54', '201404', 'NUI', 9), ('c54', '201404', 'REP', 8), ('c54', '201405', 'ETP', 9), ('c54', '201405', 'KM', 615), ('c54', '201405', 'NUI', 6), ('c54', '201405', 'REP', 9), ('c54', '201406', 'ETP', 4), ('c54', '201406', 'KM', 701), ('c54', '201406', 'NUI', 13), ('c54', '201406', 'REP', 18), ('c54', '201407', 'ETP', 7), ('c54', '201407', 'KM', 599), ('c54', '201407', 'NUI', 16), ('c54', '201407', 'REP', 7), ('c54', '201408', 'ETP', 3), ('c54', '201408', 'KM', 462), ('c54', '201408', 'NUI', 14), ('c54', '201408', 'REP', 12), ('c54', '201409', 'ETP', 2), ('c54', '201409', 'KM', 796), ('c54', '201409', 'NUI', 12), ('c54', '201409', 'REP', 5), ('d13', '201401', 'ETP', 5), ('d13', '201401', 'KM', 350), ('d13', '201401', 'NUI', 7), ('d13', '201401', 'REP', 3), ('d13', '201402', 'ETP', 6), ('d13', '201402', 'KM', 330), ('d13', '201402', 'NUI', 6), ('d13', '201402', 'REP', 16), ('d13', '201403', 'ETP', 5), ('d13', '201403', 'KM', 889), ('d13', '201403', 'NUI', 7), ('d13', '201403', 'REP', 6), ('d13', '201404', 'ETP', 15), ('d13', '201404', 'KM', 428), ('d13', '201404', 'NUI', 14), ('d13', '201404', 'REP', 19), ('d13', '201405', 'ETP', 18), ('d13', '201405', 'KM', 503), ('d13', '201405', 'NUI', 8), ('d13', '201405', 'REP', 16), ('d13', '201406', 'ETP', 6), ('d13', '201406', 'KM', 916), ('d13', '201406', 'NUI', 12), ('d13', '201406', 'REP', 6), ('d13', '201407', 'ETP', 19), ('d13', '201407', 'KM', 418), ('d13', '201407', 'NUI', 6), ('d13', '201407', 'REP', 9), ('d13', '201408', 'ETP', 11), ('d13', '201408', 'KM', 915), ('d13', '201408', 'NUI', 14), ('d13', '201408', 'REP', 13), ('d13', '201409', 'ETP', 4), ('d13', '201409', 'KM', 459), ('d13', '201409', 'NUI', 15), ('d13', '201409', 'REP', 18), ('d51', '201401', 'ETP', 8), ('d51', '201401', 'KM', 954), ('d51', '201401', 'NUI', 15), ('d51', '201401', 'REP', 15), ('d51', '201402', 'ETP', 6), ('d51', '201402', 'KM', 450), ('d51', '201402', 'NUI', 12), ('d51', '201402', 'REP', 2), ('d51', '201403', 'ETP', 9), ('d51', '201403', 'KM', 855), ('d51', '201403', 'NUI', 11), ('d51', '201403', 'REP', 7), ('d51', '201404', 'ETP', 20), ('d51', '201404', 'KM', 918), ('d51', '201404', 'NUI', 10), ('d51', '201404', 'REP', 11), ('d51', '201405', 'ETP', 11), ('d51', '201405', 'KM', 444), ('d51', '201405', 'NUI', 15), ('d51', '201405', 'REP', 3), ('d51', '201406', 'ETP', 4), ('d51', '201406', 'KM', 987), ('d51', '201406', 'NUI', 5), ('d51', '201406', 'REP', 3), ('d51', '201407', 'ETP', 9), ('d51', '201407', 'KM', 948), ('d51', '201407', 'NUI', 5), ('d51', '201407', 'REP', 19), ('d51', '201408', 'ETP', 10), ('d51', '201408', 'KM', 480), ('d51', '201408', 'NUI', 11), ('d51', '201408', 'REP', 12), ('d51', '201409', 'ETP', 17), ('d51', '201409', 'KM', 789), ('d51', '201409', 'NUI', 12), ('d51', '201409', 'REP', 11), ('e22', '201401', 'ETP', 13), ('e22', '201401', 'KM', 625), ('e22', '201401', 'NUI', 5), ('e22', '201401', 'REP', 14), ('e22', '201402', 'ETP', 11), ('e22', '201402', 'KM', 493), ('e22', '201402', 'NUI', 14), ('e22', '201402', 'REP', 12), ('e22', '201403', 'ETP', 11), ('e22', '201403', 'KM', 545), ('e22', '201403', 'NUI', 19), ('e22', '201403', 'REP', 4), ('e22', '201404', 'ETP', 5), ('e22', '201404', 'KM', 586), ('e22', '201404', 'NUI', 6), ('e22', '201404', 'REP', 17), ('e22', '201405', 'ETP', 15), ('e22', '201405', 'KM', 767), ('e22', '201405', 'NUI', 11), ('e22', '201405', 'REP', 14), ('e22', '201406', 'ETP', 14), ('e22', '201406', 'KM', 892), ('e22', '201406', 'NUI', 2), ('e22', '201406', 'REP', 4), ('e22', '201407', 'ETP', 4), ('e22', '201407', 'KM', 414), ('e22', '201407', 'NUI', 15), ('e22', '201407', 'REP', 4), ('e22', '201408', 'ETP', 14), ('e22', '201408', 'KM', 536), ('e22', '201408', 'NUI', 17), ('e22', '201408', 'REP', 4), ('e22', '201409', 'ETP', 9), ('e22', '201409', 'KM', 712), ('e22', '201409', 'NUI', 5), ('e22', '201409', 'REP', 5), ('e24', '201401', 'ETP', 19), ('e24', '201401', 'KM', 744), ('e24', '201401', 'NUI', 6), ('e24', '201401', 'REP', 14), ('e24', '201402', 'ETP', 8), ('e24', '201402', 'KM', 786), ('e24', '201402', 'NUI', 17), ('e24', '201402', 'REP', 13), ('e24', '201403', 'ETP', 6), ('e24', '201403', 'KM', 640), ('e24', '201403', 'NUI', 5), ('e24', '201403', 'REP', 10), ('e24', '201404', 'ETP', 15), ('e24', '201404', 'KM', 460), ('e24', '201404', 'NUI', 6), ('e24', '201404', 'REP', 4), ('e24', '201405', 'ETP', 7), ('e24', '201405', 'KM', 749), ('e24', '201405', 'NUI', 7), ('e24', '201405', 'REP', 5), ('e24', '201406', 'ETP', 5), ('e24', '201406', 'KM', 961), ('e24', '201406', 'NUI', 6), ('e24', '201406', 'REP', 12), ('e24', '201407', 'ETP', 18), ('e24', '201407', 'KM', 897), ('e24', '201407', 'NUI', 9), ('e24', '201407', 'REP', 15), ('e24', '201408', 'ETP', 12), ('e24', '201408', 'KM', 711), ('e24', '201408', 'NUI', 13), ('e24', '201408', 'REP', 12), ('e24', '201409', 'ETP', 16), ('e24', '201409', 'KM', 908), ('e24', '201409', 'NUI', 5), ('e24', '201409', 'REP', 14), ('e39', '201401', 'ETP', 13), ('e39', '201401', 'KM', 938), ('e39', '201401', 'NUI', 2), ('e39', '201401', 'REP', 20), ('e39', '201402', 'ETP', 14), ('e39', '201402', 'KM', 606), ('e39', '201402', 'NUI', 10), ('e39', '201402', 'REP', 19), ('e39', '201403', 'ETP', 2), ('e39', '201403', 'KM', 766), ('e39', '201403', 'NUI', 7), ('e39', '201403', 'REP', 10), ('e39', '201404', 'ETP', 7), ('e39', '201404', 'KM', 518), ('e39', '201404', 'NUI', 19), ('e39', '201404', 'REP', 4), ('e39', '201405', 'ETP', 13), ('e39', '201405', 'KM', 719), ('e39', '201405', 'NUI', 5), ('e39', '201405', 'REP', 18), ('e39', '201406', 'ETP', 11), ('e39', '201406', 'KM', 469), ('e39', '201406', 'NUI', 8), ('e39', '201406', 'REP', 3), ('e39', '201407', 'ETP', 3), ('e39', '201407', 'KM', 623), ('e39', '201407', 'NUI', 8), ('e39', '201407', 'REP', 18), ('e39', '201408', 'ETP', 20), ('e39', '201408', 'KM', 984), ('e39', '201408', 'NUI', 11), ('e39', '201408', 'REP', 12), ('e39', '201409', 'ETP', 6), ('e39', '201409', 'KM', 302), ('e39', '201409', 'NUI', 14), ('e39', '201409', 'REP', 5), ('e49', '201401', 'ETP', 10), ('e49', '201401', 'KM', 485), ('e49', '201401', 'NUI', 4), ('e49', '201401', 'REP', 6), ('e49', '201402', 'ETP', 16), ('e49', '201402', 'KM', 984), ('e49', '201402', 'NUI', 16), ('e49', '201402', 'REP', 14), ('e49', '201403', 'ETP', 15), ('e49', '201403', 'KM', 901), ('e49', '201403', 'NUI', 19), ('e49', '201403', 'REP', 20), ('e49', '201404', 'ETP', 9), ('e49', '201404', 'KM', 390), ('e49', '201404', 'NUI', 10), ('e49', '201404', 'REP', 2), ('e49', '201405', 'ETP', 11), ('e49', '201405', 'KM', 654), ('e49', '201405', 'NUI', 15), ('e49', '201405', 'REP', 9), ('e49', '201406', 'ETP', 20), ('e49', '201406', 'KM', 447), ('e49', '201406', 'NUI', 11), ('e49', '201406', 'REP', 20), ('e49', '201407', 'ETP', 12), ('e49', '201407', 'KM', 972), ('e49', '201407', 'NUI', 5), ('e49', '201407', 'REP', 7), ('e49', '201408', 'ETP', 5), ('e49', '201408', 'KM', 981), ('e49', '201408', 'NUI', 13), ('e49', '201408', 'REP', 8), ('e49', '201409', 'ETP', 13), ('e49', '201409', 'KM', 977), ('e49', '201409', 'NUI', 4), ('e49', '201409', 'REP', 11), ('e5', '201401', 'ETP', 17), ('e5', '201401', 'KM', 414), ('e5', '201401', 'NUI', 13), ('e5', '201401', 'REP', 16), ('e5', '201402', 'ETP', 10), ('e5', '201402', 'KM', 495), ('e5', '201402', 'NUI', 7), ('e5', '201402', 'REP', 14), ('e5', '201403', 'ETP', 13), ('e5', '201403', 'KM', 674), ('e5', '201403', 'NUI', 4), ('e5', '201403', 'REP', 3), ('e5', '201404', 'ETP', 17), ('e5', '201404', 'KM', 752), ('e5', '201404', 'NUI', 10), ('e5', '201404', 'REP', 12), ('e5', '201405', 'ETP', 6), ('e5', '201405', 'KM', 884), ('e5', '201405', 'NUI', 2), ('e5', '201405', 'REP', 2), ('e5', '201406', 'ETP', 11), ('e5', '201406', 'KM', 873), ('e5', '201406', 'NUI', 6), ('e5', '201406', 'REP', 19), ('e5', '201407', 'ETP', 12), ('e5', '201407', 'KM', 870), ('e5', '201407', 'NUI', 20), ('e5', '201407', 'REP', 7), ('e5', '201408', 'ETP', 4), ('e5', '201408', 'KM', 681), ('e5', '201408', 'NUI', 12), ('e5', '201408', 'REP', 13), ('e5', '201409', 'ETP', 7), ('e5', '201409', 'KM', 457), ('e5', '201409', 'NUI', 17), ('e5', '201409', 'REP', 15), ('e52', '201401', 'ETP', 13), ('e52', '201401', 'KM', 703), ('e52', '201401', 'NUI', 3), ('e52', '201401', 'REP', 6), ('e52', '201402', 'ETP', 4), ('e52', '201402', 'KM', 870), ('e52', '201402', 'NUI', 5), ('e52', '201402', 'REP', 2), ('e52', '201403', 'ETP', 12), ('e52', '201403', 'KM', 763), ('e52', '201403', 'NUI', 11), ('e52', '201403', 'REP', 13), ('e52', '201404', 'ETP', 19), ('e52', '201404', 'KM', 533), ('e52', '201404', 'NUI', 19), ('e52', '201404', 'REP', 19), ('e52', '201405', 'ETP', 17), ('e52', '201405', 'KM', 686), ('e52', '201405', 'NUI', 15), ('e52', '201405', 'REP', 10), ('e52', '201406', 'ETP', 8), ('e52', '201406', 'KM', 673), ('e52', '201406', 'NUI', 15), ('e52', '201406', 'REP', 5), ('e52', '201407', 'ETP', 3), ('e52', '201407', 'KM', 998), ('e52', '201407', 'NUI', 8), ('e52', '201407', 'REP', 12), ('e52', '201408', 'ETP', 4), ('e52', '201408', 'KM', 412), ('e52', '201408', 'NUI', 9), ('e52', '201408', 'REP', 12), ('e52', '201409', 'ETP', 3), ('e52', '201409', 'KM', 822), ('e52', '201409', 'NUI', 5), ('e52', '201409', 'REP', 14), ('f21', '201401', 'ETP', 3), ('f21', '201401', 'KM', 979), ('f21', '201401', 'NUI', 13), ('f21', '201401', 'REP', 17), ('f21', '201402', 'ETP', 14), ('f21', '201402', 'KM', 685), ('f21', '201402', 'NUI', 20), ('f21', '201402', 'REP', 11), ('f21', '201403', 'ETP', 19), ('f21', '201403', 'KM', 795), ('f21', '201403', 'NUI', 5), ('f21', '201403', 'REP', 14), ('f21', '201404', 'ETP', 11), ('f21', '201404', 'KM', 411), ('f21', '201404', 'NUI', 11), ('f21', '201404', 'REP', 17), ('f21', '201405', 'ETP', 10), ('f21', '201405', 'KM', 387), ('f21', '201405', 'NUI', 17), ('f21', '201405', 'REP', 19), ('f21', '201406', 'ETP', 8), ('f21', '201406', 'KM', 526), ('f21', '201406', 'NUI', 11), ('f21', '201406', 'REP', 9), ('f21', '201407', 'ETP', 8), ('f21', '201407', 'KM', 981), ('f21', '201407', 'NUI', 8), ('f21', '201407', 'REP', 7), ('f21', '201408', 'ETP', 20), ('f21', '201408', 'KM', 854), ('f21', '201408', 'NUI', 15), ('f21', '201408', 'REP', 20), ('f21', '201409', 'ETP', 9), ('f21', '201409', 'KM', 1000), ('f21', '201409', 'NUI', 9), ('f21', '201409', 'REP', 11), ('f39', '201401', 'ETP', 4), ('f39', '201401', 'KM', 520), ('f39', '201401', 'NUI', 18), ('f39', '201401', 'REP', 7), ('f39', '201402', 'ETP', 8), ('f39', '201402', 'KM', 970), ('f39', '201402', 'NUI', 17), ('f39', '201402', 'REP', 8), ('f39', '201403', 'ETP', 12), ('f39', '201403', 'KM', 750), ('f39', '201403', 'NUI', 15), ('f39', '201403', 'REP', 3), ('f39', '201404', 'ETP', 19), ('f39', '201404', 'KM', 715), ('f39', '201404', 'NUI', 8), ('f39', '201404', 'REP', 12), ('f39', '201405', 'ETP', 2), ('f39', '201405', 'KM', 668), ('f39', '201405', 'NUI', 2), ('f39', '201405', 'REP', 4), ('f39', '201406', 'ETP', 19), ('f39', '201406', 'KM', 761), ('f39', '201406', 'NUI', 14), ('f39', '201406', 'REP', 18), ('f39', '201407', 'ETP', 6), ('f39', '201407', 'KM', 799), ('f39', '201407', 'NUI', 12), ('f39', '201407', 'REP', 5), ('f39', '201408', 'ETP', 3), ('f39', '201408', 'KM', 934), ('f39', '201408', 'NUI', 13), ('f39', '201408', 'REP', 2), ('f39', '201409', 'ETP', 2), ('f39', '201409', 'KM', 969), ('f39', '201409', 'NUI', 3), ('f39', '201409', 'REP', 20), ('f4', '201401', 'ETP', 4), ('f4', '201401', 'KM', 356), ('f4', '201401', 'NUI', 18), ('f4', '201401', 'REP', 18), ('f4', '201402', 'ETP', 2), ('f4', '201402', 'KM', 300), ('f4', '201402', 'NUI', 7), ('f4', '201402', 'REP', 6), ('f4', '201403', 'ETP', 17), ('f4', '201403', 'KM', 955), ('f4', '201403', 'NUI', 5), ('f4', '201403', 'REP', 2), ('f4', '201404', 'ETP', 3), ('f4', '201404', 'KM', 722), ('f4', '201404', 'NUI', 19), ('f4', '201404', 'REP', 15), ('f4', '201405', 'ETP', 19), ('f4', '201405', 'KM', 454), ('f4', '201405', 'NUI', 9), ('f4', '201405', 'REP', 8), ('f4', '201406', 'ETP', 18), ('f4', '201406', 'KM', 656), ('f4', '201406', 'NUI', 17), ('f4', '201406', 'REP', 6), ('f4', '201407', 'ETP', 4), ('f4', '201407', 'KM', 780), ('f4', '201407', 'NUI', 4), ('f4', '201407', 'REP', 11), ('f4', '201408', 'ETP', 6), ('f4', '201408', 'KM', 628), ('f4', '201408', 'NUI', 14), ('f4', '201408', 'REP', 11), ('f4', '201409', 'ETP', 7), ('f4', '201409', 'KM', 355), ('f4', '201409', 'NUI', 6), ('f4', '201409', 'REP', 6); -- -------------------------------------------------------- -- -- Structure de la table `lignefraishorsforfait` -- CREATE TABLE IF NOT EXISTS `lignefraishorsforfait` ( `id` int(11) NOT NULL AUTO_INCREMENT, `idVisiteur` varchar(4) NOT NULL, `mois` varchar(6) NOT NULL, `libelle` varchar(100) DEFAULT NULL, `date` date DEFAULT NULL, `montant` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idVisiteur` (`idVisiteur`,`mois`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1951 ; -- -- Contenu de la table `lignefraishorsforfait` -- INSERT INTO `lignefraishorsforfait` (`id`, `idVisiteur`, `mois`, `libelle`, `date`, `montant`) VALUES (1, 'a131', '201401', 'taxi', '2014-01-07', '32.00'), (2, 'a131', '201401', 'repas avec praticien', '2014-01-12', '33.00'), (3, 'a131', '201401', 'location salle conférence', '2014-01-16', '377.00'), (4, 'a131', '201401', 'taxi', '2014-01-07', '32.00'), (5, 'a131', '201401', 'rémunération intervenant/spécialiste', '2014-01-19', '678.00'), (6, 'a131', '201401', 'location véhicule', '2014-01-13', '101.00'), (7, 'a131', '201401', 'taxi', '2014-01-10', '54.00'), (8, 'a131', '201401', 'repas avec praticien', '2014-01-24', '46.00'), (9, 'a131', '201401', 'location véhicule', '2014-01-26', '294.00'), (10, 'a131', '201401', 'location équipement vidéo/sonore', '2014-01-01', '816.00'), (11, 'a131', '201401', 'Voyage SNCF', '2014-01-10', '35.00'), (12, 'a131', '201401', 'Voyage SNCF', '2014-01-19', '43.00'), (13, 'a131', '201402', 'repas avec praticien', '2014-02-08', '43.00'), (14, 'a131', '201402', 'location salle conférence', '2014-02-16', '589.00'), (15, 'a131', '201402', 'frais vestimentaire/représentation', '2014-02-26', '437.00'), (16, 'a131', '201402', 'location véhicule', '2014-02-21', '145.00'), (17, 'a131', '201402', 'location salle conférence', '2014-02-11', '122.00'), (18, 'a131', '201402', 'location véhicule', '2014-02-27', '178.00'), (19, 'a131', '201403', 'achat de matériel de papeterie', '2014-03-06', '50.00'), (20, 'a131', '201403', 'rémunération intervenant/spécialiste', '2014-03-05', '918.00'), (21, 'a131', '201403', 'rémunération intervenant/spécialiste', '2014-03-10', '837.00'), (22, 'a131', '201403', 'taxi', '2014-03-19', '72.00'), (23, 'a131', '201403', 'taxi', '2014-03-22', '21.00'), (24, 'a131', '201403', 'location salle conférence', '2014-03-26', '164.00'), (25, 'a131', '201403', 'location équipement vidéo/sonore', '2014-03-05', '128.00'), (26, 'a131', '201403', 'location équipement vidéo/sonore', '2014-03-02', '811.00'), (27, 'a131', '201403', 'achat de matériel de papeterie', '2014-03-20', '43.00'), (28, 'a131', '201403', 'traiteur, alimentation, boisson', '2014-03-01', '142.00'), (29, 'a131', '201403', 'repas avec praticien', '2014-03-08', '33.00'), (30, 'a131', '201404', 'rémunération intervenant/spécialiste', '2014-04-16', '909.00'), (31, 'a131', '201404', 'taxi', '2014-04-14', '37.00'), (32, 'a131', '201404', 'repas avec praticien', '2014-04-11', '31.00'), (33, 'a131', '201404', 'location équipement vidéo/sonore', '2014-04-19', '840.00'), (34, 'a131', '201404', 'taxi', '2014-04-26', '77.00'), (35, 'a131', '201404', 'achat de matériel de papeterie', '2014-04-17', '28.00'), (36, 'a131', '201404', 'taxi', '2014-04-16', '26.00'), (37, 'a131', '201404', 'repas avec praticien', '2014-04-26', '49.00'), (38, 'a131', '201405', 'location véhicule', '2014-05-17', '264.00'), (39, 'a131', '201405', 'location véhicule', '2014-05-21', '416.00'), (40, 'a131', '201405', 'repas avec praticien', '2014-05-22', '46.00'), (41, 'a131', '201405', 'achat de matériel de papeterie', '2014-05-26', '34.00'), (42, 'a131', '201405', 'achat de matériel de papeterie', '2014-05-25', '14.00'), (43, 'a131', '201405', 'location équipement vidéo/sonore', '2014-05-18', '619.00'), (44, 'a131', '201405', 'rémunération intervenant/spécialiste', '2014-05-02', '928.00'), (45, 'a131', '201405', 'rémunération intervenant/spécialiste', '2014-05-21', '735.00'), (46, 'a131', '201406', 'achat de matériel de papeterie', '2014-06-09', '21.00'), (47, 'a131', '201406', 'rémunération intervenant/spécialiste', '2014-06-24', '439.00'), (48, 'a131', '201406', 'Voyage SNCF', '2014-06-26', '77.00'), (49, 'a131', '201406', 'location salle conférence', '2014-06-10', '246.00'), (50, 'a131', '201406', 'taxi', '2014-06-08', '46.00'), (51, 'a131', '201406', 'rémunération intervenant/spécialiste', '2014-06-28', '777.00'), (52, 'a131', '201406', 'Voyage SNCF', '2014-06-17', '84.00'), (53, 'a131', '201406', 'rémunération intervenant/spécialiste', '2014-06-01', '452.00'), (54, 'a131', '201407', 'Voyage SNCF', '2014-07-04', '142.00'), (55, 'a131', '201407', 'achat de matériel de papeterie', '2014-07-13', '12.00'), (56, 'a131', '201407', 'Voyage SNCF', '2014-07-19', '31.00'), (57, 'a131', '201407', 'repas avec praticien', '2014-07-19', '45.00'), (58, 'a131', '201407', 'location salle conférence', '2014-07-21', '563.00'), (59, 'a131', '201407', 'frais vestimentaire/représentation', '2014-07-18', '392.00'), (60, 'a131', '201407', 'location équipement vidéo/sonore', '2014-07-05', '430.00'), (61, 'a131', '201408', 'location équipement vidéo/sonore', '2014-08-24', '128.00'), (62, 'a131', '201408', 'traiteur, alimentation, boisson', '2014-08-07', '63.00'), (63, 'a131', '201408', 'repas avec praticien', '2014-08-14', '43.00'), (64, 'a131', '201408', 'frais vestimentaire/représentation', '2014-08-17', '168.00'), (65, 'a131', '201408', 'traiteur, alimentation, boisson', '2014-08-15', '235.00'), (66, 'a131', '201408', 'achat de matériel de papeterie', '2014-08-09', '25.00'), (67, 'a131', '201408', 'location équipement vidéo/sonore', '2014-08-05', '302.00'), (68, 'a131', '201408', 'traiteur, alimentation, boisson', '2014-08-26', '219.00'), (69, 'a131', '201408', 'rémunération intervenant/spécialiste', '2014-08-02', '929.00'), (70, 'a131', '201408', 'achat de matériel de papeterie', '2014-08-15', '18.00'), (71, 'a131', '201408', 'Voyage SNCF', '2014-08-11', '87.00'), (72, 'a131', '201409', 'repas avec praticien', '2014-09-16', '38.00'), (73, 'a131', '201409', 'repas avec praticien', '2014-09-09', '49.00'), (74, 'a131', '201409', 'frais vestimentaire/représentation', '2014-09-25', '268.00'), (75, 'a131', '201409', 'frais vestimentaire/représentation', '2014-09-17', '421.00'), (76, 'a131', '201409', 'taxi', '2014-09-15', '67.00'), (77, 'a131', '201409', 'location salle conférence', '2014-09-24', '558.00'), (78, 'a131', '201409', 'Voyage SNCF', '2014-09-19', '84.00'), (79, 'a131', '201409', 'traiteur, alimentation, boisson', '2014-09-14', '379.00'), (80, 'a131', '201409', 'repas avec praticien', '2014-09-07', '50.00'), (81, 'a17', '201401', 'repas avec praticien', '2014-01-20', '50.00'), (82, 'a17', '201401', 'achat de matériel de papeterie', '2014-01-26', '29.00'), (83, 'a17', '201401', 'rémunération intervenant/spécialiste', '2014-01-13', '731.00'), (84, 'a17', '201401', 'rémunération intervenant/spécialiste', '2014-01-04', '443.00'), (85, 'a17', '201401', 'rémunération intervenant/spécialiste', '2014-01-19', '774.00'), (86, 'a17', '201401', 'achat de matériel de papeterie', '2014-01-13', '30.00'), (87, 'a17', '201401', 'repas avec praticien', '2014-01-14', '32.00'), (88, 'a17', '201401', 'rémunération intervenant/spécialiste', '2014-01-05', '1074.00'), (89, 'a17', '201402', 'repas avec praticien', '2014-02-25', '30.00'), (90, 'a17', '201402', 'traiteur, alimentation, boisson', '2014-02-02', '440.00'), (91, 'a17', '201402', 'location véhicule', '2014-02-21', '88.00'), (92, 'a17', '201402', 'taxi', '2014-02-12', '80.00'), (93, 'a17', '201402', 'taxi', '2014-02-10', '68.00'), (94, 'a17', '201402', 'rémunération intervenant/spécialiste', '2014-02-07', '909.00'), (95, 'a17', '201402', 'location salle conférence', '2014-02-13', '188.00'), (96, 'a17', '201402', 'location salle conférence', '2014-02-08', '215.00'), (97, 'a17', '201402', 'taxi', '2014-02-03', '62.00'), (98, 'a17', '201402', 'taxi', '2014-02-25', '28.00'), (99, 'a17', '201402', 'achat de matériel de papeterie', '2014-02-01', '35.00'), (100, 'a17', '201403', 'location équipement vidéo/sonore', '2014-03-01', '488.00'), (101, 'a17', '201403', 'frais vestimentaire/représentation', '2014-03-15', '426.00'), (102, 'a17', '201403', 'location véhicule', '2014-03-05', '440.00'), (103, 'a17', '201403', 'rémunération intervenant/spécialiste', '2014-03-09', '1028.00'), (104, 'a17', '201403', 'location salle conférence', '2014-03-16', '465.00'), (105, 'a17', '201404', 'location équipement vidéo/sonore', '2014-04-24', '228.00'), (106, 'a17', '201404', 'location équipement vidéo/sonore', '2014-04-06', '175.00'), (107, 'a17', '201404', 'rémunération intervenant/spécialiste', '2014-04-03', '448.00'), (108, 'a17', '201405', 'location équipement vidéo/sonore', '2014-05-03', '332.00'), (109, 'a17', '201405', 'frais vestimentaire/représentation', '2014-05-07', '395.00'), (110, 'a17', '201405', 'location véhicule', '2014-05-06', '55.00'), (111, 'a17', '201405', 'taxi', '2014-05-08', '79.00'), (112, 'a17', '201405', 'location équipement vidéo/sonore', '2014-05-07', '521.00'), (113, 'a17', '201405', 'repas avec praticien', '2014-05-02', '41.00'), (114, 'a17', '201405', 'location équipement vidéo/sonore', '2014-05-25', '273.00'), (115, 'a17', '201405', 'achat de matériel de papeterie', '2014-05-05', '32.00'), (116, 'a17', '201405', 'rémunération intervenant/spécialiste', '2014-05-08', '1127.00'), (117, 'a17', '201405', 'Voyage SNCF', '2014-05-22', '58.00'), (118, 'a17', '201406', 'location salle conférence', '2014-06-19', '337.00'), (119, 'a17', '201407', 'repas avec praticien', '2014-07-26', '44.00'), (120, 'a17', '201407', 'traiteur, alimentation, boisson', '2014-07-11', '426.00'), (121, 'a17', '201407', 'traiteur, alimentation, boisson', '2014-07-22', '296.00'), (122, 'a17', '201407', 'repas avec praticien', '2014-07-02', '41.00'), (123, 'a17', '201407', 'repas avec praticien', '2014-07-27', '46.00'), (124, 'a17', '201407', 'traiteur, alimentation, boisson', '2014-07-05', '294.00'), (125, 'a17', '201408', 'location équipement vidéo/sonore', '2014-08-09', '165.00'), (126, 'a17', '201408', 'Voyage SNCF', '2014-08-10', '55.00'), (127, 'a17', '201408', 'location équipement vidéo/sonore', '2014-08-11', '512.00'), (128, 'a17', '201408', 'location véhicule', '2014-08-27', '350.00'), (129, 'a17', '201408', 'achat de matériel de papeterie', '2014-08-21', '38.00'), (130, 'a17', '201408', 'location salle conférence', '2014-08-06', '520.00'), (131, 'a17', '201408', 'location véhicule', '2014-08-04', '57.00'), (132, 'a17', '201409', 'rémunération intervenant/spécialiste', '2014-09-17', '972.00'), (133, 'a17', '201409', 'location équipement vidéo/sonore', '2014-09-19', '366.00'), (134, 'a17', '201409', 'frais vestimentaire/représentation', '2014-09-12', '117.00'), (135, 'a17', '201409', 'location salle conférence', '2014-09-08', '446.00'), (136, 'a17', '201409', 'frais vestimentaire/représentation', '2014-09-11', '190.00'), (137, 'a17', '201409', 'location véhicule', '2014-09-06', '311.00'), (138, 'a17', '201409', 'traiteur, alimentation, boisson', '2014-09-16', '263.00'), (139, 'a17', '201409', 'repas avec praticien', '2014-09-06', '32.00'), (140, 'a17', '201409', 'taxi', '2014-09-09', '64.00'), (141, 'a17', '201409', 'frais vestimentaire/représentation', '2014-09-21', '402.00'), (142, 'a17', '201409', 'location véhicule', '2014-09-10', '232.00'), (143, 'a55', '201401', 'taxi', '2014-01-19', '60.00'), (144, 'a55', '201401', 'repas avec praticien', '2014-01-25', '35.00'), (145, 'a55', '201401', 'frais vestimentaire/représentation', '2014-01-26', '167.00'), (146, 'a55', '201401', 'rémunération intervenant/spécialiste', '2014-01-03', '447.00'), (147, 'a55', '201401', 'rémunération intervenant/spécialiste', '2014-01-15', '310.00'), (148, 'a55', '201401', 'traiteur, alimentation, boisson', '2014-01-28', '32.00'), (149, 'a55', '201401', 'taxi', '2014-01-28', '40.00'), (150, 'a55', '201401', 'rémunération intervenant/spécialiste', '2014-01-08', '462.00'), (151, 'a55', '201402', 'location équipement vidéo/sonore', '2014-02-23', '679.00'), (152, 'a55', '201402', 'rémunération intervenant/spécialiste', '2014-02-21', '860.00'), (153, 'a55', '201402', 'repas avec praticien', '2014-02-26', '31.00'), (154, 'a55', '201402', 'Voyage SNCF', '2014-02-14', '65.00'), (155, 'a55', '201402', 'location véhicule', '2014-02-18', '390.00'), (156, 'a55', '201402', 'Voyage SNCF', '2014-02-06', '41.00'), (157, 'a55', '201402', 'Voyage SNCF', '2014-02-27', '56.00'), (158, 'a55', '201402', 'repas avec praticien', '2014-02-07', '42.00'), (159, 'a55', '201403', 'location équipement vidéo/sonore', '2014-03-14', '727.00'), (160, 'a55', '201403', 'frais vestimentaire/représentation', '2014-03-13', '287.00'), (161, 'a55', '201403', 'achat de matériel de papeterie', '2014-03-27', '25.00'), (162, 'a55', '201403', 'taxi', '2014-03-13', '33.00'), (163, 'a55', '201403', 'Voyage SNCF', '2014-03-04', '90.00'), (164, 'a55', '201403', 'location équipement vidéo/sonore', '2014-03-11', '464.00'), (165, 'a55', '201403', 'Voyage SNCF', '2014-03-04', '126.00'), (166, 'a55', '201403', 'rémunération intervenant/spécialiste', '2014-03-01', '675.00'), (167, 'a55', '201403', 'location équipement vidéo/sonore', '2014-03-08', '145.00'), (168, 'a55', '201404', 'traiteur, alimentation, boisson', '2014-04-24', '322.00'), (169, 'a55', '201404', 'traiteur, alimentation, boisson', '2014-04-09', '74.00'), (170, 'a55', '201404', 'Voyage SNCF', '2014-04-13', '78.00'), (171, 'a55', '201404', 'achat de matériel de papeterie', '2014-04-09', '11.00'), (172, 'a55', '201404', 'taxi', '2014-04-25', '73.00'), (173, 'a55', '201404', 'location équipement vidéo/sonore', '2014-04-22', '459.00'), (174, 'a55', '201404', 'location véhicule', '2014-04-24', '396.00'), (175, 'a55', '201404', 'Voyage SNCF', '2014-04-27', '59.00'), (176, 'a55', '201404', 'location salle conférence', '2014-04-28', '285.00'), (177, 'a55', '201404', 'repas avec praticien', '2014-04-26', '45.00'), (178, 'a55', '201404', 'Voyage SNCF', '2014-04-17', '52.00'), (179, 'a55', '201405', 'location véhicule', '2014-05-14', '397.00'), (180, 'a55', '201405', 'frais vestimentaire/représentation', '2014-05-07', '110.00'), (181, 'a55', '201405', 'taxi', '2014-05-05', '41.00'), (182, 'a55', '201405', 'traiteur, alimentation, boisson', '2014-05-02', '186.00'), (183, 'a55', '201405', 'repas avec praticien', '2014-05-23', '48.00'), (184, 'a55', '201405', 'traiteur, alimentation, boisson', '2014-05-10', '243.00'), (185, 'a55', '201405', 'repas avec praticien', '2014-05-23', '30.00'), (186, 'a55', '201405', 'location véhicule', '2014-05-02', '429.00'), (187, 'a55', '201405', 'rémunération intervenant/spécialiste', '2014-05-04', '983.00'), (188, 'a55', '201405', 'rémunération intervenant/spécialiste', '2014-05-26', '496.00'), (189, 'a55', '201406', 'traiteur, alimentation, boisson', '2014-06-19', '173.00'), (190, 'a55', '201406', 'Voyage SNCF', '2014-06-04', '122.00'), (191, 'a55', '201406', 'location véhicule', '2014-06-25', '68.00'), (192, 'a55', '201406', 'frais vestimentaire/représentation', '2014-06-09', '108.00'), (193, 'a55', '201406', 'traiteur, alimentation, boisson', '2014-06-12', '312.00'), (194, 'a55', '201406', 'location équipement vidéo/sonore', '2014-06-03', '786.00'), (195, 'a55', '201406', 'taxi', '2014-06-21', '27.00'), (196, 'a55', '201406', 'location équipement vidéo/sonore', '2014-06-17', '295.00'), (197, 'a55', '201407', 'location véhicule', '2014-07-01', '387.00'), (198, 'a55', '201407', 'taxi', '2014-07-19', '72.00'), (199, 'a55', '201407', 'location équipement vidéo/sonore', '2014-07-28', '343.00'), (200, 'a55', '201407', 'frais vestimentaire/représentation', '2014-07-23', '356.00'), (201, 'a55', '201407', 'location équipement vidéo/sonore', '2014-07-08', '395.00'), (202, 'a55', '201407', 'achat de matériel de papeterie', '2014-07-07', '21.00'), (203, 'a55', '201407', 'achat de matériel de papeterie', '2014-07-05', '21.00'), (204, 'a55', '201407', 'achat de matériel de papeterie', '2014-07-20', '37.00'), (205, 'a55', '201408', 'location salle conférence', '2014-08-11', '529.00'), (206, 'a55', '201408', 'location véhicule', '2014-08-22', '342.00'), (207, 'a55', '201408', 'location équipement vidéo/sonore', '2014-08-09', '340.00'), (208, 'a55', '201408', 'Voyage SNCF', '2014-08-15', '129.00'), (209, 'a55', '201408', 'location véhicule', '2014-08-02', '174.00'), (210, 'a55', '201408', 'traiteur, alimentation, boisson', '2014-08-04', '295.00'), (211, 'a55', '201409', 'repas avec praticien', '2014-09-04', '36.00'), (212, 'a55', '201409', 'location équipement vidéo/sonore', '2014-09-11', '764.00'), (213, 'a55', '201409', 'taxi', '2014-09-23', '53.00'), (214, 'a55', '201409', 'location véhicule', '2014-09-03', '144.00'), (215, 'a55', '201409', 'rémunération intervenant/spécialiste', '2014-09-09', '615.00'), (216, 'a55', '201409', 'traiteur, alimentation, boisson', '2014-09-08', '431.00'), (217, 'a55', '201409', 'rémunération intervenant/spécialiste', '2014-09-06', '753.00'), (218, 'a55', '201409', 'location équipement vidéo/sonore', '2014-09-19', '743.00'), (219, 'a55', '201409', 'achat de matériel de papeterie', '2014-09-12', '26.00'), (220, 'a93', '201401', 'frais vestimentaire/représentation', '2014-01-08', '379.00'), (221, 'a93', '201401', 'taxi', '2014-01-14', '39.00'), (222, 'a93', '201401', 'location véhicule', '2014-01-16', '196.00'), (223, 'a93', '201402', 'location véhicule', '2014-02-20', '290.00'), (224, 'a93', '201402', 'frais vestimentaire/représentation', '2014-02-16', '411.00'), (225, 'a93', '201402', 'achat de matériel de papeterie', '2014-02-18', '45.00'), (226, 'a93', '201402', 'location véhicule', '2014-02-19', '106.00'), (227, 'a93', '201403', 'repas avec praticien', '2014-03-13', '37.00'), (228, 'a93', '201403', 'traiteur, alimentation, boisson', '2014-03-16', '347.00'), (229, 'a93', '201403', 'location véhicule', '2014-03-13', '327.00'), (230, 'a93', '201403', 'frais vestimentaire/représentation', '2014-03-09', '264.00'), (231, 'a93', '201403', 'location salle conférence', '2014-03-22', '437.00'), (232, 'a93', '201403', 'repas avec praticien', '2014-03-07', '50.00'), (233, 'a93', '201403', 'frais vestimentaire/représentation', '2014-03-21', '359.00'), (234, 'a93', '201403', 'taxi', '2014-03-17', '49.00'), (235, 'a93', '201403', 'frais vestimentaire/représentation', '2014-03-12', '175.00'), (236, 'a93', '201403', 'repas avec praticien', '2014-03-01', '36.00'), (237, 'a93', '201404', 'taxi', '2014-04-02', '25.00'), (238, 'a93', '201404', 'location équipement vidéo/sonore', '2014-04-28', '717.00'), (239, 'a93', '201404', 'location équipement vidéo/sonore', '2014-04-24', '554.00'), (240, 'a93', '201404', 'achat de matériel de papeterie', '2014-04-20', '13.00'), (241, 'a93', '201404', 'location véhicule', '2014-04-09', '207.00'), (242, 'a93', '201404', 'Voyage SNCF', '2014-04-27', '36.00'), (243, 'a93', '201404', 'taxi', '2014-04-27', '22.00'), (244, 'a93', '201404', 'location salle conférence', '2014-04-20', '246.00'), (245, 'a93', '201405', 'achat de matériel de papeterie', '2014-05-14', '17.00'), (246, 'a93', '201405', 'location équipement vidéo/sonore', '2014-05-12', '661.00'), (247, 'a93', '201405', 'location véhicule', '2014-05-15', '212.00'), (248, 'a93', '201405', 'location équipement vidéo/sonore', '2014-05-05', '701.00'), (249, 'a93', '201405', 'achat de matériel de papeterie', '2014-05-22', '31.00'), (250, 'a93', '201405', 'achat de matériel de papeterie', '2014-05-18', '42.00'), (251, 'a93', '201405', 'location équipement vidéo/sonore', '2014-05-09', '718.00'), (252, 'a93', '201405', 'location équipement vidéo/sonore', '2014-05-01', '538.00'), (253, 'a93', '201406', 'repas avec praticien', '2014-06-23', '43.00'), (254, 'a93', '201406', 'achat de matériel de papeterie', '2014-06-11', '17.00'), (255, 'a93', '201406', 'location salle conférence', '2014-06-02', '618.00'), (256, 'a93', '201406', 'achat de matériel de papeterie', '2014-06-28', '27.00'), (257, 'a93', '201406', 'location équipement vidéo/sonore', '2014-06-21', '686.00'), (258, 'a93', '201406', 'location véhicule', '2014-06-18', '80.00'), (259, 'a93', '201407', 'location équipement vidéo/sonore', '2014-07-15', '326.00'), (260, 'a93', '201407', 'traiteur, alimentation, boisson', '2014-07-01', '87.00'), (261, 'a93', '201407', 'location équipement vidéo/sonore', '2014-07-05', '603.00'), (262, 'a93', '201407', 'Voyage SNCF', '2014-07-26', '68.00'), (263, 'a93', '201407', 'location salle conférence', '2014-07-13', '366.00'), (264, 'a93', '201407', 'location équipement vidéo/sonore', '2014-07-04', '831.00'), (265, 'a93', '201407', 'frais vestimentaire/représentation', '2014-07-13', '145.00'), (266, 'a93', '201407', 'taxi', '2014-07-25', '37.00'), (267, 'a93', '201407', 'frais vestimentaire/représentation', '2014-07-06', '424.00'), (268, 'a93', '201407', 'Voyage SNCF', '2014-07-01', '31.00'), (269, 'a93', '201407', 'repas avec praticien', '2014-07-22', '45.00'), (270, 'a93', '201408', 'location équipement vidéo/sonore', '2014-08-24', '402.00'), (271, 'a93', '201408', 'traiteur, alimentation, boisson', '2014-08-02', '284.00'), (272, 'a93', '201408', 'rémunération intervenant/spécialiste', '2014-08-23', '918.00'), (273, 'a93', '201408', 'traiteur, alimentation, boisson', '2014-08-06', '292.00'), (274, 'a93', '201408', 'frais vestimentaire/représentation', '2014-08-28', '419.00'), (275, 'a93', '201408', 'taxi', '2014-08-28', '34.00'), (276, 'a93', '201409', 'taxi', '2014-09-22', '49.00'), (277, 'a93', '201409', 'frais vestimentaire/représentation', '2014-09-06', '240.00'), (278, 'a93', '201409', 'frais vestimentaire/représentation', '2014-09-02', '203.00'), (279, 'a93', '201409', 'frais vestimentaire/représentation', '2014-09-23', '72.00'), (280, 'b13', '201401', 'location équipement vidéo/sonore', '2014-01-26', '521.00'), (281, 'b13', '201401', 'taxi', '2014-01-28', '42.00'), (282, 'b13', '201401', 'achat de matériel de papeterie', '2014-01-22', '24.00'), (283, 'b13', '201401', 'traiteur, alimentation, boisson', '2014-01-17', '134.00'), (284, 'b13', '201401', 'traiteur, alimentation, boisson', '2014-01-19', '102.00'), (285, 'b13', '201401', 'location salle conférence', '2014-01-25', '608.00'), (286, 'b13', '201401', 'achat de matériel de papeterie', '2014-01-10', '41.00'), (287, 'b13', '201401', 'location salle conférence', '2014-01-05', '203.00'), (288, 'b13', '201401', 'frais vestimentaire/représentation', '2014-01-13', '45.00'), (289, 'b13', '201401', 'traiteur, alimentation, boisson', '2014-01-14', '181.00'), (290, 'b13', '201402', 'location salle conférence', '2014-02-26', '466.00'), (291, 'b13', '201402', 'location équipement vidéo/sonore', '2014-02-12', '660.00'), (292, 'b13', '201402', 'repas avec praticien', '2014-02-27', '30.00'), (293, 'b13', '201402', 'location équipement vidéo/sonore', '2014-02-27', '242.00'), (294, 'b13', '201402', 'repas avec praticien', '2014-02-28', '34.00'), (295, 'b13', '201402', 'frais vestimentaire/représentation', '2014-02-28', '221.00'), (296, 'b13', '201402', 'rémunération intervenant/spécialiste', '2014-02-06', '944.00'), (297, 'b13', '201402', 'traiteur, alimentation, boisson', '2014-02-22', '424.00'), (298, 'b13', '201402', 'rémunération intervenant/spécialiste', '2014-02-02', '357.00'), (299, 'b13', '201402', 'location véhicule', '2014-02-06', '438.00'), (300, 'b13', '201402', 'rémunération intervenant/spécialiste', '2014-02-13', '541.00'), (301, 'b13', '201403', 'achat de matériel de papeterie', '2014-03-04', '10.00'), (302, 'b13', '201403', 'location véhicule', '2014-03-09', '34.00'), (303, 'b13', '201403', 'location salle conférence', '2014-03-18', '162.00'), (304, 'b13', '201403', 'repas avec praticien', '2014-03-07', '37.00'), (305, 'b13', '201403', 'rémunération intervenant/spécialiste', '2014-03-12', '765.00'), (306, 'b13', '201403', 'location salle conférence', '2014-03-19', '284.00'), (307, 'b13', '201403', 'Voyage SNCF', '2014-03-10', '51.00'), (308, 'b13', '201403', 'rémunération intervenant/spécialiste', '2014-03-18', '365.00'), (309, 'b13', '201403', 'frais vestimentaire/représentation', '2014-03-07', '280.00'), (310, 'b13', '201403', 'location salle conférence', '2014-03-18', '551.00'), (311, 'b13', '201404', 'frais vestimentaire/représentation', '2014-04-23', '357.00'), (312, 'b13', '201404', 'frais vestimentaire/représentation', '2014-04-17', '238.00'), (313, 'b13', '201404', 'traiteur, alimentation, boisson', '2014-04-16', '107.00'), (314, 'b13', '201404', 'taxi', '2014-04-24', '33.00'), (315, 'b13', '201404', 'frais vestimentaire/représentation', '2014-04-05', '313.00'), (316, 'b13', '201404', 'traiteur, alimentation, boisson', '2014-04-12', '56.00'), (317, 'b13', '201404', 'Voyage SNCF', '2014-04-21', '111.00'), (318, 'b13', '201404', 'location salle conférence', '2014-04-23', '630.00'), (319, 'b13', '201405', 'repas avec praticien', '2014-05-06', '40.00'), (320, 'b13', '201405', 'traiteur, alimentation, boisson', '2014-05-23', '225.00'), (321, 'b13', '201405', 'traiteur, alimentation, boisson', '2014-05-01', '30.00'), (322, 'b13', '201405', 'location véhicule', '2014-05-10', '77.00'), (323, 'b13', '201405', 'rémunération intervenant/spécialiste', '2014-05-18', '619.00'), (324, 'b13', '201405', 'frais vestimentaire/représentation', '2014-05-12', '416.00'), (325, 'b13', '201406', 'traiteur, alimentation, boisson', '2014-06-15', '336.00'), (326, 'b13', '201406', 'location équipement vidéo/sonore', '2014-06-17', '696.00'), (327, 'b13', '201406', 'location équipement vidéo/sonore', '2014-06-08', '321.00'), (328, 'b13', '201406', 'location salle conférence', '2014-06-19', '602.00'), (329, 'b13', '201406', 'location salle conférence', '2014-06-25', '501.00'), (330, 'b13', '201407', 'frais vestimentaire/représentation', '2014-07-10', '221.00'), (331, 'b13', '201407', 'achat de matériel de papeterie', '2014-07-03', '27.00'), (332, 'b13', '201407', 'traiteur, alimentation, boisson', '2014-07-26', '248.00'), (333, 'b13', '201407', 'rémunération intervenant/spécialiste', '2014-07-27', '713.00'), (334, 'b13', '201407', 'Voyage SNCF', '2014-07-19', '112.00'), (335, 'b13', '201408', 'location équipement vidéo/sonore', '2014-08-18', '769.00'), (336, 'b13', '201408', 'Voyage SNCF', '2014-08-05', '126.00'), (337, 'b13', '201408', 'location équipement vidéo/sonore', '2014-08-18', '269.00'), (338, 'b13', '201408', 'location équipement vidéo/sonore', '2014-08-10', '640.00'), (339, 'b13', '201408', 'taxi', '2014-08-06', '55.00'), (340, 'b13', '201408', 'repas avec praticien', '2014-08-04', '33.00'), (341, 'b13', '201409', 'Voyage SNCF', '2014-09-03', '34.00'), (342, 'b13', '201409', 'location équipement vidéo/sonore', '2014-09-25', '799.00'), (343, 'b13', '201409', 'rémunération intervenant/spécialiste', '2014-09-13', '348.00'), (344, 'b16', '201401', 'traiteur, alimentation, boisson', '2014-01-15', '179.00'), (345, 'b16', '201401', 'Voyage SNCF', '2014-01-12', '50.00'), (346, 'b16', '201401', 'repas avec praticien', '2014-01-28', '49.00'), (347, 'b16', '201401', 'traiteur, alimentation, boisson', '2014-01-21', '283.00'), (348, 'b16', '201402', 'frais vestimentaire/représentation', '2014-02-27', '180.00'), (349, 'b16', '201402', 'location salle conférence', '2014-02-03', '615.00'), (350, 'b16', '201402', 'achat de matériel de papeterie', '2014-02-04', '47.00'), (351, 'b16', '201402', 'rémunération intervenant/spécialiste', '2014-02-04', '1109.00'), (352, 'b16', '201402', 'location véhicule', '2014-02-06', '195.00'), (353, 'b16', '201402', 'repas avec praticien', '2014-02-01', '45.00'), (354, 'b16', '201402', 'Voyage SNCF', '2014-02-25', '129.00'), (355, 'b16', '201402', 'taxi', '2014-02-09', '69.00'), (356, 'b16', '201402', 'rémunération intervenant/spécialiste', '2014-02-04', '445.00'), (357, 'b16', '201403', 'rémunération intervenant/spécialiste', '2014-03-18', '1189.00'), (358, 'b16', '201403', 'location salle conférence', '2014-03-06', '521.00'), (359, 'b16', '201403', 'repas avec praticien', '2014-03-13', '33.00'), (360, 'b16', '201403', 'location véhicule', '2014-03-03', '287.00'), (361, 'b16', '201403', 'rémunération intervenant/spécialiste', '2014-03-02', '896.00'), (362, 'b16', '201403', 'location salle conférence', '2014-03-19', '637.00'), (363, 'b16', '201403', 'Voyage SNCF', '2014-03-08', '40.00'), (364, 'b16', '201403', 'location salle conférence', '2014-03-11', '564.00'), (365, 'b16', '201403', 'frais vestimentaire/représentation', '2014-03-05', '73.00'), (366, 'b16', '201403', 'achat de matériel de papeterie', '2014-03-07', '17.00'), (367, 'b16', '201403', 'taxi', '2014-03-08', '69.00'), (368, 'b16', '201404', 'achat de matériel de papeterie', '2014-04-07', '14.00'), (369, 'b16', '201404', 'location équipement vidéo/sonore', '2014-04-13', '734.00'), (370, 'b16', '201404', 'Voyage SNCF', '2014-04-12', '143.00'), (371, 'b16', '201404', 'traiteur, alimentation, boisson', '2014-04-26', '77.00'), (372, 'b16', '201404', 'traiteur, alimentation, boisson', '2014-04-15', '37.00'), (373, 'b16', '201404', 'location véhicule', '2014-04-14', '255.00'), (374, 'b16', '201404', 'rémunération intervenant/spécialiste', '2014-04-02', '512.00'), (375, 'b16', '201404', 'location salle conférence', '2014-04-16', '342.00'), (376, 'b16', '201404', 'rémunération intervenant/spécialiste', '2014-04-03', '383.00'), (377, 'b16', '201404', 'location équipement vidéo/sonore', '2014-04-18', '318.00'), (378, 'b16', '201404', 'taxi', '2014-04-24', '53.00'), (379, 'b16', '201405', 'repas avec praticien', '2014-05-11', '39.00'), (380, 'b16', '201405', 'repas avec praticien', '2014-05-12', '41.00'), (381, 'b16', '201405', 'Voyage SNCF', '2014-05-28', '144.00'), (382, 'b16', '201405', 'frais vestimentaire/représentation', '2014-05-12', '174.00'), (383, 'b16', '201405', 'taxi', '2014-05-14', '76.00'), (384, 'b16', '201405', 'achat de matériel de papeterie', '2014-05-25', '36.00'), (385, 'b16', '201405', 'frais vestimentaire/représentation', '2014-05-01', '219.00'), (386, 'b16', '201405', 'location équipement vidéo/sonore', '2014-05-28', '443.00'), (387, 'b16', '201405', 'location équipement vidéo/sonore', '2014-05-01', '164.00'), (388, 'b16', '201406', 'rémunération intervenant/spécialiste', '2014-06-06', '973.00'), (389, 'b16', '201406', 'repas avec praticien', '2014-06-08', '31.00'), (390, 'b16', '201406', 'achat de matériel de papeterie', '2014-06-24', '33.00'), (391, 'b16', '201406', 'traiteur, alimentation, boisson', '2014-06-06', '235.00'), (392, 'b16', '201406', 'achat de matériel de papeterie', '2014-06-02', '26.00'), (393, 'b16', '201406', 'repas avec praticien', '2014-06-10', '33.00'), (394, 'b16', '201406', 'rémunération intervenant/spécialiste', '2014-06-12', '1175.00'), (395, 'b16', '201406', 'repas avec praticien', '2014-06-18', '48.00'), (396, 'b16', '201406', 'rémunération intervenant/spécialiste', '2014-06-09', '997.00'), (397, 'b16', '201406', 'achat de matériel de papeterie', '2014-06-14', '14.00'), (398, 'b16', '201406', 'location véhicule', '2014-06-14', '440.00'), (399, 'b16', '201407', 'frais vestimentaire/représentation', '2014-07-28', '178.00'), (400, 'b16', '201407', 'Voyage SNCF', '2014-07-24', '109.00'), (401, 'b16', '201407', 'Voyage SNCF', '2014-07-26', '125.00'), (402, 'b16', '201407', 'achat de matériel de papeterie', '2014-07-01', '50.00'), (403, 'b16', '201408', 'location salle conférence', '2014-08-05', '592.00'), (404, 'b16', '201408', 'taxi', '2014-08-12', '31.00'), (405, 'b16', '201408', 'traiteur, alimentation, boisson', '2014-08-20', '100.00'), (406, 'b16', '201408', 'location équipement vidéo/sonore', '2014-08-22', '182.00'), (407, 'b16', '201408', 'taxi', '2014-08-26', '53.00'), (408, 'b16', '201408', 'taxi', '2014-08-17', '55.00'), (409, 'b16', '201408', 'traiteur, alimentation, boisson', '2014-08-05', '179.00'), (410, 'b16', '201408', 'location salle conférence', '2014-08-09', '215.00'), (411, 'b16', '201408', 'location équipement vidéo/sonore', '2014-08-09', '842.00'), (412, 'b16', '201408', 'location équipement vidéo/sonore', '2014-08-22', '731.00'), (413, 'b16', '201409', 'frais vestimentaire/représentation', '2014-09-22', '75.00'), (414, 'b16', '201409', 'repas avec praticien', '2014-09-28', '44.00'), (415, 'b16', '201409', 'location salle conférence', '2014-09-04', '330.00'), (416, 'b16', '201409', 'taxi', '2014-09-18', '59.00'), (417, 'b16', '201409', 'frais vestimentaire/représentation', '2014-09-28', '164.00'), (418, 'b16', '201409', 'location véhicule', '2014-09-01', '204.00'), (419, 'b16', '201409', 'location salle conférence', '2014-09-08', '482.00'), (420, 'b16', '201409', 'rémunération intervenant/spécialiste', '2014-09-06', '562.00'), (421, 'b16', '201409', 'rémunération intervenant/spécialiste', '2014-09-22', '319.00'), (422, 'b19', '201401', 'taxi', '2014-01-07', '55.00'), (423, 'b19', '201401', 'Voyage SNCF', '2014-01-01', '75.00'), (424, 'b19', '201401', 'achat de matériel de papeterie', '2014-01-18', '19.00'), (425, 'b19', '201401', 'frais vestimentaire/représentation', '2014-01-10', '120.00'), (426, 'b19', '201401', 'Voyage SNCF', '2014-01-24', '150.00'), (427, 'b19', '201402', 'repas avec praticien', '2014-02-01', '33.00'), (428, 'b19', '201402', 'Voyage SNCF', '2014-02-18', '44.00'), (429, 'b19', '201402', 'frais vestimentaire/représentation', '2014-02-12', '330.00'), (430, 'b19', '201402', 'repas avec praticien', '2014-02-24', '47.00'), (431, 'b19', '201402', 'location salle conférence', '2014-02-02', '493.00'), (432, 'b19', '201402', 'rémunération intervenant/spécialiste', '2014-02-02', '358.00'), (433, 'b19', '201402', 'taxi', '2014-02-27', '61.00'), (434, 'b19', '201402', 'taxi', '2014-02-16', '57.00'), (435, 'b19', '201402', 'frais vestimentaire/représentation', '2014-02-26', '351.00'), (436, 'b19', '201402', 'rémunération intervenant/spécialiste', '2014-02-24', '725.00'), (437, 'b19', '201402', 'repas avec praticien', '2014-02-20', '43.00'), (438, 'b19', '201403', 'location salle conférence', '2014-03-21', '137.00'), (439, 'b19', '201403', 'frais vestimentaire/représentation', '2014-03-06', '254.00'), (440, 'b19', '201403', 'location salle conférence', '2014-03-17', '412.00'), (441, 'b19', '201403', 'location salle conférence', '2014-03-17', '428.00'), (442, 'b19', '201403', 'repas avec praticien', '2014-03-17', '36.00'), (443, 'b19', '201403', 'traiteur, alimentation, boisson', '2014-03-05', '94.00'), (444, 'b19', '201403', 'taxi', '2014-03-12', '44.00'), (445, 'b19', '201403', 'rémunération intervenant/spécialiste', '2014-03-16', '1163.00'), (446, 'b19', '201403', 'location véhicule', '2014-03-15', '83.00'), (447, 'b19', '201403', 'repas avec praticien', '2014-03-05', '35.00'), (448, 'b19', '201404', 'achat de matériel de papeterie', '2014-04-11', '23.00'), (449, 'b19', '201404', 'location salle conférence', '2014-04-16', '307.00'), (450, 'b19', '201404', 'location véhicule', '2014-04-23', '283.00'), (451, 'b19', '201404', 'frais vestimentaire/représentation', '2014-04-08', '238.00'), (452, 'b19', '201405', 'repas avec praticien', '2014-05-18', '40.00'), (453, 'b19', '201405', 'location salle conférence', '2014-05-15', '432.00'), (454, 'b19', '201405', 'location véhicule', '2014-05-17', '407.00'), (455, 'b19', '201405', 'traiteur, alimentation, boisson', '2014-05-19', '257.00'), (456, 'b19', '201405', 'location salle conférence', '2014-05-20', '353.00'), (457, 'b19', '201405', 'location salle conférence', '2014-05-09', '232.00'), (458, 'b19', '201405', 'repas avec praticien', '2014-05-11', '41.00'), (459, 'b19', '201406', 'frais vestimentaire/représentation', '2014-06-27', '364.00'), (460, 'b19', '201406', 'location équipement vidéo/sonore', '2014-06-17', '797.00'), (461, 'b19', '201406', 'location équipement vidéo/sonore', '2014-06-24', '502.00'), (462, 'b19', '201406', 'location véhicule', '2014-06-01', '289.00'), (463, 'b19', '201406', 'frais vestimentaire/représentation', '2014-06-02', '304.00'), (464, 'b19', '201406', 'location équipement vidéo/sonore', '2014-06-15', '199.00'), (465, 'b19', '201406', 'rémunération intervenant/spécialiste', '2014-06-10', '646.00'), (466, 'b19', '201406', 'Voyage SNCF', '2014-06-16', '125.00'), (467, 'b19', '201407', 'repas avec praticien', '2014-07-10', '41.00'), (468, 'b19', '201407', 'frais vestimentaire/représentation', '2014-07-10', '36.00'), (469, 'b19', '201407', 'location équipement vidéo/sonore', '2014-07-17', '420.00'), (470, 'b19', '201407', 'taxi', '2014-07-10', '78.00'), (471, 'b19', '201407', 'achat de matériel de papeterie', '2014-07-08', '19.00'), (472, 'b19', '201407', 'traiteur, alimentation, boisson', '2014-07-03', '353.00'), (473, 'b19', '201407', 'location salle conférence', '2014-07-24', '345.00'), (474, 'b19', '201407', 'location équipement vidéo/sonore', '2014-07-22', '482.00'), (475, 'b19', '201407', 'frais vestimentaire/représentation', '2014-07-22', '330.00'), (476, 'b19', '201407', 'achat de matériel de papeterie', '2014-07-28', '44.00'), (477, 'b19', '201408', 'rémunération intervenant/spécialiste', '2014-08-17', '937.00'), (478, 'b19', '201408', 'location véhicule', '2014-08-14', '28.00'), (479, 'b19', '201408', 'Voyage SNCF', '2014-08-28', '140.00'), (480, 'b19', '201408', 'location salle conférence', '2014-08-25', '236.00'), (481, 'b19', '201408', 'location équipement vidéo/sonore', '2014-08-19', '440.00'), (482, 'b19', '201408', 'location salle conférence', '2014-08-25', '184.00'), (483, 'b19', '201408', 'Voyage SNCF', '2014-08-26', '52.00'), (484, 'b19', '201408', 'location équipement vidéo/sonore', '2014-08-20', '664.00'), (485, 'b19', '201408', 'traiteur, alimentation, boisson', '2014-08-12', '70.00'), (486, 'b19', '201409', 'taxi', '2014-09-24', '69.00'), (487, 'b19', '201409', 'repas avec praticien', '2014-09-05', '47.00'), (488, 'b19', '201409', 'location véhicule', '2014-09-01', '162.00'), (489, 'b19', '201409', 'location véhicule', '2014-09-04', '412.00'), (490, 'b19', '201409', 'frais vestimentaire/représentation', '2014-09-21', '90.00'), (491, 'b19', '201409', 'location salle conférence', '2014-09-21', '174.00'), (492, 'b19', '201409', 'rémunération intervenant/spécialiste', '2014-09-19', '931.00'), (493, 'b19', '201409', 'location véhicule', '2014-09-26', '292.00'), (494, 'b19', '201409', 'taxi', '2014-09-26', '28.00'), (495, 'b19', '201409', 'Voyage SNCF', '2014-09-26', '129.00'), (496, 'b19', '201409', 'location salle conférence', '2014-09-03', '401.00'), (497, 'b25', '201401', 'taxi', '2014-01-01', '62.00'), (498, 'b25', '201401', 'Voyage SNCF', '2014-01-22', '106.00'), (499, 'b25', '201401', 'frais vestimentaire/représentation', '2014-01-12', '160.00'), (500, 'b25', '201401', 'location salle conférence', '2014-01-05', '167.00'), (501, 'b25', '201401', 'taxi', '2014-01-28', '73.00'), (502, 'b25', '201401', 'achat de matériel de papeterie', '2014-01-04', '21.00'), (503, 'b25', '201401', 'Voyage SNCF', '2014-01-10', '136.00'), (504, 'b25', '201401', 'location salle conférence', '2014-01-12', '262.00'), (505, 'b25', '201401', 'traiteur, alimentation, boisson', '2014-01-04', '324.00'), (506, 'b25', '201401', 'traiteur, alimentation, boisson', '2014-01-03', '366.00'), (507, 'b25', '201402', 'traiteur, alimentation, boisson', '2014-02-08', '174.00'), (508, 'b25', '201402', 'frais vestimentaire/représentation', '2014-02-03', '273.00'), (509, 'b25', '201402', 'Voyage SNCF', '2014-02-18', '76.00'), (510, 'b25', '201402', 'traiteur, alimentation, boisson', '2014-02-13', '268.00'), (511, 'b25', '201402', 'achat de matériel de papeterie', '2014-02-18', '11.00'), (512, 'b25', '201402', 'frais vestimentaire/représentation', '2014-02-26', '39.00'), (513, 'b25', '201402', 'location salle conférence', '2014-02-25', '308.00'), (514, 'b25', '201402', 'location salle conférence', '2014-02-12', '208.00'), (515, 'b25', '201402', 'traiteur, alimentation, boisson', '2014-02-17', '446.00'), (516, 'b25', '201402', 'Voyage SNCF', '2014-02-25', '105.00'), (517, 'b25', '201402', 'location véhicule', '2014-02-28', '206.00'), (518, 'b25', '201402', 'traiteur, alimentation, boisson', '2014-02-17', '361.00'), (519, 'b25', '201403', 'taxi', '2014-03-22', '52.00'), (520, 'b25', '201403', 'repas avec praticien', '2014-03-23', '39.00'), (521, 'b25', '201403', 'location salle conférence', '2014-03-08', '179.00'), (522, 'b25', '201403', 'location véhicule', '2014-03-12', '116.00'), (523, 'b25', '201403', 'Voyage SNCF', '2014-03-28', '140.00'), (524, 'b25', '201403', 'taxi', '2014-03-16', '26.00'), (525, 'b25', '201403', 'traiteur, alimentation, boisson', '2014-03-22', '253.00'), (526, 'b25', '201404', 'traiteur, alimentation, boisson', '2014-04-19', '144.00'), (527, 'b25', '201404', 'frais vestimentaire/représentation', '2014-04-28', '319.00'), (528, 'b25', '201404', 'location véhicule', '2014-04-24', '426.00'), (529, 'b25', '201404', 'rémunération intervenant/spécialiste', '2014-04-06', '372.00'), (530, 'b25', '201404', 'frais vestimentaire/représentation', '2014-04-04', '428.00'), (531, 'b25', '201404', 'location salle conférence', '2014-04-04', '542.00'), (532, 'b25', '201404', 'location salle conférence', '2014-04-02', '173.00'), (533, 'b25', '201405', 'Voyage SNCF', '2014-05-13', '50.00'), (534, 'b25', '201405', 'location véhicule', '2014-05-19', '375.00'), (535, 'b25', '201405', 'achat de matériel de papeterie', '2014-05-13', '38.00'), (536, 'b25', '201405', 'taxi', '2014-05-11', '74.00'), (537, 'b25', '201405', 'location équipement vidéo/sonore', '2014-05-26', '772.00'), (538, 'b25', '201405', 'location équipement vidéo/sonore', '2014-05-09', '669.00'), (539, 'b25', '201405', 'location véhicule', '2014-05-26', '166.00'), (540, 'b25', '201405', 'Voyage SNCF', '2014-05-22', '42.00'), (541, 'b25', '201405', 'taxi', '2014-05-07', '28.00'), (542, 'b25', '201406', 'repas avec praticien', '2014-06-14', '35.00'), (543, 'b25', '201406', 'traiteur, alimentation, boisson', '2014-06-28', '287.00'), (544, 'b25', '201406', 'frais vestimentaire/représentation', '2014-06-06', '353.00'), (545, 'b25', '201406', 'location salle conférence', '2014-06-22', '208.00'), (546, 'b25', '201406', 'location salle conférence', '2014-06-08', '323.00'), (547, 'b25', '201406', 'location équipement vidéo/sonore', '2014-06-21', '233.00'), (548, 'b25', '201406', 'location véhicule', '2014-06-21', '230.00'), (549, 'b25', '201406', 'repas avec praticien', '2014-06-05', '50.00'), (550, 'b25', '201406', 'frais vestimentaire/représentation', '2014-06-08', '95.00'), (551, 'b25', '201406', 'Voyage SNCF', '2014-06-19', '59.00'), (552, 'b25', '201407', 'location équipement vidéo/sonore', '2014-07-13', '381.00'), (553, 'b25', '201407', 'taxi', '2014-07-20', '56.00'), (554, 'b25', '201407', 'repas avec praticien', '2014-07-08', '42.00'), (555, 'b25', '201407', 'achat de matériel de papeterie', '2014-07-14', '24.00'), (556, 'b25', '201407', 'Voyage SNCF', '2014-07-25', '137.00'), (557, 'b25', '201407', 'repas avec praticien', '2014-07-26', '39.00'), (558, 'b25', '201407', 'traiteur, alimentation, boisson', '2014-07-27', '346.00'), (559, 'b25', '201407', 'Voyage SNCF', '2014-07-23', '150.00'), (560, 'b25', '201407', 'achat de matériel de papeterie', '2014-07-01', '33.00'), (561, 'b25', '201407', 'location équipement vidéo/sonore', '2014-07-11', '613.00'), (562, 'b25', '201407', 'achat de matériel de papeterie', '2014-07-26', '41.00'), (563, 'b25', '201408', 'taxi', '2014-08-14', '41.00'), (564, 'b25', '201408', 'taxi', '2014-08-18', '77.00'), (565, 'b25', '201408', 'rémunération intervenant/spécialiste', '2014-08-04', '602.00'), (566, 'b25', '201408', 'taxi', '2014-08-20', '25.00'), (567, 'b25', '201408', 'taxi', '2014-08-02', '27.00'), (568, 'b25', '201408', 'repas avec praticien', '2014-08-02', '37.00'), (569, 'b25', '201408', 'taxi', '2014-08-24', '61.00'), (570, 'b25', '201408', 'repas avec praticien', '2014-08-15', '49.00'), (571, 'b25', '201408', 'rémunération intervenant/spécialiste', '2014-08-21', '895.00'), (572, 'b25', '201408', 'location véhicule', '2014-08-03', '201.00'), (573, 'b25', '201408', 'frais vestimentaire/représentation', '2014-08-27', '280.00'), (574, 'b25', '201408', 'location véhicule', '2014-08-01', '132.00'), (575, 'b25', '201409', 'repas avec praticien', '2014-09-01', '48.00'), (576, 'b25', '201409', 'location équipement vidéo/sonore', '2014-09-17', '296.00'), (577, 'b25', '201409', 'location véhicule', '2014-09-18', '250.00'), (578, 'b25', '201409', 'Voyage SNCF', '2014-09-28', '92.00'), (579, 'b25', '201409', 'rémunération intervenant/spécialiste', '2014-09-07', '690.00'), (580, 'b25', '201409', 'traiteur, alimentation, boisson', '2014-09-17', '289.00'), (581, 'b25', '201409', 'location véhicule', '2014-09-27', '150.00'), (582, 'b25', '201409', 'rémunération intervenant/spécialiste', '2014-09-18', '968.00'), (583, 'b25', '201409', 'location équipement vidéo/sonore', '2014-09-22', '732.00'), (584, 'b25', '201409', 'Voyage SNCF', '2014-09-25', '113.00'), (585, 'b25', '201409', 'taxi', '2014-09-23', '43.00'), (586, 'b28', '201401', 'repas avec praticien', '2014-01-20', '36.00'), (587, 'b28', '201401', 'frais vestimentaire/représentation', '2014-01-19', '220.00'), (588, 'b28', '201401', 'Voyage SNCF', '2014-01-11', '135.00'), (589, 'b28', '201401', 'Voyage SNCF', '2014-01-16', '121.00'), (590, 'b28', '201401', 'achat de matériel de papeterie', '2014-01-17', '17.00'), (591, 'b28', '201402', 'traiteur, alimentation, boisson', '2014-02-17', '346.00'), (592, 'b28', '201402', 'location salle conférence', '2014-02-20', '124.00'), (593, 'b28', '201402', 'location véhicule', '2014-02-10', '290.00'), (594, 'b28', '201402', 'frais vestimentaire/représentation', '2014-02-12', '415.00'), (595, 'b28', '201403', 'frais vestimentaire/représentation', '2014-03-01', '432.00'), (596, 'b28', '201403', 'location salle conférence', '2014-03-15', '485.00'), (597, 'b28', '201403', 'achat de matériel de papeterie', '2014-03-19', '26.00'), (598, 'b28', '201403', 'location équipement vidéo/sonore', '2014-03-18', '168.00'), (599, 'b28', '201403', 'location véhicule', '2014-03-14', '98.00'), (600, 'b28', '201403', 'location salle conférence', '2014-03-26', '464.00'), (601, 'b28', '201403', 'traiteur, alimentation, boisson', '2014-03-03', '296.00'), (602, 'b28', '201403', 'traiteur, alimentation, boisson', '2014-03-18', '74.00'), (603, 'b28', '201403', 'traiteur, alimentation, boisson', '2014-03-08', '133.00'), (604, 'b28', '201403', 'taxi', '2014-03-15', '33.00'), (605, 'b28', '201403', 'location équipement vidéo/sonore', '2014-03-10', '715.00'), (606, 'b28', '201404', 'location véhicule', '2014-04-27', '107.00'), (607, 'b28', '201404', 'location équipement vidéo/sonore', '2014-04-21', '310.00'), (608, 'b28', '201404', 'traiteur, alimentation, boisson', '2014-04-06', '178.00'), (609, 'b28', '201404', 'taxi', '2014-04-28', '24.00'), (610, 'b28', '201404', 'rémunération intervenant/spécialiste', '2014-04-03', '1111.00'), (611, 'b28', '201405', 'frais vestimentaire/représentation', '2014-05-18', '307.00'), (612, 'b28', '201405', 'location salle conférence', '2014-05-23', '152.00'), (613, 'b28', '201405', 'traiteur, alimentation, boisson', '2014-05-15', '193.00'), (614, 'b28', '201405', 'repas avec praticien', '2014-05-18', '33.00'), (615, 'b28', '201405', 'location salle conférence', '2014-05-10', '459.00'), (616, 'b28', '201405', 'achat de matériel de papeterie', '2014-05-08', '22.00'), (617, 'b28', '201405', 'location salle conférence', '2014-05-10', '282.00'), (618, 'b28', '201405', 'achat de matériel de papeterie', '2014-05-06', '18.00'), (619, 'b28', '201405', 'achat de matériel de papeterie', '2014-05-03', '10.00'), (620, 'b28', '201405', 'taxi', '2014-05-03', '64.00'), (621, 'b28', '201405', 'frais vestimentaire/représentation', '2014-05-21', '189.00'), (622, 'b28', '201406', 'repas avec praticien', '2014-06-07', '32.00'), (623, 'b28', '201406', 'taxi', '2014-06-13', '33.00'), (624, 'b28', '201406', 'location véhicule', '2014-06-25', '110.00'), (625, 'b28', '201406', 'location équipement vidéo/sonore', '2014-06-08', '596.00'), (626, 'b28', '201406', 'location véhicule', '2014-06-08', '80.00'), (627, 'b28', '201406', 'achat de matériel de papeterie', '2014-06-27', '29.00'), (628, 'b28', '201406', 'rémunération intervenant/spécialiste', '2014-06-17', '1195.00'), (629, 'b28', '201406', 'achat de matériel de papeterie', '2014-06-17', '37.00'), (630, 'b28', '201406', 'Voyage SNCF', '2014-06-06', '69.00'), (631, 'b28', '201407', 'achat de matériel de papeterie', '2014-07-25', '24.00'), (632, 'b28', '201407', 'location salle conférence', '2014-07-20', '528.00'), (633, 'b28', '201407', 'location équipement vidéo/sonore', '2014-07-08', '470.00'), (634, 'b28', '201407', 'location salle conférence', '2014-07-07', '430.00'), (635, 'b28', '201407', 'frais vestimentaire/représentation', '2014-07-09', '378.00'), (636, 'b28', '201407', 'location équipement vidéo/sonore', '2014-07-01', '663.00'), (637, 'b28', '201408', 'location véhicule', '2014-08-13', '413.00'), (638, 'b28', '201408', 'Voyage SNCF', '2014-08-09', '116.00'), (639, 'b28', '201408', 'repas avec praticien', '2014-08-02', '42.00'), (640, 'b28', '201408', 'repas avec praticien', '2014-08-06', '44.00'), (641, 'b28', '201408', 'location salle conférence', '2014-08-26', '412.00'), (642, 'b28', '201408', 'achat de matériel de papeterie', '2014-08-19', '40.00'), (643, 'b28', '201408', 'rémunération intervenant/spécialiste', '2014-08-20', '423.00'), (644, 'b28', '201409', 'Voyage SNCF', '2014-09-10', '119.00'), (645, 'b28', '201409', 'achat de matériel de papeterie', '2014-09-23', '10.00'), (646, 'b28', '201409', 'location véhicule', '2014-09-09', '276.00'), (647, 'b28', '201409', 'location salle conférence', '2014-09-25', '537.00'), (648, 'b34', '201401', 'Voyage SNCF', '2014-01-07', '48.00'), (649, 'b34', '201401', 'location véhicule', '2014-01-25', '309.00'), (650, 'b34', '201401', 'taxi', '2014-01-12', '56.00'), (651, 'b34', '201401', 'Voyage SNCF', '2014-01-20', '35.00'), (652, 'b34', '201401', 'Voyage SNCF', '2014-01-05', '134.00'), (653, 'b34', '201401', 'location véhicule', '2014-01-15', '154.00'), (654, 'b34', '201401', 'location équipement vidéo/sonore', '2014-01-19', '389.00'), (655, 'b34', '201401', 'location salle conférence', '2014-01-27', '304.00'), (656, 'b34', '201402', 'repas avec praticien', '2014-02-22', '31.00'), (657, 'b34', '201402', 'frais vestimentaire/représentation', '2014-02-16', '196.00'), (658, 'b34', '201402', 'traiteur, alimentation, boisson', '2014-02-25', '447.00'), (659, 'b34', '201402', 'location véhicule', '2014-02-28', '275.00'), (660, 'b34', '201402', 'Voyage SNCF', '2014-02-15', '93.00'), (661, 'b34', '201402', 'traiteur, alimentation, boisson', '2014-02-12', '311.00'), (662, 'b34', '201402', 'repas avec praticien', '2014-02-15', '40.00'), (663, 'b34', '201402', 'taxi', '2014-02-15', '51.00'), (664, 'b34', '201402', 'rémunération intervenant/spécialiste', '2014-02-23', '1173.00'), (665, 'b34', '201402', 'frais vestimentaire/représentation', '2014-02-22', '74.00'), (666, 'b34', '201403', 'traiteur, alimentation, boisson', '2014-03-26', '304.00'), (667, 'b34', '201403', 'Voyage SNCF', '2014-03-05', '126.00'), (668, 'b34', '201403', 'rémunération intervenant/spécialiste', '2014-03-05', '1139.00'), (669, 'b34', '201403', 'location équipement vidéo/sonore', '2014-03-07', '373.00'); INSERT INTO `lignefraishorsforfait` (`id`, `idVisiteur`, `mois`, `libelle`, `date`, `montant`) VALUES (670, 'b34', '201403', 'location véhicule', '2014-03-01', '132.00'), (671, 'b34', '201403', 'achat de matériel de papeterie', '2014-03-19', '39.00'), (672, 'b34', '201403', 'Voyage SNCF', '2014-03-11', '39.00'), (673, 'b34', '201403', 'traiteur, alimentation, boisson', '2014-03-12', '254.00'), (674, 'b34', '201403', 'taxi', '2014-03-10', '32.00'), (675, 'b34', '201403', 'repas avec praticien', '2014-03-01', '35.00'), (676, 'b34', '201403', 'traiteur, alimentation, boisson', '2014-03-27', '104.00'), (677, 'b34', '201404', 'traiteur, alimentation, boisson', '2014-04-08', '360.00'), (678, 'b34', '201404', 'achat de matériel de papeterie', '2014-04-05', '50.00'), (679, 'b34', '201404', 'rémunération intervenant/spécialiste', '2014-04-01', '454.00'), (680, 'b34', '201404', 'achat de matériel de papeterie', '2014-04-25', '16.00'), (681, 'b34', '201404', 'location salle conférence', '2014-04-05', '169.00'), (682, 'b34', '201404', 'taxi', '2014-04-24', '43.00'), (683, 'b34', '201405', 'location équipement vidéo/sonore', '2014-05-21', '586.00'), (684, 'b34', '201405', 'achat de matériel de papeterie', '2014-05-12', '43.00'), (685, 'b34', '201405', 'traiteur, alimentation, boisson', '2014-05-23', '238.00'), (686, 'b34', '201405', 'location salle conférence', '2014-05-09', '568.00'), (687, 'b34', '201405', 'location véhicule', '2014-05-07', '407.00'), (688, 'b34', '201405', 'Voyage SNCF', '2014-05-15', '97.00'), (689, 'b34', '201405', 'achat de matériel de papeterie', '2014-05-01', '30.00'), (690, 'b34', '201405', 'traiteur, alimentation, boisson', '2014-05-10', '215.00'), (691, 'b34', '201405', 'location véhicule', '2014-05-13', '313.00'), (692, 'b34', '201406', 'achat de matériel de papeterie', '2014-06-28', '15.00'), (693, 'b34', '201406', 'location équipement vidéo/sonore', '2014-06-18', '393.00'), (694, 'b34', '201406', 'location salle conférence', '2014-06-23', '576.00'), (695, 'b34', '201406', 'location salle conférence', '2014-06-18', '445.00'), (696, 'b34', '201406', 'frais vestimentaire/représentation', '2014-06-25', '84.00'), (697, 'b34', '201406', 'Voyage SNCF', '2014-06-03', '143.00'), (698, 'b34', '201406', 'repas avec praticien', '2014-06-09', '41.00'), (699, 'b34', '201406', 'frais vestimentaire/représentation', '2014-06-06', '255.00'), (700, 'b34', '201406', 'taxi', '2014-06-04', '78.00'), (701, 'b34', '201406', 'location salle conférence', '2014-06-23', '221.00'), (702, 'b34', '201406', 'achat de matériel de papeterie', '2014-06-11', '34.00'), (703, 'b34', '201407', 'Voyage SNCF', '2014-07-10', '128.00'), (704, 'b34', '201407', 'Voyage SNCF', '2014-07-14', '89.00'), (705, 'b34', '201407', 'taxi', '2014-07-28', '34.00'), (706, 'b34', '201407', 'traiteur, alimentation, boisson', '2014-07-21', '242.00'), (707, 'b34', '201407', 'achat de matériel de papeterie', '2014-07-15', '21.00'), (708, 'b34', '201407', 'location salle conférence', '2014-07-09', '251.00'), (709, 'b34', '201407', 'location équipement vidéo/sonore', '2014-07-07', '672.00'), (710, 'b34', '201407', 'achat de matériel de papeterie', '2014-07-26', '22.00'), (711, 'b34', '201407', 'location véhicule', '2014-07-18', '135.00'), (712, 'b34', '201407', 'repas avec praticien', '2014-07-12', '35.00'), (713, 'b34', '201407', 'rémunération intervenant/spécialiste', '2014-07-07', '879.00'), (714, 'b34', '201408', 'frais vestimentaire/représentation', '2014-08-27', '422.00'), (715, 'b34', '201408', 'rémunération intervenant/spécialiste', '2014-08-12', '702.00'), (716, 'b34', '201408', 'achat de matériel de papeterie', '2014-08-17', '12.00'), (717, 'b34', '201408', 'taxi', '2014-08-25', '25.00'), (718, 'b34', '201408', 'location salle conférence', '2014-08-20', '229.00'), (719, 'b34', '201408', 'location salle conférence', '2014-08-04', '436.00'), (720, 'b34', '201408', 'repas avec praticien', '2014-08-21', '45.00'), (721, 'b34', '201408', 'traiteur, alimentation, boisson', '2014-08-18', '46.00'), (722, 'b34', '201408', 'rémunération intervenant/spécialiste', '2014-08-11', '706.00'), (723, 'b34', '201408', 'location véhicule', '2014-08-11', '344.00'), (724, 'b34', '201408', 'repas avec praticien', '2014-08-24', '41.00'), (725, 'b34', '201409', 'rémunération intervenant/spécialiste', '2014-09-07', '720.00'), (726, 'b34', '201409', 'Voyage SNCF', '2014-09-26', '84.00'), (727, 'b34', '201409', 'location équipement vidéo/sonore', '2014-09-24', '152.00'), (728, 'b34', '201409', 'Voyage SNCF', '2014-09-15', '141.00'), (729, 'b4', '201401', 'location salle conférence', '2014-01-23', '330.00'), (730, 'b4', '201401', 'Voyage SNCF', '2014-01-17', '88.00'), (731, 'b4', '201401', 'traiteur, alimentation, boisson', '2014-01-09', '31.00'), (732, 'b4', '201401', 'location véhicule', '2014-01-20', '189.00'), (733, 'b4', '201401', 'location équipement vidéo/sonore', '2014-01-02', '236.00'), (734, 'b4', '201401', 'traiteur, alimentation, boisson', '2014-01-19', '88.00'), (735, 'b4', '201401', 'achat de matériel de papeterie', '2014-01-23', '25.00'), (736, 'b4', '201401', 'rémunération intervenant/spécialiste', '2014-01-10', '902.00'), (737, 'b4', '201402', 'location équipement vidéo/sonore', '2014-02-07', '849.00'), (738, 'b4', '201402', 'repas avec praticien', '2014-02-19', '36.00'), (739, 'b4', '201402', 'location véhicule', '2014-02-15', '311.00'), (740, 'b4', '201402', 'location équipement vidéo/sonore', '2014-02-11', '413.00'), (741, 'b4', '201402', 'achat de matériel de papeterie', '2014-02-12', '23.00'), (742, 'b4', '201402', 'location équipement vidéo/sonore', '2014-02-22', '607.00'), (743, 'b4', '201402', 'repas avec praticien', '2014-02-24', '32.00'), (744, 'b4', '201402', 'achat de matériel de papeterie', '2014-02-06', '40.00'), (745, 'b4', '201402', 'repas avec praticien', '2014-02-21', '46.00'), (746, 'b4', '201402', 'achat de matériel de papeterie', '2014-02-22', '14.00'), (747, 'b4', '201403', 'rémunération intervenant/spécialiste', '2014-03-16', '626.00'), (748, 'b4', '201403', 'location salle conférence', '2014-03-21', '120.00'), (749, 'b4', '201403', 'repas avec praticien', '2014-03-26', '44.00'), (750, 'b4', '201403', 'location salle conférence', '2014-03-19', '532.00'), (751, 'b4', '201403', 'traiteur, alimentation, boisson', '2014-03-20', '200.00'), (752, 'b4', '201403', 'location véhicule', '2014-03-27', '334.00'), (753, 'b4', '201403', 'taxi', '2014-03-17', '41.00'), (754, 'b4', '201403', 'frais vestimentaire/représentation', '2014-03-22', '216.00'), (755, 'b4', '201403', 'location véhicule', '2014-03-21', '315.00'), (756, 'b4', '201403', 'achat de matériel de papeterie', '2014-03-02', '41.00'), (757, 'b4', '201403', 'repas avec praticien', '2014-03-01', '34.00'), (758, 'b4', '201404', 'frais vestimentaire/représentation', '2014-04-25', '410.00'), (759, 'b4', '201404', 'Voyage SNCF', '2014-04-26', '68.00'), (760, 'b4', '201404', 'repas avec praticien', '2014-04-19', '46.00'), (761, 'b4', '201404', 'frais vestimentaire/représentation', '2014-04-16', '296.00'), (762, 'b4', '201404', 'traiteur, alimentation, boisson', '2014-04-02', '284.00'), (763, 'b4', '201404', 'location véhicule', '2014-04-19', '191.00'), (764, 'b4', '201404', 'achat de matériel de papeterie', '2014-04-20', '26.00'), (765, 'b4', '201404', 'traiteur, alimentation, boisson', '2014-04-09', '443.00'), (766, 'b4', '201405', 'rémunération intervenant/spécialiste', '2014-05-23', '475.00'), (767, 'b4', '201405', 'traiteur, alimentation, boisson', '2014-05-14', '295.00'), (768, 'b4', '201405', 'Voyage SNCF', '2014-05-13', '150.00'), (769, 'b4', '201405', 'location salle conférence', '2014-05-18', '267.00'), (770, 'b4', '201405', 'repas avec praticien', '2014-05-23', '31.00'), (771, 'b4', '201405', 'taxi', '2014-05-24', '59.00'), (772, 'b4', '201405', 'achat de matériel de papeterie', '2014-05-07', '13.00'), (773, 'b4', '201405', 'location équipement vidéo/sonore', '2014-05-23', '778.00'), (774, 'b4', '201405', 'repas avec praticien', '2014-05-05', '35.00'), (775, 'b4', '201406', 'repas avec praticien', '2014-06-15', '36.00'), (776, 'b4', '201406', 'location salle conférence', '2014-06-12', '351.00'), (777, 'b4', '201406', 'repas avec praticien', '2014-06-05', '35.00'), (778, 'b4', '201406', 'Voyage SNCF', '2014-06-24', '81.00'), (779, 'b4', '201406', 'Voyage SNCF', '2014-06-19', '35.00'), (780, 'b4', '201406', 'Voyage SNCF', '2014-06-02', '75.00'), (781, 'b4', '201406', 'frais vestimentaire/représentation', '2014-06-04', '285.00'), (782, 'b4', '201406', 'location salle conférence', '2014-06-02', '494.00'), (783, 'b4', '201406', 'achat de matériel de papeterie', '2014-06-23', '43.00'), (784, 'b4', '201406', 'rémunération intervenant/spécialiste', '2014-06-02', '1180.00'), (785, 'b4', '201406', 'taxi', '2014-06-13', '35.00'), (786, 'b4', '201407', 'location salle conférence', '2014-07-21', '509.00'), (787, 'b4', '201407', 'repas avec praticien', '2014-07-21', '38.00'), (788, 'b4', '201407', 'traiteur, alimentation, boisson', '2014-07-16', '433.00'), (789, 'b4', '201407', 'location salle conférence', '2014-07-04', '224.00'), (790, 'b4', '201407', 'location véhicule', '2014-07-08', '136.00'), (791, 'b4', '201407', 'location véhicule', '2014-07-13', '412.00'), (792, 'b4', '201407', 'repas avec praticien', '2014-07-16', '30.00'), (793, 'b4', '201407', 'traiteur, alimentation, boisson', '2014-07-27', '146.00'), (794, 'b4', '201408', 'rémunération intervenant/spécialiste', '2014-08-14', '376.00'), (795, 'b4', '201408', 'repas avec praticien', '2014-08-10', '37.00'), (796, 'b4', '201408', 'repas avec praticien', '2014-08-22', '37.00'), (797, 'b4', '201408', 'achat de matériel de papeterie', '2014-08-05', '22.00'), (798, 'b4', '201408', 'location salle conférence', '2014-08-22', '225.00'), (799, 'b4', '201408', 'frais vestimentaire/représentation', '2014-08-23', '243.00'), (800, 'b4', '201408', 'taxi', '2014-08-16', '59.00'), (801, 'b4', '201408', 'traiteur, alimentation, boisson', '2014-08-22', '27.00'), (802, 'b4', '201408', 'rémunération intervenant/spécialiste', '2014-08-28', '1093.00'), (803, 'b4', '201408', 'taxi', '2014-08-10', '46.00'), (804, 'b4', '201408', 'location salle conférence', '2014-08-27', '427.00'), (805, 'b4', '201408', 'achat de matériel de papeterie', '2014-08-21', '22.00'), (806, 'b4', '201409', 'achat de matériel de papeterie', '2014-09-04', '44.00'), (807, 'b4', '201409', 'achat de matériel de papeterie', '2014-09-27', '25.00'), (808, 'b4', '201409', 'location équipement vidéo/sonore', '2014-09-20', '490.00'), (809, 'b4', '201409', 'frais vestimentaire/représentation', '2014-09-01', '106.00'), (810, 'b4', '201409', 'taxi', '2014-09-08', '63.00'), (811, 'b4', '201409', 'taxi', '2014-09-16', '69.00'), (812, 'b4', '201409', 'Voyage SNCF', '2014-09-17', '60.00'), (813, 'b4', '201409', 'taxi', '2014-09-22', '39.00'), (814, 'b4', '201409', 'rémunération intervenant/spécialiste', '2014-09-14', '315.00'), (815, 'b50', '201402', 'frais vestimentaire/représentation', '2014-02-28', '235.00'), (816, 'b50', '201402', 'Voyage SNCF', '2014-02-25', '69.00'), (817, 'b50', '201402', 'traiteur, alimentation, boisson', '2014-02-22', '268.00'), (818, 'b50', '201402', 'taxi', '2014-02-13', '74.00'), (819, 'b50', '201402', 'repas avec praticien', '2014-02-04', '34.00'), (820, 'b50', '201402', 'repas avec praticien', '2014-02-10', '36.00'), (821, 'b50', '201402', 'repas avec praticien', '2014-02-24', '42.00'), (822, 'b50', '201402', 'rémunération intervenant/spécialiste', '2014-02-01', '1057.00'), (823, 'b50', '201402', 'rémunération intervenant/spécialiste', '2014-02-08', '1129.00'), (824, 'b50', '201402', 'rémunération intervenant/spécialiste', '2014-02-03', '574.00'), (825, 'b50', '201403', 'location salle conférence', '2014-03-23', '506.00'), (826, 'b50', '201403', 'achat de matériel de papeterie', '2014-03-23', '43.00'), (827, 'b50', '201403', 'achat de matériel de papeterie', '2014-03-24', '37.00'), (828, 'b50', '201403', 'location équipement vidéo/sonore', '2014-03-16', '522.00'), (829, 'b50', '201403', 'traiteur, alimentation, boisson', '2014-03-18', '60.00'), (830, 'b50', '201403', 'location équipement vidéo/sonore', '2014-03-15', '202.00'), (831, 'b50', '201403', 'frais vestimentaire/représentation', '2014-03-15', '27.00'), (832, 'b50', '201404', 'rémunération intervenant/spécialiste', '2014-04-18', '967.00'), (833, 'b50', '201404', 'location salle conférence', '2014-04-01', '194.00'), (834, 'b50', '201404', 'frais vestimentaire/représentation', '2014-04-23', '187.00'), (835, 'b50', '201404', 'taxi', '2014-04-26', '65.00'), (836, 'b50', '201404', 'location salle conférence', '2014-04-14', '311.00'), (837, 'b50', '201404', 'rémunération intervenant/spécialiste', '2014-04-26', '622.00'), (838, 'b50', '201404', 'taxi', '2014-04-16', '73.00'), (839, 'b50', '201404', 'location véhicule', '2014-04-08', '335.00'), (840, 'b50', '201405', 'traiteur, alimentation, boisson', '2014-05-01', '427.00'), (841, 'b50', '201405', 'taxi', '2014-05-15', '31.00'), (842, 'b50', '201405', 'frais vestimentaire/représentation', '2014-05-02', '445.00'), (843, 'b50', '201405', 'Voyage SNCF', '2014-05-08', '44.00'), (844, 'b50', '201405', 'achat de matériel de papeterie', '2014-05-11', '33.00'), (845, 'b50', '201405', 'Voyage SNCF', '2014-05-21', '147.00'), (846, 'b50', '201405', 'location véhicule', '2014-05-14', '199.00'), (847, 'b50', '201406', 'location salle conférence', '2014-06-04', '346.00'), (848, 'b50', '201406', 'frais vestimentaire/représentation', '2014-06-20', '233.00'), (849, 'b50', '201406', 'traiteur, alimentation, boisson', '2014-06-04', '153.00'), (850, 'b50', '201406', 'location salle conférence', '2014-06-07', '607.00'), (851, 'b50', '201406', 'location véhicule', '2014-06-20', '47.00'), (852, 'b50', '201406', 'taxi', '2014-06-21', '68.00'), (853, 'b50', '201406', 'location équipement vidéo/sonore', '2014-06-15', '227.00'), (854, 'b50', '201406', 'taxi', '2014-06-17', '53.00'), (855, 'b50', '201406', 'achat de matériel de papeterie', '2014-06-22', '39.00'), (856, 'b50', '201406', 'Voyage SNCF', '2014-06-27', '51.00'), (857, 'b50', '201406', 'location véhicule', '2014-06-24', '127.00'), (858, 'b50', '201407', 'traiteur, alimentation, boisson', '2014-07-18', '401.00'), (859, 'b50', '201407', 'frais vestimentaire/représentation', '2014-07-25', '169.00'), (860, 'b50', '201407', 'rémunération intervenant/spécialiste', '2014-07-28', '935.00'), (861, 'b50', '201407', 'achat de matériel de papeterie', '2014-07-02', '34.00'), (862, 'b50', '201407', 'location équipement vidéo/sonore', '2014-07-13', '282.00'), (863, 'b50', '201407', 'taxi', '2014-07-02', '62.00'), (864, 'b50', '201407', 'location véhicule', '2014-07-28', '432.00'), (865, 'b50', '201407', 'achat de matériel de papeterie', '2014-07-13', '45.00'), (866, 'b50', '201407', 'Voyage SNCF', '2014-07-03', '70.00'), (867, 'b50', '201407', 'location salle conférence', '2014-07-07', '448.00'), (868, 'b50', '201408', 'repas avec praticien', '2014-08-21', '33.00'), (869, 'b50', '201408', 'achat de matériel de papeterie', '2014-08-14', '16.00'), (870, 'b50', '201408', 'location salle conférence', '2014-08-20', '635.00'), (871, 'b50', '201408', 'frais vestimentaire/représentation', '2014-08-05', '143.00'), (872, 'b50', '201408', 'Voyage SNCF', '2014-08-27', '104.00'), (873, 'b50', '201408', 'location véhicule', '2014-08-16', '251.00'), (874, 'b50', '201408', 'location équipement vidéo/sonore', '2014-08-28', '468.00'), (875, 'b50', '201409', 'traiteur, alimentation, boisson', '2014-09-11', '57.00'), (876, 'b50', '201409', 'location équipement vidéo/sonore', '2014-09-02', '684.00'), (877, 'b50', '201409', 'location véhicule', '2014-09-04', '399.00'), (878, 'b50', '201409', 'location salle conférence', '2014-09-06', '131.00'), (879, 'b50', '201409', 'frais vestimentaire/représentation', '2014-09-26', '295.00'), (880, 'b50', '201409', 'location véhicule', '2014-09-19', '107.00'), (881, 'b50', '201409', 'achat de matériel de papeterie', '2014-09-04', '39.00'), (882, 'b50', '201409', 'frais vestimentaire/représentation', '2014-09-25', '396.00'), (883, 'b59', '201401', 'Voyage SNCF', '2014-01-02', '103.00'), (884, 'b59', '201401', 'frais vestimentaire/représentation', '2014-01-14', '343.00'), (885, 'b59', '201401', 'Voyage SNCF', '2014-01-20', '43.00'), (886, 'b59', '201401', 'repas avec praticien', '2014-01-09', '49.00'), (887, 'b59', '201401', 'location équipement vidéo/sonore', '2014-01-16', '448.00'), (888, 'b59', '201401', 'location salle conférence', '2014-01-08', '127.00'), (889, 'b59', '201401', 'achat de matériel de papeterie', '2014-01-24', '44.00'), (890, 'b59', '201401', 'traiteur, alimentation, boisson', '2014-01-11', '370.00'), (891, 'b59', '201401', 'taxi', '2014-01-11', '21.00'), (892, 'b59', '201402', 'traiteur, alimentation, boisson', '2014-02-28', '301.00'), (893, 'b59', '201402', 'traiteur, alimentation, boisson', '2014-02-02', '29.00'), (894, 'b59', '201402', 'location salle conférence', '2014-02-25', '413.00'), (895, 'b59', '201402', 'taxi', '2014-02-01', '26.00'), (896, 'b59', '201403', 'location salle conférence', '2014-03-04', '347.00'), (897, 'b59', '201403', 'achat de matériel de papeterie', '2014-03-26', '29.00'), (898, 'b59', '201403', 'frais vestimentaire/représentation', '2014-03-26', '68.00'), (899, 'b59', '201403', 'rémunération intervenant/spécialiste', '2014-03-26', '812.00'), (900, 'b59', '201403', 'traiteur, alimentation, boisson', '2014-03-25', '136.00'), (901, 'b59', '201403', 'frais vestimentaire/représentation', '2014-03-23', '87.00'), (902, 'b59', '201403', 'frais vestimentaire/représentation', '2014-03-12', '33.00'), (903, 'b59', '201403', 'location véhicule', '2014-03-14', '297.00'), (904, 'b59', '201403', 'location véhicule', '2014-03-02', '274.00'), (905, 'b59', '201404', 'traiteur, alimentation, boisson', '2014-04-27', '245.00'), (906, 'b59', '201404', 'Voyage SNCF', '2014-04-22', '135.00'), (907, 'b59', '201404', 'traiteur, alimentation, boisson', '2014-04-23', '123.00'), (908, 'b59', '201404', 'frais vestimentaire/représentation', '2014-04-21', '274.00'), (909, 'b59', '201404', 'location véhicule', '2014-04-07', '66.00'), (910, 'b59', '201404', 'location véhicule', '2014-04-25', '423.00'), (911, 'b59', '201405', 'frais vestimentaire/représentation', '2014-05-10', '263.00'), (912, 'b59', '201405', 'location véhicule', '2014-05-20', '360.00'), (913, 'b59', '201405', 'repas avec praticien', '2014-05-23', '45.00'), (914, 'b59', '201405', 'location équipement vidéo/sonore', '2014-05-05', '253.00'), (915, 'b59', '201405', 'location véhicule', '2014-05-09', '361.00'), (916, 'b59', '201405', 'location équipement vidéo/sonore', '2014-05-07', '224.00'), (917, 'b59', '201405', 'Voyage SNCF', '2014-05-20', '135.00'), (918, 'b59', '201405', 'repas avec praticien', '2014-05-04', '36.00'), (919, 'b59', '201405', 'location équipement vidéo/sonore', '2014-05-26', '596.00'), (920, 'b59', '201405', 'location équipement vidéo/sonore', '2014-05-04', '206.00'), (921, 'b59', '201405', 'location véhicule', '2014-05-08', '250.00'), (922, 'b59', '201405', 'location véhicule', '2014-05-18', '122.00'), (923, 'b59', '201406', 'location véhicule', '2014-06-21', '301.00'), (924, 'b59', '201406', 'Voyage SNCF', '2014-06-06', '93.00'), (925, 'b59', '201406', 'achat de matériel de papeterie', '2014-06-26', '43.00'), (926, 'b59', '201406', 'Voyage SNCF', '2014-06-06', '89.00'), (927, 'b59', '201406', 'location salle conférence', '2014-06-02', '422.00'), (928, 'b59', '201406', 'Voyage SNCF', '2014-06-03', '42.00'), (929, 'b59', '201406', 'traiteur, alimentation, boisson', '2014-06-10', '72.00'), (930, 'b59', '201406', 'repas avec praticien', '2014-06-23', '33.00'), (931, 'b59', '201406', 'achat de matériel de papeterie', '2014-06-19', '18.00'), (932, 'b59', '201406', 'frais vestimentaire/représentation', '2014-06-15', '29.00'), (933, 'b59', '201406', 'taxi', '2014-06-24', '47.00'), (934, 'b59', '201406', 'traiteur, alimentation, boisson', '2014-06-16', '276.00'), (935, 'b59', '201407', 'traiteur, alimentation, boisson', '2014-07-05', '435.00'), (936, 'b59', '201407', 'location véhicule', '2014-07-02', '32.00'), (937, 'b59', '201408', 'Voyage SNCF', '2014-08-04', '34.00'), (938, 'b59', '201408', 'rémunération intervenant/spécialiste', '2014-08-06', '310.00'), (939, 'b59', '201408', 'location véhicule', '2014-08-26', '392.00'), (940, 'b59', '201408', 'rémunération intervenant/spécialiste', '2014-08-25', '689.00'), (941, 'b59', '201408', 'achat de matériel de papeterie', '2014-08-20', '48.00'), (942, 'b59', '201408', 'repas avec praticien', '2014-08-05', '31.00'), (943, 'b59', '201408', 'location équipement vidéo/sonore', '2014-08-21', '358.00'), (944, 'b59', '201408', 'frais vestimentaire/représentation', '2014-08-01', '163.00'), (945, 'b59', '201408', 'rémunération intervenant/spécialiste', '2014-08-20', '549.00'), (946, 'b59', '201408', 'location véhicule', '2014-08-27', '350.00'), (947, 'b59', '201408', 'Voyage SNCF', '2014-08-15', '77.00'), (948, 'b59', '201409', 'repas avec praticien', '2014-09-26', '36.00'), (949, 'b59', '201409', 'rémunération intervenant/spécialiste', '2014-09-28', '268.00'), (950, 'b59', '201409', 'location salle conférence', '2014-09-18', '427.00'), (951, 'b59', '201409', 'traiteur, alimentation, boisson', '2014-09-27', '259.00'), (952, 'b59', '201409', 'taxi', '2014-09-18', '26.00'), (953, 'b59', '201409', 'Voyage SNCF', '2014-09-27', '104.00'), (954, 'b59', '201409', 'location véhicule', '2014-09-13', '44.00'), (955, 'b59', '201409', 'taxi', '2014-09-16', '71.00'), (956, 'b59', '201409', 'location salle conférence', '2014-09-25', '165.00'), (957, 'b59', '201409', 'taxi', '2014-09-18', '57.00'), (958, 'c14', '201401', 'Voyage SNCF', '2014-01-25', '113.00'), (959, 'c14', '201401', 'rémunération intervenant/spécialiste', '2014-01-17', '336.00'), (960, 'c14', '201401', 'Voyage SNCF', '2014-01-12', '70.00'), (961, 'c14', '201401', 'location équipement vidéo/sonore', '2014-01-10', '538.00'), (962, 'c14', '201401', 'taxi', '2014-01-20', '30.00'), (963, 'c14', '201401', 'location salle conférence', '2014-01-09', '126.00'), (964, 'c14', '201402', 'location équipement vidéo/sonore', '2014-02-04', '480.00'), (965, 'c14', '201402', 'location véhicule', '2014-02-03', '45.00'), (966, 'c14', '201402', 'achat de matériel de papeterie', '2014-02-16', '37.00'), (967, 'c14', '201402', 'traiteur, alimentation, boisson', '2014-02-25', '107.00'), (968, 'c14', '201402', 'frais vestimentaire/représentation', '2014-02-25', '183.00'), (969, 'c14', '201402', 'traiteur, alimentation, boisson', '2014-02-08', '260.00'), (970, 'c14', '201402', 'achat de matériel de papeterie', '2014-02-28', '25.00'), (971, 'c14', '201402', 'traiteur, alimentation, boisson', '2014-02-11', '200.00'), (972, 'c14', '201402', 'Voyage SNCF', '2014-02-20', '63.00'), (973, 'c14', '201402', 'achat de matériel de papeterie', '2014-02-17', '41.00'), (974, 'c14', '201402', 'location salle conférence', '2014-02-03', '544.00'), (975, 'c14', '201402', 'location salle conférence', '2014-02-27', '445.00'), (976, 'c14', '201403', 'frais vestimentaire/représentation', '2014-03-18', '321.00'), (977, 'c14', '201404', 'location équipement vidéo/sonore', '2014-04-27', '569.00'), (978, 'c14', '201405', 'traiteur, alimentation, boisson', '2014-05-07', '234.00'), (979, 'c14', '201405', 'frais vestimentaire/représentation', '2014-05-14', '242.00'), (980, 'c14', '201405', 'rémunération intervenant/spécialiste', '2014-05-27', '332.00'), (981, 'c14', '201405', 'repas avec praticien', '2014-05-13', '40.00'), (982, 'c14', '201405', 'repas avec praticien', '2014-05-17', '36.00'), (983, 'c14', '201405', 'frais vestimentaire/représentation', '2014-05-03', '175.00'), (984, 'c14', '201405', 'traiteur, alimentation, boisson', '2014-05-28', '187.00'), (985, 'c14', '201405', 'Voyage SNCF', '2014-05-08', '84.00'), (986, 'c14', '201406', 'repas avec praticien', '2014-06-21', '50.00'), (987, 'c14', '201406', 'location véhicule', '2014-06-25', '110.00'), (988, 'c14', '201406', 'taxi', '2014-06-02', '42.00'), (989, 'c14', '201406', 'achat de matériel de papeterie', '2014-06-24', '14.00'), (990, 'c14', '201406', 'taxi', '2014-06-05', '33.00'), (991, 'c14', '201406', 'location véhicule', '2014-06-15', '424.00'), (992, 'c14', '201406', 'rémunération intervenant/spécialiste', '2014-06-24', '1074.00'), (993, 'c14', '201406', 'taxi', '2014-06-28', '74.00'), (994, 'c14', '201406', 'taxi', '2014-06-25', '63.00'), (995, 'c14', '201407', 'repas avec praticien', '2014-07-06', '30.00'), (996, 'c14', '201407', 'achat de matériel de papeterie', '2014-07-19', '31.00'), (997, 'c14', '201407', 'frais vestimentaire/représentation', '2014-07-17', '67.00'), (998, 'c14', '201407', 'Voyage SNCF', '2014-07-03', '118.00'), (999, 'c14', '201407', 'Voyage SNCF', '2014-07-19', '39.00'), (1000, 'c14', '201407', 'location équipement vidéo/sonore', '2014-07-02', '686.00'), (1001, 'c14', '201408', 'traiteur, alimentation, boisson', '2014-08-02', '199.00'), (1002, 'c14', '201408', 'frais vestimentaire/représentation', '2014-08-03', '329.00'), (1003, 'c14', '201408', 'Voyage SNCF', '2014-08-08', '64.00'), (1004, 'c14', '201408', 'location équipement vidéo/sonore', '2014-08-21', '261.00'), (1005, 'c14', '201408', 'achat de matériel de papeterie', '2014-08-20', '31.00'), (1006, 'c14', '201408', 'frais vestimentaire/représentation', '2014-08-20', '275.00'), (1007, 'c14', '201408', 'repas avec praticien', '2014-08-16', '34.00'), (1008, 'c14', '201409', 'location véhicule', '2014-09-04', '129.00'), (1009, 'c14', '201409', 'location véhicule', '2014-09-23', '128.00'), (1010, 'c14', '201409', 'rémunération intervenant/spécialiste', '2014-09-28', '617.00'), (1011, 'c14', '201409', 'traiteur, alimentation, boisson', '2014-09-22', '112.00'), (1012, 'c3', '201401', 'taxi', '2014-01-10', '38.00'), (1013, 'c3', '201401', 'location véhicule', '2014-01-07', '394.00'), (1014, 'c3', '201401', 'frais vestimentaire/représentation', '2014-01-01', '206.00'), (1015, 'c3', '201401', 'rémunération intervenant/spécialiste', '2014-01-07', '277.00'), (1016, 'c3', '201402', 'frais vestimentaire/représentation', '2014-02-06', '155.00'), (1017, 'c3', '201402', 'location équipement vidéo/sonore', '2014-02-05', '578.00'), (1018, 'c3', '201402', 'location véhicule', '2014-02-02', '60.00'), (1019, 'c3', '201402', 'Voyage SNCF', '2014-02-09', '39.00'), (1020, 'c3', '201402', 'location véhicule', '2014-02-12', '244.00'), (1021, 'c3', '201402', 'Voyage SNCF', '2014-02-06', '73.00'), (1022, 'c3', '201402', 'location véhicule', '2014-02-06', '182.00'), (1023, 'c3', '201402', 'location véhicule', '2014-02-26', '351.00'), (1024, 'c3', '201402', 'traiteur, alimentation, boisson', '2014-02-06', '136.00'), (1025, 'c3', '201402', 'rémunération intervenant/spécialiste', '2014-02-24', '535.00'), (1026, 'c3', '201403', 'location véhicule', '2014-03-12', '244.00'), (1027, 'c3', '201403', 'frais vestimentaire/représentation', '2014-03-27', '51.00'), (1028, 'c3', '201403', 'location véhicule', '2014-03-23', '200.00'), (1029, 'c3', '201403', 'taxi', '2014-03-01', '76.00'), (1030, 'c3', '201403', 'location équipement vidéo/sonore', '2014-03-11', '735.00'), (1031, 'c3', '201403', 'frais vestimentaire/représentation', '2014-03-24', '241.00'), (1032, 'c3', '201403', 'frais vestimentaire/représentation', '2014-03-16', '310.00'), (1033, 'c3', '201404', 'location équipement vidéo/sonore', '2014-04-01', '688.00'), (1034, 'c3', '201404', 'location véhicule', '2014-04-28', '191.00'), (1035, 'c3', '201404', 'location véhicule', '2014-04-21', '259.00'), (1036, 'c3', '201404', 'achat de matériel de papeterie', '2014-04-12', '45.00'), (1037, 'c3', '201404', 'location véhicule', '2014-04-21', '259.00'), (1038, 'c3', '201404', 'location salle conférence', '2014-04-24', '361.00'), (1039, 'c3', '201404', 'location véhicule', '2014-04-15', '424.00'), (1040, 'c3', '201404', 'rémunération intervenant/spécialiste', '2014-04-25', '816.00'), (1041, 'c3', '201404', 'taxi', '2014-04-28', '24.00'), (1042, 'c3', '201404', 'frais vestimentaire/représentation', '2014-04-07', '182.00'), (1043, 'c3', '201404', 'achat de matériel de papeterie', '2014-04-28', '34.00'), (1044, 'c3', '201405', 'location équipement vidéo/sonore', '2014-05-22', '282.00'), (1045, 'c3', '201405', 'repas avec praticien', '2014-05-04', '47.00'), (1046, 'c3', '201405', 'location salle conférence', '2014-05-03', '562.00'), (1047, 'c3', '201405', 'rémunération intervenant/spécialiste', '2014-05-01', '391.00'), (1048, 'c3', '201405', 'traiteur, alimentation, boisson', '2014-05-21', '57.00'), (1049, 'c3', '201405', 'Voyage SNCF', '2014-05-04', '142.00'), (1050, 'c3', '201406', 'location équipement vidéo/sonore', '2014-06-28', '267.00'), (1051, 'c3', '201406', 'location salle conférence', '2014-06-28', '407.00'), (1052, 'c3', '201406', 'Voyage SNCF', '2014-06-01', '95.00'), (1053, 'c3', '201406', 'location salle conférence', '2014-06-06', '220.00'), (1054, 'c3', '201406', 'repas avec praticien', '2014-06-06', '40.00'), (1055, 'c3', '201406', 'traiteur, alimentation, boisson', '2014-06-05', '250.00'), (1056, 'c3', '201406', 'achat de matériel de papeterie', '2014-06-22', '23.00'), (1057, 'c3', '201406', 'frais vestimentaire/représentation', '2014-06-21', '33.00'), (1058, 'c3', '201406', 'rémunération intervenant/spécialiste', '2014-06-16', '1006.00'), (1059, 'c3', '201406', 'Voyage SNCF', '2014-06-05', '85.00'), (1060, 'c3', '201407', 'location véhicule', '2014-07-02', '61.00'), (1061, 'c3', '201407', 'taxi', '2014-07-24', '49.00'), (1062, 'c3', '201407', 'location véhicule', '2014-07-18', '78.00'), (1063, 'c3', '201407', 'traiteur, alimentation, boisson', '2014-07-28', '301.00'), (1064, 'c3', '201407', 'repas avec praticien', '2014-07-24', '44.00'), (1065, 'c3', '201407', 'location véhicule', '2014-07-28', '391.00'), (1066, 'c3', '201407', 'location salle conférence', '2014-07-25', '378.00'), (1067, 'c3', '201407', 'location équipement vidéo/sonore', '2014-07-24', '678.00'), (1068, 'c3', '201407', 'taxi', '2014-07-28', '77.00'), (1069, 'c3', '201408', 'location équipement vidéo/sonore', '2014-08-13', '706.00'), (1070, 'c3', '201408', 'rémunération intervenant/spécialiste', '2014-08-07', '814.00'), (1071, 'c3', '201408', 'taxi', '2014-08-14', '70.00'), (1072, 'c3', '201408', 'traiteur, alimentation, boisson', '2014-08-04', '294.00'), (1073, 'c3', '201408', 'traiteur, alimentation, boisson', '2014-08-22', '282.00'), (1074, 'c3', '201408', 'achat de matériel de papeterie', '2014-08-21', '39.00'), (1075, 'c3', '201408', 'repas avec praticien', '2014-08-02', '50.00'), (1076, 'c3', '201409', 'Voyage SNCF', '2014-09-09', '59.00'), (1077, 'c3', '201409', 'achat de matériel de papeterie', '2014-09-01', '29.00'), (1078, 'c3', '201409', 'rémunération intervenant/spécialiste', '2014-09-01', '833.00'), (1079, 'c3', '201409', 'location véhicule', '2014-09-15', '410.00'), (1080, 'c3', '201409', 'traiteur, alimentation, boisson', '2014-09-07', '419.00'), (1081, 'c3', '201409', 'location équipement vidéo/sonore', '2014-09-22', '256.00'), (1082, 'c3', '201409', 'Voyage SNCF', '2014-09-28', '84.00'), (1083, 'c3', '201409', 'location équipement vidéo/sonore', '2014-09-09', '617.00'), (1084, 'c3', '201409', 'achat de matériel de papeterie', '2014-09-13', '16.00'), (1085, 'c3', '201409', 'achat de matériel de papeterie', '2014-09-12', '10.00'), (1086, 'c54', '201401', 'traiteur, alimentation, boisson', '2014-01-01', '412.00'), (1087, 'c54', '201401', 'traiteur, alimentation, boisson', '2014-01-19', '428.00'), (1088, 'c54', '201401', 'frais vestimentaire/représentation', '2014-01-26', '281.00'), (1089, 'c54', '201401', 'traiteur, alimentation, boisson', '2014-01-17', '305.00'), (1090, 'c54', '201401', 'rémunération intervenant/spécialiste', '2014-01-03', '859.00'), (1091, 'c54', '201401', 'achat de matériel de papeterie', '2014-01-02', '12.00'), (1092, 'c54', '201402', 'taxi', '2014-02-20', '30.00'), (1093, 'c54', '201402', 'traiteur, alimentation, boisson', '2014-02-22', '283.00'), (1094, 'c54', '201402', 'frais vestimentaire/représentation', '2014-02-09', '80.00'), (1095, 'c54', '201402', 'repas avec praticien', '2014-02-08', '42.00'), (1096, 'c54', '201402', 'location véhicule', '2014-02-02', '346.00'), (1097, 'c54', '201402', 'Voyage SNCF', '2014-02-03', '90.00'), (1098, 'c54', '201402', 'repas avec praticien', '2014-02-20', '45.00'), (1099, 'c54', '201402', 'location équipement vidéo/sonore', '2014-02-16', '173.00'), (1100, 'c54', '201402', 'traiteur, alimentation, boisson', '2014-02-26', '63.00'), (1101, 'c54', '201402', 'location véhicule', '2014-02-19', '361.00'), (1102, 'c54', '201403', 'achat de matériel de papeterie', '2014-03-22', '24.00'), (1103, 'c54', '201403', 'location équipement vidéo/sonore', '2014-03-26', '374.00'), (1104, 'c54', '201403', 'repas avec praticien', '2014-03-28', '32.00'), (1105, 'c54', '201403', 'Voyage SNCF', '2014-03-16', '133.00'), (1106, 'c54', '201403', 'frais vestimentaire/représentation', '2014-03-23', '357.00'), (1107, 'c54', '201403', 'Voyage SNCF', '2014-03-23', '126.00'), (1108, 'c54', '201403', 'achat de matériel de papeterie', '2014-03-13', '46.00'), (1109, 'c54', '201403', 'taxi', '2014-03-27', '54.00'), (1110, 'c54', '201403', 'traiteur, alimentation, boisson', '2014-03-25', '249.00'), (1111, 'c54', '201403', 'achat de matériel de papeterie', '2014-03-12', '12.00'), (1112, 'c54', '201404', 'taxi', '2014-04-28', '38.00'), (1113, 'c54', '201404', 'traiteur, alimentation, boisson', '2014-04-18', '145.00'), (1114, 'c54', '201404', 'rémunération intervenant/spécialiste', '2014-04-16', '342.00'), (1115, 'c54', '201404', 'location véhicule', '2014-04-02', '260.00'), (1116, 'c54', '201404', 'rémunération intervenant/spécialiste', '2014-04-28', '648.00'), (1117, 'c54', '201404', 'Voyage SNCF', '2014-04-02', '34.00'), (1118, 'c54', '201404', 'frais vestimentaire/représentation', '2014-04-06', '41.00'), (1119, 'c54', '201404', 'achat de matériel de papeterie', '2014-04-22', '10.00'), (1120, 'c54', '201404', 'Voyage SNCF', '2014-04-02', '99.00'), (1121, 'c54', '201404', 'Voyage SNCF', '2014-04-16', '117.00'), (1122, 'c54', '201404', 'achat de matériel de papeterie', '2014-04-18', '29.00'), (1123, 'c54', '201405', 'Voyage SNCF', '2014-05-02', '67.00'), (1124, 'c54', '201405', 'achat de matériel de papeterie', '2014-05-01', '34.00'), (1125, 'c54', '201405', 'rémunération intervenant/spécialiste', '2014-05-19', '741.00'), (1126, 'c54', '201405', 'repas avec praticien', '2014-05-23', '41.00'), (1127, 'c54', '201405', 'traiteur, alimentation, boisson', '2014-05-08', '204.00'), (1128, 'c54', '201405', 'rémunération intervenant/spécialiste', '2014-05-16', '975.00'), (1129, 'c54', '201405', 'frais vestimentaire/représentation', '2014-05-28', '221.00'), (1130, 'c54', '201405', 'location salle conférence', '2014-05-21', '191.00'), (1131, 'c54', '201405', 'traiteur, alimentation, boisson', '2014-05-28', '259.00'), (1132, 'c54', '201405', 'location équipement vidéo/sonore', '2014-05-24', '402.00'), (1133, 'c54', '201405', 'repas avec praticien', '2014-05-24', '36.00'), (1134, 'c54', '201406', 'location salle conférence', '2014-06-19', '406.00'), (1135, 'c54', '201406', 'Voyage SNCF', '2014-06-21', '95.00'), (1136, 'c54', '201406', 'location véhicule', '2014-06-21', '74.00'), (1137, 'c54', '201406', 'frais vestimentaire/représentation', '2014-06-10', '220.00'), (1138, 'c54', '201406', 'location équipement vidéo/sonore', '2014-06-10', '639.00'), (1139, 'c54', '201406', 'location véhicule', '2014-06-13', '399.00'), (1140, 'c54', '201406', 'traiteur, alimentation, boisson', '2014-06-01', '399.00'), (1141, 'c54', '201406', 'repas avec praticien', '2014-06-04', '47.00'), (1142, 'c54', '201406', 'Voyage SNCF', '2014-06-04', '46.00'), (1143, 'c54', '201406', 'location véhicule', '2014-06-16', '81.00'), (1144, 'c54', '201407', 'location équipement vidéo/sonore', '2014-07-24', '327.00'), (1145, 'c54', '201407', 'location équipement vidéo/sonore', '2014-07-24', '102.00'), (1146, 'c54', '201407', 'location véhicule', '2014-07-11', '388.00'), (1147, 'c54', '201407', 'repas avec praticien', '2014-07-11', '35.00'), (1148, 'c54', '201408', 'location véhicule', '2014-08-26', '394.00'), (1149, 'c54', '201408', 'location véhicule', '2014-08-06', '267.00'), (1150, 'c54', '201408', 'traiteur, alimentation, boisson', '2014-08-01', '385.00'), (1151, 'c54', '201409', 'frais vestimentaire/représentation', '2014-09-15', '383.00'), (1152, 'c54', '201409', 'frais vestimentaire/représentation', '2014-09-24', '298.00'), (1153, 'c54', '201409', 'achat de matériel de papeterie', '2014-09-15', '37.00'), (1154, 'c54', '201409', 'frais vestimentaire/représentation', '2014-09-15', '199.00'), (1155, 'c54', '201409', 'frais vestimentaire/représentation', '2014-09-15', '113.00'), (1156, 'c54', '201409', 'location équipement vidéo/sonore', '2014-09-18', '418.00'), (1157, 'c54', '201409', 'rémunération intervenant/spécialiste', '2014-09-25', '626.00'), (1158, 'c54', '201409', 'location véhicule', '2014-09-18', '320.00'), (1159, 'c54', '201409', 'location véhicule', '2014-09-20', '430.00'), (1160, 'c54', '201409', 'location salle conférence', '2014-09-15', '219.00'), (1161, 'd13', '201401', 'frais vestimentaire/représentation', '2014-01-19', '220.00'), (1162, 'd13', '201401', 'achat de matériel de papeterie', '2014-01-17', '16.00'), (1163, 'd13', '201401', 'frais vestimentaire/représentation', '2014-01-13', '216.00'), (1164, 'd13', '201401', 'repas avec praticien', '2014-01-20', '41.00'), (1165, 'd13', '201401', 'traiteur, alimentation, boisson', '2014-01-27', '402.00'), (1166, 'd13', '201401', 'Voyage SNCF', '2014-01-13', '138.00'), (1167, 'd13', '201402', 'taxi', '2014-02-23', '37.00'), (1168, 'd13', '201402', 'achat de matériel de papeterie', '2014-02-03', '27.00'), (1169, 'd13', '201402', 'achat de matériel de papeterie', '2014-02-13', '12.00'), (1170, 'd13', '201402', 'location véhicule', '2014-02-13', '328.00'), (1171, 'd13', '201402', 'Voyage SNCF', '2014-02-22', '34.00'), (1172, 'd13', '201403', 'Voyage SNCF', '2014-03-16', '105.00'), (1173, 'd13', '201403', 'Voyage SNCF', '2014-03-24', '85.00'), (1174, 'd13', '201403', 'frais vestimentaire/représentation', '2014-03-02', '318.00'), (1175, 'd13', '201403', 'location salle conférence', '2014-03-11', '316.00'), (1176, 'd13', '201403', 'traiteur, alimentation, boisson', '2014-03-01', '398.00'), (1177, 'd13', '201403', 'location véhicule', '2014-03-23', '326.00'), (1178, 'd13', '201404', 'taxi', '2014-04-21', '68.00'), (1179, 'd13', '201404', 'taxi', '2014-04-08', '73.00'), (1180, 'd13', '201405', 'location véhicule', '2014-05-05', '326.00'), (1181, 'd13', '201405', 'location salle conférence', '2014-05-02', '474.00'), (1182, 'd13', '201405', 'location véhicule', '2014-05-25', '352.00'), (1183, 'd13', '201405', 'location équipement vidéo/sonore', '2014-05-15', '376.00'), (1184, 'd13', '201405', 'taxi', '2014-05-05', '33.00'), (1185, 'd13', '201405', 'rémunération intervenant/spécialiste', '2014-05-06', '1040.00'), (1186, 'd13', '201405', 'taxi', '2014-05-15', '77.00'), (1187, 'd13', '201405', 'repas avec praticien', '2014-05-09', '50.00'), (1188, 'd13', '201405', 'Voyage SNCF', '2014-05-12', '114.00'), (1189, 'd13', '201405', 'location salle conférence', '2014-05-12', '332.00'), (1190, 'd13', '201406', 'location équipement vidéo/sonore', '2014-06-17', '570.00'), (1191, 'd13', '201406', 'frais vestimentaire/représentation', '2014-06-13', '45.00'), (1192, 'd13', '201406', 'location équipement vidéo/sonore', '2014-06-26', '822.00'), (1193, 'd13', '201406', 'location salle conférence', '2014-06-13', '560.00'), (1194, 'd13', '201406', 'location véhicule', '2014-06-27', '235.00'), (1195, 'd13', '201406', 'taxi', '2014-06-12', '64.00'), (1196, 'd13', '201406', 'location véhicule', '2014-06-03', '300.00'), (1197, 'd13', '201406', 'taxi', '2014-06-16', '69.00'), (1198, 'd13', '201406', 'location véhicule', '2014-06-14', '213.00'), (1199, 'd13', '201407', 'traiteur, alimentation, boisson', '2014-07-03', '140.00'), (1200, 'd13', '201407', 'location équipement vidéo/sonore', '2014-07-08', '244.00'), (1201, 'd13', '201407', 'location salle conférence', '2014-07-04', '223.00'), (1202, 'd13', '201407', 'Voyage SNCF', '2014-07-15', '97.00'), (1203, 'd13', '201407', 'repas avec praticien', '2014-07-19', '37.00'), (1204, 'd13', '201407', 'frais vestimentaire/représentation', '2014-07-04', '286.00'), (1205, 'd13', '201407', 'taxi', '2014-07-17', '26.00'), (1206, 'd13', '201407', 'achat de matériel de papeterie', '2014-07-01', '27.00'), (1207, 'd13', '201407', 'location équipement vidéo/sonore', '2014-07-25', '301.00'), (1208, 'd13', '201407', 'location salle conférence', '2014-07-03', '438.00'), (1209, 'd13', '201407', 'traiteur, alimentation, boisson', '2014-07-24', '251.00'), (1210, 'd13', '201408', 'repas avec praticien', '2014-08-07', '49.00'), (1211, 'd13', '201408', 'location salle conférence', '2014-08-06', '467.00'), (1212, 'd13', '201408', 'location équipement vidéo/sonore', '2014-08-22', '105.00'), (1213, 'd13', '201408', 'achat de matériel de papeterie', '2014-08-11', '43.00'), (1214, 'd13', '201408', 'location salle conférence', '2014-08-07', '342.00'), (1215, 'd13', '201408', 'location véhicule', '2014-08-02', '445.00'), (1216, 'd13', '201409', 'location salle conférence', '2014-09-19', '390.00'), (1217, 'd51', '201401', 'taxi', '2014-01-10', '46.00'), (1218, 'd51', '201401', 'location véhicule', '2014-01-21', '145.00'), (1219, 'd51', '201401', 'rémunération intervenant/spécialiste', '2014-01-24', '820.00'), (1220, 'd51', '201401', 'location véhicule', '2014-01-21', '344.00'), (1221, 'd51', '201401', 'location équipement vidéo/sonore', '2014-01-06', '725.00'), (1222, 'd51', '201402', 'traiteur, alimentation, boisson', '2014-02-16', '248.00'), (1223, 'd51', '201402', 'frais vestimentaire/représentation', '2014-02-17', '110.00'), (1224, 'd51', '201402', 'location équipement vidéo/sonore', '2014-02-03', '132.00'), (1225, 'd51', '201402', 'location salle conférence', '2014-02-23', '452.00'), (1226, 'd51', '201402', 'frais vestimentaire/représentation', '2014-02-19', '149.00'), (1227, 'd51', '201402', 'location salle conférence', '2014-02-04', '135.00'), (1228, 'd51', '201402', 'location véhicule', '2014-02-01', '203.00'), (1229, 'd51', '201402', 'taxi', '2014-02-27', '55.00'), (1230, 'd51', '201402', 'achat de matériel de papeterie', '2014-02-25', '26.00'), (1231, 'd51', '201402', 'Voyage SNCF', '2014-02-03', '46.00'), (1232, 'd51', '201402', 'taxi', '2014-02-06', '41.00'), (1233, 'd51', '201403', 'traiteur, alimentation, boisson', '2014-03-02', '425.00'), (1234, 'd51', '201403', 'rémunération intervenant/spécialiste', '2014-03-12', '606.00'), (1235, 'd51', '201404', 'location équipement vidéo/sonore', '2014-04-11', '563.00'), (1236, 'd51', '201404', 'Voyage SNCF', '2014-04-22', '115.00'), (1237, 'd51', '201404', 'location véhicule', '2014-04-09', '64.00'), (1238, 'd51', '201404', 'location équipement vidéo/sonore', '2014-04-09', '517.00'), (1239, 'd51', '201404', 'frais vestimentaire/représentation', '2014-04-14', '86.00'), (1240, 'd51', '201404', 'location salle conférence', '2014-04-23', '364.00'), (1241, 'd51', '201404', 'taxi', '2014-04-20', '80.00'), (1242, 'd51', '201404', 'frais vestimentaire/représentation', '2014-04-08', '223.00'), (1243, 'd51', '201404', 'location équipement vidéo/sonore', '2014-04-25', '174.00'), (1244, 'd51', '201404', 'achat de matériel de papeterie', '2014-04-15', '36.00'), (1245, 'd51', '201404', 'Voyage SNCF', '2014-04-28', '63.00'), (1246, 'd51', '201405', 'location équipement vidéo/sonore', '2014-05-01', '637.00'), (1247, 'd51', '201405', 'location véhicule', '2014-05-02', '288.00'), (1248, 'd51', '201405', 'Voyage SNCF', '2014-05-17', '40.00'), (1249, 'd51', '201405', 'location salle conférence', '2014-05-25', '431.00'), (1250, 'd51', '201405', 'traiteur, alimentation, boisson', '2014-05-02', '185.00'), (1251, 'd51', '201405', 'rémunération intervenant/spécialiste', '2014-05-01', '421.00'), (1252, 'd51', '201405', 'repas avec praticien', '2014-05-07', '34.00'), (1253, 'd51', '201405', 'frais vestimentaire/représentation', '2014-05-26', '196.00'), (1254, 'd51', '201405', 'taxi', '2014-05-07', '37.00'), (1255, 'd51', '201406', 'taxi', '2014-06-09', '54.00'), (1256, 'd51', '201406', 'rémunération intervenant/spécialiste', '2014-06-27', '810.00'), (1257, 'd51', '201406', 'location véhicule', '2014-06-10', '389.00'), (1258, 'd51', '201406', 'frais vestimentaire/représentation', '2014-06-17', '252.00'), (1259, 'd51', '201406', 'location véhicule', '2014-06-18', '335.00'), (1260, 'd51', '201406', 'rémunération intervenant/spécialiste', '2014-06-24', '533.00'), (1261, 'd51', '201406', 'location équipement vidéo/sonore', '2014-06-28', '468.00'), (1262, 'd51', '201406', 'location salle conférence', '2014-06-24', '291.00'), (1263, 'd51', '201406', 'location véhicule', '2014-06-25', '40.00'), (1264, 'd51', '201407', 'Voyage SNCF', '2014-07-20', '123.00'), (1265, 'd51', '201407', 'achat de matériel de papeterie', '2014-07-07', '44.00'), (1266, 'd51', '201407', 'Voyage SNCF', '2014-07-09', '51.00'), (1267, 'd51', '201407', 'Voyage SNCF', '2014-07-06', '93.00'), (1268, 'd51', '201407', 'frais vestimentaire/représentation', '2014-07-13', '115.00'), (1269, 'd51', '201407', 'Voyage SNCF', '2014-07-12', '42.00'), (1270, 'd51', '201407', 'Voyage SNCF', '2014-07-24', '134.00'), (1271, 'd51', '201408', 'location salle conférence', '2014-08-18', '498.00'), (1272, 'd51', '201408', 'taxi', '2014-08-25', '47.00'), (1273, 'd51', '201408', 'location salle conférence', '2014-08-07', '376.00'), (1274, 'd51', '201408', 'rémunération intervenant/spécialiste', '2014-08-19', '870.00'), (1275, 'd51', '201408', 'repas avec praticien', '2014-08-10', '50.00'), (1276, 'd51', '201408', 'frais vestimentaire/représentation', '2014-08-03', '230.00'), (1277, 'd51', '201408', 'location véhicule', '2014-08-24', '183.00'), (1278, 'd51', '201408', 'taxi', '2014-08-05', '63.00'), (1279, 'd51', '201408', 'Voyage SNCF', '2014-08-12', '66.00'), (1280, 'd51', '201409', 'frais vestimentaire/représentation', '2014-09-09', '434.00'), (1281, 'd51', '201409', 'achat de matériel de papeterie', '2014-09-13', '24.00'), (1282, 'd51', '201409', 'taxi', '2014-09-09', '69.00'), (1283, 'd51', '201409', 'Voyage SNCF', '2014-09-19', '103.00'), (1284, 'e22', '201401', 'taxi', '2014-01-20', '32.00'), (1285, 'e22', '201401', 'rémunération intervenant/spécialiste', '2014-01-11', '770.00'), (1286, 'e22', '201401', 'location salle conférence', '2014-01-15', '556.00'), (1287, 'e22', '201401', 'frais vestimentaire/représentation', '2014-01-25', '326.00'), (1288, 'e22', '201401', 'frais vestimentaire/représentation', '2014-01-04', '172.00'), (1289, 'e22', '201401', 'location véhicule', '2014-01-10', '432.00'), (1290, 'e22', '201401', 'traiteur, alimentation, boisson', '2014-01-10', '257.00'), (1291, 'e22', '201401', 'Voyage SNCF', '2014-01-26', '100.00'), (1292, 'e22', '201401', 'Voyage SNCF', '2014-01-11', '91.00'), (1293, 'e22', '201401', 'location équipement vidéo/sonore', '2014-01-14', '805.00'), (1294, 'e22', '201402', 'repas avec praticien', '2014-02-15', '45.00'), (1295, 'e22', '201402', 'location véhicule', '2014-02-26', '208.00'), (1296, 'e22', '201402', 'taxi', '2014-02-10', '48.00'), (1297, 'e22', '201402', 'frais vestimentaire/représentation', '2014-02-14', '327.00'), (1298, 'e22', '201402', 'traiteur, alimentation, boisson', '2014-02-15', '350.00'), (1299, 'e22', '201402', 'traiteur, alimentation, boisson', '2014-02-25', '292.00'), (1300, 'e22', '201402', 'location équipement vidéo/sonore', '2014-02-05', '152.00'), (1301, 'e22', '201402', 'taxi', '2014-02-16', '24.00'), (1302, 'e22', '201402', 'traiteur, alimentation, boisson', '2014-02-15', '151.00'), (1303, 'e22', '201403', 'location équipement vidéo/sonore', '2014-03-19', '141.00'), (1304, 'e22', '201403', 'repas avec praticien', '2014-03-28', '31.00'), (1305, 'e22', '201403', 'traiteur, alimentation, boisson', '2014-03-08', '34.00'), (1306, 'e22', '201403', 'repas avec praticien', '2014-03-25', '30.00'), (1307, 'e22', '201403', 'location équipement vidéo/sonore', '2014-03-25', '572.00'), (1308, 'e22', '201403', 'location véhicule', '2014-03-23', '156.00'), (1309, 'e22', '201403', 'location véhicule', '2014-03-10', '346.00'), (1310, 'e22', '201403', 'repas avec praticien', '2014-03-20', '31.00'), (1311, 'e22', '201403', 'rémunération intervenant/spécialiste', '2014-03-01', '485.00'), (1312, 'e22', '201403', 'location salle conférence', '2014-03-27', '482.00'), (1313, 'e22', '201403', 'location véhicule', '2014-03-05', '99.00'), (1314, 'e22', '201403', 'repas avec praticien', '2014-03-19', '34.00'), (1315, 'e22', '201404', 'repas avec praticien', '2014-04-03', '31.00'), (1316, 'e22', '201404', 'Voyage SNCF', '2014-04-04', '146.00'), (1317, 'e22', '201404', 'taxi', '2014-04-06', '49.00'), (1318, 'e22', '201404', 'location salle conférence', '2014-04-11', '212.00'), (1319, 'e22', '201404', 'location équipement vidéo/sonore', '2014-04-22', '557.00'), (1320, 'e22', '201404', 'location salle conférence', '2014-04-20', '157.00'), (1321, 'e22', '201404', 'taxi', '2014-04-05', '55.00'), (1322, 'e22', '201404', 'location salle conférence', '2014-04-25', '449.00'), (1323, 'e22', '201404', 'location véhicule', '2014-04-04', '413.00'), (1324, 'e22', '201405', 'taxi', '2014-05-26', '22.00'), (1325, 'e22', '201405', 'repas avec praticien', '2014-05-23', '31.00'), (1326, 'e22', '201405', 'rémunération intervenant/spécialiste', '2014-05-18', '587.00'), (1327, 'e22', '201405', 'rémunération intervenant/spécialiste', '2014-05-10', '614.00'), (1328, 'e22', '201406', 'traiteur, alimentation, boisson', '2014-06-19', '328.00'), (1329, 'e22', '201406', 'frais vestimentaire/représentation', '2014-06-21', '444.00'), (1330, 'e22', '201406', 'traiteur, alimentation, boisson', '2014-06-26', '389.00'), (1331, 'e22', '201406', 'repas avec praticien', '2014-06-27', '46.00'), (1332, 'e22', '201406', 'location véhicule', '2014-06-14', '340.00'), (1333, 'e22', '201406', 'repas avec praticien', '2014-06-12', '43.00'), (1334, 'e22', '201406', 'location salle conférence', '2014-06-26', '342.00'), (1335, 'e22', '201406', 'achat de matériel de papeterie', '2014-06-01', '44.00'), (1336, 'e22', '201406', 'Voyage SNCF', '2014-06-12', '95.00'), (1337, 'e22', '201406', 'achat de matériel de papeterie', '2014-06-20', '49.00'), (1338, 'e22', '201407', 'traiteur, alimentation, boisson', '2014-07-06', '122.00'), (1339, 'e22', '201407', 'location salle conférence', '2014-07-22', '525.00'), (1340, 'e22', '201407', 'achat de matériel de papeterie', '2014-07-14', '43.00'), (1341, 'e22', '201407', 'traiteur, alimentation, boisson', '2014-07-08', '76.00'); INSERT INTO `lignefraishorsforfait` (`id`, `idVisiteur`, `mois`, `libelle`, `date`, `montant`) VALUES (1342, 'e22', '201407', 'achat de matériel de papeterie', '2014-07-07', '13.00'), (1343, 'e22', '201408', 'Voyage SNCF', '2014-08-03', '62.00'), (1344, 'e22', '201408', 'traiteur, alimentation, boisson', '2014-08-18', '431.00'), (1345, 'e22', '201408', 'location équipement vidéo/sonore', '2014-08-10', '489.00'), (1346, 'e22', '201408', 'achat de matériel de papeterie', '2014-08-10', '42.00'), (1347, 'e22', '201408', 'frais vestimentaire/représentation', '2014-08-11', '91.00'), (1348, 'e22', '201408', 'taxi', '2014-08-22', '66.00'), (1349, 'e22', '201408', 'repas avec praticien', '2014-08-28', '31.00'), (1350, 'e22', '201408', 'location salle conférence', '2014-08-27', '605.00'), (1351, 'e22', '201408', 'Voyage SNCF', '2014-08-16', '40.00'), (1352, 'e22', '201408', 'traiteur, alimentation, boisson', '2014-08-06', '320.00'), (1353, 'e22', '201408', 'achat de matériel de papeterie', '2014-08-11', '22.00'), (1354, 'e22', '201408', 'location équipement vidéo/sonore', '2014-08-20', '186.00'), (1355, 'e22', '201409', 'taxi', '2014-09-03', '62.00'), (1356, 'e22', '201409', 'repas avec praticien', '2014-09-13', '41.00'), (1357, 'e22', '201409', 'achat de matériel de papeterie', '2014-09-07', '19.00'), (1358, 'e22', '201409', 'location salle conférence', '2014-09-09', '143.00'), (1359, 'e22', '201409', 'taxi', '2014-09-17', '36.00'), (1360, 'e22', '201409', 'traiteur, alimentation, boisson', '2014-09-02', '439.00'), (1361, 'e22', '201409', 'frais vestimentaire/représentation', '2014-09-14', '412.00'), (1362, 'e22', '201409', 'location salle conférence', '2014-09-18', '568.00'), (1363, 'e22', '201409', 'taxi', '2014-09-15', '41.00'), (1364, 'e22', '201409', 'traiteur, alimentation, boisson', '2014-09-15', '79.00'), (1365, 'e22', '201409', 'rémunération intervenant/spécialiste', '2014-09-20', '389.00'), (1366, 'e24', '201402', 'achat de matériel de papeterie', '2014-02-13', '46.00'), (1367, 'e24', '201402', 'location équipement vidéo/sonore', '2014-02-05', '753.00'), (1368, 'e24', '201402', 'location véhicule', '2014-02-07', '323.00'), (1369, 'e24', '201402', 'Voyage SNCF', '2014-02-28', '136.00'), (1370, 'e24', '201402', 'traiteur, alimentation, boisson', '2014-02-17', '189.00'), (1371, 'e24', '201402', 'location équipement vidéo/sonore', '2014-02-22', '609.00'), (1372, 'e24', '201402', 'traiteur, alimentation, boisson', '2014-02-27', '430.00'), (1373, 'e24', '201402', 'achat de matériel de papeterie', '2014-02-17', '49.00'), (1374, 'e24', '201402', 'taxi', '2014-02-10', '42.00'), (1375, 'e24', '201402', 'Voyage SNCF', '2014-02-02', '127.00'), (1376, 'e24', '201402', 'location équipement vidéo/sonore', '2014-02-17', '721.00'), (1377, 'e24', '201403', 'location véhicule', '2014-03-25', '167.00'), (1378, 'e24', '201403', 'frais vestimentaire/représentation', '2014-03-07', '310.00'), (1379, 'e24', '201403', 'Voyage SNCF', '2014-03-25', '113.00'), (1380, 'e24', '201403', 'taxi', '2014-03-19', '74.00'), (1381, 'e24', '201404', 'traiteur, alimentation, boisson', '2014-04-26', '375.00'), (1382, 'e24', '201404', 'achat de matériel de papeterie', '2014-04-18', '48.00'), (1383, 'e24', '201404', 'location véhicule', '2014-04-17', '436.00'), (1384, 'e24', '201404', 'taxi', '2014-04-14', '49.00'), (1385, 'e24', '201404', 'taxi', '2014-04-08', '71.00'), (1386, 'e24', '201404', 'location véhicule', '2014-04-12', '31.00'), (1387, 'e24', '201404', 'taxi', '2014-04-22', '56.00'), (1388, 'e24', '201404', 'taxi', '2014-04-24', '61.00'), (1389, 'e24', '201404', 'traiteur, alimentation, boisson', '2014-04-21', '113.00'), (1390, 'e24', '201405', 'location salle conférence', '2014-05-24', '450.00'), (1391, 'e24', '201405', 'location équipement vidéo/sonore', '2014-05-10', '239.00'), (1392, 'e24', '201406', 'achat de matériel de papeterie', '2014-06-20', '42.00'), (1393, 'e24', '201406', 'Voyage SNCF', '2014-06-12', '70.00'), (1394, 'e24', '201406', 'traiteur, alimentation, boisson', '2014-06-01', '227.00'), (1395, 'e24', '201406', 'location équipement vidéo/sonore', '2014-06-11', '287.00'), (1396, 'e24', '201406', 'achat de matériel de papeterie', '2014-06-02', '39.00'), (1397, 'e24', '201406', 'repas avec praticien', '2014-06-12', '35.00'), (1398, 'e24', '201406', 'frais vestimentaire/représentation', '2014-06-19', '134.00'), (1399, 'e24', '201406', 'frais vestimentaire/représentation', '2014-06-21', '189.00'), (1400, 'e24', '201406', 'location véhicule', '2014-06-20', '204.00'), (1401, 'e24', '201406', 'taxi', '2014-06-13', '70.00'), (1402, 'e24', '201406', 'Voyage SNCF', '2014-06-28', '47.00'), (1403, 'e24', '201407', 'achat de matériel de papeterie', '2014-07-10', '22.00'), (1404, 'e24', '201407', 'frais vestimentaire/représentation', '2014-07-01', '119.00'), (1405, 'e24', '201407', 'taxi', '2014-07-07', '79.00'), (1406, 'e24', '201407', 'taxi', '2014-07-20', '28.00'), (1407, 'e24', '201407', 'Voyage SNCF', '2014-07-08', '35.00'), (1408, 'e24', '201407', 'taxi', '2014-07-13', '68.00'), (1409, 'e24', '201407', 'repas avec praticien', '2014-07-17', '40.00'), (1410, 'e24', '201407', 'achat de matériel de papeterie', '2014-07-27', '15.00'), (1411, 'e24', '201407', 'location salle conférence', '2014-07-21', '226.00'), (1412, 'e24', '201408', 'repas avec praticien', '2014-08-16', '35.00'), (1413, 'e24', '201408', 'taxi', '2014-08-10', '32.00'), (1414, 'e24', '201408', 'location véhicule', '2014-08-20', '90.00'), (1415, 'e24', '201408', 'achat de matériel de papeterie', '2014-08-18', '20.00'), (1416, 'e24', '201408', 'repas avec praticien', '2014-08-03', '43.00'), (1417, 'e24', '201408', 'Voyage SNCF', '2014-08-15', '49.00'), (1418, 'e24', '201409', 'repas avec praticien', '2014-09-24', '42.00'), (1419, 'e39', '201401', 'traiteur, alimentation, boisson', '2014-01-18', '89.00'), (1420, 'e39', '201401', 'rémunération intervenant/spécialiste', '2014-01-26', '434.00'), (1421, 'e39', '201401', 'rémunération intervenant/spécialiste', '2014-01-22', '1114.00'), (1422, 'e39', '201401', 'rémunération intervenant/spécialiste', '2014-01-27', '1129.00'), (1423, 'e39', '201401', 'Voyage SNCF', '2014-01-08', '88.00'), (1424, 'e39', '201401', 'location salle conférence', '2014-01-15', '220.00'), (1425, 'e39', '201401', 'taxi', '2014-01-01', '40.00'), (1426, 'e39', '201401', 'rémunération intervenant/spécialiste', '2014-01-11', '926.00'), (1427, 'e39', '201401', 'rémunération intervenant/spécialiste', '2014-01-07', '496.00'), (1428, 'e39', '201401', 'traiteur, alimentation, boisson', '2014-01-05', '209.00'), (1429, 'e39', '201402', 'rémunération intervenant/spécialiste', '2014-02-21', '1179.00'), (1430, 'e39', '201402', 'location équipement vidéo/sonore', '2014-02-16', '525.00'), (1431, 'e39', '201402', 'location équipement vidéo/sonore', '2014-02-27', '243.00'), (1432, 'e39', '201402', 'location véhicule', '2014-02-15', '295.00'), (1433, 'e39', '201402', 'location véhicule', '2014-02-06', '55.00'), (1434, 'e39', '201402', 'location équipement vidéo/sonore', '2014-02-28', '115.00'), (1435, 'e39', '201402', 'location équipement vidéo/sonore', '2014-02-11', '310.00'), (1436, 'e39', '201402', 'location équipement vidéo/sonore', '2014-02-04', '255.00'), (1437, 'e39', '201402', 'traiteur, alimentation, boisson', '2014-02-24', '108.00'), (1438, 'e39', '201402', 'location équipement vidéo/sonore', '2014-02-13', '683.00'), (1439, 'e39', '201402', 'traiteur, alimentation, boisson', '2014-02-14', '95.00'), (1440, 'e39', '201403', 'rémunération intervenant/spécialiste', '2014-03-23', '980.00'), (1441, 'e39', '201403', 'location équipement vidéo/sonore', '2014-03-16', '848.00'), (1442, 'e39', '201403', 'location salle conférence', '2014-03-26', '534.00'), (1443, 'e39', '201403', 'repas avec praticien', '2014-03-15', '35.00'), (1444, 'e39', '201403', 'taxi', '2014-03-01', '24.00'), (1445, 'e39', '201403', 'rémunération intervenant/spécialiste', '2014-03-07', '624.00'), (1446, 'e39', '201403', 'location véhicule', '2014-03-04', '213.00'), (1447, 'e39', '201403', 'location salle conférence', '2014-03-17', '235.00'), (1448, 'e39', '201403', 'location véhicule', '2014-03-09', '106.00'), (1449, 'e39', '201403', 'rémunération intervenant/spécialiste', '2014-03-28', '553.00'), (1450, 'e39', '201404', 'location salle conférence', '2014-04-18', '570.00'), (1451, 'e39', '201404', 'location équipement vidéo/sonore', '2014-04-18', '220.00'), (1452, 'e39', '201404', 'traiteur, alimentation, boisson', '2014-04-27', '174.00'), (1453, 'e39', '201404', 'location véhicule', '2014-04-08', '334.00'), (1454, 'e39', '201404', 'location salle conférence', '2014-04-12', '227.00'), (1455, 'e39', '201404', 'repas avec praticien', '2014-04-28', '43.00'), (1456, 'e39', '201404', 'location salle conférence', '2014-04-06', '450.00'), (1457, 'e39', '201404', 'location véhicule', '2014-04-14', '99.00'), (1458, 'e39', '201404', 'taxi', '2014-04-14', '23.00'), (1459, 'e39', '201405', 'taxi', '2014-05-19', '38.00'), (1460, 'e39', '201405', 'location salle conférence', '2014-05-23', '346.00'), (1461, 'e39', '201405', 'traiteur, alimentation, boisson', '2014-05-10', '414.00'), (1462, 'e39', '201405', 'repas avec praticien', '2014-05-16', '30.00'), (1463, 'e39', '201405', 'location équipement vidéo/sonore', '2014-05-23', '654.00'), (1464, 'e39', '201405', 'location salle conférence', '2014-05-19', '176.00'), (1465, 'e39', '201405', 'traiteur, alimentation, boisson', '2014-05-26', '446.00'), (1466, 'e39', '201405', 'rémunération intervenant/spécialiste', '2014-05-19', '707.00'), (1467, 'e39', '201406', 'traiteur, alimentation, boisson', '2014-06-05', '109.00'), (1468, 'e39', '201406', 'location équipement vidéo/sonore', '2014-06-23', '129.00'), (1469, 'e39', '201406', 'rémunération intervenant/spécialiste', '2014-06-26', '1161.00'), (1470, 'e39', '201406', 'location véhicule', '2014-06-01', '403.00'), (1471, 'e39', '201406', 'rémunération intervenant/spécialiste', '2014-06-02', '735.00'), (1472, 'e39', '201406', 'location équipement vidéo/sonore', '2014-06-09', '341.00'), (1473, 'e39', '201406', 'frais vestimentaire/représentation', '2014-06-09', '249.00'), (1474, 'e39', '201406', 'location salle conférence', '2014-06-05', '469.00'), (1475, 'e39', '201406', 'traiteur, alimentation, boisson', '2014-06-01', '144.00'), (1476, 'e39', '201406', 'frais vestimentaire/représentation', '2014-06-04', '315.00'), (1477, 'e39', '201406', 'achat de matériel de papeterie', '2014-06-15', '46.00'), (1478, 'e39', '201406', 'Voyage SNCF', '2014-06-05', '138.00'), (1479, 'e39', '201407', 'Voyage SNCF', '2014-07-20', '75.00'), (1480, 'e39', '201407', 'location équipement vidéo/sonore', '2014-07-10', '690.00'), (1481, 'e39', '201407', 'location équipement vidéo/sonore', '2014-07-10', '590.00'), (1482, 'e39', '201407', 'repas avec praticien', '2014-07-05', '37.00'), (1483, 'e39', '201407', 'location véhicule', '2014-07-19', '63.00'), (1484, 'e39', '201407', 'location équipement vidéo/sonore', '2014-07-23', '328.00'), (1485, 'e39', '201407', 'traiteur, alimentation, boisson', '2014-07-11', '199.00'), (1486, 'e39', '201408', 'Voyage SNCF', '2014-08-05', '101.00'), (1487, 'e39', '201408', 'traiteur, alimentation, boisson', '2014-08-08', '89.00'), (1488, 'e39', '201408', 'taxi', '2014-08-28', '50.00'), (1489, 'e39', '201408', 'frais vestimentaire/représentation', '2014-08-28', '306.00'), (1490, 'e39', '201408', 'location équipement vidéo/sonore', '2014-08-03', '485.00'), (1491, 'e39', '201408', 'rémunération intervenant/spécialiste', '2014-08-15', '1168.00'), (1492, 'e39', '201408', 'traiteur, alimentation, boisson', '2014-08-09', '372.00'), (1493, 'e39', '201408', 'location véhicule', '2014-08-04', '327.00'), (1494, 'e39', '201408', 'achat de matériel de papeterie', '2014-08-18', '12.00'), (1495, 'e39', '201408', 'location véhicule', '2014-08-03', '187.00'), (1496, 'e39', '201408', 'location véhicule', '2014-08-09', '305.00'), (1497, 'e39', '201408', 'location salle conférence', '2014-08-23', '417.00'), (1498, 'e39', '201409', 'frais vestimentaire/représentation', '2014-09-28', '149.00'), (1499, 'e39', '201409', 'achat de matériel de papeterie', '2014-09-05', '17.00'), (1500, 'e39', '201409', 'location salle conférence', '2014-09-04', '277.00'), (1501, 'e39', '201409', 'location équipement vidéo/sonore', '2014-09-15', '752.00'), (1502, 'e39', '201409', 'taxi', '2014-09-15', '29.00'), (1503, 'e39', '201409', 'traiteur, alimentation, boisson', '2014-09-28', '217.00'), (1504, 'e39', '201409', 'repas avec praticien', '2014-09-08', '30.00'), (1505, 'e39', '201409', 'rémunération intervenant/spécialiste', '2014-09-09', '933.00'), (1506, 'e39', '201409', 'Voyage SNCF', '2014-09-10', '35.00'), (1507, 'e39', '201409', 'frais vestimentaire/représentation', '2014-09-13', '371.00'), (1508, 'e39', '201409', 'location équipement vidéo/sonore', '2014-09-21', '359.00'), (1509, 'e49', '201401', 'repas avec praticien', '2014-01-05', '46.00'), (1510, 'e49', '201401', 'traiteur, alimentation, boisson', '2014-01-27', '360.00'), (1511, 'e49', '201401', 'location salle conférence', '2014-01-04', '560.00'), (1512, 'e49', '201401', 'repas avec praticien', '2014-01-26', '37.00'), (1513, 'e49', '201401', 'traiteur, alimentation, boisson', '2014-01-09', '388.00'), (1514, 'e49', '201401', 'achat de matériel de papeterie', '2014-01-27', '12.00'), (1515, 'e49', '201401', 'location équipement vidéo/sonore', '2014-01-17', '197.00'), (1516, 'e49', '201402', 'frais vestimentaire/représentation', '2014-02-24', '113.00'), (1517, 'e49', '201402', 'traiteur, alimentation, boisson', '2014-02-20', '271.00'), (1518, 'e49', '201402', 'location salle conférence', '2014-02-06', '644.00'), (1519, 'e49', '201402', 'location véhicule', '2014-02-09', '320.00'), (1520, 'e49', '201402', 'location salle conférence', '2014-02-12', '385.00'), (1521, 'e49', '201402', 'taxi', '2014-02-15', '57.00'), (1522, 'e49', '201402', 'frais vestimentaire/représentation', '2014-02-22', '144.00'), (1523, 'e49', '201403', 'repas avec praticien', '2014-03-16', '37.00'), (1524, 'e49', '201403', 'taxi', '2014-03-28', '26.00'), (1525, 'e49', '201403', 'repas avec praticien', '2014-03-28', '46.00'), (1526, 'e49', '201403', 'achat de matériel de papeterie', '2014-03-20', '41.00'), (1527, 'e49', '201403', 'frais vestimentaire/représentation', '2014-03-25', '112.00'), (1528, 'e49', '201403', 'repas avec praticien', '2014-03-07', '30.00'), (1529, 'e49', '201403', 'frais vestimentaire/représentation', '2014-03-10', '334.00'), (1530, 'e49', '201403', 'rémunération intervenant/spécialiste', '2014-03-23', '410.00'), (1531, 'e49', '201403', 'location véhicule', '2014-03-01', '219.00'), (1532, 'e49', '201403', 'repas avec praticien', '2014-03-03', '49.00'), (1533, 'e49', '201403', 'traiteur, alimentation, boisson', '2014-03-10', '329.00'), (1534, 'e49', '201403', 'traiteur, alimentation, boisson', '2014-03-14', '251.00'), (1535, 'e49', '201404', 'achat de matériel de papeterie', '2014-04-10', '20.00'), (1536, 'e49', '201404', 'rémunération intervenant/spécialiste', '2014-04-27', '903.00'), (1537, 'e49', '201404', 'location véhicule', '2014-04-28', '49.00'), (1538, 'e49', '201404', 'location salle conférence', '2014-04-08', '588.00'), (1539, 'e49', '201404', 'frais vestimentaire/représentation', '2014-04-16', '326.00'), (1540, 'e49', '201404', 'location équipement vidéo/sonore', '2014-04-09', '467.00'), (1541, 'e49', '201404', 'location équipement vidéo/sonore', '2014-04-04', '682.00'), (1542, 'e49', '201404', 'repas avec praticien', '2014-04-25', '42.00'), (1543, 'e49', '201404', 'traiteur, alimentation, boisson', '2014-04-13', '97.00'), (1544, 'e49', '201404', 'taxi', '2014-04-18', '30.00'), (1545, 'e49', '201405', 'traiteur, alimentation, boisson', '2014-05-26', '134.00'), (1546, 'e49', '201405', 'repas avec praticien', '2014-05-28', '46.00'), (1547, 'e49', '201405', 'rémunération intervenant/spécialiste', '2014-05-26', '307.00'), (1548, 'e49', '201406', 'location véhicule', '2014-06-02', '359.00'), (1549, 'e49', '201406', 'repas avec praticien', '2014-06-18', '41.00'), (1550, 'e49', '201406', 'traiteur, alimentation, boisson', '2014-06-14', '138.00'), (1551, 'e49', '201406', 'location véhicule', '2014-06-15', '310.00'), (1552, 'e49', '201406', 'taxi', '2014-06-08', '57.00'), (1553, 'e49', '201406', 'taxi', '2014-06-01', '26.00'), (1554, 'e49', '201407', 'achat de matériel de papeterie', '2014-07-18', '18.00'), (1555, 'e49', '201407', 'Voyage SNCF', '2014-07-27', '100.00'), (1556, 'e49', '201407', 'traiteur, alimentation, boisson', '2014-07-14', '449.00'), (1557, 'e49', '201407', 'achat de matériel de papeterie', '2014-07-08', '43.00'), (1558, 'e49', '201407', 'traiteur, alimentation, boisson', '2014-07-10', '229.00'), (1559, 'e49', '201407', 'rémunération intervenant/spécialiste', '2014-07-21', '736.00'), (1560, 'e49', '201407', 'location salle conférence', '2014-07-02', '581.00'), (1561, 'e49', '201407', 'location équipement vidéo/sonore', '2014-07-09', '818.00'), (1562, 'e49', '201407', 'location véhicule', '2014-07-14', '28.00'), (1563, 'e49', '201407', 'achat de matériel de papeterie', '2014-07-06', '18.00'), (1564, 'e49', '201408', 'frais vestimentaire/représentation', '2014-08-21', '359.00'), (1565, 'e49', '201408', 'location équipement vidéo/sonore', '2014-08-23', '681.00'), (1566, 'e49', '201408', 'location salle conférence', '2014-08-09', '144.00'), (1567, 'e49', '201408', 'repas avec praticien', '2014-08-04', '44.00'), (1568, 'e49', '201408', 'traiteur, alimentation, boisson', '2014-08-08', '274.00'), (1569, 'e49', '201408', 'repas avec praticien', '2014-08-08', '34.00'), (1570, 'e49', '201408', 'traiteur, alimentation, boisson', '2014-08-08', '104.00'), (1571, 'e49', '201408', 'location salle conférence', '2014-08-06', '307.00'), (1572, 'e49', '201408', 'location équipement vidéo/sonore', '2014-08-20', '563.00'), (1573, 'e49', '201408', 'rémunération intervenant/spécialiste', '2014-08-17', '781.00'), (1574, 'e49', '201408', 'frais vestimentaire/représentation', '2014-08-15', '141.00'), (1575, 'e49', '201409', 'Voyage SNCF', '2014-09-18', '124.00'), (1576, 'e49', '201409', 'traiteur, alimentation, boisson', '2014-09-16', '418.00'), (1577, 'e49', '201409', 'location salle conférence', '2014-09-02', '422.00'), (1578, 'e5', '201401', 'location équipement vidéo/sonore', '2014-01-02', '738.00'), (1579, 'e5', '201401', 'location salle conférence', '2014-01-04', '365.00'), (1580, 'e5', '201401', 'location véhicule', '2014-01-22', '328.00'), (1581, 'e5', '201401', 'location véhicule', '2014-01-01', '232.00'), (1582, 'e5', '201401', 'traiteur, alimentation, boisson', '2014-01-18', '46.00'), (1583, 'e5', '201401', 'repas avec praticien', '2014-01-04', '33.00'), (1584, 'e5', '201401', 'achat de matériel de papeterie', '2014-01-21', '17.00'), (1585, 'e5', '201401', 'location équipement vidéo/sonore', '2014-01-09', '392.00'), (1586, 'e5', '201401', 'taxi', '2014-01-28', '20.00'), (1587, 'e5', '201401', 'location salle conférence', '2014-01-12', '225.00'), (1588, 'e5', '201402', 'Voyage SNCF', '2014-02-27', '108.00'), (1589, 'e5', '201402', 'rémunération intervenant/spécialiste', '2014-02-21', '1084.00'), (1590, 'e5', '201402', 'taxi', '2014-02-12', '68.00'), (1591, 'e5', '201402', 'repas avec praticien', '2014-02-14', '30.00'), (1592, 'e5', '201402', 'traiteur, alimentation, boisson', '2014-02-14', '308.00'), (1593, 'e5', '201402', 'traiteur, alimentation, boisson', '2014-02-06', '206.00'), (1594, 'e5', '201402', 'location salle conférence', '2014-02-10', '353.00'), (1595, 'e5', '201402', 'location équipement vidéo/sonore', '2014-02-26', '795.00'), (1596, 'e5', '201402', 'location salle conférence', '2014-02-21', '545.00'), (1597, 'e5', '201403', 'repas avec praticien', '2014-03-22', '30.00'), (1598, 'e5', '201403', 'rémunération intervenant/spécialiste', '2014-03-24', '1041.00'), (1599, 'e5', '201403', 'achat de matériel de papeterie', '2014-03-11', '49.00'), (1600, 'e5', '201403', 'location équipement vidéo/sonore', '2014-03-18', '118.00'), (1601, 'e5', '201403', 'traiteur, alimentation, boisson', '2014-03-13', '423.00'), (1602, 'e5', '201403', 'achat de matériel de papeterie', '2014-03-13', '32.00'), (1603, 'e5', '201403', 'taxi', '2014-03-25', '49.00'), (1604, 'e5', '201403', 'repas avec praticien', '2014-03-03', '45.00'), (1605, 'e5', '201403', 'traiteur, alimentation, boisson', '2014-03-22', '41.00'), (1606, 'e5', '201403', 'frais vestimentaire/représentation', '2014-03-02', '204.00'), (1607, 'e5', '201404', 'Voyage SNCF', '2014-04-09', '72.00'), (1608, 'e5', '201404', 'location salle conférence', '2014-04-28', '531.00'), (1609, 'e5', '201404', 'Voyage SNCF', '2014-04-06', '49.00'), (1610, 'e5', '201404', 'Voyage SNCF', '2014-04-24', '149.00'), (1611, 'e5', '201404', 'rémunération intervenant/spécialiste', '2014-04-11', '582.00'), (1612, 'e5', '201404', 'location véhicule', '2014-04-21', '386.00'), (1613, 'e5', '201404', 'location véhicule', '2014-04-15', '409.00'), (1614, 'e5', '201404', 'taxi', '2014-04-13', '33.00'), (1615, 'e5', '201404', 'taxi', '2014-04-19', '75.00'), (1616, 'e5', '201404', 'location véhicule', '2014-04-05', '355.00'), (1617, 'e5', '201404', 'rémunération intervenant/spécialiste', '2014-04-22', '385.00'), (1618, 'e5', '201405', 'Voyage SNCF', '2014-05-16', '44.00'), (1619, 'e5', '201405', 'repas avec praticien', '2014-05-14', '44.00'), (1620, 'e5', '201405', 'rémunération intervenant/spécialiste', '2014-05-12', '796.00'), (1621, 'e5', '201405', 'Voyage SNCF', '2014-05-07', '145.00'), (1622, 'e5', '201405', 'Voyage SNCF', '2014-05-16', '65.00'), (1623, 'e5', '201405', 'achat de matériel de papeterie', '2014-05-25', '17.00'), (1624, 'e5', '201405', 'rémunération intervenant/spécialiste', '2014-05-07', '848.00'), (1625, 'e5', '201406', 'Voyage SNCF', '2014-06-14', '134.00'), (1626, 'e5', '201406', 'traiteur, alimentation, boisson', '2014-06-17', '220.00'), (1627, 'e5', '201406', 'frais vestimentaire/représentation', '2014-06-15', '298.00'), (1628, 'e5', '201406', 'frais vestimentaire/représentation', '2014-06-20', '376.00'), (1629, 'e5', '201406', 'location véhicule', '2014-06-09', '121.00'), (1630, 'e5', '201406', 'location salle conférence', '2014-06-02', '262.00'), (1631, 'e5', '201406', 'achat de matériel de papeterie', '2014-06-06', '10.00'), (1632, 'e5', '201406', 'traiteur, alimentation, boisson', '2014-06-13', '253.00'), (1633, 'e5', '201406', 'rémunération intervenant/spécialiste', '2014-06-07', '622.00'), (1634, 'e5', '201407', 'repas avec praticien', '2014-07-13', '42.00'), (1635, 'e5', '201408', 'location salle conférence', '2014-08-26', '518.00'), (1636, 'e5', '201408', 'Voyage SNCF', '2014-08-28', '43.00'), (1637, 'e5', '201408', 'location équipement vidéo/sonore', '2014-08-07', '549.00'), (1638, 'e5', '201408', 'location véhicule', '2014-08-06', '395.00'), (1639, 'e5', '201408', 'achat de matériel de papeterie', '2014-08-10', '31.00'), (1640, 'e5', '201408', 'achat de matériel de papeterie', '2014-08-16', '48.00'), (1641, 'e5', '201408', 'location véhicule', '2014-08-28', '390.00'), (1642, 'e5', '201408', 'frais vestimentaire/représentation', '2014-08-03', '359.00'), (1643, 'e5', '201409', 'Voyage SNCF', '2014-09-07', '117.00'), (1644, 'e5', '201409', 'achat de matériel de papeterie', '2014-09-12', '50.00'), (1645, 'e5', '201409', 'achat de matériel de papeterie', '2014-09-24', '11.00'), (1646, 'e5', '201409', 'traiteur, alimentation, boisson', '2014-09-27', '232.00'), (1647, 'e5', '201409', 'location équipement vidéo/sonore', '2014-09-23', '206.00'), (1648, 'e5', '201409', 'repas avec praticien', '2014-09-07', '37.00'), (1649, 'e5', '201409', 'taxi', '2014-09-15', '41.00'), (1650, 'e5', '201409', 'location salle conférence', '2014-09-03', '402.00'), (1651, 'e5', '201409', 'rémunération intervenant/spécialiste', '2014-09-26', '971.00'), (1652, 'e52', '201401', 'location équipement vidéo/sonore', '2014-01-03', '785.00'), (1653, 'e52', '201401', 'location équipement vidéo/sonore', '2014-01-27', '419.00'), (1654, 'e52', '201402', 'frais vestimentaire/représentation', '2014-02-13', '229.00'), (1655, 'e52', '201402', 'achat de matériel de papeterie', '2014-02-13', '49.00'), (1656, 'e52', '201402', 'Voyage SNCF', '2014-02-18', '35.00'), (1657, 'e52', '201402', 'taxi', '2014-02-17', '67.00'), (1658, 'e52', '201404', 'frais vestimentaire/représentation', '2014-04-02', '289.00'), (1659, 'e52', '201404', 'rémunération intervenant/spécialiste', '2014-04-26', '433.00'), (1660, 'e52', '201404', 'location véhicule', '2014-04-06', '239.00'), (1661, 'e52', '201404', 'location équipement vidéo/sonore', '2014-04-21', '334.00'), (1662, 'e52', '201404', 'location salle conférence', '2014-04-14', '222.00'), (1663, 'e52', '201404', 'taxi', '2014-04-25', '71.00'), (1664, 'e52', '201404', 'achat de matériel de papeterie', '2014-04-26', '19.00'), (1665, 'e52', '201404', 'location véhicule', '2014-04-21', '231.00'), (1666, 'e52', '201404', 'traiteur, alimentation, boisson', '2014-04-08', '361.00'), (1667, 'e52', '201404', 'frais vestimentaire/représentation', '2014-04-20', '190.00'), (1668, 'e52', '201404', 'rémunération intervenant/spécialiste', '2014-04-07', '1036.00'), (1669, 'e52', '201404', 'taxi', '2014-04-19', '46.00'), (1670, 'e52', '201405', 'location salle conférence', '2014-05-08', '535.00'), (1671, 'e52', '201405', 'Voyage SNCF', '2014-05-12', '143.00'), (1672, 'e52', '201405', 'repas avec praticien', '2014-05-23', '36.00'), (1673, 'e52', '201405', 'traiteur, alimentation, boisson', '2014-05-03', '367.00'), (1674, 'e52', '201405', 'rémunération intervenant/spécialiste', '2014-05-26', '1162.00'), (1675, 'e52', '201405', 'taxi', '2014-05-23', '55.00'), (1676, 'e52', '201405', 'achat de matériel de papeterie', '2014-05-05', '43.00'), (1677, 'e52', '201405', 'location équipement vidéo/sonore', '2014-05-06', '826.00'), (1678, 'e52', '201405', 'Voyage SNCF', '2014-05-04', '54.00'), (1679, 'e52', '201405', 'location salle conférence', '2014-05-20', '228.00'), (1680, 'e52', '201405', 'frais vestimentaire/représentation', '2014-05-10', '405.00'), (1681, 'e52', '201406', 'location salle conférence', '2014-06-15', '451.00'), (1682, 'e52', '201406', 'location salle conférence', '2014-06-02', '509.00'), (1683, 'e52', '201406', 'location équipement vidéo/sonore', '2014-06-23', '507.00'), (1684, 'e52', '201406', 'taxi', '2014-06-19', '70.00'), (1685, 'e52', '201406', 'frais vestimentaire/représentation', '2014-06-20', '234.00'), (1686, 'e52', '201406', 'frais vestimentaire/représentation', '2014-06-26', '26.00'), (1687, 'e52', '201407', 'taxi', '2014-07-26', '41.00'), (1688, 'e52', '201407', 'rémunération intervenant/spécialiste', '2014-07-23', '824.00'), (1689, 'e52', '201407', 'Voyage SNCF', '2014-07-24', '97.00'), (1690, 'e52', '201407', 'rémunération intervenant/spécialiste', '2014-07-18', '304.00'), (1691, 'e52', '201407', 'achat de matériel de papeterie', '2014-07-19', '48.00'), (1692, 'e52', '201407', 'Voyage SNCF', '2014-07-23', '61.00'), (1693, 'e52', '201407', 'rémunération intervenant/spécialiste', '2014-07-11', '420.00'), (1694, 'e52', '201407', 'achat de matériel de papeterie', '2014-07-11', '17.00'), (1695, 'e52', '201407', 'taxi', '2014-07-17', '40.00'), (1696, 'e52', '201407', 'achat de matériel de papeterie', '2014-07-06', '11.00'), (1697, 'e52', '201407', 'location véhicule', '2014-07-15', '55.00'), (1698, 'e52', '201407', 'achat de matériel de papeterie', '2014-07-08', '29.00'), (1699, 'e52', '201408', 'location véhicule', '2014-08-09', '192.00'), (1700, 'e52', '201408', 'location véhicule', '2014-08-03', '371.00'), (1701, 'e52', '201408', 'taxi', '2014-08-24', '59.00'), (1702, 'e52', '201408', 'Voyage SNCF', '2014-08-28', '124.00'), (1703, 'e52', '201408', 'taxi', '2014-08-26', '32.00'), (1704, 'e52', '201408', 'achat de matériel de papeterie', '2014-08-02', '46.00'), (1705, 'e52', '201408', 'traiteur, alimentation, boisson', '2014-08-28', '443.00'), (1706, 'e52', '201408', 'location équipement vidéo/sonore', '2014-08-17', '622.00'), (1707, 'e52', '201408', 'rémunération intervenant/spécialiste', '2014-08-26', '464.00'), (1708, 'e52', '201408', 'taxi', '2014-08-08', '22.00'), (1709, 'e52', '201408', 'taxi', '2014-08-21', '43.00'), (1710, 'e52', '201409', 'repas avec praticien', '2014-09-01', '36.00'), (1711, 'e52', '201409', 'achat de matériel de papeterie', '2014-09-14', '22.00'), (1712, 'e52', '201409', 'traiteur, alimentation, boisson', '2014-09-17', '48.00'), (1713, 'e52', '201409', 'repas avec praticien', '2014-09-01', '44.00'), (1714, 'e52', '201409', 'location équipement vidéo/sonore', '2014-09-01', '539.00'), (1715, 'f21', '201401', 'location salle conférence', '2014-01-23', '223.00'), (1716, 'f21', '201401', 'location équipement vidéo/sonore', '2014-01-14', '404.00'), (1717, 'f21', '201401', 'location équipement vidéo/sonore', '2014-01-07', '647.00'), (1718, 'f21', '201401', 'Voyage SNCF', '2014-01-03', '38.00'), (1719, 'f21', '201401', 'location véhicule', '2014-01-15', '396.00'), (1720, 'f21', '201401', 'achat de matériel de papeterie', '2014-01-20', '42.00'), (1721, 'f21', '201401', 'traiteur, alimentation, boisson', '2014-01-07', '62.00'), (1722, 'f21', '201401', 'location véhicule', '2014-01-05', '254.00'), (1723, 'f21', '201401', 'Voyage SNCF', '2014-01-08', '80.00'), (1724, 'f21', '201401', 'taxi', '2014-01-05', '70.00'), (1725, 'f21', '201401', 'location équipement vidéo/sonore', '2014-01-03', '459.00'), (1726, 'f21', '201402', 'location équipement vidéo/sonore', '2014-02-17', '594.00'), (1727, 'f21', '201402', 'location salle conférence', '2014-02-28', '214.00'), (1728, 'f21', '201402', 'taxi', '2014-02-21', '46.00'), (1729, 'f21', '201402', 'achat de matériel de papeterie', '2014-02-13', '24.00'), (1730, 'f21', '201402', 'Voyage SNCF', '2014-02-22', '78.00'), (1731, 'f21', '201402', 'Voyage SNCF', '2014-02-13', '150.00'), (1732, 'f21', '201402', 'location équipement vidéo/sonore', '2014-02-12', '836.00'), (1733, 'f21', '201402', 'Voyage SNCF', '2014-02-26', '72.00'), (1734, 'f21', '201402', 'location équipement vidéo/sonore', '2014-02-02', '662.00'), (1735, 'f21', '201402', 'location équipement vidéo/sonore', '2014-02-11', '438.00'), (1736, 'f21', '201402', 'location salle conférence', '2014-02-14', '576.00'), (1737, 'f21', '201403', 'location équipement vidéo/sonore', '2014-03-25', '701.00'), (1738, 'f21', '201403', 'frais vestimentaire/représentation', '2014-03-27', '308.00'), (1739, 'f21', '201403', 'frais vestimentaire/représentation', '2014-03-12', '289.00'), (1740, 'f21', '201403', 'achat de matériel de papeterie', '2014-03-24', '46.00'), (1741, 'f21', '201403', 'rémunération intervenant/spécialiste', '2014-03-28', '964.00'), (1742, 'f21', '201403', 'rémunération intervenant/spécialiste', '2014-03-17', '938.00'), (1743, 'f21', '201403', 'repas avec praticien', '2014-03-03', '34.00'), (1744, 'f21', '201403', 'Voyage SNCF', '2014-03-22', '134.00'), (1745, 'f21', '201403', 'location salle conférence', '2014-03-14', '186.00'), (1746, 'f21', '201403', 'location salle conférence', '2014-03-12', '474.00'), (1747, 'f21', '201403', 'rémunération intervenant/spécialiste', '2014-03-16', '404.00'), (1748, 'f21', '201404', 'frais vestimentaire/représentation', '2014-04-05', '199.00'), (1749, 'f21', '201405', 'frais vestimentaire/représentation', '2014-05-01', '91.00'), (1750, 'f21', '201405', 'location équipement vidéo/sonore', '2014-05-25', '150.00'), (1751, 'f21', '201405', 'Voyage SNCF', '2014-05-03', '90.00'), (1752, 'f21', '201405', 'rémunération intervenant/spécialiste', '2014-05-23', '792.00'), (1753, 'f21', '201405', 'location équipement vidéo/sonore', '2014-05-28', '341.00'), (1754, 'f21', '201405', 'location équipement vidéo/sonore', '2014-05-14', '603.00'), (1755, 'f21', '201405', 'taxi', '2014-05-27', '49.00'), (1756, 'f21', '201405', 'repas avec praticien', '2014-05-16', '37.00'), (1757, 'f21', '201406', 'taxi', '2014-06-02', '62.00'), (1758, 'f21', '201406', 'repas avec praticien', '2014-06-09', '31.00'), (1759, 'f21', '201406', 'traiteur, alimentation, boisson', '2014-06-22', '353.00'), (1760, 'f21', '201406', 'traiteur, alimentation, boisson', '2014-06-22', '140.00'), (1761, 'f21', '201406', 'taxi', '2014-06-19', '58.00'), (1762, 'f21', '201407', 'rémunération intervenant/spécialiste', '2014-07-25', '1006.00'), (1763, 'f21', '201407', 'frais vestimentaire/représentation', '2014-07-03', '89.00'), (1764, 'f21', '201407', 'Voyage SNCF', '2014-07-25', '41.00'), (1765, 'f21', '201407', 'frais vestimentaire/représentation', '2014-07-10', '305.00'), (1766, 'f21', '201407', 'rémunération intervenant/spécialiste', '2014-07-26', '625.00'), (1767, 'f21', '201407', 'Voyage SNCF', '2014-07-25', '149.00'), (1768, 'f21', '201407', 'location véhicule', '2014-07-18', '134.00'), (1769, 'f21', '201407', 'traiteur, alimentation, boisson', '2014-07-18', '260.00'), (1770, 'f21', '201408', 'repas avec praticien', '2014-08-11', '43.00'), (1771, 'f21', '201408', 'traiteur, alimentation, boisson', '2014-08-07', '249.00'), (1772, 'f21', '201408', 'traiteur, alimentation, boisson', '2014-08-10', '344.00'), (1773, 'f21', '201408', 'traiteur, alimentation, boisson', '2014-08-03', '226.00'), (1774, 'f21', '201408', 'location véhicule', '2014-08-05', '440.00'), (1775, 'f21', '201408', 'Voyage SNCF', '2014-08-25', '57.00'), (1776, 'f21', '201409', 'achat de matériel de papeterie', '2014-09-26', '43.00'), (1777, 'f21', '201409', 'location véhicule', '2014-09-28', '107.00'), (1778, 'f21', '201409', 'frais vestimentaire/représentation', '2014-09-05', '397.00'), (1779, 'f21', '201409', 'traiteur, alimentation, boisson', '2014-09-28', '344.00'), (1780, 'f21', '201409', 'achat de matériel de papeterie', '2014-09-05', '42.00'), (1781, 'f21', '201409', 'achat de matériel de papeterie', '2014-09-11', '39.00'), (1782, 'f21', '201409', 'traiteur, alimentation, boisson', '2014-09-01', '371.00'), (1783, 'f39', '201401', 'location équipement vidéo/sonore', '2014-01-16', '848.00'), (1784, 'f39', '201401', 'frais vestimentaire/représentation', '2014-01-05', '58.00'), (1785, 'f39', '201401', 'Voyage SNCF', '2014-01-12', '143.00'), (1786, 'f39', '201401', 'taxi', '2014-01-04', '45.00'), (1787, 'f39', '201401', 'repas avec praticien', '2014-01-12', '45.00'), (1788, 'f39', '201401', 'location équipement vidéo/sonore', '2014-01-17', '772.00'), (1789, 'f39', '201401', 'repas avec praticien', '2014-01-08', '42.00'), (1790, 'f39', '201401', 'frais vestimentaire/représentation', '2014-01-06', '368.00'), (1791, 'f39', '201401', 'achat de matériel de papeterie', '2014-01-17', '26.00'), (1792, 'f39', '201401', 'location salle conférence', '2014-01-11', '528.00'), (1793, 'f39', '201401', 'rémunération intervenant/spécialiste', '2014-01-13', '855.00'), (1794, 'f39', '201402', 'location salle conférence', '2014-02-12', '120.00'), (1795, 'f39', '201402', 'location véhicule', '2014-02-03', '386.00'), (1796, 'f39', '201402', 'frais vestimentaire/représentation', '2014-02-07', '225.00'), (1797, 'f39', '201402', 'achat de matériel de papeterie', '2014-02-15', '22.00'), (1798, 'f39', '201402', 'achat de matériel de papeterie', '2014-02-04', '29.00'), (1799, 'f39', '201402', 'rémunération intervenant/spécialiste', '2014-02-11', '391.00'), (1800, 'f39', '201402', 'repas avec praticien', '2014-02-18', '46.00'), (1801, 'f39', '201402', 'taxi', '2014-02-26', '31.00'), (1802, 'f39', '201402', 'location salle conférence', '2014-02-03', '208.00'), (1803, 'f39', '201403', 'location véhicule', '2014-03-25', '252.00'), (1804, 'f39', '201403', 'location équipement vidéo/sonore', '2014-03-10', '664.00'), (1805, 'f39', '201403', 'achat de matériel de papeterie', '2014-03-15', '27.00'), (1806, 'f39', '201403', 'repas avec praticien', '2014-03-01', '50.00'), (1807, 'f39', '201403', 'frais vestimentaire/représentation', '2014-03-27', '293.00'), (1808, 'f39', '201403', 'taxi', '2014-03-20', '50.00'), (1809, 'f39', '201403', 'location équipement vidéo/sonore', '2014-03-08', '319.00'), (1810, 'f39', '201403', 'taxi', '2014-03-10', '68.00'), (1811, 'f39', '201403', 'location véhicule', '2014-03-16', '366.00'), (1812, 'f39', '201403', 'location véhicule', '2014-03-22', '45.00'), (1813, 'f39', '201403', 'Voyage SNCF', '2014-03-28', '44.00'), (1814, 'f39', '201404', 'rémunération intervenant/spécialiste', '2014-04-11', '770.00'), (1815, 'f39', '201404', 'location équipement vidéo/sonore', '2014-04-09', '493.00'), (1816, 'f39', '201404', 'Voyage SNCF', '2014-04-28', '31.00'), (1817, 'f39', '201404', 'frais vestimentaire/représentation', '2014-04-01', '447.00'), (1818, 'f39', '201404', 'Voyage SNCF', '2014-04-05', '106.00'), (1819, 'f39', '201404', 'traiteur, alimentation, boisson', '2014-04-26', '64.00'), (1820, 'f39', '201404', 'rémunération intervenant/spécialiste', '2014-04-07', '435.00'), (1821, 'f39', '201404', 'location véhicule', '2014-04-16', '351.00'), (1822, 'f39', '201404', 'location véhicule', '2014-04-05', '70.00'), (1823, 'f39', '201404', 'repas avec praticien', '2014-04-21', '38.00'), (1824, 'f39', '201404', 'repas avec praticien', '2014-04-27', '42.00'), (1825, 'f39', '201405', 'repas avec praticien', '2014-05-14', '46.00'), (1826, 'f39', '201405', 'achat de matériel de papeterie', '2014-05-16', '24.00'), (1827, 'f39', '201405', 'repas avec praticien', '2014-05-13', '36.00'), (1828, 'f39', '201405', 'rémunération intervenant/spécialiste', '2014-05-08', '1128.00'), (1829, 'f39', '201405', 'location véhicule', '2014-05-16', '423.00'), (1830, 'f39', '201405', 'Voyage SNCF', '2014-05-15', '121.00'), (1831, 'f39', '201405', 'rémunération intervenant/spécialiste', '2014-05-20', '1185.00'), (1832, 'f39', '201405', 'achat de matériel de papeterie', '2014-05-06', '42.00'), (1833, 'f39', '201405', 'location équipement vidéo/sonore', '2014-05-17', '119.00'), (1834, 'f39', '201405', 'repas avec praticien', '2014-05-26', '40.00'), (1835, 'f39', '201405', 'Voyage SNCF', '2014-05-03', '42.00'), (1836, 'f39', '201406', 'frais vestimentaire/représentation', '2014-06-01', '191.00'), (1837, 'f39', '201406', 'traiteur, alimentation, boisson', '2014-06-17', '62.00'), (1838, 'f39', '201406', 'taxi', '2014-06-02', '60.00'), (1839, 'f39', '201406', 'achat de matériel de papeterie', '2014-06-01', '19.00'), (1840, 'f39', '201406', 'traiteur, alimentation, boisson', '2014-06-24', '449.00'), (1841, 'f39', '201406', 'location équipement vidéo/sonore', '2014-06-25', '175.00'), (1842, 'f39', '201406', 'frais vestimentaire/représentation', '2014-06-02', '48.00'), (1843, 'f39', '201406', 'Voyage SNCF', '2014-06-06', '137.00'), (1844, 'f39', '201406', 'traiteur, alimentation, boisson', '2014-06-15', '37.00'), (1845, 'f39', '201406', 'taxi', '2014-06-08', '34.00'), (1846, 'f39', '201407', 'traiteur, alimentation, boisson', '2014-07-11', '100.00'), (1847, 'f39', '201407', 'rémunération intervenant/spécialiste', '2014-07-27', '490.00'), (1848, 'f39', '201407', 'repas avec praticien', '2014-07-20', '37.00'), (1849, 'f39', '201407', 'rémunération intervenant/spécialiste', '2014-07-04', '856.00'), (1850, 'f39', '201407', 'location véhicule', '2014-07-21', '430.00'), (1851, 'f39', '201408', 'rémunération intervenant/spécialiste', '2014-08-28', '1125.00'), (1852, 'f39', '201408', 'frais vestimentaire/représentation', '2014-08-05', '312.00'), (1853, 'f39', '201408', 'location salle conférence', '2014-08-03', '632.00'), (1854, 'f39', '201408', 'repas avec praticien', '2014-08-12', '45.00'), (1855, 'f39', '201408', 'taxi', '2014-08-04', '21.00'), (1856, 'f39', '201408', 'Voyage SNCF', '2014-08-02', '38.00'), (1857, 'f39', '201408', 'repas avec praticien', '2014-08-24', '50.00'), (1858, 'f39', '201408', 'traiteur, alimentation, boisson', '2014-08-01', '329.00'), (1859, 'f39', '201408', 'location salle conférence', '2014-08-19', '478.00'), (1860, 'f39', '201408', 'frais vestimentaire/représentation', '2014-08-23', '101.00'), (1861, 'f39', '201409', 'taxi', '2014-09-24', '35.00'), (1862, 'f39', '201409', 'repas avec praticien', '2014-09-22', '42.00'), (1863, 'f39', '201409', 'repas avec praticien', '2014-09-18', '46.00'), (1864, 'f39', '201409', 'Voyage SNCF', '2014-09-10', '123.00'), (1865, 'f39', '201409', 'location salle conférence', '2014-09-25', '414.00'), (1866, 'f39', '201409', 'location équipement vidéo/sonore', '2014-09-21', '508.00'), (1867, 'f39', '201409', 'rémunération intervenant/spécialiste', '2014-09-04', '635.00'), (1868, 'f39', '201409', 'taxi', '2014-09-10', '22.00'), (1869, 'f39', '201409', 'rémunération intervenant/spécialiste', '2014-09-09', '1032.00'), (1870, 'f39', '201409', 'frais vestimentaire/représentation', '2014-09-19', '221.00'), (1871, 'f4', '201401', 'location salle conférence', '2014-01-06', '519.00'), (1872, 'f4', '201401', 'Voyage SNCF', '2014-01-10', '75.00'), (1873, 'f4', '201401', 'location véhicule', '2014-01-19', '192.00'), (1874, 'f4', '201401', 'Voyage SNCF', '2014-01-13', '42.00'), (1875, 'f4', '201401', 'repas avec praticien', '2014-01-12', '36.00'), (1876, 'f4', '201401', 'location salle conférence', '2014-01-02', '598.00'), (1877, 'f4', '201401', 'location véhicule', '2014-01-02', '189.00'), (1878, 'f4', '201401', 'location véhicule', '2014-01-06', '97.00'), (1879, 'f4', '201401', 'location véhicule', '2014-01-10', '63.00'), (1880, 'f4', '201401', 'frais vestimentaire/représentation', '2014-01-22', '89.00'), (1881, 'f4', '201401', 'frais vestimentaire/représentation', '2014-01-08', '251.00'), (1882, 'f4', '201402', 'achat de matériel de papeterie', '2014-02-03', '11.00'), (1883, 'f4', '201402', 'location équipement vidéo/sonore', '2014-02-06', '502.00'), (1884, 'f4', '201402', 'location véhicule', '2014-02-05', '284.00'), (1885, 'f4', '201402', 'taxi', '2014-02-21', '56.00'), (1886, 'f4', '201402', 'traiteur, alimentation, boisson', '2014-02-14', '407.00'), (1887, 'f4', '201402', 'traiteur, alimentation, boisson', '2014-02-11', '43.00'), (1888, 'f4', '201403', 'taxi', '2014-03-12', '80.00'), (1889, 'f4', '201403', 'location équipement vidéo/sonore', '2014-03-17', '172.00'), (1890, 'f4', '201403', 'taxi', '2014-03-04', '43.00'), (1891, 'f4', '201403', 'location salle conférence', '2014-03-16', '377.00'), (1892, 'f4', '201403', 'location véhicule', '2014-03-13', '241.00'), (1893, 'f4', '201403', 'achat de matériel de papeterie', '2014-03-16', '15.00'), (1894, 'f4', '201404', 'Voyage SNCF', '2014-04-17', '96.00'), (1895, 'f4', '201404', 'location véhicule', '2014-04-01', '247.00'), (1896, 'f4', '201404', 'taxi', '2014-04-14', '37.00'), (1897, 'f4', '201404', 'repas avec praticien', '2014-04-08', '41.00'), (1898, 'f4', '201404', 'taxi', '2014-04-06', '51.00'), (1899, 'f4', '201404', 'Voyage SNCF', '2014-04-28', '43.00'), (1900, 'f4', '201404', 'taxi', '2014-04-01', '38.00'), (1901, 'f4', '201404', 'location salle conférence', '2014-04-09', '213.00'), (1902, 'f4', '201404', 'taxi', '2014-04-07', '30.00'), (1903, 'f4', '201404', 'location équipement vidéo/sonore', '2014-04-10', '564.00'), (1904, 'f4', '201404', 'frais vestimentaire/représentation', '2014-04-16', '197.00'), (1905, 'f4', '201404', 'location salle conférence', '2014-04-12', '331.00'), (1906, 'f4', '201405', 'taxi', '2014-05-16', '32.00'), (1907, 'f4', '201405', 'location équipement vidéo/sonore', '2014-05-14', '331.00'), (1908, 'f4', '201405', 'repas avec praticien', '2014-05-19', '37.00'), (1909, 'f4', '201405', 'location équipement vidéo/sonore', '2014-05-23', '480.00'), (1910, 'f4', '201405', 'location équipement vidéo/sonore', '2014-05-08', '244.00'), (1911, 'f4', '201405', 'frais vestimentaire/représentation', '2014-05-10', '234.00'), (1912, 'f4', '201405', 'repas avec praticien', '2014-05-12', '35.00'), (1913, 'f4', '201405', 'location salle conférence', '2014-05-24', '488.00'), (1914, 'f4', '201405', 'frais vestimentaire/représentation', '2014-05-17', '53.00'), (1915, 'f4', '201405', 'location véhicule', '2014-05-08', '236.00'), (1916, 'f4', '201406', 'rémunération intervenant/spécialiste', '2014-06-14', '760.00'), (1917, 'f4', '201406', 'location équipement vidéo/sonore', '2014-06-25', '574.00'), (1918, 'f4', '201406', 'rémunération intervenant/spécialiste', '2014-06-11', '929.00'), (1919, 'f4', '201406', 'location véhicule', '2014-06-16', '181.00'), (1920, 'f4', '201406', 'achat de matériel de papeterie', '2014-06-14', '24.00'), (1921, 'f4', '201406', 'location véhicule', '2014-06-19', '276.00'), (1922, 'f4', '201406', 'Voyage SNCF', '2014-06-01', '123.00'), (1923, 'f4', '201406', 'rémunération intervenant/spécialiste', '2014-06-24', '630.00'), (1924, 'f4', '201406', 'achat de matériel de papeterie', '2014-06-18', '37.00'), (1925, 'f4', '201406', 'achat de matériel de papeterie', '2014-06-16', '14.00'), (1926, 'f4', '201406', 'taxi', '2014-06-20', '38.00'), (1927, 'f4', '201406', 'traiteur, alimentation, boisson', '2014-06-12', '241.00'), (1928, 'f4', '201407', 'location équipement vidéo/sonore', '2014-07-02', '537.00'), (1929, 'f4', '201407', 'achat de matériel de papeterie', '2014-07-25', '22.00'), (1930, 'f4', '201407', 'location salle conférence', '2014-07-18', '375.00'), (1931, 'f4', '201407', 'frais vestimentaire/représentation', '2014-07-07', '125.00'), (1932, 'f4', '201407', 'repas avec praticien', '2014-07-08', '31.00'), (1933, 'f4', '201407', 'frais vestimentaire/représentation', '2014-07-12', '445.00'), (1934, 'f4', '201407', 'traiteur, alimentation, boisson', '2014-07-12', '69.00'), (1935, 'f4', '201407', 'location salle conférence', '2014-07-02', '387.00'), (1936, 'f4', '201408', 'location équipement vidéo/sonore', '2014-08-04', '630.00'), (1937, 'f4', '201408', 'taxi', '2014-08-12', '46.00'), (1938, 'f4', '201408', 'taxi', '2014-08-03', '25.00'), (1939, 'f4', '201408', 'location salle conférence', '2014-08-10', '442.00'), (1940, 'f4', '201408', 'location véhicule', '2014-08-06', '352.00'), (1941, 'f4', '201408', 'frais vestimentaire/représentation', '2014-08-10', '120.00'), (1942, 'f4', '201409', 'location salle conférence', '2014-09-09', '320.00'), (1943, 'f4', '201409', 'location équipement vidéo/sonore', '2014-09-25', '599.00'), (1944, 'f4', '201409', 'location véhicule', '2014-09-20', '345.00'), (1945, 'f4', '201409', 'repas avec praticien', '2014-09-06', '46.00'), (1946, 'f4', '201409', 'location véhicule', '2014-09-20', '317.00'), (1947, 'f4', '201409', 'location équipement vidéo/sonore', '2014-09-04', '529.00'), (1948, 'f4', '201409', 'repas avec praticien', '2014-09-13', '38.00'), (1949, 'f4', '201409', 'Voyage SNCF', '2014-09-14', '94.00'), (1950, 'f4', '201409', 'taxi', '2014-09-17', '30.00'); -- -------------------------------------------------------- -- -- Structure de la table `region` -- CREATE TABLE IF NOT EXISTS `region` ( `idR` int(11) NOT NULL AUTO_INCREMENT, `nomRegion` varchar(50) NOT NULL, PRIMARY KEY (`idR`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=25 ; -- -- Contenu de la table `region` -- INSERT INTO `region` (`idR`, `nomRegion`) VALUES (1, 'Alsace'), (2, 'Aquitaine'), (3, 'Auvergne'), (4, '<NAME>'), (5, 'Bourgogne'), (6, 'Bretagne'), (7, 'Centre'), (8, 'Champagne Ardenne'), (9, 'Corse'), (10, 'Franche Comté'), (11, '<NAME>'), (12, 'Ile de France'), (13, '<NAME>'), (14, 'Limousin'), (15, 'Lorraine'), (16, 'Midi-Pyrénées'), (17, '<NAME>'), (18, 'Provence Alpes Côte d''Azur'), (19, 'Pays de Loire'), (20, 'Picardie'), (21, 'Poitou Charente'), (22, 'Rhone Alpes'), (23, 'DOM-TOM-Atlantique'), (24, 'DOM-TOM-Indien'); -- -------------------------------------------------------- -- -- Structure de la table `typeutilisateur` -- CREATE TABLE IF NOT EXISTS `typeutilisateur` ( `codeType` char(1) NOT NULL, `libelleType` varchar(25) NOT NULL, PRIMARY KEY (`codeType`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `typeutilisateur` -- INSERT INTO `typeutilisateur` (`codeType`, `libelleType`) VALUES ('c', 'comptable'), ('h', 'resources humaines'), ('r', 'responsable suivi frais'), ('s', 'secrétaire'), ('v', 'visiteur'); -- -------------------------------------------------------- -- -- Structure de la table `utilisateur` -- CREATE TABLE IF NOT EXISTS `utilisateur` ( `id` varchar(4) NOT NULL, `nom` varchar(30) NOT NULL, `prenom` varchar(30) NOT NULL, `login` varchar(20) NOT NULL, `mdp` varchar(20) NOT NULL, `adresse` varchar(30) NOT NULL, `cp` varchar(5) NOT NULL, `ville` varchar(30) NOT NULL, `dateEmbauche` date NOT NULL, `idTypeUtilisateur` char(1) NOT NULL, `tel_fixe` varchar(20) DEFAULT NULL, `tel_portable` varchar(20) DEFAULT NULL, `idRegion` int(11) NOT NULL, PRIMARY KEY (`id`), KEY `idTypeUtilisateur` (`idTypeUtilisateur`), KEY `idRegion` (`idRegion`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `utilisateur` -- INSERT INTO `utilisateur` (`id`, `nom`, `prenom`, `login`, `mdp`, `adresse`, `cp`, `ville`, `dateEmbauche`, `idTypeUtilisateur`, `tel_fixe`, `tel_portable`, `idRegion`) VALUES ('4569', 'jack', 'ryan', 'rjack', 'rjack', '3 grand rue', '29150', 'chateaulin', '2014-10-22', 'c', NULL, NULL, 1), ('a131', 'Villechalane', 'Louis', 'lvillachane', 'jux7g', '8 rue des Charmes', '46000', 'Cahors', '2005-12-21', 'v', NULL, NULL, 1), ('a17', 'Andre', 'David', 'dandre', 'oppg5', '1 rue Petit', '46200', 'Lalbenque', '1998-11-23', 'v', NULL, NULL, 1), ('a55', 'Bedos', 'Christian', 'cbedos', 'gmhxd', '1 rue Peranud', '46250', 'Montcuq', '1995-01-12', 'v', NULL, NULL, 1), ('a93', 'Tusseau', 'Louis', 'ltusseau', 'ktp3s', '22 rue des Ternes', '46123', 'Gramat', '2000-05-01', 'v', NULL, NULL, 1), ('b112', 'felicity', 'smoak', 'sfelicity', 'sfelicity', 'starling', '10000', 'starling city', '2015-03-02', 's', NULL, NULL, 23), ('b113', 'jean', 'jacques', 'jjean', 'jjean', 'rue du chemin', '11000', 'gourin', '2015-03-02', 'r', NULL, NULL, 6), ('b114', 'jean', 'michel', 'jmichel', 'jmichel', 'rue du chemin', '15000', 'brest', '2015-03-02', 'h', NULL, NULL, 5), ('b13', 'Bentot', 'Pascal', 'pbentot', 'doyw1', '11 allée des Cerises', '46512', 'Bessines', '1992-07-09', 'v', NULL, NULL, 1), ('b16', 'Bioret', 'Luc', 'lbioret', 'hrjfs', '1 Avenue gambetta', '46000', 'Cahors', '1998-05-11', 'v', NULL, NULL, 1), ('b19', 'Bunisset', 'Francis', 'fbunisset', '4vbnd', '10 rue des Perles', '93100', 'Montreuil', '1987-10-21', 'v', NULL, NULL, 1), ('b25', 'Bunisset', 'Denise', 'dbunisset', 's1y1r', '23 rue Manin', '75019', 'paris', '2010-12-05', 'v', NULL, NULL, 1), ('b28', 'Cacheux', 'Bernard', 'bcacheux', 'uf7r3', '114 rue Blanche', '75017', 'Paris', '2009-11-12', 'v', NULL, NULL, 1), ('b34', 'Cadic', 'Eric', 'ecadic', '6u8dc', '123 avenue de la République', '75011', 'Paris', '2008-09-23', 'v', NULL, NULL, 1), ('b4', 'Charoze', 'Catherine', 'ccharoze', 'u817o', '100 rue Petit', '75019', 'Paris', '2005-11-12', 'v', NULL, NULL, 1), ('b50', 'Clepkens', 'Christophe', 'cclepkens', 'bw1us', '12 allée des Anges', '93230', 'Romainville', '2003-08-11', 'v', NULL, NULL, 1), ('b59', 'Cottin', 'Vincenne', 'vcottin', '2hoh9', '36 rue Des Roches', '93100', 'Monteuil', '2001-11-18', 'v', NULL, NULL, 1), ('c14', 'Daburon', 'François', 'fdaburon', '7oqpv', '13 rue de Chanzy', '94000', 'Créteil', '2002-02-11', 'v', NULL, NULL, 1), ('c3', 'De', 'Philippe', 'pde', 'gk9kx', '13 rue Barthes', '94000', 'Créteil', '2010-12-14', 'v', NULL, NULL, 1), ('c54', 'Debelle', 'Michel', 'mdebelle', 'od5rt', '181 avenue Barbusse', '93210', 'Rosny', '2006-11-23', 'v', NULL, NULL, 1), ('d13', 'Debelle', 'Jeanne', 'jdebelle', 'nvwqq', '134 allée des Joncs', '44000', 'Nantes', '2000-05-11', 'v', NULL, NULL, 1), ('d51', 'Debroise', 'Michel', 'mdebroise', 'sghkb', '2 Bld Jourdain', '44000', 'Nantes', '2001-04-17', 'v', NULL, NULL, 1), ('e22', 'Desmarquest', 'Nathalie', 'ndesmarquest', 'f1fob', '14 Place d Arc', '45000', 'Orléans', '2005-11-12', 'v', NULL, NULL, 1), ('e24', 'Desnost', 'Pierre', 'pdesnost', '4k2o5', '16 avenue des Cèdres', '23200', 'Guéret', '2001-02-05', 'v', NULL, NULL, 1), ('e39', 'Dudouit', 'Frédéric', 'fdudouit', '44im8', '18 rue de l église', '23120', 'GrandBourg', '2000-08-01', 'v', NULL, NULL, 1), ('e49', 'Duncombe', 'Claude', 'cduncombe', 'qf77j', '19 rue de la tour', '23100', 'La souteraine', '1987-10-10', 'v', NULL, NULL, 1), ('e5', 'Enault-Pascreau', 'Céline', 'cenault', 'y2qdu', '25 place de la gare', '23200', 'Gueret', '1995-09-01', 'v', NULL, NULL, 1), ('e52', 'Eynde', 'Valérie', 'veynde', 'i7sn3', '3 Grand Place', '13015', 'Marseille', '1999-11-01', 'v', NULL, NULL, 1), ('f21', 'Finck', 'Jacques', 'jfinck', 'mpb3t', '10 avenue du Prado', '13002', 'Marseille', '2001-11-10', 'v', NULL, NULL, 1), ('f39', 'Frémont', 'Fernande', 'ffremont', 'xs5tq', '4 route de la mer', '13012', 'Allauh', '1998-10-01', 'v', NULL, NULL, 1), ('f4', 'Gest', 'Alain', 'agest', 'dywvt', '30 avenue de la mer', '13025', 'Berre', '1985-11-01', 'v', NULL, NULL, 1); -- -------------------------------------------------------- -- -- Doublure de structure pour la vue `visiteur` -- CREATE TABLE IF NOT EXISTS `visiteur` ( `id` varchar(4) ,`nom` varchar(30) ,`prenom` varchar(30) ,`login` varchar(20) ,`mdp` varchar(20) ,`adresse` varchar(30) ,`cp` varchar(5) ,`ville` varchar(30) ,`dateEmbauche` date ,`idTypeUtilisateur` char(1) ,`tel_fixe` varchar(20) ,`tel_portable` varchar(20) ,`idRegion` int(11) ); -- -------------------------------------------------------- -- -- Structure de la vue `visiteur` -- DROP TABLE IF EXISTS `visiteur`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `visiteur` AS select `utilisateur`.`id` AS `id`,`utilisateur`.`nom` AS `nom`,`utilisateur`.`prenom` AS `prenom`,`utilisateur`.`login` AS `login`,`utilisateur`.`mdp` AS `mdp`,`utilisateur`.`adresse` AS `adresse`,`utilisateur`.`cp` AS `cp`,`utilisateur`.`ville` AS `ville`,`utilisateur`.`dateEmbauche` AS `dateEmbauche`,`utilisateur`.`idTypeUtilisateur` AS `idTypeUtilisateur`,`utilisateur`.`tel_fixe` AS `tel_fixe`,`utilisateur`.`tel_portable` AS `tel_portable`,`utilisateur`.`idRegion` AS `idRegion` from `utilisateur` where (`utilisateur`.`idTypeUtilisateur` = 'v'); -- -- Contraintes pour les tables exportées -- -- -- Contraintes pour la table `fichefrais` -- ALTER TABLE `fichefrais` ADD CONSTRAINT `fichefrais_ibfk_1` FOREIGN KEY (`idEtat`) REFERENCES `etat` (`id`), ADD CONSTRAINT `fichefrais_ibfk_2` FOREIGN KEY (`idVisiteur`) REFERENCES `utilisateur` (`id`); -- -- Contraintes pour la table `lignefraisforfait` -- ALTER TABLE `lignefraisforfait` ADD CONSTRAINT `lignefraisforfait_ibfk_1` FOREIGN KEY (`idVisiteur`, `mois`) REFERENCES `fichefrais` (`idVisiteur`, `mois`), ADD CONSTRAINT `lignefraisforfait_ibfk_2` FOREIGN KEY (`idFraisForfait`) REFERENCES `fraisforfait` (`id`), ADD CONSTRAINT `lignefraisforfait_ibfk_4` FOREIGN KEY (`idVisiteur`) REFERENCES `fichefrais` (`idVisiteur`); -- -- Contraintes pour la table `lignefraishorsforfait` -- ALTER TABLE `lignefraishorsforfait` ADD CONSTRAINT `lignefraishorsforfait_ibfk_1` FOREIGN KEY (`idVisiteur`, `mois`) REFERENCES `fichefrais` (`idVisiteur`, `mois`), ADD CONSTRAINT `lignefraishorsforfait_ibfk_3` FOREIGN KEY (`idVisiteur`) REFERENCES `fichefrais` (`idVisiteur`); -- -- Contraintes pour la table `utilisateur` -- ALTER TABLE `utilisateur` ADD CONSTRAINT `utilisateur_ibfk_1` FOREIGN KEY (`idTypeUtilisateur`) REFERENCES `typeutilisateur` (`codeType`), ADD CONSTRAINT `utilisateur_ibfk_2` FOREIGN KEY (`idRegion`) REFERENCES `region` (`idR`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/gsb_php/controleurs/c_accueil.php <?php include("vues/v_sommaire.php"); //$action = $_REQUEST['action']; //$idVisiteur = $_SESSION['idVisiteur']; include("vues/v_accueil.php"); ?><file_sep>/gsb_php/vues/v_entete_contenu.php <div id="contenu"> <h2><?php echo $titre ?></h2> <file_sep>/gsb_php/vues/v_validerFrais.php  <div id="sousContenu"> <h3>Fiche de frais du mois de <?php echo obtenirLibelleMois($numMois)." ".$numAnnee?> :</h3> <!--<div class="encadre">--> <!-- <p> Etat : <?php echo $libEtat?> depuis le <?php echo $dateModif?> <br> Montant validé : <?php echo $montantValide?> </p> --> <div id="etatMontant"> <div id="etat" class="<?php echo $idEtat;?>"> <?php echo $libEtat?> depuis le <?php echo $dateModif?> </div> <div id="montantValide"> Montant validé <div id="valeurMontant"><?php echo $montantValide?> &#8364;</div> </div> </div> <h4>Eléments forfaitisés :</h4> <table class="listeLegere"> <tr> <?php $total=0; foreach ( $lesFraisForfait as $unFraisForfait ) { $libelle = $unFraisForfait['libelle']; ?> <th> <?php echo $libelle?></th> <?php } ?> </tr> <tr> <?php foreach ( $lesFraisForfait as $unFraisForfait ) { $quantite = $unFraisForfait['quantite']; $total += $quantite; ?> <td class="qteForfait"><?php echo $quantite?> </td> <?php } ?> </tr> </table> <h4>Descriptif des éléments hors forfait -<?php echo $nbJustificatifs ?> justificatifs reçus -</h4> <table class="listeLegere"> <tr> <th class="date">Date</th> <th class="libelle">Libellé</th> <th class="montant">Montant</th> <th>&nbsp;</th> <th>&nbsp;</th> </tr> <?php foreach ( $lesFraisHorsForfait as $unFraisHorsForfait ) { $date = $unFraisHorsForfait['date']; $libelle = $unFraisHorsForfait['libelle']; $montant = $unFraisHorsForfait['montant']; $id = $unFraisHorsForfait['id']; ?> <tr class="nonvalide"> <td><?php echo $date ?></td> <td class="libelle"><?php echo $libelle ?></td> <td class="montant"><?php echo $montant ?></td> <td><img src="<?php echo $cheminImages; ?>delete.png" onclick="choixHF(this,'A')"/></td> <td><a href="index.php?uc=validerFrais&action=reporterFrais&idFrais=<?php echo $id; ?>&lstFiche=<?php echo $ficheASelectionner; ?>" onclick="return confirm('Voulez-vous vraiment reporter ce frais au mois suivant?');"> <img src="<?php echo $cheminImages; ?>redo.png"/> </a> </td> </tr> <?php } ?> </table> &nbsp; <div class="piedForm"> <p> <input id="ajouter" type="submit" class="bouton" value="Valider" size="20" /> <input id="effacer" type="button" class="bouton" value="Annuler " size="20" /> </p> </div> &nbsp; </div> <script type="text/javascript"> getElementById("valeurMontant").innerHTML = <?php echo($total) ?> </script> </div> <file_sep>/gsb_java/src/com/vue/JDialogInfoVisiteur.java package com.vue; import java.awt.BorderLayout; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.awt.Font; import javax.swing.JTextField; import com.metier.Utilisateur; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class JDialogInfoVisiteur extends JDialog { private final JPanel contentPanel = new JPanel(); private JTextField txtNom; private JTextField txtAdresse; private JTextField txtCP; private JTextField txtVille; private JTextField txtFixe; private JTextField txtPortable; private JTextField txtPrenom; private JTextField txtDate; private JTextField txtRgion; /** * Create the dialog. */ public JDialogInfoVisiteur(Utilisateur u) { setBounds(100, 100, 640, 584); this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); this.setVisible(true); this.setTitle("Fiche de " + u.getNom() + " " + u.getPrenom()); getContentPane().setLayout(new BorderLayout()); contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); getContentPane().add(contentPanel, BorderLayout.CENTER); contentPanel.setLayout(null); JLabel lblNom = new JLabel("Nom :"); lblNom.setFont(new Font("Dialog", Font.PLAIN, 20)); lblNom.setBounds(90, 62, 200, 30); contentPanel.add(lblNom); JLabel lblAdresse = new JLabel("Adresse : "); lblAdresse.setFont(new Font("Dialog", Font.PLAIN, 20)); lblAdresse.setBounds(90, 192, 200, 30); contentPanel.add(lblAdresse); JLabel lblCodePostal = new JLabel("Code postal : "); lblCodePostal.setFont(new Font("Dialog", Font.PLAIN, 20)); lblCodePostal.setBounds(90, 232, 200, 30); contentPanel.add(lblCodePostal); JLabel lblVille = new JLabel("Ville : "); lblVille.setFont(new Font("Dialog", Font.PLAIN, 20)); lblVille.setBounds(90, 272, 200, 30); contentPanel.add(lblVille); JLabel lblFixe = new JLabel("Tel fixe : "); lblFixe.setFont(new Font("Dialog", Font.PLAIN, 20)); lblFixe.setBounds(90, 312, 200, 30); contentPanel.add(lblFixe); JLabel lblPortable = new JLabel("Tel portable : "); lblPortable.setFont(new Font("Dialog", Font.PLAIN, 20)); lblPortable.setBounds(90, 352, 200, 30); contentPanel.add(lblPortable); JLabel lblDateDembauche = new JLabel("Date d'embauche"); lblDateDembauche.setFont(new Font("Dialog", Font.PLAIN, 20)); lblDateDembauche.setBounds(90, 152, 200, 30); contentPanel.add(lblDateDembauche); JLabel lblRgion = new JLabel("Région : "); lblRgion.setFont(new Font("Dialog", Font.PLAIN, 20)); lblRgion.setBounds(90, 392, 200, 30); contentPanel.add(lblRgion); txtNom = new JTextField(); txtNom.setColumns(10); txtNom.setBounds(409, 67, 86, 20); txtNom.setEditable(false); txtNom.setText(u.getNom()); contentPanel.add(txtNom); txtAdresse = new JTextField(); txtAdresse.setColumns(10); txtAdresse.setBounds(409, 197, 86, 20); txtAdresse.setEditable(false); txtAdresse.setText(u.getAdresse()); contentPanel.add(txtAdresse); txtCP = new JTextField(); txtCP.setColumns(10); txtCP.setBounds(409, 237, 86, 20); txtCP.setEditable(false); txtCP.setText(u.getCp()); contentPanel.add(txtCP); txtVille = new JTextField(); txtVille.setColumns(10); txtVille.setBounds(409, 277, 86, 20); txtVille.setEditable(false); txtVille.setText(u.getVille()); contentPanel.add(txtVille); txtFixe = new JTextField(); txtFixe.setColumns(10); txtFixe.setBounds(409, 317, 86, 20); txtFixe.setEditable(false); txtFixe.setText(u.getTel_fixe()); contentPanel.add(txtFixe); txtPortable = new JTextField(); txtPortable.setColumns(10); txtPortable.setBounds(409, 357, 86, 20); txtPortable.setEditable(false); txtPortable.setText(u.getTel_portable()); contentPanel.add(txtPortable); JLabel lblPrenom = new JLabel("Prénom : "); lblPrenom.setFont(new Font("Dialog", Font.PLAIN, 20)); lblPrenom.setBounds(90, 108, 220, 30); contentPanel.add(lblPrenom); txtPrenom = new JTextField(); txtPrenom.setColumns(10); txtPrenom.setBounds(409, 113, 86, 20); txtPrenom.setEditable(false); txtPrenom.setText(u.getPrenom()); contentPanel.add(txtPrenom); txtDate = new JTextField(); txtDate.setColumns(10); txtDate.setBounds(409, 160, 86, 20); txtDate.setEditable(false); txtDate.setText(u.getDateEmbauche().toString()); contentPanel.add(txtDate); txtRgion = new JTextField(); txtRgion.setColumns(10); txtRgion.setBounds(409, 400, 86, 20); txtRgion.setEditable(false); txtRgion.setText(u.getRegion().getNomRegion()); contentPanel.add(txtRgion); { JPanel buttonPane = new JPanel(); buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); getContentPane().add(buttonPane, BorderLayout.SOUTH); { JButton okButton = new JButton("OK"); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); okButton.setActionCommand("OK"); buttonPane.add(okButton); getRootPane().setDefaultButton(okButton); } } } } <file_sep>/gsb_java/src/com/metier/Etat.java package com.metier; import javax.persistence.*; @Entity @Table(name = "etat") public class Etat { // ########## PROPRIETES ##########// @Id @Column(name = "id") private String id; @Column(name = "libelle") private String libelle; // ################################// // ########## CONSTRUCTEURS ##########// /** * Constructeur de Etat * * @param id * @param libelle */ public Etat(String id, String libelle) { super(); this.id = id; this.libelle = libelle; } /** * Constructeur vide de Etat */ public Etat() { super(); } // ###################################// // ########## METHODES ##########// /** * Accesseur de l'id * * @return id */ public String getId() { return id; } /** * Mutateurs de l'id * * @param id */ public void setId(String id) { this.id = id; } /** * Accesseur du libelle * * @return libelle */ public String getLibelle() { return libelle; } /** * Mutateurs du libelle * * @param id */ public void setLibelle(String libelle) { this.libelle = libelle; } /** * Méthode toString * * @return id, libelle */ @Override public String toString() { return "Etat [id=" + id + ", libelle=" + libelle + "]"; } // ##############################// } <file_sep>/gsb_php/controleurs/c_etatFraisComptable.php <?php include("vues/v_sommaire.php"); $action = $_REQUEST['action']; $idVisiteur = $_SESSION['idVisiteur']; $titre = "Suivi remboursement"; include("vues/v_entete_contenu.php"); switch($action){ case 'selectionnerUtilisateurMois':{ $lesInfos=$pdo->get_LesMoisValides(); $leMois=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $moisASelectionner=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $leMoisU[0]=$lesInfos[0]["id"]; $leMoisU[1]=$lesInfos[0]["mois"]; break; } case 'voirRemboursement':{ if (isset($_REQUEST['lstMois'])) { $leMois = $_REQUEST['lstMois']; $moisASelectionner = $leMois; } else { $leMois=""; $moisASelectionner=""; } $leMois = $_REQUEST['lstMois']; $leMoisU= $leMois; $leMoisU= explode("-",$leMoisU); $lesInfos=$pdo->get_LesMoisValides(); break; } case 'rembourser':{ $leMois = $_REQUEST['lstMois']; $moisASelectionner = $leMois; $leMoisU= $leMois; $leMoisU= explode("-",$leMoisU); $lesInfos=$pdo->get_LesMoisValides(); $info = 'Les remboursements ont bien été effectués'; include("vues/v_info.php"); $pdo->majEtatFicheFrais($leMoisU[0],$leMoisU[1],"RB"); $lesInfos=$pdo->get_LesMoisValides(); $leMois=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $moisASelectionner=$lesInfos[0]["id"]."-".$lesInfos[0]["mois"]; $leMoisU[0]=$lesInfos[0]["id"]; $leMoisU[1]=$lesInfos[0]["mois"]; break; } } if (nbErreurs() != 0 ){ include("vues/v_erreurs.php"); } else{ include("vues/v_listeVisiteursMois.php"); $lesFraisHorsForfait = $pdo->getLesFraisHorsForfait($leMoisU[0],$leMoisU[1]); $lesFraisForfait= $pdo->getLesFraisForfait($leMoisU[0],$leMoisU[1]); $lesInfosFicheFrais = $pdo->getLesInfosFicheFrais($leMoisU[0],$leMoisU[1]); $numAnnee = substr( $leMoisU[1],0,4); $numMois = substr( $leMoisU[1],4,2); $libEtat = $lesInfosFicheFrais['libEtat']; $idEtat = $lesInfosFicheFrais['idEtat']; $montantValide = $lesInfosFicheFrais['montantValide']; $nbJustificatifs = $lesInfosFicheFrais['nbJustificatifs']; $dateModif = $lesInfosFicheFrais['dateModif']; $dateModif = convertirDateAnglaisVersFrancais($dateModif); include("vues/v_etatFraisComptable.php"); } ?><file_sep>/README.md # GSB Projets de BTS consistant à développer un intranet en PHP suivant le modèle MVC, et une application métier en JAVA. Ces 2 projets étaient articulés autour du même contexte, GSB, une entreprise de représentant en produit pharmaceutique. <file_sep>/gsb_java/src/com/modele/ModeleMoyenneFHF.java package com.modele; import java.util.List; import javax.swing.table.AbstractTableModel; import com.metier.Region; import com.persistance.AccesData; public class ModeleMoyenneFHF extends AbstractTableModel { private final String[] entetes = { "Région", "Nombre de visiteur", "Moyenne par Visiteur"}; private List<Region> listeRegion; //private List<Utilisateur> listeVisiteur; private double montant; private String mois; public ModeleMoyenneFHF() { // TODO Auto-generated constructor stub } public ModeleMoyenneFHF(List<Region> listeRegion, String mois){ super(); this.listeRegion = listeRegion; this.mois = mois; } @Override public int getColumnCount() { return entetes.length; } @Override public int getRowCount() { return listeRegion.size(); } @Override public String getColumnName(int columnIndex) { return entetes[columnIndex]; } @Override public Object getValueAt(int rowIndex, int columnIndex) { //List<LigneFraisForfait> fraisHF = AccesData.getLesLignesFraisForfait(listeVisiteur.get(rowIndex).getId(), mois); switch (columnIndex) { case 0: // Nom de la région return listeRegion.get(rowIndex).getNomRegion(); case 1: // Nombre de visiteur pour cette région return AccesData.getListeVisiteur(listeRegion.get(rowIndex).getIdR()).size(); case 2: // Moyenne montant FraisForfait if(AccesData.getListeVisiteur(listeRegion.get(rowIndex).getIdR()).size() == 0) { return "Aucun visiteur pour cette région"; } else { return String.format("%.2f", AccesData.getMoyenneFHF(listeRegion.get(rowIndex).getIdR(), mois)) + " €"; } default: throw new IllegalArgumentException(); } } } <file_sep>/gsb_java/src/com/vue/JFrameMenuPrincipale.java package com.vue; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.SwingConstants; import com.metier.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class JFrameMenuPrincipale extends JFrame { private JPanel contentPane; private static JFrameMenuPrincipale frame2; private static Utilisateur util; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { frame2 = new JFrameMenuPrincipale(util); frame2.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public JFrameMenuPrincipale(Utilisateur util) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1200, 800); setIconImage(new ImageIcon("./images/logo.png").getImage()); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); String nomUtil = util.getNom() + " " + util.getPrenom(); // ########## Menu gestion ########## // JMenu mnGestionVisiteur = new JMenu("Gestion Visiteur"); JMenuItem mntmConsultation = new JMenuItem("Consultation"); mntmConsultation.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { consultation(); } }); JMenuItem mntmModification = new JMenuItem("Modification / Suppression"); mntmModification.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { modification(); } }); JMenuItem mntmCration = new JMenuItem("Cr\u00E9ation"); mntmCration.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { creation(); } }); /*mnGestionVisiteur.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { consultation(); } });*/ // ################################ // // ########## Menu des stats ########## // JMenu mnStatistics = new JMenu("Statistics"); JMenuItem mntmMoyenneParRgion = new JMenuItem("Moyenne par r\u00E9gion"); mntmMoyenneParRgion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statsMoyenne(); } }); mnStatistics.add(mntmMoyenneParRgion); JMenuItem mntmFraisParMois = new JMenuItem("Frais par mois par visiteur"); mntmFraisParMois.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { statsNombreFrais(); } }); mnStatistics.add(mntmFraisParMois); // #################################### // // ########## Menu perso ########## // JMenu mnNomUtil = new JMenu(nomUtil); mnNomUtil.setHorizontalAlignment(SwingConstants.LEADING); mnNomUtil.setEnabled(true); menuBar.add(mnNomUtil); JMenuItem mntmDeconnexion = new JMenuItem("Deconnexion"); mntmDeconnexion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); } }); mnNomUtil.add(mntmDeconnexion); // #################################### // char grade = util.getTypeUtilisateur().getCodeType(); switch(grade) { case 's': menuBar.add(mnGestionVisiteur); mnGestionVisiteur.add(mntmConsultation); mnGestionVisiteur.add(mntmModification); mnGestionVisiteur.add(mntmCration); // menu relatif a la personne connecte menuBar.add(Box.createHorizontalGlue()); menuBar.add(mnNomUtil); break; case 'r': menuBar.add(mnStatistics); menuBar.add(mnNomUtil); // menu relatif a la personne connecte menuBar.add(Box.createHorizontalGlue()); menuBar.add(mnNomUtil); break; case 'h': menuBar.add(mnGestionVisiteur); mnGestionVisiteur.add(mntmConsultation); // menu relatif a la personne connecte menuBar.add(Box.createHorizontalGlue()); menuBar.add(mnNomUtil); break; } contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); } private void consultation() { this.setContentPane(new JPanelConsultationVisiteur()); this.revalidate(); } private void modification() { this.setContentPane(new JPanelModificationVisiteur()); this.revalidate(); } private void creation() { this.setContentPane(new JPanelAjoutVisiteur()); this.revalidate(); } private void statsMoyenne() { this.setContentPane(new JPanelStatsMoyenneFF()); this.revalidate(); } private void statsNombreFrais() { this.setContentPane(new JPanelStatsMontantFF()); this.revalidate(); } }
c90e1dfaae78b7f86fe7abdcc15486e8104d779a
[ "SQL", "Markdown", "Java", "Text", "PHP" ]
24
PHP
StrikeBhack/GSB
d051afe602ee006f2afba2021a7ddec7fd2e772e
c1e1d24237a805c37eecb9bd8328f7d1f2d3e237
refs/heads/master
<repo_name>luual/JenkinsTest<file_sep>/main.c /************************************************************* ** ** File Name : main.c ** ** Purpose : ** ** Creation Date : $USER ** ** Last Modified : dim. 04 sept. 2016 10:59:21 CEST ** ** Created by : <NAME> <https://github.com/luual> ** **************************************************************/ #include <stdio.h> int main() { i = 5; return 0; }
f640bcbcfd9fab96ec2567bd1ae9edfe727c680a
[ "C" ]
1
C
luual/JenkinsTest
c7ad836cfdc140b594e536f7cb005368f28a083d
7d96a0e57add315b48293c31bf45936433d0ddea
refs/heads/master
<file_sep># btest # version 2.2.0 <file_sep># version 2.0.0
d6a44754531987fb561d6e322bfbffd2dd93f0cc
[ "Markdown", "Python" ]
2
Markdown
kangvcar/btest
97bfbb4f0228d65a213564bcdf4ea374aeeda9a3
601c3dbb4ec46f05f8047371a5455d963871b473
refs/heads/master
<file_sep>package util.graph; import util.graph.*; import util.intset.*; import java.awt.*; import java.util.*; import java.io.*; public class ColorGraph { public Graph G; public int R; public int K; private Stack<Integer> pile; public IntSet removed; public IntSet spill; public int[] couleur; public Node[] int2Node; static int NOCOLOR = -1; public ColorGraph(Graph G, int K, int[] phi) { this.G = G; this.K = K; pile = new Stack<Integer>(); R = G.nodeCount(); couleur = new int[R]; removed = new IntSet(R); spill = new IntSet(R); int2Node = G.nodeArray(); for (int v = 0; v < R; v++) { int preColor = phi[v]; if (preColor >= 0 && preColor < K) couleur[v] = phi[v]; else couleur[v] = NOCOLOR; } } /*-------------------------------------------------------------------------------------------------------------*/ /* associe une couleur à tous les sommets se trouvant dans la pile */ /*-------------------------------------------------------------------------------------------------------------*/ public void selection() { while(!pile.empty()){ int s = pile.pop(); IntSet c = couleursVoisins(s); // La boucle permet de déterminer si une couleur n'est pas utilisée par les voisins // et se retrouve donc disponible pour le noeud courant for (int index = 0; index < c.getSize(); index++) { if(!c.isMember(index)){ couleur[s] = choisisCouleur(c); break; } couleur[s] = NOCOLOR; } } } /*-------------------------------------------------------------------------------------------------------------*/ /* récupère les couleurs des voisins de t */ /*-------------------------------------------------------------------------------------------------------------*/ public IntSet couleursVoisins(int t) { IntSet neighbourColors = new IntSet(K); Node node = int2Node[t]; NodeList neighbours = node.adj(); // Parcours les voisins et ajoute dans neighbourColors les couleurs déjà utilisées par les voisins // du noeud dont l'indexe est passé en argument à la fonction for (NodeList q = neighbours; q != null; q = q.tail) { // Si la couleur est déjà ajoutée au set : continue if (neighbourColors.isMember(couleur[q.head.mykey])) { continue; } else { // Aussi non on rajoute la couleur utilisée par le noeud au set de couleur neighbourColors.add(couleur[q.head.mykey]); } } return neighbourColors; } /*-------------------------------------------------------------------------------------------------------------*/ /* recherche une couleur absente de colorSet */ /*-------------------------------------------------------------------------------------------------------------*/ public int choisisCouleur(IntSet colorSet) { //choisit la 1ere couleur non utilisé dans l’ensemble de couleurs ColorSet int size = colorSet.getSize(); for (int i = 0; i < size; i++) { if (!colorSet.isMember(i)) return i; } //valeur par default cad NOCOLOR return -1; } /*-------------------------------------------------------------------------------------------------------------*/ /* calcule le nombre de voisins du sommet t */ /*-------------------------------------------------------------------------------------------------------------*/ public int nbVoisins(int t) { Node node = int2Node[t]; NodeList neighbours = node.adj(); int count = 0; //Parcours les voisins du noeud passé en argument pour les dénombrer for (NodeList q = neighbours; q != null; q = q.tail) { count++; } return count; } /*-------------------------------------------------------------------------------------------------------------*/ /* simplifie le graphe d'interférence g */ /* la simplification consiste à enlever du graphe les temporaires qui ont moins de k voisins */ /* et à les mettre dans une pile */ /* à la fin du processus, le graphe peut ne pas être vide, il s'agit des temporaires qui ont au moins k voisin */ /*-------------------------------------------------------------------------------------------------------------*/ public void simplification() { boolean modif = true; while (pile.size() != R && modif) { modif = false; for (var node : int2Node) { if (nbVoisins(node.mykey) < K && couleur[node.mykey] == NOCOLOR) { pile.push(node.mykey); removed.add(node.mykey); modif = true; } } } } /*-------------------------------------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------------------------------------*/ public void debordement() { //TODO modifier la fonction erreur de debordement index -1 while (pile.size() != R) { int s = choisi_sommet(); pile.push(s); removed.add(s); spill.add(s); simplification(); } } private int choisi_sommet() { for (int i = 0; i < removed.getSize(); ++i) if (!removed.isMember(i) && couleur[i] == NOCOLOR) return i; return -1; } /*-------------------------------------------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------------------------------------------*/ public void coloration() { this.simplification(); this.debordement(); this.selection(); } void affiche() { System.out.println("vertex\tcolor"); for (int i = 0; i < R; i++) { System.out.println(i + "\t" + couleur[i]); } } } <file_sep>import sa.*; import ts.Ts; import ts.TsItemVar; public class Sa2ts extends SaDepthFirstVisitor <Void>{ Ts tableGlobale; Ts tableLocale; public Sa2ts(SaNode root) { tableGlobale = new Ts(); root.accept(this); } @Override public void defaultIn(SaNode node) { super.defaultIn(node); } @Override public Void visit(SaVarSimple node) { node.tsItem = (tableGlobale.variables.containsKey(node.getNom())) ? tableGlobale.variables.get(node.getNom()) : tableLocale.variables.get(node.getNom()); if(!(tableLocale != null && tableLocale.variables.containsKey(node.getNom()))) { if (!tableGlobale.variables.containsKey(node.getNom())) { throw new RuntimeException("Variable " + node.getNom() + " non déclarée"); } } return super.visit(node); } @Override public Void visit(SaVarIndicee node) { node.tsItem = tableGlobale.variables.get(node.getNom()); if(!tableGlobale.variables.containsKey(node.getNom())) throw new RuntimeException("La variable " + node.getNom() + " n'a pas été définie"); return super.visit(node); } @Override public Void visit(SaDecTab node) { String identif = node.getNom(); if(tableLocale != null) throw new RuntimeException("On ne peut pas déclarer un tableau dans une fonction"); if(tableGlobale.variables.containsKey(identif)) throw new RuntimeException("Le tableau " + identif + " a déjà été défini"); tableGlobale.addVar(node.getNom(),node.getTaille()); return super.visit(node); } @Override public Void visit(SaDecFonc node) { String identif = node.getNom(); tableLocale = new Ts(); if(tableGlobale.fonctions.containsKey(identif)) throw new RuntimeException("Fonction " + identif + " déjà déclarée"); int arg ; if(node.getVariable() == null) arg = 0; else arg = node.getVariable().length(); tableGlobale.addFct(identif,arg , tableLocale, node); SaLDec lparam = node.getVariable(); SaDec tete; if (node.getParametres() != null) { node.getParametres().accept(this); } while (lparam != null && (tete = lparam.getTete()) != null) { tableLocale.addParam(tete.getNom()); lparam = lparam.getQueue(); } node.getCorps().accept(this); tableLocale = null; return null; } @Override public Void visit(SaDecVar node) { Ts table; if(tableLocale == null) table = tableGlobale; else table = tableLocale; if((table.variables.containsKey(node.getNom()))) throw new RuntimeException("Variable " + node.getNom() + " déjà déclarée"); table.addVar(node.getNom(), 1); return super.visit(node); } @Override public Void visit(SaAppel node) { node.tsItem = tableGlobale.fonctions.get(node.getNom()); if (!tableGlobale.fonctions.containsKey(node.getNom())) { throw new RuntimeException("La fonction " + node.getNom() + "n'a pas été définie"); } return super.visit(node); } public Ts getTableGlobale() { return tableGlobale; } } <file_sep>import c3a.*; import nasm.Nasm; import nasm.*; import ts.Ts; import ts.TsItemFct; import ts.TsItemVar; public class C3a2nasm implements C3aVisitor<NasmOperand> { private Nasm nasm; private Ts tableGlobale; private C3a c3a; private TsItemFct currentFct; public C3a2nasm(C3a c3a, Ts table) { this.nasm = new Nasm(table); nasm.setTempCounter(c3a.getTempCounter()); NasmLabel labelMain = new NasmLabel("main"); nasm.ajouteInst(new NasmCall(null, labelMain, "")); NasmRegister reg_eax = nasm.newRegister(); reg_eax.colorRegister(Nasm.REG_EAX); NasmRegister reg_ebx = nasm.newRegister(); reg_ebx.colorRegister(Nasm.REG_EBX); nasm.ajouteInst(new NasmMov(null, reg_ebx, new NasmConstant(0), " valeur de retour du programme")); nasm.ajouteInst(new NasmMov(null, reg_eax, new NasmConstant(1), "")); nasm.ajouteInst(new NasmInt(null, "")); for (C3aInst instruction : c3a.listeInst) { instruction.accept(this); } } public Nasm getNasm() { return nasm; } @Override public NasmOperand visit(C3aInstAdd inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmOperand oper1 = inst.op1.accept(this); NasmOperand oper2 = inst.op2.accept(this); NasmOperand dest = inst.result.accept(this); nasm.ajouteInst(new NasmMov(label, dest, oper1, "")); nasm.ajouteInst(new NasmAdd(null, dest, oper2, "")); return null; } @Override public NasmOperand visit(C3aInstCall inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmRegister reg_esp = new NasmRegister(Nasm.REG_ESP); reg_esp.colorRegister(Nasm.REG_ESP); nasm.ajouteInst(new NasmSub(label,reg_esp,new NasmConstant(4),"allocation mémoire pour la valeur de retour")); nasm.ajouteInst(new NasmCall(null,inst.op1.accept(this), "")); nasm.ajouteInst(new NasmPop(null,inst.result.accept(this),"récupération de la valeur de retour")); if (inst.op1.val.nbArgs > 0) { nasm.ajouteInst(new NasmAdd(null, reg_esp, new NasmConstant(inst.op1.val.nbArgs * 4), "désallocation des arguments")); } return null; } @Override public NasmOperand visit(C3aInstFBegin inst) { currentFct = inst.val; currentFct.nbArgs = inst.val.nbArgs; NasmRegister reg_ebp = new NasmRegister(Nasm.REG_EBP); reg_ebp.colorRegister(Nasm.REG_EBP); NasmRegister reg_esp = new NasmRegister(Nasm.REG_ESP); reg_esp.colorRegister(Nasm.REG_ESP); NasmLabel label = new NasmLabel(currentFct.getIdentif()); nasm.ajouteInst(new NasmPush(label,reg_ebp,"sauvegarde la valeur de ebp")); nasm.ajouteInst(new NasmMov(null,reg_ebp,reg_esp,"nouvelle valeur de ebp")); nasm.ajouteInst(new NasmSub(null,reg_esp,new NasmConstant(4*currentFct.getTable().nbVar()),"allocation des variables locales")); return null; } @Override public NasmOperand visit(C3aInst inst) { //doit rester intact ? return null; } @Override public NasmOperand visit(C3aInstJumpIfLess inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; nasm.ajouteInst(new NasmCmp(label, inst.op1.accept(this), inst.op2.accept(this), "JumpIfLess 1")); nasm.ajouteInst(new NasmJl(null, inst.result.accept(this),"JumpIfLess 2")); return null; } @Override public NasmOperand visit(C3aInstMult inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmOperand oper1 = inst.op1.accept(this); NasmOperand oper2 = inst.op2.accept(this); NasmOperand dest = inst.result.accept(this); nasm.ajouteInst(new NasmMov(label, dest, oper1, "")); nasm.ajouteInst(new NasmMul(null, dest, oper2, "")); return null; } @Override public NasmOperand visit(C3aInstRead inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; var dest = inst.result.accept(this); var eax = nasm.newRegister(); eax.colorRegister(Nasm.REG_EAX); nasm.ajouteInst(new NasmMov(label, eax, new NasmConstant(2), "")); nasm.ajouteInst(new NasmCall(null, new NasmLabel("readline"), "")); nasm.ajouteInst(new NasmCall(null, new NasmLabel("atoi"), "")); nasm.ajouteInst(new NasmMov(null, dest, eax, "")); return null; } @Override public NasmOperand visit(C3aInstSub inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmOperand oper1 = inst.op1.accept(this); NasmOperand oper2 = inst.op2.accept(this); NasmOperand dest = inst.result.accept(this); nasm.ajouteInst(new NasmMov(label, dest, oper1, "")); nasm.ajouteInst(new NasmSub(null, dest, oper2, "")); return null; } @Override public NasmOperand visit(C3aInstAffect inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; nasm.ajouteInst(new NasmMov(label, inst.result.accept(this), inst.op1.accept(this), "Affect")); return null; } @Override public NasmOperand visit(C3aInstDiv inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmOperand result = inst.result.accept(this); NasmRegister reg_eax = nasm.newRegister(); reg_eax.colorRegister(Nasm.REG_EAX); nasm.ajouteInst(new NasmMov(label, reg_eax, inst.op1.accept(this), "")); NasmRegister destination = nasm.newRegister(); nasm.ajouteInst(new NasmMov(null, destination, inst.op2.accept(this), "")); nasm.ajouteInst(new NasmDiv(null, destination, "")); nasm.ajouteInst(new NasmMov(null, result, reg_eax, "")); return null; } @Override public NasmOperand visit(C3aInstFEnd inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmRegister reg_esp = new NasmRegister(Nasm.REG_ESP); reg_esp.colorRegister(Nasm.REG_ESP); NasmRegister reg_ebp = new NasmRegister(Nasm.REG_EBP); reg_ebp.colorRegister(Nasm.REG_EBP); nasm.ajouteInst(new NasmAdd(label, reg_esp,new NasmConstant(currentFct.getTable().nbVar()*4),"désallocation des variables locales")); nasm.ajouteInst(new NasmPop(null,reg_ebp,"restaure la valeur de ebp")); nasm.ajouteInst(new NasmRet(null,"")); return null; } @Override public NasmOperand visit(C3aInstJumpIfEqual inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; nasm.ajouteInst(new NasmCmp(label, inst.op1.accept(this), inst.op2.accept(this), "JumpIfEqual 1")); nasm.ajouteInst(new NasmJe(null, inst.result.accept(this),"JumpIfEqual 2")); return null; } @Override public NasmOperand visit(C3aInstJumpIfNotEqual inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; nasm.ajouteInst(new NasmCmp(label, inst.op1.accept(this), inst.op2.accept(this), "jumpIfNotEqual 1")); nasm.ajouteInst(new NasmJne(null, inst.result.accept(this),"jumpIfNotEqual 2")); return null; } @Override public NasmOperand visit(C3aInstJump inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; nasm.ajouteInst(new NasmJmp(label, inst.result.accept(this),"Jump")); return null; } @Override public NasmOperand visit(C3aInstParam inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; nasm.ajouteInst(new NasmPush(label,inst.op1.accept(this),"Param")); return null; } @Override public NasmOperand visit(C3aInstReturn inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmRegister reg_ebp = new NasmRegister(Nasm.REG_EBP); reg_ebp.colorRegister(Nasm.REG_EBP); nasm.ajouteInst(new NasmMov(label, new NasmAddress(reg_ebp, '+', new NasmConstant(2)), inst.op1.accept(this),"ecriture de la valeur de retour")); return null; } @Override public NasmOperand visit(C3aInstWrite inst) { NasmOperand label = (inst.label != null) ? inst.label.accept(this) : null; NasmRegister reg_eax = nasm.newRegister(); reg_eax.colorRegister(Nasm.REG_EAX); nasm.ajouteInst(new NasmMov(label,reg_eax, inst.op1.accept(this),"Write 1")); NasmLabel IprintLF = new NasmLabel("iprintLF"); nasm.ajouteInst(new NasmCall(null,IprintLF,"Write 2")); return null; } @Override public NasmOperand visit(C3aConstant oper) { return new NasmConstant(oper.val); } @Override public NasmOperand visit(C3aLabel oper) { return new NasmLabel(oper.toString()); } @Override public NasmOperand visit(C3aTemp oper) { return new NasmRegister(oper.num) ; } @Override public NasmOperand visit(C3aVar oper) { //fonction filé TsItemVar variable = oper.item; NasmRegister reg_ebp = new NasmRegister(Nasm.REG_EBP); reg_ebp.colorRegister(Nasm.REG_EBP); if (variable.isParam) { return new NasmAddress(reg_ebp, '+', new NasmConstant(2 + variable.portee.nbArg() - variable.adresse)); } if (oper.index != null) { return new NasmAddress(new NasmLabel(variable.getIdentif()), '+', oper.index.accept(this)); } if (currentFct.getTable().variables.containsKey(variable.identif)) { return new NasmAddress(reg_ebp, '-', new NasmConstant(1 + variable.adresse)); } return new NasmAddress(new NasmLabel(variable.identif)); } @Override public NasmOperand visit(C3aFunction oper) { return new NasmLabel(oper.toString()); } }
99df0477853d3cd044579a9800842d5fa9e27445
[ "Java" ]
3
Java
JaiPasDidee/compilationl3-public
f38f2d671498fb460a1fe4c3e6776f8aad31c062
b8022dd8583721a22b55a11fe2d93ed1c1f62d22
refs/heads/master
<file_sep>json.extract! assignation, :id, :datarequest_id, :user_id, :created_at, :updated_at json.url assignation_url(assignation, format: :json) <file_sep>require 'test_helper' class UsersControllerTest < ActionDispatch::IntegrationTest setup do @user = users(:one) end test "should get index" do get users_url assert_response :success end test "should get new" do logout! get new_user_registration_url assert_response :success assert_select 'em', '(6 characters minimum)' end test "should create user" do logout! assert_difference('User.count') do post user_registration_url, params: { user: { email: '<EMAIL>', name: @user.name, password: '<PASSWORD>', user_type: 'Admin' } } end assert_redirected_to user_url(User.last) end test "should show user" do get user_url(@user) assert_response :success end test "should get edit" do get edit_user_url(@user) assert_response :success end test "should update user" do patch user_url(@user), params: { user: { email: @user.email, name: @user.name, password: '<PASSWORD>', password_confirmation: '<PASSWORD>', user_type: @user.user_type } } assert_redirected_to user_url(@user) end test "should destroy user" do assert_difference('User.count', -1) do delete user_url(@user) end assert_redirected_to users_url end test "should prompt for login" do logout! get new_user_session_url assert_response :success assert_select 'a', 'Forgot your password?' end test "should login" do logout! user1 = users(:one) post user_session_url , params: { user: { email: user1.email, password: '<PASSWORD>' } } assert_redirected_to todo_index_url assert_equal user1, @controller.current_user end test "should fail login" do logout! user1 = users(:one) post user_session_url , params: { user: { email: user1.email, password: '<PASSWORD>' } } assert_select 'p.alert', 'Invalid Email or password.' assert_nil @controller.current_user end test "should logout" do delete destroy_user_session_url assert_redirected_to todo_index_url assert_nil @controller.current_user end end <file_sep>class DataRequest < ApplicationRecord has_many :assignations, dependent: :destroy belongs_to :user validates :title, :description, :required_before, presence: true validates :description, allow_blank: true, length: {minimum: 10, message: 'Minimum ten characters pls.'} end <file_sep>require 'test_helper' class DataRequestMailerTest < ActionMailer::TestCase test "created" do @data_request = DataRequest.first mail = DataRequestMailer.created(@data_request) assert_equal 'Successfully submitted data request', mail.subject assert_equal [@data_request.user.email], mail.to assert_equal ["<EMAIL>"], mail.from assert_match "Your request has been successfully created", mail.body.encoded end test "assigned" do @assignation = Assignation.first mail = DataRequestMailer.assigned(@assignation) assert_equal 'You have been tasked with a new request.', mail.subject assert_equal [@assignation.user.email], mail.to assert_equal ["<EMAIL>"], mail.from assert_match "You have received a new assignment.", mail.body.encoded end test "notify" do @assignation = Assignation.first mail = DataRequestMailer.notify(@assignation) assert_equal 'Your request has been assigned to an analyst.', mail.subject assert_equal [@assignation.data_request.user.email], mail.to assert_equal ["<EMAIL>"], mail.from assert_match "Your data request has been assigned to an analyst.", mail.body.encoded end test "completed" do @assignation = Assignation.first mail = DataRequestMailer.completed(@assignation) assert_equal 'Data request has been fulfilled.', mail.subject emails = [@assignation.data_request.user.email] User.where(user_type: 'Admin').each do |user| emails << user.email end assert_equal emails, mail.to assert_equal ["<EMAIL>"], mail.from assert_match "Your data request has been fulfilled", mail.body.encoded end end <file_sep>json.array! @data_requests, partial: "data_requests/data_request", as: :data_request <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Assignation.delete_all DataRequest.delete_all User.delete_all leong = User.create!(name: 'Leong', password: '<PASSWORD>', email: '<EMAIL>', user_type: 0 ) james = User.create!(name: 'James', password: '<PASSWORD>', email: '<EMAIL>', user_type: 1 ) seng = User.create!(name: '<NAME>', password: '<PASSWORD>', email: '<EMAIL>', user_type: 2 ) nick = User.create!(name: 'Nicolas', password: '<PASSWORD>', email: '<EMAIL>', user_type: 2 ) data1 = DataRequest.create!(title: 'Suspend Vendors With Poor Ratings', description: "We are looking to suspend the vendors who have an overall average rating below 3.0 to ensure we eliminate vendors who are not qualified and unprofessional. I need your help to pull out data on all our vendor's overall rating from the beginning of time (2014-present). I'll need the data export to have the following criteria: - Vendor ID - Intercom UUID - Business Name - Email - Total number of reviews received (all time) - Overall rating (all time) - Account Status I will need this report on every last day of every month as this is gonna be an ongoing process/SOP moving forward. Would be great if there's a report in Holistic to generate this data every month. Let me know if you have any questions. Thank you for your help.", required_before: 2.days.ago, user: seng) data2 = DataRequest.create!(title: "Mother's Day Promo", description: "Hi team, We recently did a Mother's day promo (Code: THANKYOUMOM30) We got 60 redemptions as of today. And of these 60, 30 users have booked the services. I would like to ask for the personal details of these 30 users who have booked. I will need their names, addresses (the place for service fulfilment) and contact number. And possibly, I will need to know if these services have been fulfilled already or not. We will be sending flower bouquets to them prior to Mother's day next week. Kindly advise. Thanks!", required_before: 5.days.ago, user: nick) DataRequest.create!(title: "Lighting Installation Promo", description: "Hey Data, Need your help again to know the data for Lighting Installation (27) from Jan 2018 - April 2018 for request which answered yes and no to question 3 (Does The Lighting Contractor Have To Supply The Lights?). Also would like to know which vendor quoted for those job0s0.0 Country : Malaysia Service Type : Lighting Repair (27) Request Period : January 2018 - April 2018 Additional : Which requests answered yes and no to question 3 (Does The Lighting Contractor Have To Supply The Lights?). Also would like to know which vendor quoted for those jobs. Thank you!", required_before: 25.days.ago, user: seng, completed_at: Time.now, assigned_bool: true, assigned_at: Time.now) Assignation.create!(user: james, data_request: data1) Assignation.create!(user: james, data_request: data2, completed_at: Time.now)<file_sep>json.array! @assignations, partial: "assignations/assignation", as: :assignation <file_sep>json.partial! "assignations/assignation", assignation: @assignation <file_sep>json.extract! data_request, :id, :title, :description, :required_before, :created_at, :updated_at json.url data_request_url(data_request, format: :json) <file_sep>require 'test_helper' class DataRequestTest < ActiveSupport::TestCase fixtures :data_requests # test "the truth" do # assert true # end end <file_sep>class ApplicationController < ActionController::Base # before_action :authorize before_action :authenticate_user! skip_before_action :verify_authenticity_token protected def is_admin unless current_user.user_type == 'Admin' redirect_back(fallback_location: todo_index_url, notice: "You need to be logged in as an admin to do this.") end end end <file_sep>Rails.application.routes.draw do devise_for :users, controllers: { sessions: 'users/sessions', registrations: 'users/registrations' } get 'todo' => 'todo#index' resources :assignations do get :report, on: :member post :complete, on: :member end resources :users resources :data_requests do get :assign, on: :member end root 'todo#index', as: 'todo_index', via: :all end <file_sep>require 'test_helper' class DataRequestsControllerTest < ActionDispatch::IntegrationTest setup do @data_request = data_requests(:one) end test "should get index" do get data_requests_url assert_response :success end test "should get new" do get new_data_request_url assert_response :success end test "should create data_request" do assert_difference('DataRequest.count') do post data_requests_url, params: { data_request: { description: @data_request.description, required_before: @data_request.required_before, title: @data_request.title } } end assert_redirected_to data_request_url(DataRequest.last) end test "should show data_request" do get data_request_url(@data_request) assert_response :success end test "should get edit" do get edit_data_request_url(@data_request) assert_response :success end test "should update data_request" do patch data_request_url(@data_request), params: { data_request: { description: @data_request.description, required_before: @data_request.required_before, title: @data_request.title } } assert_redirected_to data_request_url(@data_request) end test "should destroy data_request" do assert_difference('DataRequest.count', -1) do delete data_request_url(@data_request) end assert_redirected_to data_requests_url end end <file_sep>json.partial! "data_requests/data_request", data_request: @data_request <file_sep>require "application_system_test_case" class DataRequestsTest < ApplicationSystemTestCase setup do @data_request = data_requests(:one) end test "visiting the index" do visit data_requests_url assert_selector "h1", text: "Data Requests" end test "creating a Data request" do visit data_requests_url click_on "New Data Request" fill_in "Description", with: @data_request.description fill_in "Required before", with: @data_request.required_before fill_in "Title", with: @data_request.title click_on "Create Data request" assert_text "Data request was successfully created" click_on "Back" end test "updating a Data request" do visit data_requests_url click_on "Edit", match: :first fill_in "Description", with: @data_request.description fill_in "Required before", with: @data_request.required_before fill_in "Title", with: @data_request.title click_on "Update Data request" assert_text "Data request was successfully updated" click_on "Back" end test "destroying a Data request" do visit data_requests_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Data request was successfully destroyed" end end <file_sep># Preview all emails at http://localhost:3000/rails/mailers/data_request_mailer class DataRequestMailerPreview < ActionMailer::Preview # Preview this email at http://localhost:3000/rails/mailers/data_request_mailer/created def created DataRequestMailer.created end # Preview this email at http://localhost:3000/rails/mailers/data_request_mailer/assigned def assigned DataRequestMailer.assigned end # Preview this email at http://localhost:3000/rails/mailers/data_request_mailer/completed def completed DataRequestMailer.completed end end <file_sep>class Assignation < ApplicationRecord belongs_to :data_request belongs_to :user end <file_sep>class AssignationsController < ApplicationController before_action :is_admin, only: [:new, :create, :destroy] before_action :set_assignation, only: [:show, :edit, :update, :destroy, :report, :complete] before_action :owns_assignation, only: [:edit, :update, :destroy] # GET /assignations # GET /assignations.json def index if current_user.user_type == 'Admin' @assignations = Assignation.all else # @assignations = Assignation.where(user: User.find(session[:user_id])) @assignations = Assignation.where(user: User.find(current_user.id)) end end # GET /assignations/1 # GET /assignations/1.json def show end # GET /assignations/new def new @assignation = Assignation.new @user_id = nil if params.has_key? :data_request @data_request = DataRequest.find(params[:data_request]) else @data_request = nil end end # GET /assignations/1/edit def edit @user_id = @assignation.user_id end # POST /assignations # POST /assignations.json def create @assignation = Assignation.new(assignation_params) respond_to do |format| if @assignation.save DataRequestMailer.assigned(@assignation).deliver_later DataRequestMailer.notify(@assignation).deliver_later format.html { redirect_to @assignation, notice: 'Assignation was successfully created.' } format.json { render :show, status: :created, location: @assignation } else format.html { render :new } format.json { render json: @assignation.errors, status: :unprocessable_entity } end end end # PATCH/PUT /assignations/1 # PATCH/PUT /assignations/1.json def update respond_to do |format| if @assignation.update(assignation_eta_params) format.html { redirect_to @assignation, notice: 'Assignation was successfully updated.' } format.json { render :show, status: :ok, location: @assignation } else format.html { render :edit } format.json { render json: @assignation.errors, status: :unprocessable_entity } end end end # DELETE /assignations/1 # DELETE /assignations/1.json def destroy @assignation.destroy respond_to do |format| format.html { redirect_to assignations_url, notice: 'Assignation was successfully destroyed.' } format.json { head :no_content } end end def complete report = params[:report] @assignation.report = report @assignation.completed_at = Time.now @assignation.data_request.completed_at = @assignation.completed_at respond_to do |format| if @assignation.save && @assignation.data_request.save DataRequestMailer.completed(@assignation).deliver_later format.html { redirect_to @assignation, notice: 'Assignation was successfully completed.' } format.json { render :show, status: :created, location: @assignation } else format.html { render :new } format.json { render json: @assignation.errors, status: :unprocessable_entity } end end end def report end private # Use callbacks to share common setup or constraints between actions. def set_assignation @assignation = Assignation.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def assignation_params params.require(:assignation).permit(:data_request_id, :user_id, :report) end def assignation_eta_params params.require(:assignation).permit(:eta) end # Never trust parameters from the scary internet, only allow the white list through. def owns_assignation unless current_user == @assignation.user || current_user.user_type == 'Admin' redirect_back(fallback_location: assignations_url, notice: "You do not own this assignation.") end end end <file_sep>require "application_system_test_case" class AssignationsTest < ApplicationSystemTestCase setup do @assignation = assignations(:one) end test "visiting the index" do visit assignations_url assert_selector "h1", text: "Assignations" end test "creating a Assignation" do visit assignations_url click_on "New Assignation" fill_in "Datarequest", with: @assignation.datarequest_id fill_in "User", with: @assignation.user_id click_on "Create Assignation" assert_text "Assignation was successfully created" click_on "Back" end test "updating a Assignation" do visit assignations_url click_on "Edit", match: :first fill_in "Datarequest", with: @assignation.datarequest_id fill_in "User", with: @assignation.user_id click_on "Update Assignation" assert_text "Assignation was successfully updated" click_on "Back" end test "destroying a Assignation" do visit assignations_url page.accept_confirm do click_on "Destroy", match: :first end assert_text "Assignation was successfully destroyed" end end <file_sep>class DataRequestsController < ApplicationController before_action :set_data_request, only: [:show, :edit, :update, :destroy] before_action :is_data_request_owner, only: [:edit, :update, :destroy] # GET /data_requests # GET /data_requests.json def index @data_requests = DataRequest.where(completed_at: nil).order(:required_before) @completed = DataRequest.where.not(completed_at: nil).order(updated_at: :desc) end # GET /data_requests/1 # GET /data_requests/1.json def show end # GET /data_requests/new def new @data_request = DataRequest.new end # GET /data_requests/1/edit def edit end # POST /data_requests # POST /data_requests.json def create @data_request = DataRequest.new(data_request_params) @data_request.user = current_user respond_to do |format| if @data_request.save DataRequestMailer.created(@data_request).deliver_later format.html { redirect_to @data_request, notice: 'Data request was successfully created.' } format.json { render :show, status: :created, location: @data_request } else format.html { render :new } format.json { render json: @data_request.errors, status: :unprocessable_entity } end end end # PATCH/PUT /data_requests/1 # PATCH/PUT /data_requests/1.json def update respond_to do |format| if @data_request.update(data_request_params) format.html { redirect_to @data_request, notice: 'Data request was successfully updated.' } format.json { render :show, status: :ok, location: @data_request } else format.html { render :edit } format.json { render json: @data_request.errors, status: :unprocessable_entity } end end end # DELETE /data_requests/1 # DELETE /data_requests/1.json def destroy @data_request.destroy respond_to do |format| format.html { redirect_to data_requests_url, notice: 'Data request was successfully destroyed.' } format.json { head :no_content } end end def assign @data_request = DataRequest.find(params[:id]) end private # Use callbacks to share common setup or constraints between actions. def set_data_request @data_request = DataRequest.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def data_request_params params.require(:data_request).permit(:title, :description, :required_before) end def is_data_request_owner unless (session[:user_type] == 'Admin') || @data_request.user == current_user redirect_back(fallback_location: data_requests_url, notice: "Only admin and data request owners are allowed to do this.") end end end <file_sep>class TodoController < ApplicationController # skip_before_action :authorize def index @todos = DataRequest.where(completed_at: nil).all end end <file_sep>class DataRequestMailer < ApplicationMailer # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.data_request_mailer.created.subject # def created(data_request) @data_request = data_request mail to: @data_request.user.email, subject: 'Successfully submitted data request' end # Subject can be set in your I18n file at config/locales/en.yml # with the following lookup: # # en.data_request_mailer.assigned.subject # def assigned(assignation) @assignation = assignation @data_request = assignation.data_request mail to: @assignation.user.email, subject: 'You have been tasked with a new request.' end def notify(assignation) @assignation = assignation @data_request = assignation.data_request mail to: @data_request.user.email, subject: 'Your request has been assigned to an analyst.' end def completed(assignation) @assignation = assignation @data_request = assignation.data_request emails = [@data_request.user.email] User.where(user_type: 'Admin').each do |user| emails << user.email end mail to: emails, subject: 'Data request has been fulfilled.' end end <file_sep>require 'test_helper' class AssignationsControllerTest < ActionDispatch::IntegrationTest setup do @assignation = assignations(:one) end test "should get index" do get assignations_url assert_response :success end test "should get new" do get new_assignation_url assert_response :success end test "should create assignation" do assert_difference('Assignation.count') do post assignations_url, params: { assignation: { data_request_id: @assignation.data_request_id, user_id: @assignation.user_id } } end assert_redirected_to assignation_url(Assignation.last) end test "should show assignation" do get assignation_url(@assignation) assert_response :success end test "should get edit" do get edit_assignation_url(@assignation) assert_response :success end test "should update assignation" do patch assignation_url(@assignation), params: { assignation: { data_request_id: @assignation.data_request_id, user_id: @assignation.user_id } } assert_redirected_to assignation_url(@assignation) end test "should destroy assignation" do assert_difference('Assignation.count', -1) do delete assignation_url(@assignation) end assert_redirected_to assignations_url end end
7fd6601ef8616bf01df175a282dd5cca5202e1d7
[ "Ruby" ]
23
Ruby
jamestjw/datateam
d6d43a055b1581c948c303c52d3ad5355b5d841a
5e183ae38509cce6948188c52c3fa760f8ad7f99