Advertisement
Guest User

Untitled

a guest
May 26th, 2017
527
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.53 KB | None | 0 0
  1. package com.ts.web.rest;
  2.  
  3.  
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.sql.Connection;
  7. import java.sql.DriverManager;
  8. import java.sql.ResultSet;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11. import java.text.DateFormat;
  12. import java.text.SimpleDateFormat;
  13. import java.util.ArrayList;
  14. import java.util.Collections;
  15. import java.util.Comparator;
  16. import java.util.Date;
  17. import java.util.LinkedHashMap;
  18. import java.util.Map;
  19. import java.util.Properties;
  20.  
  21. import org.apache.log4j.LogManager;
  22. import org.apache.log4j.Logger;
  23. import org.apache.log4j.PropertyConfigurator;
  24. import org.springframework.context.ApplicationContext;
  25. import org.springframework.context.support.ClassPathXmlApplicationContext;
  26.  
  27. import com.ncubo.configuracion.Enviroment;
  28. import com.ts.configuracion.Api2ManagerREST;
  29. import com.ts.db.Log;
  30. import com.ts.db.Recuperados;
  31. import com.ts.libraries.Browser;
  32. import com.ts.libraries.Canal.Tipo;
  33. import com.ts.libraries.Correo;
  34. import com.ts.libraries.Firma;
  35. import com.ts.libraries.Hexadecimal;
  36. import com.ts.libraries.IPv4;
  37. import com.ts.libraries.Sistema;
  38. import com.ts.main.Procesador;
  39. import com.ts.procesadores.ProcesadorDeComandos;
  40.  
  41. public class GeneradorDeLogDeComandos
  42. {
  43. private final static Logger logger = Logger.getLogger(GeneradorDeLogDeComandos.class);
  44. private static DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  45. private static Connection conexion;
  46. private static final String JDBC_CONNECTOR = "jdbc:mysql://bd.qa14.ncubo.com:3306/baseline2";
  47. private static final String USER_BD = "logwriter";
  48. private static final String PASS_BD = "logwriter";
  49. private static final String NOMBRE_DE_LA_BD = "baseline2";
  50.  
  51. public static void main(String[] args) throws IOException
  52. {
  53. Properties props = new Properties();
  54. InputStream configStream = GeneradorDeLogDeComandos.class.getResourceAsStream( "/log4jtestcases.properties");
  55. props.load(configStream);
  56. configStream.close();
  57. LogManager.resetConfiguration();
  58. PropertyConfigurator.configure(props);
  59. String compania = "",comando = "",respuestaDelComandoEjecutado= "" ;
  60.  
  61. long time_start, time_end;
  62. time_start = System.currentTimeMillis();
  63.  
  64. String comandoConLaSalidaGrande = "";
  65. int longitudDeLaSalidaMasGrande = 0;
  66.  
  67. Ordenar ordenador = new Ordenar();
  68.  
  69. Statement stmt = null;
  70. try
  71. {
  72. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/testcasesaplication.xml");
  73. Comercios comerciosController = new Comercios();
  74. Enviroment env = (Enviroment)applicationContext.getBean("enviroment") ;
  75. comerciosController.setEnviroment( env );
  76. Class.forName("com.mysql.jdbc.Driver");
  77.  
  78. conexion = DriverManager.getConnection(JDBC_CONNECTOR, USER_BD, PASS_BD);
  79. stmt = conexion.createStatement();
  80. ResultSet rs = stmt.executeQuery("SHOW TABLES;");
  81.  
  82. Api2ManagerREST api2 = new Api2ManagerREST("");
  83.  
  84. String actualCompania = "";
  85. String apartirDe ="distribuidoranimbustech";
  86.  
  87. Procesador.estoyEnDesarrolloNoQuieroGuardarEsteDia(24, 5, 2017);
  88. while (rs.next())
  89. {
  90. compania = rs.getString("Tables_in_"+NOMBRE_DE_LA_BD);
  91.  
  92. if(! apartirDe.isEmpty() && ! compania.equals(apartirDe) )
  93. {
  94. continue;
  95. }
  96. else if( compania.equals(apartirDe) )
  97. {
  98. apartirDe ="";
  99. }
  100.  
  101. Firma firmaActual = new Firma(new Browser(),new IPv4(), Sistema.fechaHoraActual(), Tipo.CONSOLA, new Correo("no-user@ncubo.com"), new Hexadecimal("0000"));
  102. if( ! actualCompania.equals( compania))
  103. {
  104. actualCompania =compania;
  105. api2.setCompania(compania);
  106. }
  107. api2.cargarInformacionDeContexto( firmaActual);
  108.  
  109. if( compania.endsWith("_r") || compania.startsWith("c_") || compania.equals("pagos") || compania.startsWith("comerciov_"))
  110. {
  111. continue;
  112. }
  113.  
  114. props = new Properties();
  115. configStream = GeneradorDeLogDeComandos.class.getResourceAsStream( "/log4jtestcases.properties");
  116. props.load(configStream);
  117. props.setProperty("log4j.appender.tc.File", "G:/GeneradorDeComandos/"+compania+"bb.log");
  118. props.setProperty("log4j.appender.logfile.encoding", "UTF-8");
  119.  
  120. configStream.close();
  121. LogManager.resetConfiguration();
  122. PropertyConfigurator.configure(props);
  123.  
  124. Statement comandosStmt = conexion.createStatement();
  125. ResultSet comandosDeCompania = comandosStmt.executeQuery("SELECT id, FechaHora, Comando, tiene_recuperado FROM "+compania+" order by id ASC;");
  126. Statement comandosStmt2 = conexion.createStatement();
  127. ResultSet queryParaTraerElTotalDeComandosEnLaCompannia = comandosStmt2.executeQuery("SELECT count(*) as cantidad FROM "+compania+";");
  128. queryParaTraerElTotalDeComandosEnLaCompannia.next();
  129. int cantidadTotalDeComandosDeLaCompannia = queryParaTraerElTotalDeComandosEnLaCompannia.getInt("cantidad");
  130. comandosStmt2.close();
  131. queryParaTraerElTotalDeComandosEnLaCompannia.close();
  132.  
  133. final Connection conexion2 = DriverManager.getConnection(env.getConnectionMySQL(), env.getUsuarioMySQL(), env.getPasswordMySQL());
  134. Statement stmttrun = conexion2.createStatement();
  135. stmttrun.executeUpdate("DROP TABLE IF EXISTS "+compania+" cascade;");
  136. stmttrun.executeUpdate("DROP TABLE IF EXISTS "+compania+"_r"+" cascade;");
  137. stmttrun.close();
  138. conexion2.close();
  139.  
  140. System.out.println("Empieza " +compania);
  141. int cantidadDeComandosEjecutados = 0;
  142. while (comandosDeCompania.next())
  143. {
  144. comando = comandosDeCompania.getString("Comando").trim();
  145.  
  146. cargarUnProcesadorAlHiloActual(compania, comerciosController);
  147.  
  148. if(comando.startsWith("//"))continue; //TODO:ESTO ES TEMPORAL PARA QUE NO SE EJECUTEN LOS COMANDOS QUE TIENEN COMENTARIOS
  149. Date fechaHora = comandosDeCompania.getDate("FechaHora");
  150. String fechaHoraFormat = DATE_FORMAT.format(fechaHora);
  151.  
  152. String comandoGenerado = api2.newCommand().add(comando).getCommandSustituido(fechaHoraFormat);
  153. try
  154. {
  155. boolean tieneRecuperado = comandosDeCompania.getInt("tiene_recuperado") == 1;
  156. if(tieneRecuperado)
  157. {
  158. Log.abrirConexion(JDBC_CONNECTOR, USER_BD, PASS_BD);
  159. Log log = new Log(conexion, compania);
  160. Recuperados variablesDeContextoDelHistorial = log.variablesDeContextoALaTabla(compania, comandosDeCompania);
  161. ProcesadorDeComandos.miProcesador().tablaDeSimbolos.guardarRecuperados(variablesDeContextoDelHistorial.objetosDeTipoPull(), false);
  162. }
  163. respuestaDelComandoEjecutado = comerciosController.atenderUnComercios(comandoGenerado, compania);
  164. }
  165. catch(RuntimeException e)
  166. {
  167. System.err.println(compania+" | "+comando);
  168. respuestaDelComandoEjecutado = e.getMessage();
  169. e.printStackTrace();
  170. }
  171. cantidadDeComandosEjecutados++;
  172. if (respuestaDelComandoEjecutado.length() > longitudDeLaSalidaMasGrande)
  173. {
  174. comandoConLaSalidaGrande = comando;
  175. longitudDeLaSalidaMasGrande = respuestaDelComandoEjecutado.length();
  176. }
  177.  
  178.  
  179. String jsonString = ordenador.ordenarJson(respuestaDelComandoEjecutado) ;
  180. if( ! jsonString.equals("[]"))
  181. {
  182. jsonString = jsonString.replace(",", ",\n");
  183. jsonString = jsonString.replace("{", "{\n");
  184. jsonString = jsonString.replace("[", "[\n");
  185. }
  186.  
  187. //logger.debug (" ");
  188. //logger.debug (jsonString);
  189. }
  190. comandosStmt.close();
  191. comandosDeCompania.close();
  192. comerciosController.dejarDeAtenderUnComercios(compania);
  193. }
  194. rs.close();
  195. }
  196. catch (SQLException e)
  197. {
  198. throw new RuntimeException(e);
  199. }
  200. catch (ClassNotFoundException e)
  201. {
  202. throw new RuntimeException(e);
  203. }
  204. catch (Exception e)
  205. {
  206. System.err.println(compania+" | "+comando+" | "+respuestaDelComandoEjecutado );
  207. throw new RuntimeException(e);
  208. }
  209. finally
  210. {
  211. if (conexion != null) try { conexion.close(); } catch (SQLException logOrIgnore) {}
  212. if (stmt != null) try { stmt.close(); } catch (SQLException ignore) {}
  213. }
  214. System.out.println("YA TERMINE DE GENERAR EL BASELINE");
  215. time_end = System.currentTimeMillis();
  216. System.out.println("Generar el baseLine tomo "+ ( time_end - time_start ) +" milliseconds");
  217. System.out.println("Comando con la salida más grande ( "+longitudDeLaSalidaMasGrande+ " caracteres):");
  218. System.out.println(comandoConLaSalidaGrande);
  219. }
  220.  
  221. private static void cargarUnProcesadorAlHiloActual(String compania, Comercios comerciosController) throws IOException
  222. {
  223. Thread.currentThread().setName(compania);
  224. comerciosController.cargarUnComercio(compania);
  225. }
  226. }
  227.  
  228. class Ordenar
  229. {
  230. //private Gson gson = new Gson();
  231. private char[] resto;
  232. private int indiceResto = 0;
  233. private final StringComparator comparador = new StringComparator ();
  234. private final static int CACHE_MAX_SIZE = 100;
  235. private LinkedHashMap<String, String> cache;
  236.  
  237. Ordenar ()
  238. {
  239. this.cache = new LinkedHashMap<String, String>(CACHE_MAX_SIZE, 0.75f, true)
  240. {
  241. protected boolean removeEldestEntry (Map.Entry<String, String> eldest)
  242. {
  243. return size() > CACHE_MAX_SIZE;
  244. }
  245. };
  246. }
  247.  
  248. String ordenarJson (String jsonPorOrdenar)
  249. {
  250. String stringEnCache = this.cache.get(jsonPorOrdenar);
  251. if (stringEnCache != null) return stringEnCache;
  252.  
  253. resto = jsonPorOrdenar.toCharArray();
  254. indiceResto = 0;
  255.  
  256. String resultado = ordenarJson();
  257.  
  258. if (indiceResto != resto.length)
  259. {
  260. new RuntimeException("Ordenando \r" + jsonPorOrdenar + "\r sobro esto: '"+ new String(resto, indiceResto, resto.length-indiceResto) +"'");
  261. }
  262. if(resultado.isEmpty())return jsonPorOrdenar;
  263. this.cache.put(jsonPorOrdenar, resultado);
  264. return resultado;
  265. }
  266.  
  267. private boolean restoStartsWith(char caracter)
  268. {
  269. return resto[indiceResto] == caracter;
  270. }
  271.  
  272. private boolean restoStartsWith(String hilera)
  273. {
  274. for (int i = 0; i < hilera.length(); i++)
  275. {
  276. if (resto[indiceResto+i] != hilera.charAt(i)) return false;
  277. }
  278. return true;
  279. }
  280.  
  281. private char restoCharAt()
  282. {
  283. return resto[indiceResto];
  284. }
  285.  
  286. private void restoAvance()
  287. {
  288. indiceResto++;
  289. }
  290.  
  291. private String ordenarJson()
  292. {
  293. String resultado = "";
  294. if (restoStartsWith('['))
  295. {
  296. resultado = ordenarArreglo ();
  297. }
  298. else if (restoStartsWith('{'))
  299. {
  300. resultado = ordenarObjeto ();
  301. }
  302. else if (restoStartsWith('\'') || restoStartsWith('"'))
  303. {
  304. resultado = hilera ();
  305. }
  306. else if (restoStartsWith("true"))
  307. {
  308. aceptar("true");
  309. resultado = "true";
  310. }
  311. else if (restoStartsWith("false"))
  312. {
  313. aceptar("false");
  314. resultado = "false";
  315. }
  316. else if (restoStartsWith("null"))
  317. {
  318. aceptar("null");
  319. resultado = "null";
  320. }
  321. else if (Character.isDigit(restoCharAt()))
  322. {
  323. resultado = numero();
  324. }
  325.  
  326. return resultado;
  327. }
  328.  
  329. private void aceptar (char valor)
  330. {
  331. if (! restoStartsWith(valor)) new RuntimeException("Se esperaba un '" + valor + "', pero aparecio un "+ new String(resto, indiceResto, resto.length-indiceResto));
  332. restoAvance();
  333. while (indiceResto < resto.length && restoStartsWith(' '))
  334. {
  335. restoAvance();
  336. }
  337. }
  338.  
  339. private void aceptar (String valor)
  340. {
  341. if (! restoStartsWith(valor)) new RuntimeException("Se esperaba un '" + valor + "', pero aparecio un "+ new String(resto, indiceResto, resto.length-indiceResto));
  342. for (int i = 0; i < valor.length(); i++)
  343. {
  344. restoAvance();
  345. }
  346. while (indiceResto < resto.length && restoStartsWith(' '))
  347. {
  348. restoAvance();
  349. }
  350. }
  351.  
  352. private String ordenarArreglo ()
  353. {
  354. aceptar('[');
  355. boolean salir = restoStartsWith(']');
  356. ArrayList<String> elementos = new ArrayList<String>();
  357. while ( ! salir)
  358. {
  359. if (restoStartsWith(',')) aceptar(',');
  360. elementos.add( ordenarJson() );
  361. salir = restoStartsWith(']');
  362. }
  363. aceptar(']');
  364.  
  365. String resultado = arregloToString(elementos);
  366.  
  367. return resultado;
  368. }
  369.  
  370. private String ordenarObjeto ()
  371. {
  372. aceptar('{');
  373. boolean salir = restoStartsWith('}');
  374. ArrayList<String> atributos = new ArrayList<String>();
  375. ArrayList<String> valores = new ArrayList<String>();
  376. while ( ! salir)
  377. {
  378. if (restoStartsWith(',')) aceptar(',');
  379. String atributo = atributo();
  380. aceptar (':');
  381. String valor = valor();
  382.  
  383. atributos.add( atributo );
  384. valores.add( valor );
  385. salir = restoStartsWith('}');
  386.  
  387. }
  388. aceptar('}');
  389.  
  390. String resultado = objetoToString(atributos, valores);
  391.  
  392. return resultado;
  393. }
  394.  
  395. private String hilera()
  396. {
  397. StringBuilder resultado = new StringBuilder();
  398. char comilla = restoCharAt();
  399. aceptar(comilla);
  400. resultado.append(comilla);
  401. while (restoCharAt() != comilla)
  402. {
  403. if (restoCharAt() == '\\' && restoCharAt() == comilla)
  404. {
  405. resultado.append(restoCharAt());
  406. resultado.append(restoCharAt());
  407. restoAvance();
  408. restoAvance();
  409. }
  410. else
  411. {
  412. resultado.append(restoCharAt());
  413. restoAvance();
  414. }
  415. }
  416. aceptar(comilla);
  417. resultado.append(comilla);
  418. return resultado.toString();
  419. }
  420.  
  421. private String atributo()
  422. {
  423. StringBuilder resultado = new StringBuilder();
  424. if (restoCharAt() == '"')
  425. {
  426. return hilera();
  427. }
  428. else
  429. {
  430. while (! restoStartsWith(' ') && ! restoStartsWith(':'))
  431. {
  432. resultado.append( restoCharAt() );
  433. restoAvance();
  434. }
  435. }
  436. return resultado.toString();
  437. }
  438.  
  439. private String numero()
  440. {
  441. StringBuilder resultado = new StringBuilder();
  442. if (restoCharAt() == '-')
  443. {
  444. aceptar('-');
  445. resultado.append('-');
  446. }
  447. while (Character.isDigit(restoCharAt()))
  448. {
  449. resultado.append( restoCharAt() );
  450. restoAvance();
  451. }
  452. if (restoCharAt() == '.')
  453. {
  454. aceptar('.');
  455. resultado.append('.');
  456. while (Character.isDigit(restoCharAt()))
  457. {
  458. resultado.append( restoCharAt() );
  459. restoAvance();
  460. }
  461. }
  462. if (restoCharAt() == 'E')
  463. {
  464. aceptar('E');
  465. resultado.append('E');
  466. }
  467. else if (restoCharAt() == 'e')
  468. {
  469. aceptar('e');
  470. resultado.append('e');
  471. }
  472. if (restoCharAt() == '+')
  473. {
  474. aceptar('+');
  475. resultado.append('+');
  476. while (Character.isDigit(restoCharAt()))
  477. {
  478. resultado.append( restoCharAt() );
  479. restoAvance();
  480. }
  481. }
  482. else if (restoCharAt() == '-')
  483. {
  484. aceptar('-');
  485. resultado.append('-');
  486. while (Character.isDigit(restoCharAt()))
  487. {
  488. resultado.append( restoCharAt() );
  489. restoAvance();
  490. }
  491. }
  492. else
  493. {
  494. while (Character.isDigit(restoCharAt()))
  495. {
  496. resultado.append( restoCharAt() );
  497. restoAvance();
  498. }
  499. }
  500. while (indiceResto < resto.length && restoStartsWith(' '))
  501. {
  502. restoAvance();
  503. }
  504. return resultado.toString();
  505. }
  506.  
  507. private String valor()
  508. {
  509. String resultado = ordenarJson();
  510. return resultado;
  511. }
  512.  
  513. private String arregloToString(ArrayList<String> arreglo)
  514. {
  515. StringBuilder resultado = new StringBuilder();
  516. tabsToString(resultado);
  517. resultado.append('[');
  518. tabs++;
  519. resultado.append('\n');
  520. Collections.sort( arreglo, comparador);
  521. for (int i = 0; i < arreglo.size(); i++)
  522. {
  523. if (resultado.length() > 1)
  524. {
  525. resultado.append(',');
  526. resultado.append('\n');
  527. }
  528. tabsToString(resultado);
  529. resultado.append( arreglo.get(i) );
  530. }
  531. tabs--;
  532. resultado.append('\n');
  533. tabsToString(resultado);
  534. resultado.append(']');
  535. return resultado.toString();
  536. }
  537. private int tabs = 0;
  538. private void tabsToString( StringBuilder resultado)
  539. {
  540. for( int j =0; j< tabs; j++)
  541. {
  542. resultado.append(' ');
  543. }
  544. }
  545. private String objetoToString(ArrayList<String> atributos, ArrayList<String> valores)
  546. {
  547. StringBuilder resultado = new StringBuilder();
  548.  
  549. tabsToString(resultado);
  550.  
  551. resultado.append('{');
  552. tabs++;
  553. resultado.append('\n');
  554. ArrayList<String> arreglo = new ArrayList<String>(atributos);
  555. Collections.sort( arreglo, comparador);
  556. for (int i = 0; i < arreglo.size(); i++)
  557. {
  558. if (resultado.length() > 1) resultado.append(", ");
  559. String atributo = arreglo.get(i);
  560. int indiceValor = atributos.indexOf(atributo);
  561. String valor = valores.get(indiceValor);
  562.  
  563. tabsToString(resultado);
  564.  
  565. resultado.append(atributo);
  566. resultado.append(':');
  567. resultado.append(valor);
  568. resultado.append('\n');
  569.  
  570. }
  571. resultado.append('\n');
  572. tabs--;
  573. tabsToString(resultado);
  574. resultado.append('}');
  575. return resultado.toString();
  576. }
  577.  
  578. class StringComparator implements Comparator<String>
  579. {
  580. public int compare(String obj1, String obj2) {
  581. if (obj1 == obj2) {
  582. return 0;
  583. }
  584. if (obj1 == null) {
  585. return -1;
  586. }
  587. if (obj2 == null) {
  588. return 1;
  589. }
  590. return obj1.compareTo(obj2);
  591. }
  592. }
  593. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement