Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.ts.web.rest;
- import java.io.IOException;
- import java.io.InputStream;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.text.DateFormat;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.Date;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.Properties;
- import org.apache.log4j.LogManager;
- import org.apache.log4j.Logger;
- import org.apache.log4j.PropertyConfigurator;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.ncubo.configuracion.Enviroment;
- import com.ts.configuracion.Api2ManagerREST;
- import com.ts.db.Log;
- import com.ts.db.Recuperados;
- import com.ts.libraries.Browser;
- import com.ts.libraries.Canal.Tipo;
- import com.ts.libraries.Correo;
- import com.ts.libraries.Firma;
- import com.ts.libraries.Hexadecimal;
- import com.ts.libraries.IPv4;
- import com.ts.libraries.Sistema;
- import com.ts.main.Procesador;
- import com.ts.procesadores.ProcesadorDeComandos;
- public class GeneradorDeLogDeComandos
- {
- private final static Logger logger = Logger.getLogger(GeneradorDeLogDeComandos.class);
- private static DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
- private static Connection conexion;
- private static final String JDBC_CONNECTOR = "jdbc:mysql://bd.qa14.ncubo.com:3306/baseline2";
- private static final String USER_BD = "logwriter";
- private static final String PASS_BD = "logwriter";
- private static final String NOMBRE_DE_LA_BD = "baseline2";
- public static void main(String[] args) throws IOException
- {
- Properties props = new Properties();
- InputStream configStream = GeneradorDeLogDeComandos.class.getResourceAsStream( "/log4jtestcases.properties");
- props.load(configStream);
- configStream.close();
- LogManager.resetConfiguration();
- PropertyConfigurator.configure(props);
- String compania = "",comando = "",respuestaDelComandoEjecutado= "" ;
- long time_start, time_end;
- time_start = System.currentTimeMillis();
- String comandoConLaSalidaGrande = "";
- int longitudDeLaSalidaMasGrande = 0;
- Ordenar ordenador = new Ordenar();
- Statement stmt = null;
- try
- {
- ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/testcasesaplication.xml");
- Comercios comerciosController = new Comercios();
- Enviroment env = (Enviroment)applicationContext.getBean("enviroment") ;
- comerciosController.setEnviroment( env );
- Class.forName("com.mysql.jdbc.Driver");
- conexion = DriverManager.getConnection(JDBC_CONNECTOR, USER_BD, PASS_BD);
- stmt = conexion.createStatement();
- ResultSet rs = stmt.executeQuery("SHOW TABLES;");
- Api2ManagerREST api2 = new Api2ManagerREST("");
- String actualCompania = "";
- String apartirDe ="distribuidoranimbustech";
- Procesador.estoyEnDesarrolloNoQuieroGuardarEsteDia(24, 5, 2017);
- while (rs.next())
- {
- compania = rs.getString("Tables_in_"+NOMBRE_DE_LA_BD);
- if(! apartirDe.isEmpty() && ! compania.equals(apartirDe) )
- {
- continue;
- }
- else if( compania.equals(apartirDe) )
- {
- apartirDe ="";
- }
- Firma firmaActual = new Firma(new Browser(),new IPv4(), Sistema.fechaHoraActual(), Tipo.CONSOLA, new Correo("no-user@ncubo.com"), new Hexadecimal("0000"));
- if( ! actualCompania.equals( compania))
- {
- actualCompania =compania;
- api2.setCompania(compania);
- }
- api2.cargarInformacionDeContexto( firmaActual);
- if( compania.endsWith("_r") || compania.startsWith("c_") || compania.equals("pagos") || compania.startsWith("comerciov_"))
- {
- continue;
- }
- props = new Properties();
- configStream = GeneradorDeLogDeComandos.class.getResourceAsStream( "/log4jtestcases.properties");
- props.load(configStream);
- props.setProperty("log4j.appender.tc.File", "G:/GeneradorDeComandos/"+compania+"bb.log");
- props.setProperty("log4j.appender.logfile.encoding", "UTF-8");
- configStream.close();
- LogManager.resetConfiguration();
- PropertyConfigurator.configure(props);
- Statement comandosStmt = conexion.createStatement();
- ResultSet comandosDeCompania = comandosStmt.executeQuery("SELECT id, FechaHora, Comando, tiene_recuperado FROM "+compania+" order by id ASC;");
- Statement comandosStmt2 = conexion.createStatement();
- ResultSet queryParaTraerElTotalDeComandosEnLaCompannia = comandosStmt2.executeQuery("SELECT count(*) as cantidad FROM "+compania+";");
- queryParaTraerElTotalDeComandosEnLaCompannia.next();
- int cantidadTotalDeComandosDeLaCompannia = queryParaTraerElTotalDeComandosEnLaCompannia.getInt("cantidad");
- comandosStmt2.close();
- queryParaTraerElTotalDeComandosEnLaCompannia.close();
- final Connection conexion2 = DriverManager.getConnection(env.getConnectionMySQL(), env.getUsuarioMySQL(), env.getPasswordMySQL());
- Statement stmttrun = conexion2.createStatement();
- stmttrun.executeUpdate("DROP TABLE IF EXISTS "+compania+" cascade;");
- stmttrun.executeUpdate("DROP TABLE IF EXISTS "+compania+"_r"+" cascade;");
- stmttrun.close();
- conexion2.close();
- System.out.println("Empieza " +compania);
- int cantidadDeComandosEjecutados = 0;
- while (comandosDeCompania.next())
- {
- comando = comandosDeCompania.getString("Comando").trim();
- cargarUnProcesadorAlHiloActual(compania, comerciosController);
- if(comando.startsWith("//"))continue; //TODO:ESTO ES TEMPORAL PARA QUE NO SE EJECUTEN LOS COMANDOS QUE TIENEN COMENTARIOS
- Date fechaHora = comandosDeCompania.getDate("FechaHora");
- String fechaHoraFormat = DATE_FORMAT.format(fechaHora);
- String comandoGenerado = api2.newCommand().add(comando).getCommandSustituido(fechaHoraFormat);
- try
- {
- boolean tieneRecuperado = comandosDeCompania.getInt("tiene_recuperado") == 1;
- if(tieneRecuperado)
- {
- Log.abrirConexion(JDBC_CONNECTOR, USER_BD, PASS_BD);
- Log log = new Log(conexion, compania);
- Recuperados variablesDeContextoDelHistorial = log.variablesDeContextoALaTabla(compania, comandosDeCompania);
- ProcesadorDeComandos.miProcesador().tablaDeSimbolos.guardarRecuperados(variablesDeContextoDelHistorial.objetosDeTipoPull(), false);
- }
- respuestaDelComandoEjecutado = comerciosController.atenderUnComercios(comandoGenerado, compania);
- }
- catch(RuntimeException e)
- {
- System.err.println(compania+" | "+comando);
- respuestaDelComandoEjecutado = e.getMessage();
- e.printStackTrace();
- }
- cantidadDeComandosEjecutados++;
- if (respuestaDelComandoEjecutado.length() > longitudDeLaSalidaMasGrande)
- {
- comandoConLaSalidaGrande = comando;
- longitudDeLaSalidaMasGrande = respuestaDelComandoEjecutado.length();
- }
- String jsonString = ordenador.ordenarJson(respuestaDelComandoEjecutado) ;
- if( ! jsonString.equals("[]"))
- {
- jsonString = jsonString.replace(",", ",\n");
- jsonString = jsonString.replace("{", "{\n");
- jsonString = jsonString.replace("[", "[\n");
- }
- //logger.debug (" ");
- //logger.debug (jsonString);
- }
- comandosStmt.close();
- comandosDeCompania.close();
- comerciosController.dejarDeAtenderUnComercios(compania);
- }
- rs.close();
- }
- catch (SQLException e)
- {
- throw new RuntimeException(e);
- }
- catch (ClassNotFoundException e)
- {
- throw new RuntimeException(e);
- }
- catch (Exception e)
- {
- System.err.println(compania+" | "+comando+" | "+respuestaDelComandoEjecutado );
- throw new RuntimeException(e);
- }
- finally
- {
- if (conexion != null) try { conexion.close(); } catch (SQLException logOrIgnore) {}
- if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
- }
- System.out.println("YA TERMINE DE GENERAR EL BASELINE");
- time_end = System.currentTimeMillis();
- System.out.println("Generar el baseLine tomo "+ ( time_end - time_start ) +" milliseconds");
- System.out.println("Comando con la salida más grande ( "+longitudDeLaSalidaMasGrande+ " caracteres):");
- System.out.println(comandoConLaSalidaGrande);
- }
- private static void cargarUnProcesadorAlHiloActual(String compania, Comercios comerciosController) throws IOException
- {
- Thread.currentThread().setName(compania);
- comerciosController.cargarUnComercio(compania);
- }
- }
- class Ordenar
- {
- //private Gson gson = new Gson();
- private char[] resto;
- private int indiceResto = 0;
- private final StringComparator comparador = new StringComparator ();
- private final static int CACHE_MAX_SIZE = 100;
- private LinkedHashMap<String, String> cache;
- Ordenar ()
- {
- this.cache = new LinkedHashMap<String, String>(CACHE_MAX_SIZE, 0.75f, true)
- {
- protected boolean removeEldestEntry (Map.Entry<String, String> eldest)
- {
- return size() > CACHE_MAX_SIZE;
- }
- };
- }
- String ordenarJson (String jsonPorOrdenar)
- {
- String stringEnCache = this.cache.get(jsonPorOrdenar);
- if (stringEnCache != null) return stringEnCache;
- resto = jsonPorOrdenar.toCharArray();
- indiceResto = 0;
- String resultado = ordenarJson();
- if (indiceResto != resto.length)
- {
- new RuntimeException("Ordenando \r" + jsonPorOrdenar + "\r sobro esto: '"+ new String(resto, indiceResto, resto.length-indiceResto) +"'");
- }
- if(resultado.isEmpty())return jsonPorOrdenar;
- this.cache.put(jsonPorOrdenar, resultado);
- return resultado;
- }
- private boolean restoStartsWith(char caracter)
- {
- return resto[indiceResto] == caracter;
- }
- private boolean restoStartsWith(String hilera)
- {
- for (int i = 0; i < hilera.length(); i++)
- {
- if (resto[indiceResto+i] != hilera.charAt(i)) return false;
- }
- return true;
- }
- private char restoCharAt()
- {
- return resto[indiceResto];
- }
- private void restoAvance()
- {
- indiceResto++;
- }
- private String ordenarJson()
- {
- String resultado = "";
- if (restoStartsWith('['))
- {
- resultado = ordenarArreglo ();
- }
- else if (restoStartsWith('{'))
- {
- resultado = ordenarObjeto ();
- }
- else if (restoStartsWith('\'') || restoStartsWith('"'))
- {
- resultado = hilera ();
- }
- else if (restoStartsWith("true"))
- {
- aceptar("true");
- resultado = "true";
- }
- else if (restoStartsWith("false"))
- {
- aceptar("false");
- resultado = "false";
- }
- else if (restoStartsWith("null"))
- {
- aceptar("null");
- resultado = "null";
- }
- else if (Character.isDigit(restoCharAt()))
- {
- resultado = numero();
- }
- return resultado;
- }
- private void aceptar (char valor)
- {
- if (! restoStartsWith(valor)) new RuntimeException("Se esperaba un '" + valor + "', pero aparecio un "+ new String(resto, indiceResto, resto.length-indiceResto));
- restoAvance();
- while (indiceResto < resto.length && restoStartsWith(' '))
- {
- restoAvance();
- }
- }
- private void aceptar (String valor)
- {
- if (! restoStartsWith(valor)) new RuntimeException("Se esperaba un '" + valor + "', pero aparecio un "+ new String(resto, indiceResto, resto.length-indiceResto));
- for (int i = 0; i < valor.length(); i++)
- {
- restoAvance();
- }
- while (indiceResto < resto.length && restoStartsWith(' '))
- {
- restoAvance();
- }
- }
- private String ordenarArreglo ()
- {
- aceptar('[');
- boolean salir = restoStartsWith(']');
- ArrayList<String> elementos = new ArrayList<String>();
- while ( ! salir)
- {
- if (restoStartsWith(',')) aceptar(',');
- elementos.add( ordenarJson() );
- salir = restoStartsWith(']');
- }
- aceptar(']');
- String resultado = arregloToString(elementos);
- return resultado;
- }
- private String ordenarObjeto ()
- {
- aceptar('{');
- boolean salir = restoStartsWith('}');
- ArrayList<String> atributos = new ArrayList<String>();
- ArrayList<String> valores = new ArrayList<String>();
- while ( ! salir)
- {
- if (restoStartsWith(',')) aceptar(',');
- String atributo = atributo();
- aceptar (':');
- String valor = valor();
- atributos.add( atributo );
- valores.add( valor );
- salir = restoStartsWith('}');
- }
- aceptar('}');
- String resultado = objetoToString(atributos, valores);
- return resultado;
- }
- private String hilera()
- {
- StringBuilder resultado = new StringBuilder();
- char comilla = restoCharAt();
- aceptar(comilla);
- resultado.append(comilla);
- while (restoCharAt() != comilla)
- {
- if (restoCharAt() == '\\' && restoCharAt() == comilla)
- {
- resultado.append(restoCharAt());
- resultado.append(restoCharAt());
- restoAvance();
- restoAvance();
- }
- else
- {
- resultado.append(restoCharAt());
- restoAvance();
- }
- }
- aceptar(comilla);
- resultado.append(comilla);
- return resultado.toString();
- }
- private String atributo()
- {
- StringBuilder resultado = new StringBuilder();
- if (restoCharAt() == '"')
- {
- return hilera();
- }
- else
- {
- while (! restoStartsWith(' ') && ! restoStartsWith(':'))
- {
- resultado.append( restoCharAt() );
- restoAvance();
- }
- }
- return resultado.toString();
- }
- private String numero()
- {
- StringBuilder resultado = new StringBuilder();
- if (restoCharAt() == '-')
- {
- aceptar('-');
- resultado.append('-');
- }
- while (Character.isDigit(restoCharAt()))
- {
- resultado.append( restoCharAt() );
- restoAvance();
- }
- if (restoCharAt() == '.')
- {
- aceptar('.');
- resultado.append('.');
- while (Character.isDigit(restoCharAt()))
- {
- resultado.append( restoCharAt() );
- restoAvance();
- }
- }
- if (restoCharAt() == 'E')
- {
- aceptar('E');
- resultado.append('E');
- }
- else if (restoCharAt() == 'e')
- {
- aceptar('e');
- resultado.append('e');
- }
- if (restoCharAt() == '+')
- {
- aceptar('+');
- resultado.append('+');
- while (Character.isDigit(restoCharAt()))
- {
- resultado.append( restoCharAt() );
- restoAvance();
- }
- }
- else if (restoCharAt() == '-')
- {
- aceptar('-');
- resultado.append('-');
- while (Character.isDigit(restoCharAt()))
- {
- resultado.append( restoCharAt() );
- restoAvance();
- }
- }
- else
- {
- while (Character.isDigit(restoCharAt()))
- {
- resultado.append( restoCharAt() );
- restoAvance();
- }
- }
- while (indiceResto < resto.length && restoStartsWith(' '))
- {
- restoAvance();
- }
- return resultado.toString();
- }
- private String valor()
- {
- String resultado = ordenarJson();
- return resultado;
- }
- private String arregloToString(ArrayList<String> arreglo)
- {
- StringBuilder resultado = new StringBuilder();
- tabsToString(resultado);
- resultado.append('[');
- tabs++;
- resultado.append('\n');
- Collections.sort( arreglo, comparador);
- for (int i = 0; i < arreglo.size(); i++)
- {
- if (resultado.length() > 1)
- {
- resultado.append(',');
- resultado.append('\n');
- }
- tabsToString(resultado);
- resultado.append( arreglo.get(i) );
- }
- tabs--;
- resultado.append('\n');
- tabsToString(resultado);
- resultado.append(']');
- return resultado.toString();
- }
- private int tabs = 0;
- private void tabsToString( StringBuilder resultado)
- {
- for( int j =0; j< tabs; j++)
- {
- resultado.append(' ');
- }
- }
- private String objetoToString(ArrayList<String> atributos, ArrayList<String> valores)
- {
- StringBuilder resultado = new StringBuilder();
- tabsToString(resultado);
- resultado.append('{');
- tabs++;
- resultado.append('\n');
- ArrayList<String> arreglo = new ArrayList<String>(atributos);
- Collections.sort( arreglo, comparador);
- for (int i = 0; i < arreglo.size(); i++)
- {
- if (resultado.length() > 1) resultado.append(", ");
- String atributo = arreglo.get(i);
- int indiceValor = atributos.indexOf(atributo);
- String valor = valores.get(indiceValor);
- tabsToString(resultado);
- resultado.append(atributo);
- resultado.append(':');
- resultado.append(valor);
- resultado.append('\n');
- }
- resultado.append('\n');
- tabs--;
- tabsToString(resultado);
- resultado.append('}');
- return resultado.toString();
- }
- class StringComparator implements Comparator<String>
- {
- public int compare(String obj1, String obj2) {
- if (obj1 == obj2) {
- return 0;
- }
- if (obj1 == null) {
- return -1;
- }
- if (obj2 == null) {
- return 1;
- }
- return obj1.compareTo(obj2);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement