Advertisement
Guest User

Untitled

a guest
May 26th, 2017
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.70 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.google.gson.Gson;
  28. import com.google.gson.GsonBuilder;
  29. import com.google.gson.JsonObject;
  30. import com.google.gson.JsonParser;
  31. import com.ncubo.configuracion.Enviroment;
  32. import com.ts.configuracion.Api2ManagerREST;
  33. import com.ts.db.Log;
  34. import com.ts.db.Recuperados;
  35. import com.ts.libraries.Browser;
  36. import com.ts.libraries.Canal.Tipo;
  37. import com.ts.libraries.Correo;
  38. import com.ts.libraries.Firma;
  39. import com.ts.libraries.Hexadecimal;
  40. import com.ts.libraries.IPv4;
  41. import com.ts.libraries.Sistema;
  42. import com.ts.main.Procesador;
  43. import com.ts.procesadores.ProcesadorDeComandos;
  44.  
  45. public class GeneradorDeLogDeComandos
  46. {
  47. private final static Logger logger = Logger.getLogger(GeneradorDeLogDeComandos.class);
  48. private static DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
  49. private static Connection conexion;
  50. private static final String JDBC_CONNECTOR = "jdbc:mysql://bd.qa14.ncubo.com:3306/baseline2";
  51. private static final String USER_BD = "logwriter";
  52. private static final String PASS_BD = "logwriter";
  53. private static final String NOMBRE_DE_LA_BD = "baseline2";
  54.  
  55. public static void main(String[] args) throws IOException
  56. {
  57. Properties props = new Properties();
  58. InputStream configStream = GeneradorDeLogDeComandos.class.getResourceAsStream( "/log4jtestcases.properties");
  59. props.load(configStream);
  60. configStream.close();
  61. LogManager.resetConfiguration();
  62. PropertyConfigurator.configure(props);
  63. String compania = "",comando = "",respuestaDelComandoEjecutado= "" ;
  64.  
  65. long time_start, time_end;
  66. time_start = System.currentTimeMillis();
  67.  
  68. String comandoConLaSalidaGrande = "";
  69. int longitudDeLaSalidaMasGrande = 0;
  70.  
  71. Ordenar ordenador = new Ordenar();
  72.  
  73. Statement stmt = null;
  74. try
  75. {
  76. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/testcasesaplication.xml");
  77. Comercios comerciosController = new Comercios();
  78. Enviroment env = (Enviroment)applicationContext.getBean("enviroment") ;
  79. comerciosController.setEnviroment( env );
  80. Class.forName("com.mysql.jdbc.Driver");
  81.  
  82. conexion = DriverManager.getConnection(JDBC_CONNECTOR, USER_BD, PASS_BD);
  83. stmt = conexion.createStatement();
  84. ResultSet rs = stmt.executeQuery("SHOW TABLES;");
  85.  
  86. Api2ManagerREST api2 = new Api2ManagerREST("");
  87.  
  88. String actualCompania = "";
  89. String apartirDe ="";//"";
  90.  
  91. Procesador.estoyEnDesarrolloNoQuieroGuardarEsteDia(26, 5, 2017);
  92. while (rs.next())
  93. {
  94. compania = rs.getString("Tables_in_"+NOMBRE_DE_LA_BD);
  95.  
  96. if(! apartirDe.isEmpty() && ! compania.equals(apartirDe) )
  97. {
  98. continue;
  99. }
  100. else if( compania.equals(apartirDe) )
  101. {
  102. apartirDe ="";
  103. }
  104.  
  105. Firma firmaActual = new Firma(new Browser(),new IPv4(), Sistema.fechaHoraActual(), Tipo.CONSOLA, new Correo("no-user@ncubo.com"), new Hexadecimal("0000"));
  106. if( ! actualCompania.equals( compania))
  107. {
  108. actualCompania =compania;
  109. api2.setCompania(compania);
  110. }
  111. api2.cargarInformacionDeContexto( firmaActual);
  112.  
  113. if( compania.endsWith("_r") || compania.startsWith("c_") || compania.equals("pagos") || compania.startsWith("comerciov_"))
  114. {
  115. continue;
  116. }
  117.  
  118. props = new Properties();
  119. configStream = GeneradorDeLogDeComandos.class.getResourceAsStream( "/log4jtestcases.properties");
  120. props.load(configStream);
  121. props.setProperty("log4j.appender.tc.File", "G:/GeneradorDeComandos/"+compania+"bb.log");
  122. props.setProperty("log4j.appender.tc", "org.apache.log4j.RollingFileAppender");
  123. props.setProperty("log4j.appender.tc.encoding", "UTF-8");
  124. props.setProperty("log4j.appender.tc.MaxFileSize", "200MB");
  125.  
  126. configStream.close();
  127. LogManager.resetConfiguration();
  128. PropertyConfigurator.configure(props);
  129.  
  130. Statement comandosStmt = conexion.createStatement();
  131. ResultSet comandosDeCompania = comandosStmt.executeQuery("SELECT id, FechaHora, Comando, tiene_recuperado FROM "+compania+" order by id ASC;");
  132. Statement comandosStmt2 = conexion.createStatement();
  133. ResultSet queryParaTraerElTotalDeComandosEnLaCompannia = comandosStmt2.executeQuery("SELECT count(*) as cantidad FROM "+compania+";");
  134. queryParaTraerElTotalDeComandosEnLaCompannia.next();
  135. int cantidadTotalDeComandosDeLaCompannia = queryParaTraerElTotalDeComandosEnLaCompannia.getInt("cantidad");
  136. comandosStmt2.close();
  137. queryParaTraerElTotalDeComandosEnLaCompannia.close();
  138.  
  139. final Connection conexion2 = DriverManager.getConnection(env.getConnectionMySQL(), env.getUsuarioMySQL(), env.getPasswordMySQL());
  140. Statement stmttrun = conexion2.createStatement();
  141. stmttrun.executeUpdate("DROP TABLE IF EXISTS "+compania+" cascade;");
  142. stmttrun.executeUpdate("DROP TABLE IF EXISTS "+compania+"_r"+" cascade;");
  143. stmttrun.close();
  144. conexion2.close();
  145.  
  146. System.out.println("Empieza " +compania);
  147. int cantidadDeComandosEjecutados = 0;
  148. while (comandosDeCompania.next())
  149. {
  150. comando = comandosDeCompania.getString("Comando").trim();
  151.  
  152. cargarUnProcesadorAlHiloActual(compania, comerciosController);
  153.  
  154. if(comando.startsWith("//"))continue; //TODO:ESTO ES TEMPORAL PARA QUE NO SE EJECUTEN LOS COMANDOS QUE TIENEN COMENTARIOS
  155. Date fechaHora = comandosDeCompania.getDate("FechaHora");
  156. String fechaHoraFormat = DATE_FORMAT.format(fechaHora);
  157.  
  158. String comandoGenerado = api2.newCommand().add(comando).getCommandSustituido(fechaHoraFormat);
  159. try
  160. {
  161. boolean tieneRecuperado = comandosDeCompania.getInt("tiene_recuperado") == 1;
  162. if(tieneRecuperado)
  163. {
  164. Log.abrirConexion(JDBC_CONNECTOR, USER_BD, PASS_BD);
  165. Log log = new Log(conexion, compania);
  166. Recuperados variablesDeContextoDelHistorial = log.variablesDeContextoALaTabla(compania, comandosDeCompania);
  167. ProcesadorDeComandos.miProcesador().tablaDeSimbolos.guardarRecuperados(variablesDeContextoDelHistorial.objetosDeTipoPull(), false);
  168. }
  169. respuestaDelComandoEjecutado = comerciosController.atenderUnComercios(comandoGenerado, compania);
  170. }
  171. catch(RuntimeException e)
  172. {
  173. System.err.println(compania+" | "+comando);
  174. respuestaDelComandoEjecutado = e.getMessage();
  175. e.printStackTrace();
  176. }
  177. cantidadDeComandosEjecutados++;
  178. if (respuestaDelComandoEjecutado.length() > longitudDeLaSalidaMasGrande)
  179. {
  180. comandoConLaSalidaGrande = comando;
  181. longitudDeLaSalidaMasGrande = respuestaDelComandoEjecutado.length();
  182. }
  183.  
  184.  
  185. String jsonString = ordenador.ordenarJson(respuestaDelComandoEjecutado) ;
  186.  
  187. logger.debug ("id->"+comandosDeCompania.getInt("Id"));
  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. if( arreglo.size() == 0)
  517. {
  518. resultado.append('[');
  519. resultado.append(']');
  520. return resultado.toString();
  521. }
  522.  
  523. tabsToString(resultado);
  524. resultado.append('[');
  525. tabs++;
  526. resultado.append('\n');
  527. Collections.sort( arreglo, comparador);
  528. for (int i = 0; i < arreglo.size(); i++)
  529. {
  530. tabsToString(resultado);
  531. if (i > 0)
  532. {
  533. resultado.append(',');
  534. resultado.append('\n');
  535. }
  536. resultado.append( arreglo.get(i) );
  537. }
  538. resultado.append('\n');
  539. tabsToString(resultado);
  540. resultado.append(']');
  541. tabs--;
  542. return resultado.toString();
  543. }
  544. private int tabs = 0;
  545. private void tabsToString( StringBuilder resultado)
  546. {
  547. for( int j =0; j< tabs; j++)
  548. {
  549. resultado.append(' ');
  550. }
  551. }
  552. private String objetoToString(ArrayList<String> atributos, ArrayList<String> valores)
  553. {
  554. StringBuilder resultado = new StringBuilder();
  555.  
  556. tabsToString(resultado);
  557.  
  558. resultado.append('{');
  559. tabs++;
  560. resultado.append('\n');
  561. ArrayList<String> arreglo = new ArrayList<String>(atributos);
  562. Collections.sort( arreglo, comparador);
  563. for (int i = 0; i < arreglo.size(); i++)
  564. {
  565. tabsToString(resultado);
  566.  
  567. if ( i > 0) resultado.append(", ");
  568. String atributo = arreglo.get(i);
  569. int indiceValor = atributos.indexOf(atributo);
  570. String valor = valores.get(indiceValor);
  571.  
  572. resultado.append(atributo);
  573. resultado.append(':');
  574. resultado.append(valor);
  575. resultado.append('\n');
  576.  
  577. }
  578. resultado.append('\n');
  579. tabsToString(resultado);
  580. resultado.append('}');
  581. tabs--;
  582. return resultado.toString();
  583. }
  584.  
  585. class StringComparator implements Comparator<String>
  586. {
  587. public int compare(String obj1, String obj2) {
  588. if (obj1 == obj2) {
  589. return 0;
  590. }
  591. if (obj1 == null) {
  592. return -1;
  593. }
  594. if (obj2 == null) {
  595. return 1;
  596. }
  597. return obj1.compareTo(obj2);
  598. }
  599. }
  600. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement