@Override
 public void getValidationQuery() {
   HikariDataSource dataSource = createDataSource(0, 4);
   dataSource.setConnectionTestQuery("SELECT FROM FOO");
   assertThat(new HikariDataSourcePoolMetadata(dataSource).getValidationQuery())
       .isEqualTo("SELECT FROM FOO");
 }
 private HikariDataSource createDataSource(int minSize, int maxSize) {
   HikariDataSource dataSource =
       (HikariDataSource) initializeBuilder().type(HikariDataSource.class).build();
   dataSource.setMinimumIdle(minSize);
   dataSource.setMaximumPoolSize(maxSize);
   return dataSource;
 }
  // @Test
  public void testConnectionCloseBlocking() throws SQLException {
    HikariConfig config = new HikariConfig();
    config.setMinimumIdle(0);
    config.setMaximumPoolSize(1);
    config.setConnectionTimeout(1500);
    config.setDataSource(new CustomMockDataSource());

    long start = ClockSource.INSTANCE.currentTime();
    try (HikariDataSource ds = new HikariDataSource(config)) {
      Connection connection = ds.getConnection();
      connection.close();

      // Hikari only checks for validity for connections with lastAccess > 1000 ms so we sleep for
      // 1001 ms to force
      // Hikari to do a connection validation which will fail and will trigger the connection to be
      // closed
      UtilityElf.quietlySleep(1100L);

      shouldFail = true;

      // on physical connection close we sleep 2 seconds
      connection = ds.getConnection();

      Assert.assertTrue(
          "Waited longer than timeout",
          (ClockSource.INSTANCE.elapsedMillis(start) < config.getConnectionTimeout()));
    } catch (SQLException e) {
      Assert.assertTrue(
          "getConnection failed because close connection took longer than timeout",
          (ClockSource.INSTANCE.elapsedMillis(start) < config.getConnectionTimeout()));
    }
  }
Ejemplo n.º 4
0
  public static void saveTwitch(SkuddUser user) {
    Connection c = null;
    PreparedStatement ps = null;
    String create =
        "INSERT INTO " + user.getServerID() + "_twitch VALUES(?,?)ON DUPLICATE KEY UPDATE xp=?";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(create);

      ps.setString(1, user.getTwitchUsername());
      ps.setInt(2, user.getXp());
      ps.setInt(3, user.getXp());

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 5
0
  /**
   * permet d'effacer une Alignement
   *
   * @param ds
   * @param id
   */
  public void efaceAligSour(HikariDataSource ds, int id) {
    Statement stmt;
    Connection conn;

    try {
      // Get connection from pool
      conn = ds.getConnection();
      try {
        stmt = conn.createStatement();
        try {
          stmt = conn.createStatement();

          String query = "delete from alignement_source" + " where id =" + id;
          stmt.executeUpdate(query);

        } finally {
          stmt.close();
        }
      } finally {
        conn.close();
      }
    } catch (SQLException sqle) {
      // Log exception
      log.error("Error while delete Alignement : ", sqle);
    }
  }
Ejemplo n.º 6
0
  /**
   * permet d'ajouter une source d'alignement à un ou plusieurs thésaurus on supprime d'abord les
   * anciennes valeurs, puis on ajoute les nouvelles
   *
   * @param ds
   * @param authorizedThesaurus
   * @param listThesos
   * @param idAlignement
   * @return
   */
  public boolean addSourceAlignementToTheso(
      HikariDataSource ds,
      ArrayList<Map.Entry<String, String>> authorizedThesaurus,
      List<String> listThesos,
      int idAlignement) {
    boolean status = false;
    try {
      Connection conn = ds.getConnection();
      conn.setAutoCommit(false);

      // suppression des anciennes relations
      for (Map.Entry<String, String> auEntry : authorizedThesaurus) {
        if (!deleteSourceAlignementFromTheso(conn, auEntry.getValue(), idAlignement)) {
          conn.rollback();
          conn.close();
          return false;
        }
      }

      for (String listTheso : listThesos) {
        if (!insertSourceAlignementToTheso(conn, listTheso, idAlignement)) {
          conn.rollback();
          conn.close();
          return false;
        }
      }
      conn.commit();
      conn.close();
      status = true;

    } catch (SQLException ex) {
      Logger.getLogger(AlignmentHelper.class.getName()).log(Level.SEVERE, null, ex);
    }
    return status;
  }
Ejemplo n.º 7
0
  /**
   * Retourne la liste des types d'alignements sous forme de MAP (id + Nom)
   *
   * @param ds
   * @return
   */
  public HashMap<String, String> getAlignmentType(HikariDataSource ds) {

    Connection conn;
    Statement stmt;
    ResultSet resultSet;
    HashMap<String, String> map = new HashMap<>();

    try {
      // Get connection from pool--- aqui salta para el install
      conn = ds.getConnection();
      try {
        stmt = conn.createStatement();
        try {
          String query = "select id, label_skos from alignement_type";

          stmt.executeQuery(query);
          resultSet = stmt.getResultSet();
          while (resultSet.next()) {
            map.put(String.valueOf(resultSet.getInt("id")), resultSet.getString("label_skos"));
          }
          resultSet.close();

        } finally {
          stmt.close();
        }
      } finally {
        conn.close();
      }
    } catch (SQLException sqle) {
      // Log exception
      log.error("Error while getting Map of Type of Alignment : " + map.toString(), sqle);
    }
    return map;
  }
Ejemplo n.º 8
0
  /**
   * Cette fonction permet de mettre à jour un Terme à la table Term, en paramètre un objet Classe
   * Term
   *
   * @param ds
   * @param idAlignment
   * @param conceptTarget
   * @param thesaurusTarget
   * @param idConcept
   * @param idTypeAlignment
   * @param uriTarget
   * @param idThesaurus
   * @return
   */
  public boolean updateAlignment(
      HikariDataSource ds,
      int idAlignment,
      String conceptTarget,
      String thesaurusTarget,
      String uriTarget,
      int idTypeAlignment,
      String idConcept,
      String idThesaurus) {

    Connection conn;
    Statement stmt;
    boolean status = false;
    try {
      // Get connection from pool
      conn = ds.getConnection();
      try {
        stmt = conn.createStatement();
        try {
          String query =
              "UPDATE alignement set"
                  + " concept_target = '"
                  + conceptTarget
                  + "',"
                  + " modified = current_date,"
                  + " thesaurus_target = '"
                  + thesaurusTarget
                  + "',"
                  + " uri_target = '"
                  + uriTarget
                  + "',"
                  + " alignement_id_type = "
                  + idTypeAlignment
                  + ","
                  + " thesaurus_target = '"
                  + thesaurusTarget
                  + "'"
                  + " WHERE id ="
                  + idAlignment
                  + " AND internal_id_thesaurus = '"
                  + idThesaurus
                  + "'"
                  + " AND internal_id_concept = '"
                  + idConcept
                  + "'";
          stmt.executeUpdate(query);
          status = true;

        } finally {
          stmt.close();
        }
      } finally {
        conn.close();
      }
    } catch (SQLException sqle) {
      // Log exception
      log.error("Error while updating Alignment : " + idAlignment, sqle);
    }
    return status;
  }
Ejemplo n.º 9
0
  public static void deleteTwitch(String username, String serverID) {
    Connection c = null;
    PreparedStatement ps = null;
    String create = "DELETE FROM " + serverID + "_twitch WHERE twitch_user=?";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(create);

      ps.setString(1, username);

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 10
0
  private static void createTwitchTable(String serverID) {
    Connection c = null;
    PreparedStatement ps = null;

    String query =
        "CREATE TABLE "
            + serverID
            + "_twitch (twitch_user VARCHAR(100),xp INT(11) DEFAULT 0 NOT NULL, PRIMARY KEY (twitch_user));";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 11
0
  public static void banUser(String name) {
    Connection c = null;
    PreparedStatement ps = null;

    String query = "INSERT INTO banned_users VALUES(?);";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);

      ps.setString(1, name);

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
 public Connection getConnection() {
   try {
     if (sqlite) {
       // To avoid concurrency problem with SQLite, we will just use one connection. Cf :
       // constructor above for SQLite
       synchronized (SQLiteConn) {
         SQLiteConn =
             DriverManager.getConnection(
                 "jdbc:sqlite:"
                     + BAT.getInstance().getDataFolder().getAbsolutePath()
                     + File.separator
                     + "bat_database.db");
         return SQLiteConn;
       }
     }
     return ds.getConnection();
   } catch (final SQLException e) {
     BAT.getInstance()
         .getLogger()
         .severe(
             "BAT can't etablish connection with the database. Please report this and include the following lines :");
     if (e.getCause() instanceof CommunicationsException) {
       BAT.getInstance().getLogger().severe(e.getCause().getMessage());
     }
     if (BAT.getInstance().getConfiguration().isDebugMode()) {
       e.printStackTrace();
     }
     return null;
   }
 }
Ejemplo n.º 13
0
  /**
   * Send a request to the database to add a awesome user to the database.
   *
   * @param id The Discord ID associated with the person we want to add.
   */
  public static void addAwesome(String id) {
    Connection c = null;
    PreparedStatement ps = null;

    String query = "INSERT INTO awesome_users VALUES(?,?,null);";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);

      ps.setString(1, id);
      ps.setString(2, Main.getInstance().getSkuddbot().getUserByID(id).getName());

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 14
0
  /**
   * Send a request to the database to remove a admin user form the database.
   *
   * @param id The Discord ID associated with the person we want to remove.
   */
  public static void removeAdmin(String id) {
    Connection c = null;
    PreparedStatement ps = null;

    String query = "DELETE FROM admin_users WHERE id=?;;";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);

      ps.setString(1, id);

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 15
0
  /**
   * Adds a awesome string to the database!
   *
   * @param dataType Message type.
   * @param message The message itself.
   * @param id The ID of the user that added it.
   */
  public static void addAwesomeString(DataTypes dataType, String message, String id) {
    Connection c = null;
    PreparedStatement ps = null;

    String query = "INSERT INTO awesome_data VALUES(null,?,?,?);";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);

      ps.setString(1, id);
      ps.setString(2, dataType.toString());
      ps.setString(3, message);

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
Ejemplo n.º 16
0
  /**
   * Cette fonction permet de retourner la liste des alignements pour un concept
   *
   * @param ds
   * @param idConcept
   * @param idThesaurus
   * @return Objet class
   */
  public ArrayList<NodeAlignment> getAllAlignmentOfConcept(
      HikariDataSource ds, String idConcept, String idThesaurus) {

    Connection conn;
    Statement stmt;
    ResultSet resultSet;
    ArrayList<NodeAlignment> nodeAlignmentList = null;

    try {
      // Get connection from pool
      conn = ds.getConnection();
      try {
        stmt = conn.createStatement();
        try {
          String query =
              "SELECT id, created, modified,"
                  + " author, thesaurus_target, concept_target,"
                  + " uri_target, alignement_id_type, internal_id_thesaurus,"
                  + " internal_id_concept FROM alignement"
                  + " where internal_id_concept = '"
                  + idConcept
                  + "'"
                  + " and internal_id_thesaurus ='"
                  + idThesaurus
                  + "'";

          stmt.executeQuery(query);
          resultSet = stmt.getResultSet();
          nodeAlignmentList = new ArrayList<>();
          while (resultSet.next()) {
            NodeAlignment nodeAlignment = new NodeAlignment();
            nodeAlignment.setId_alignement(resultSet.getInt("id"));
            nodeAlignment.setCreated(resultSet.getDate("created"));
            nodeAlignment.setModified(resultSet.getDate("modified"));
            nodeAlignment.setId_author(resultSet.getInt("author"));
            nodeAlignment.setThesaurus_target(resultSet.getString("thesaurus_target"));
            nodeAlignment.setConcept_target(resultSet.getString("concept_target"));
            nodeAlignment.setUri_target(resultSet.getString("uri_target").trim());
            nodeAlignment.setAlignement_id_type(resultSet.getInt("alignement_id_type"));
            nodeAlignment.setInternal_id_thesaurus(resultSet.getString("internal_id_thesaurus"));
            nodeAlignment.setInternal_id_concept(resultSet.getString("internal_id_concept"));

            nodeAlignmentList.add(nodeAlignment);
          }

        } finally {
          stmt.close();
        }
      } finally {
        conn.close();
      }
    } catch (SQLException sqle) {
      // Log exception
      log.error("Error while getting All list of alignment of Concept  : " + idConcept, sqle);
    }
    return nodeAlignmentList;
  }
Ejemplo n.º 17
0
  private ConnectionSource setupConnection(DatabaseConfig dbConfig) throws SQLException {
    HikariDataSource ds = new HikariDataSource();

    if (!dbConfig.getUser().isEmpty()) {
      ds.setUsername(dbConfig.getUser());
    }
    if (!dbConfig.getPassword().isEmpty()) {
      ds.setPassword(dbConfig.getPassword());
    }

    ds.setJdbcUrl(dbConfig.getJDBCUrl());

    ds.setMaximumPoolSize(dbConfig.getMaxConnections());
    /* Keep the connection open for 5 minutes */
    //    ds.setMaxLifetime(300000);

    return new DataSourceConnectionSource(ds, new MySQLDatabase());
  }
Ejemplo n.º 18
0
 @Override
 public Connection getConnection() {
   try {
     return _source.getConnection();
   } catch (SQLException exception) {
     printErr("An Exception occurred while attempting to create a MySQL Connection!", true);
     exception.printStackTrace();
     return null;
   }
 }
Ejemplo n.º 19
0
  /**
   * Cette fonction permet d'ajouter un nouvel alignement sur un thésaurus distant pour ce concept
   *
   * @param ds
   * @param nodeAlignment
   * @return
   */
  public boolean addNewAlignment(HikariDataSource ds, NodeAlignment nodeAlignment) {

    Connection conn;
    Statement stmt;

    boolean status = false;
    try {
      // Get connection from pool
      conn = ds.getConnection();
      try {
        stmt = conn.createStatement();
        try {
          String query =
              "Insert into alignement "
                  + "(author, concept_target, thesaurus_target,"
                  + " uri_target, alignement_id_type,"
                  + " internal_id_thesaurus, internal_id_concept)"
                  + " values ("
                  + nodeAlignment.getId_author()
                  + ",'"
                  + nodeAlignment.getConcept_target()
                  + "'"
                  + ",'"
                  + nodeAlignment.getThesaurus_target()
                  + "'"
                  + ",'"
                  + nodeAlignment.getUri_target()
                  + "'"
                  + ","
                  + nodeAlignment.getAlignement_id_type()
                  + ",'"
                  + nodeAlignment.getInternal_id_thesaurus()
                  + "'"
                  + ",'"
                  + nodeAlignment.getInternal_id_concept()
                  + "')";

          stmt.executeUpdate(query);

          status = true;

        } finally {
          stmt.close();
        }
      } finally {
        conn.close();
      }
    } catch (SQLException sqle) {
      // Log exception
      log.error(
          "Error while adding external alignement with target : " + nodeAlignment.getUri_target(),
          sqle);
    }
    return status;
  }
  /** @exception SQLException if the object pool cannot be created. */
  protected void init() throws SQLException {
    M_log.info("init()");

    // Do some quick validation
    if (getUsername() == null) {
      M_log.warn("Hikari DataSource configured without a 'username'");
    }

    if (getPassword() == null) {
      M_log.warn("Hikari DataSource configured without a 'password'");
    }

    // For backward compatibility with old methods
    if (url != null && !"".equals(url)) {
      super.setJdbcUrl(url);
      // This seems to also be required as HikariCP isn't registering this class if it's specified
      // and it gives an error
      if (driverClassName != null) {
        super.setDriverClassName(driverClassName);
        try {
          Class driverClass;
          driverClass = Class.forName(driverClassName);
          DriverManager.registerDriver((Driver) driverClass.newInstance());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
          // TODO Auto-generated catch block
          String message = "driverClass not specified, might not be able to load the driver'";
          M_log.info(message, e);
        }
      }
    }

    super.setTransactionIsolation(isolationLevel);

    // Validate the class to verify it loaded
    try {
      super.validate();
    } catch (Exception t) {
      String message = "Cannot load JDBC driver class '" + driverClassName + "'";
      M_log.error(message, t);
      throw new SQLException(message, t);
    }
  }
Ejemplo n.º 21
0
  @BeforeClass
  public static void initDatabaseScheme() throws Exception {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:h2:mem:test");
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUsername("user");
    dataSource.setPassword("password");

    queryTemplate = new QueryTemplate(dataSource);

    queryTemplate.run(
        new UpdateQuery() {
          @Override
          public Integer perform(DatabaseConnection connection) throws Exception {
            return connection.executeUpdate(
                "CREATE TABLE Person(id INT PRIMARY KEY, name VARCHAR, birthday DATE, employed BOOLEAN);");
          }
        },
        true);
  }
  public static Connection connectWithHikari() throws SQLException {
    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
    } catch (ClassNotFoundException cnfe) {
      System.err.println("Error: " + cnfe.getMessage());
    } catch (InstantiationException ie) {
      System.err.println("Error: " + ie.getMessage());
    } catch (IllegalAccessException iae) {
      System.err.println("Error: " + iae.getMessage());
    }

    HikariDataSource ds = getHikari();
    if (con != null && !con.isClosed()) {
      con.close();
      con = null;
    }
    con = ds.getConnection();

    System.out.println("Returning Hikari Connection " + con);
    return con;
  }
Ejemplo n.º 23
0
  public static SkuddUser getDiscordByTwitch(String twitchUsername, String serverID) {
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    SkuddUser user = null;

    String query =
        "SELECT * FROM " + serverID + "_discord WHERE twitch_username = '******';";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);
      rs = ps.executeQuery();
      if (rs.next()) {
        user =
            new SkuddUser(
                rs.getString("discord_id"),
                serverID,
                rs.getString("discord_username"),
                rs.getInt("xp"),
                rs.getString("twitch_username"));
      } else {
        user = null;
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }

    return user;
  }
Ejemplo n.º 24
0
  public static void setupHikari(String user, String pass) {
    hikari = new HikariDataSource();
    hikari.setMaximumPoolSize(10);

    hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    hikari.addDataSourceProperty("serverName", "localhost");
    hikari.addDataSourceProperty("port", 3306);
    hikari.addDataSourceProperty("databaseName", "skuddbot");
    hikari.addDataSourceProperty("user", user);
    hikari.addDataSourceProperty("password", pass);
  }
 /**
  * Configure datasource.
  *
  * @return datasource
  * @throws PropertyVetoException
  */
 @Bean(destroyMethod = "close")
 public DataSource dataSource() throws PropertyVetoException {
   HikariDataSource dataSource = new HikariDataSource();
   dataSource.setDriverClassName(environment.getProperty("jdbc.driverClass"));
   dataSource.setJdbcUrl(environment.getProperty("jdbc.url"));
   dataSource.setUsername(environment.getProperty("jdbc.user"));
   dataSource.setPassword(environment.getProperty("jdbc.password"));
   dataSource.setMinimumIdle(environment.getProperty("datasource.pool.min_size", Integer.class));
   dataSource.setMaximumPoolSize(
       environment.getProperty("datasource.pool.max_size", Integer.class));
   return dataSource;
 }
Ejemplo n.º 26
0
  @SuppressWarnings("unchecked")
  public static JSONArray dumpTwitch() {
    JSONArray dump = new JSONArray();

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String query = "SELECT * FROM twitch_users;";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);
      rs = ps.executeQuery();

      while (rs.next()) {
        JSONObject obj = new JSONObject();
        obj.put("twitch_username", rs.getString("twitch_user"));
        obj.put("xp", rs.getInt("xp"));

        dump.add(obj);
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }

    return dump;
  }
  /**
   * Constructor used for MySQL
   *
   * @param host
   * @param port
   * @param database
   * @param username
   * @param password
   * @throws SQLException
   */
  public DataSourceHandler(
      final String host,
      final String port,
      final String database,
      final String username,
      final String password)
      throws SQLException {
    // Check database's informations and init connection
    this.host = Preconditions.checkNotNull(host);
    this.port = Preconditions.checkNotNull(port);
    this.database = Preconditions.checkNotNull(database);
    this.username = Preconditions.checkNotNull(username);
    this.password = Preconditions.checkNotNull(password);

    BAT.getInstance().getLogger().config("Initialization of HikariCP in progress ...");
    BasicConfigurator.configure(new NullAppender());
    ds = new HikariDataSource();
    ds.setJdbcUrl(
        "jdbc:mysql://"
            + this.host
            + ":"
            + this.port
            + "/"
            + this.database
            + "?useLegacyDatetimeCode=false&serverTimezone="
            + TimeZone.getDefault().getID());
    ds.setUsername(this.username);
    ds.setPassword(this.password);
    ds.addDataSourceProperty("cachePrepStmts", "true");
    ds.setMaximumPoolSize(8);
    try {
      final Connection conn = ds.getConnection();
      int intOffset =
          Calendar.getInstance().getTimeZone().getOffset(Calendar.getInstance().getTimeInMillis())
              / 1000;
      String offset =
          String.format("%02d:%02d", Math.abs(intOffset / 3600), Math.abs((intOffset / 60) % 60));
      offset = (intOffset >= 0 ? "+" : "-") + offset;
      conn.createStatement().executeQuery("SET time_zone='" + offset + "';");
      conn.close();
      BAT.getInstance().getLogger().config("BoneCP is loaded !");
    } catch (final SQLException e) {
      BAT.getInstance()
          .getLogger()
          .severe(
              "BAT encounters a problem during the initialization of the database connection."
                  + " Please check your logins and database configuration.");
      if (e.getCause() instanceof CommunicationsException) {
        BAT.getInstance().getLogger().severe(e.getCause().getMessage());
      }
      if (BAT.getInstance().getConfiguration().isDebugMode()) {
        BAT.getInstance().getLogger().log(Level.SEVERE, e.getMessage(), e);
      }
      throw e;
    }
    sqlite = false;
  }
Ejemplo n.º 28
0
  public static HashMap<Integer, SkuddUser> getTopTwitch(String serverID) {
    HashMap<Integer, SkuddUser> top = new HashMap<>();

    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    String query = "SELECT * FROM " + serverID + "_twitch ORDER BY xp DESC;";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(query);
      rs = ps.executeQuery();

      int i = 0;
      while (rs.next() && i < 10) {
        SkuddUser user = ProfileManager.getTwitchServer(rs.getString("twitch_user"), serverID);
        top.put(user.getXp(), user);
        i++;
      }

    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (rs != null) {
        try {
          rs.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }

    return top;
  }
Ejemplo n.º 29
0
  public static void saveProfile(SkuddUser user) {
    Connection c = null;
    PreparedStatement ps = null;
    String create =
        "INSERT INTO "
            + user.getServerID()
            + "_discord VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE discord_username=?,xp=?,twitch_username=?";

    try {
      c = hikari.getConnection();
      ps = c.prepareStatement(create);

      ps.setString(1, user.getId());
      ps.setString(
          2,
          (Main.getInstance().getSkuddbot().getUserByID(user.getId()) == null
              ? user.getName()
              : Main.getInstance().getSkuddbot().getUserByID(user.getId()).getName()));
      ps.setInt(3, user.getXp());
      ps.setString(4, user.getTwitchUsername());
      ps.setString(
          5,
          (Main.getInstance().getSkuddbot().getUserByID(user.getId()) == null
              ? user.getName()
              : Main.getInstance().getSkuddbot().getUserByID(user.getId()).getName()));
      ps.setInt(6, user.getXp());
      ps.setString(7, user.getTwitchUsername());

      ps.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      if (c != null) {
        try {
          c.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
      if (ps != null) {
        try {
          ps.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
  @Bean(name = "datasource")
  public DataSource restDataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
    dataSource.setJdbcUrl(env.getProperty("jdbc.url"));
    dataSource.setUsername(env.getProperty("jdbc.user"));
    dataSource.setPassword(env.getProperty("jdbc.pass"));
    dataSource.setMaximumPoolSize(Integer.valueOf(env.getProperty("jdbc.maximumPoolSize")));

    return dataSource;
  }