Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.fontolan.projetos.classes;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.text.DecimalFormat;
- import java.text.SimpleDateFormat;
- import java.util.Calendar;
- import java.util.Date;
- import com.datastax.driver.core.Cluster;
- import com.datastax.driver.core.Session;
- /**
- *
- * @author Fontolan
- */
- public class ConexaoUniversal {
- private Informacoes informacoes;
- private Connection connection;
- private Statement statement;
- private Cluster cluster;
- private Session session;
- private String url_conexao;
- private String driver_jdbc;
- private String log = "";
- public ConexaoUniversal(Informacoes info) {
- switch (info.getBancoDados()) {
- case "MySQL":
- this.setUrl_conexao("jdbc:mysql://" + info.getUrl() + ":" + info.getPorta() + "/" + info.getBase());
- this.setDriver_jdbc("com.mysql.jdbc.Driver");
- break;
- case "PostgreSQL":
- this.setUrl_conexao("jdbc:postgresql://" + info.getUrl() + ":" + info.getPorta() + "/" + info.getBase());
- this.setDriver_jdbc("org.postgresql.Driver");
- break;
- case "Cassandra":
- cluster = Cluster.builder().addContactPoint(info.getUrl()).build();
- session = cluster.connect(info.getBase());
- break;
- }
- this.informacoes = info;
- this.gerarLog("Iniciando BenchMarking para " + info.getBancoDados() + "...");
- }
- //Conexão com o Banco de Dados
- public boolean connectMain() {
- boolean ventor = false;
- switch (this.informacoes.getBancoDados()) {
- case "MySQL":
- ventor = this.connectMySQL();
- break;
- case "PostgreSQL":
- ventor = this.connectPostgreSQL();
- break;
- case "Cassandra":
- ventor = this.connectCassandra();
- break;
- case "MongoDB":
- break;
- }
- return ventor;
- }
- private boolean connectMySQL() {
- boolean ventor = false;
- try {
- Class.forName(this.getDriver_jdbc());
- this.setConnection(DriverManager.getConnection(getUrl_conexao(), this.informacoes.getUsuario(), this.informacoes.getSenha()));
- this.setStatement(this.getConnection().createStatement());
- this.gerarLog("Conexão estabelecida com sucesso!");
- ventor = true;
- } catch (ClassNotFoundException e) {
- this.gerarLog("Driver de conexão não foi encontrado!");
- } catch (SQLException sqle) {
- int vendorCode = sqle.getErrorCode();
- if (vendorCode == 1049) {
- this.gerarLog("Não foi possivel encontrar a base especificada!");
- } else if (vendorCode == 1044) {
- this.gerarLog("Usuario invalido.");
- } else if (vendorCode == 1045) {
- this.gerarLog("Senha incorreta!");
- } else {
- this.gerarLog(sqle.getMessage());
- }
- } catch (Exception e) {
- this.gerarLog("Erro ao estabelecer a conexão.");
- System.err.println(e);
- e.printStackTrace();
- }
- return ventor;
- }
- private boolean connectPostgreSQL() {
- boolean ventor = false;
- try {
- Class.forName(this.getDriver_jdbc());
- this.setConnection(DriverManager.getConnection(getUrl_conexao(), this.informacoes.getUsuario(), this.informacoes.getSenha()));
- this.setStatement(this.getConnection().createStatement());
- this.gerarLog("Conexão estabelecida com sucesso!");
- ventor = true;
- } catch (ClassNotFoundException e) {
- this.gerarLog("Driver de conexão não foi encontrado!");
- } catch (SQLException sqle) {
- int vendorCode = sqle.getErrorCode();
- if (vendorCode == 1049) {
- this.gerarLog("Não foi possivel encontrar a base especificada!");
- } else if (vendorCode == 1044) {
- this.gerarLog("Usuario invalido.");
- } else if (vendorCode == 1045) {
- this.gerarLog("Senha incorreta!");
- } else {
- this.gerarLog(sqle.getMessage());
- }
- } catch (Exception e) {
- this.gerarLog("Erro ao estabelecer a conexão.");
- System.err.println(e);
- e.printStackTrace();
- }
- return ventor;
- }
- private boolean connectCassandra() {
- boolean ventor = false;
- try {
- cluster = Cluster.builder().addContactPoint(this.informacoes.getUrl()).build();
- session = cluster.connect(this.informacoes.getBase());
- ventor = true;
- } catch (Exception exp) {
- ventor = false;
- }
- return ventor;
- }
- public String disconect() {
- String log = "";
- try {
- this.gerarLog("Finalizando Conexão.");
- this.getConnection().close();
- this.gerarLog("Conexão finalizada com sucesso!");
- } catch (SQLException ex) {
- this.gerarLog("Erro ao tentar finalizar a conexão.");
- }
- return log;
- }
- public void selectData(int repiticoes) {
- try {
- long timeInicial;
- long timeFinal;
- long timeTotal = 0;
- this.gerarLog("--- Select ---");
- timeInicial = System.nanoTime();
- for (int i = 1; i <= repiticoes; i++) {
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("SELECT * FROM usertable ");
- stringBuilder.append("WHERE YCSB_KEY = '");
- stringBuilder.append("user");
- stringBuilder.append(Utils.randomInteger(repiticoes));
- stringBuilder.append("';");
- String finalString = stringBuilder.toString();
- long timeForInicial = 0;
- long timeForFinal = 0;
- if (this.informacoes.getBancoDados().equals("Cassandra")) {
- timeForInicial = System.nanoTime();
- this.getSession().execute(finalString);
- timeForFinal = System.nanoTime();
- } else {
- timeForInicial = System.nanoTime();
- this.getStatement().executeQuery(finalString);
- timeForFinal = System.nanoTime();
- }
- timeTotal += (timeForFinal - timeForInicial);
- }
- timeFinal = System.nanoTime();
- double seconds = (double) (timeFinal - timeInicial) / 1000000000;
- double secondsTotal = (double) timeTotal / 1000000000;
- double perOperation = (double) secondsTotal / (repiticoes * 1.0);
- double perSecond = (double) ((repiticoes * 1.0)) / (timeTotal / 1000000000.0);
- this.gerarLog("Quantidade de registros: " + (repiticoes));
- this.gerarLog("Tempo total (seg): " + new DecimalFormat("#.######").format(seconds));
- this.gerarLog("Tempo somente das transações (seg): " + new DecimalFormat("#.######").format(secondsTotal));
- this.gerarLog("Tempo por transação (seg): " + new DecimalFormat("#.###########").format(perOperation));
- this.gerarLog("Transações por seg: " + new DecimalFormat("#.###########").format(perSecond));
- this.gerarLog("----- -----");
- } catch (SQLException ex) {
- this.gerarLog("Erro ao tentar executar o SQL.");
- ex.printStackTrace();
- }
- }
- public void insertData(int repiticoes) {
- Connection conn = this.getConnection();
- PreparedStatement pst = null;
- try {
- long timeInicial;
- long timeFinal;
- long timeTotal = 0;
- this.gerarLog("--- Insert ---");
- timeInicial = System.nanoTime();
- for (int i = 1; i <= repiticoes; i++) {
- String ycsb_key = "user" + i;
- String field0 = Utils.randomString();
- String field1 = Utils.randomString();
- String field2 = Utils.randomString();
- String field3 = Utils.randomString();
- String field4 = Utils.randomString();
- String field5 = Utils.randomString();
- String field6 = Utils.randomString();
- String field7 = Utils.randomString();
- String field8 = Utils.randomString();
- String field9 = Utils.randomString();
- String stm = "INSERT INTO usertable VALUES(?, ?,?,?,?,?,?,?,?,?,?)";
- pst = conn.prepareStatement(stm);
- pst.setString(1, ycsb_key);
- pst.setString(2, field0);
- pst.setString(3, field1);
- pst.setString(4, field2);
- pst.setString(5, field3);
- pst.setString(6, field4);
- pst.setString(7, field5);
- pst.setString(8, field6);
- pst.setString(9, field7);
- pst.setString(10, field8);
- pst.setString(11, field9);
- long timeForInicial = 0;
- long timeForFinal = 0;
- if (this.informacoes.getBancoDados().equals("Cassandra")) {
- timeForInicial = System.nanoTime();
- getSession().execute(pst.toString());
- timeForFinal = System.nanoTime();
- } else {
- timeForInicial = System.nanoTime();
- pst.executeUpdate();
- timeForFinal = System.nanoTime();
- }
- timeTotal += timeForFinal - timeForInicial;
- }
- timeFinal = System.nanoTime();
- double seconds = (double) (timeFinal - timeInicial) / 1000000000;
- double secondsTotal = (double) timeTotal / 1000000000;
- double perOperation = (double) secondsTotal / (repiticoes * 1.0);
- double perSecond = (double) ((repiticoes * 1.0)) / (timeTotal / 1000000000.0);
- this.gerarLog("Quantidade de registros: " + (repiticoes));
- this.gerarLog("Tempo total (seg): " + new DecimalFormat("#.######").format(seconds));
- this.gerarLog("Tempo somente das transações (seg): " + new DecimalFormat("#.######").format(secondsTotal));
- this.gerarLog("Tempo por transação (seg): " + new DecimalFormat("#.###########").format(perOperation));
- this.gerarLog("Transações por seg: " + new DecimalFormat("#.###########").format(perSecond));
- this.gerarLog("----- -----");
- } catch (SQLException ex) {
- this.gerarLog("Erro ao tentar executar o SQL.");
- }
- }
- public void limparTabela() {
- try {
- long timeTotal = 0;
- StringBuilder stringBuilder = new StringBuilder();
- stringBuilder.append("TRUNCATE usertable;");
- String finalString = stringBuilder.toString();
- long timeForInicial = System.nanoTime();
- this.getStatement().execute(finalString);
- long timeForFinal = System.nanoTime();
- timeTotal = (timeForFinal - timeForInicial);
- double secondsTotal = (double) timeTotal / 1000000000;
- this.gerarLog("Tabela limpa com sucesso!");
- this.gerarLog("Tempo de execução (seg): " + new DecimalFormat("#.######").format(secondsTotal));
- } catch (SQLException ex) {
- this.gerarLog("Erro ao tentar executar o SQL.");
- ex.printStackTrace();
- }
- }
- public String getLog() {
- return this.log;
- }
- public String resetLog() {
- this.log = "";
- return this.log;
- }
- private void gerarLog(String text) {
- this.log += this.gerarHora() + " - " + text + "\n";
- }
- private String gerarHora() {
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
- Date hora = Calendar.getInstance().getTime(); // Ou qualquer outra forma que tem
- String dataFormatada = sdf.format(hora);
- return dataFormatada;
- }
- // GETs AND SETs
- public Connection getConnection() {
- return connection;
- }
- public void setConnection(Connection connection) {
- this.connection = connection;
- }
- public Statement getStatement() {
- return statement;
- }
- public void setStatement(Statement statement) {
- this.statement = statement;
- }
- public Cluster getCluster() {
- return cluster;
- }
- public void setCluster(Cluster cluster) {
- this.cluster = cluster;
- }
- public Session getSession() {
- return session;
- }
- public void setSession(Session session) {
- this.session = session;
- }
- public String getUrl_conexao() {
- return url_conexao;
- }
- public void setUrl_conexao(String url_conexao) {
- this.url_conexao = url_conexao;
- }
- public String getDriver_jdbc() {
- return driver_jdbc;
- }
- public void setDriver_jdbc(String driver_jdbc) {
- this.driver_jdbc = driver_jdbc;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement