Advertisement
Guest User

Conexao Universal

a guest
May 27th, 2016
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.42 KB | None | 0 0
  1. package com.fontolan.projetos.classes;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.SQLException;
  7. import java.sql.Statement;
  8. import java.text.DecimalFormat;
  9. import java.text.SimpleDateFormat;
  10. import java.util.Calendar;
  11. import java.util.Date;
  12. import com.datastax.driver.core.Cluster;
  13. import com.datastax.driver.core.Session;
  14.  
  15. /**
  16.  *
  17.  * @author Fontolan
  18.  */
  19. public class ConexaoUniversal {
  20.     private Informacoes informacoes;
  21.     private Connection connection;
  22.     private Statement statement;
  23.     private Cluster cluster;
  24.     private Session session;
  25.     private String url_conexao;
  26.     private String driver_jdbc;
  27.     private String log = "";
  28.  
  29.     public ConexaoUniversal(Informacoes info) {
  30.         switch (info.getBancoDados()) {
  31.             case "MySQL":
  32.                 this.setUrl_conexao("jdbc:mysql://" + info.getUrl() + ":" + info.getPorta() + "/" + info.getBase());
  33.                 this.setDriver_jdbc("com.mysql.jdbc.Driver");
  34.                 break;
  35.             case "PostgreSQL":
  36.                 this.setUrl_conexao("jdbc:postgresql://" + info.getUrl() + ":" + info.getPorta() + "/" + info.getBase());
  37.                 this.setDriver_jdbc("org.postgresql.Driver");
  38.                 break;
  39.             case "Cassandra":
  40.                 cluster = Cluster.builder().addContactPoint(info.getUrl()).build();
  41.                 session = cluster.connect(info.getBase());
  42.                 break;
  43.         }
  44.         this.informacoes = info;
  45.  
  46.         this.gerarLog("Iniciando BenchMarking para " + info.getBancoDados() + "...");
  47.     }
  48.  
  49.     //Conexão com o Banco de Dados
  50.     public boolean connectMain() {
  51.         boolean ventor = false;
  52.         switch (this.informacoes.getBancoDados()) {
  53.             case "MySQL":
  54.                 ventor = this.connectMySQL();
  55.                 break;
  56.             case "PostgreSQL":
  57.                 ventor = this.connectPostgreSQL();
  58.                 break;
  59.             case "Cassandra":
  60.                 ventor = this.connectCassandra();
  61.                 break;
  62.             case "MongoDB":
  63.                 break;
  64.         }
  65.  
  66.         return ventor;
  67.     }
  68.  
  69.     private boolean connectMySQL() {
  70.         boolean ventor = false;
  71.         try {
  72.             Class.forName(this.getDriver_jdbc());
  73.             this.setConnection(DriverManager.getConnection(getUrl_conexao(), this.informacoes.getUsuario(), this.informacoes.getSenha()));
  74.             this.setStatement(this.getConnection().createStatement());
  75.             this.gerarLog("Conexão estabelecida com sucesso!");
  76.             ventor = true;
  77.         } catch (ClassNotFoundException e) {
  78.             this.gerarLog("Driver de conexão não foi encontrado!");
  79.         } catch (SQLException sqle) {
  80.             int vendorCode = sqle.getErrorCode();
  81.             if (vendorCode == 1049) {
  82.                 this.gerarLog("Não foi possivel encontrar a base especificada!");
  83.             } else if (vendorCode == 1044) {
  84.                 this.gerarLog("Usuario invalido.");
  85.             } else if (vendorCode == 1045) {
  86.                 this.gerarLog("Senha incorreta!");
  87.             } else {
  88.                 this.gerarLog(sqle.getMessage());
  89.             }
  90.         } catch (Exception e) {
  91.             this.gerarLog("Erro ao estabelecer a conexão.");
  92.             System.err.println(e);
  93.             e.printStackTrace();
  94.         }
  95.  
  96.         return ventor;
  97.     }
  98.  
  99.     private boolean connectPostgreSQL() {
  100.         boolean ventor = false;
  101.         try {
  102.             Class.forName(this.getDriver_jdbc());
  103.             this.setConnection(DriverManager.getConnection(getUrl_conexao(), this.informacoes.getUsuario(), this.informacoes.getSenha()));
  104.             this.setStatement(this.getConnection().createStatement());
  105.             this.gerarLog("Conexão estabelecida com sucesso!");
  106.             ventor = true;
  107.         } catch (ClassNotFoundException e) {
  108.             this.gerarLog("Driver de conexão não foi encontrado!");
  109.         } catch (SQLException sqle) {
  110.             int vendorCode = sqle.getErrorCode();
  111.             if (vendorCode == 1049) {
  112.                 this.gerarLog("Não foi possivel encontrar a base especificada!");
  113.             } else if (vendorCode == 1044) {
  114.                 this.gerarLog("Usuario invalido.");
  115.             } else if (vendorCode == 1045) {
  116.                 this.gerarLog("Senha incorreta!");
  117.             } else {
  118.                 this.gerarLog(sqle.getMessage());
  119.             }
  120.         } catch (Exception e) {
  121.             this.gerarLog("Erro ao estabelecer a conexão.");
  122.             System.err.println(e);
  123.             e.printStackTrace();
  124.         }
  125.  
  126.         return ventor;
  127.     }
  128.  
  129.     private boolean connectCassandra() {
  130.         boolean ventor = false;
  131.         try {
  132.             cluster = Cluster.builder().addContactPoint(this.informacoes.getUrl()).build();
  133.             session = cluster.connect(this.informacoes.getBase());
  134.             ventor = true;
  135.         } catch (Exception exp) {
  136.             ventor = false;
  137.         }
  138.  
  139.         return ventor;
  140.     }
  141.  
  142.     public String disconect() {
  143.         String log = "";
  144.         try {
  145.             this.gerarLog("Finalizando Conexão.");
  146.             this.getConnection().close();
  147.             this.gerarLog("Conexão finalizada com sucesso!");
  148.         } catch (SQLException ex) {
  149.             this.gerarLog("Erro ao tentar finalizar a conexão.");
  150.         }
  151.         return log;
  152.     }
  153.  
  154.     public void selectData(int repiticoes) {
  155.         try {
  156.             long timeInicial;
  157.             long timeFinal;
  158.             long timeTotal = 0;
  159.  
  160.             this.gerarLog("--- Select ---");
  161.  
  162.             timeInicial = System.nanoTime();
  163.             for (int i = 1; i <= repiticoes; i++) {
  164.                 StringBuilder stringBuilder = new StringBuilder();
  165.  
  166.                 stringBuilder.append("SELECT * FROM usertable ");
  167.                 stringBuilder.append("WHERE YCSB_KEY = '");
  168.                 stringBuilder.append("user");
  169.                 stringBuilder.append(Utils.randomInteger(repiticoes));
  170.                 stringBuilder.append("';");
  171.  
  172.                 String finalString = stringBuilder.toString();
  173.                 long timeForInicial = 0;
  174.                 long timeForFinal = 0;
  175.                 if (this.informacoes.getBancoDados().equals("Cassandra")) {
  176.                     timeForInicial = System.nanoTime();
  177.                     this.getSession().execute(finalString);
  178.                     timeForFinal = System.nanoTime();
  179.                 } else {
  180.                     timeForInicial = System.nanoTime();
  181.                     this.getStatement().executeQuery(finalString);
  182.                     timeForFinal = System.nanoTime();
  183.                 }
  184.                 timeTotal += (timeForFinal - timeForInicial);
  185.             }
  186.             timeFinal = System.nanoTime();
  187.  
  188.             double seconds = (double) (timeFinal - timeInicial) / 1000000000;
  189.             double secondsTotal = (double) timeTotal / 1000000000;
  190.             double perOperation = (double) secondsTotal / (repiticoes * 1.0);
  191.             double perSecond = (double) ((repiticoes * 1.0)) / (timeTotal / 1000000000.0);
  192.  
  193.             this.gerarLog("Quantidade de registros: " + (repiticoes));
  194.             this.gerarLog("Tempo total (seg): " + new DecimalFormat("#.######").format(seconds));
  195.             this.gerarLog("Tempo somente das transações (seg): " + new DecimalFormat("#.######").format(secondsTotal));
  196.             this.gerarLog("Tempo por transação (seg): " + new DecimalFormat("#.###########").format(perOperation));
  197.             this.gerarLog("Transações por seg: " + new DecimalFormat("#.###########").format(perSecond));
  198.             this.gerarLog("-----    -----");
  199.         } catch (SQLException ex) {
  200.             this.gerarLog("Erro ao tentar executar o SQL.");
  201.             ex.printStackTrace();
  202.         }
  203.     }
  204.  
  205.     public void insertData(int repiticoes) {
  206.         Connection conn = this.getConnection();
  207.         PreparedStatement pst = null;
  208.         try {
  209.             long timeInicial;
  210.             long timeFinal;
  211.             long timeTotal = 0;
  212.  
  213.             this.gerarLog("--- Insert ---");
  214.  
  215.             timeInicial = System.nanoTime();
  216.             for (int i = 1; i <= repiticoes; i++) {
  217.                 String ycsb_key = "user" + i;
  218.                 String field0 = Utils.randomString();
  219.                 String field1 = Utils.randomString();
  220.                 String field2 = Utils.randomString();
  221.                 String field3 = Utils.randomString();
  222.                 String field4 = Utils.randomString();
  223.                 String field5 = Utils.randomString();
  224.                 String field6 = Utils.randomString();
  225.                 String field7 = Utils.randomString();
  226.                 String field8 = Utils.randomString();
  227.                 String field9 = Utils.randomString();
  228.  
  229.                 String stm = "INSERT INTO usertable VALUES(?, ?,?,?,?,?,?,?,?,?,?)";
  230.  
  231.                 pst = conn.prepareStatement(stm);
  232.                 pst.setString(1, ycsb_key);
  233.                 pst.setString(2, field0);
  234.                 pst.setString(3, field1);
  235.                 pst.setString(4, field2);
  236.                 pst.setString(5, field3);
  237.                 pst.setString(6, field4);
  238.                 pst.setString(7, field5);
  239.                 pst.setString(8, field6);
  240.                 pst.setString(9, field7);
  241.                 pst.setString(10, field8);
  242.                 pst.setString(11, field9);
  243.  
  244.                 long timeForInicial = 0;
  245.                 long timeForFinal = 0;
  246.                 if (this.informacoes.getBancoDados().equals("Cassandra")) {
  247.                     timeForInicial = System.nanoTime();
  248.                     getSession().execute(pst.toString());
  249.                     timeForFinal = System.nanoTime();
  250.                 } else {
  251.                     timeForInicial = System.nanoTime();
  252.                     pst.executeUpdate();
  253.                     timeForFinal = System.nanoTime();
  254.                 }
  255.  
  256.                 timeTotal += timeForFinal - timeForInicial;
  257.             }
  258.             timeFinal = System.nanoTime();
  259.  
  260.             double seconds = (double) (timeFinal - timeInicial) / 1000000000;
  261.             double secondsTotal = (double) timeTotal / 1000000000;
  262.             double perOperation = (double) secondsTotal / (repiticoes * 1.0);
  263.             double perSecond = (double) ((repiticoes * 1.0)) / (timeTotal / 1000000000.0);
  264.  
  265.             this.gerarLog("Quantidade de registros: " + (repiticoes));
  266.             this.gerarLog("Tempo total (seg): " + new DecimalFormat("#.######").format(seconds));
  267.             this.gerarLog("Tempo somente das transações (seg): " + new DecimalFormat("#.######").format(secondsTotal));
  268.             this.gerarLog("Tempo por transação (seg): " + new DecimalFormat("#.###########").format(perOperation));
  269.             this.gerarLog("Transações por seg: " + new DecimalFormat("#.###########").format(perSecond));
  270.             this.gerarLog("-----    -----");
  271.  
  272.         } catch (SQLException ex) {
  273.             this.gerarLog("Erro ao tentar executar o SQL.");
  274.         }
  275.     }
  276.  
  277.     public void limparTabela() {
  278.         try {
  279.             long timeTotal = 0;
  280.  
  281.             StringBuilder stringBuilder = new StringBuilder();
  282.             stringBuilder.append("TRUNCATE usertable;");
  283.             String finalString = stringBuilder.toString();
  284.  
  285.             long timeForInicial = System.nanoTime();
  286.             this.getStatement().execute(finalString);
  287.             long timeForFinal = System.nanoTime();
  288.             timeTotal = (timeForFinal - timeForInicial);
  289.  
  290.             double secondsTotal = (double) timeTotal / 1000000000;
  291.             this.gerarLog("Tabela limpa com sucesso!");
  292.             this.gerarLog("Tempo de execução (seg): " + new DecimalFormat("#.######").format(secondsTotal));
  293.         } catch (SQLException ex) {
  294.             this.gerarLog("Erro ao tentar executar o SQL.");
  295.             ex.printStackTrace();
  296.         }
  297.     }
  298.  
  299.     public String getLog() {
  300.         return this.log;
  301.     }
  302.  
  303.     public String resetLog() {
  304.         this.log = "";
  305.         return this.log;
  306.     }
  307.  
  308.     private void gerarLog(String text) {
  309.         this.log += this.gerarHora() + " - " + text + "\n";
  310.     }
  311.  
  312.     private String gerarHora() {
  313.         SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
  314.         Date hora = Calendar.getInstance().getTime(); // Ou qualquer outra forma que tem
  315.         String dataFormatada = sdf.format(hora);
  316.  
  317.         return dataFormatada;
  318.     }
  319.  
  320.     // GETs AND SETs
  321.     public Connection getConnection() {
  322.         return connection;
  323.     }
  324.  
  325.     public void setConnection(Connection connection) {
  326.         this.connection = connection;
  327.     }
  328.  
  329.     public Statement getStatement() {
  330.         return statement;
  331.     }
  332.  
  333.     public void setStatement(Statement statement) {
  334.         this.statement = statement;
  335.     }
  336.  
  337.     public Cluster getCluster() {
  338.         return cluster;
  339.     }
  340.  
  341.     public void setCluster(Cluster cluster) {
  342.         this.cluster = cluster;
  343.     }
  344.  
  345.     public Session getSession() {
  346.         return session;
  347.     }
  348.  
  349.     public void setSession(Session session) {
  350.         this.session = session;
  351.     }
  352.  
  353.     public String getUrl_conexao() {
  354.         return url_conexao;
  355.     }
  356.  
  357.     public void setUrl_conexao(String url_conexao) {
  358.         this.url_conexao = url_conexao;
  359.     }
  360.  
  361.     public String getDriver_jdbc() {
  362.         return driver_jdbc;
  363.     }
  364.  
  365.     public void setDriver_jdbc(String driver_jdbc) {
  366.         this.driver_jdbc = driver_jdbc;
  367.     }
  368. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement