Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 6.02 KB | None | 0 0
  1. package com.strategyprocess.database;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9. import java.util.concurrent.BlockingQueue;
  10. import java.util.concurrent.LinkedBlockingDeque;
  11. import java.util.concurrent.TimeUnit;
  12.  
  13. import com.strategyprocess.config.APIConfiguration;
  14. import com.strategyprocess.config.DatabaseConfiguration;
  15. import com.strategyprocess.logging.LogSystem;
  16. import com.strategyprocess.thread.ThreadManager;
  17.  
  18. public class MySQLPool {
  19.    
  20.     private String host = DatabaseConfiguration.get().getProperty("host");
  21.     private String port = DatabaseConfiguration.get().getProperty("port");
  22.     private String database = DatabaseConfiguration.get().getProperty("database");
  23.     private String username = DatabaseConfiguration.get().getProperty("username");
  24.     private String password = DatabaseConfiguration.get().getProperty("password");
  25.    
  26.     BlockingQueue<Connection> connectionPoolQueue = new LinkedBlockingDeque<>();
  27.    
  28.     private static MySQLPool pool;
  29.    
  30.     public static MySQLPool get() {
  31.         if(pool == null) {
  32.             pool = new MySQLPool();
  33.         }
  34.         return pool;
  35.     }
  36.    
  37.     public MySQLPool() {
  38.         ThreadManager.get().getScheduledThreadPool().scheduleAtFixedRate(new Runnable() {
  39.            
  40.             @Override
  41.             public void run() {
  42.                 try {
  43.                     checkConnectionAmount();
  44.                 } catch (SQLException ex) {
  45.                     LogSystem.get().getLogger().warn("Could not delete old users...", ex);
  46.                 }
  47.             }
  48.  
  49.         }, 10, 10, TimeUnit.MINUTES);
  50.     }
  51.    
  52.     private void checkConnectionAmount() throws SQLException{
  53.         if(connectionPoolQueue.size() > APIConfiguration.databaseConnectionAmountMax) {
  54.             int amountToRemove = connectionPoolQueue.size() - APIConfiguration.databaseConnectionAmountMax;
  55.             for(int i = 0; i < amountToRemove; i++) {
  56.                 Connection con = connectionPoolQueue.poll();
  57.                 if(con != null) {
  58.                     con.close();
  59.                 }
  60.             }
  61.         }
  62.     }
  63.    
  64.     //Do not add to pool, because somebody gets it immediately
  65.     private Connection createConnection() {
  66.         try {
  67.            
  68.             Connection con = DriverManager.getConnection("jdbc:mysql://" + host + ":" + port + "/" + database, username, password);
  69.             con.setAutoCommit(false);
  70.            
  71.             LogSystem.get().info("[MySQL] Created new connection!");
  72.                    
  73.             return con;
  74.            
  75.         } catch (SQLException e) {
  76.            
  77.             LogSystem.get().error("[MySQL] Cant connect!", e);         
  78.             return null;
  79.         }      
  80.     }
  81.    
  82.     private boolean isConnectionValid(Connection con) {
  83.         try {
  84.  
  85.             if (con != null) {
  86.                
  87.                 Statement st = con.createStatement();
  88.                 st.executeQuery("SELECT 1");
  89.                 st.close();
  90.                
  91.                 return true;
  92.             } else {
  93.                 return false;
  94.             }
  95.         } catch (Exception ex) {
  96.             LogSystem.get().info("[MySQL] A connection is unvalid...");
  97.             return false;
  98.         }
  99.     }
  100.    
  101.     public Connection takeConnection() throws SQLException {
  102.         Connection con = null;
  103.         int tries = 0;
  104.        
  105.         while(con == null && tries < APIConfiguration.databaseConnectAttempts) {
  106.             con = getOrCreateConnection();
  107.            
  108.             tries++;
  109.         }
  110.        
  111.         if(con == null) {
  112.             throw new SQLException("no connection could be established");
  113.         }
  114.        
  115.         return con;
  116.     }
  117.    
  118.     public void returnConnectionAndRollbackUncommitedChanges(Connection con){
  119.         if(con != null) {
  120.             try {
  121.                 rollback(con);
  122.             } catch (SQLException e) {
  123.                 //Do not add connection to pool
  124.                 return;
  125.             }
  126.             connectionPoolQueue.add(con);
  127.         }
  128.     }
  129.    
  130.     private Connection getOrCreateConnection() {
  131.         while(true) {
  132.             if(connectionPoolQueue.isEmpty()) {
  133.                 return createConnection();
  134.             }
  135.            
  136.             Connection possibleCon = null;
  137.            
  138.             try {
  139.                 possibleCon = connectionPoolQueue.poll(100, TimeUnit.MILLISECONDS);
  140.             } catch (InterruptedException e) {}
  141.            
  142.            
  143.             if(possibleCon == null) {
  144.                 return createConnection();
  145.             }
  146.            
  147.             if(isConnectionValid(possibleCon)) {
  148.                 return possibleCon;
  149.             }
  150.             else {
  151.                 //Do not re-add to pool, because it was unvalid
  152.             }
  153.         }
  154.     }
  155.    
  156.     public PreparedStatement createStatement(Connection con, String query) throws SQLException {       
  157.         return con.prepareStatement(query);
  158.     }
  159.    
  160.     public ResultSet select(PreparedStatement statement) throws SQLException{
  161.         LogSystem.get().debug("[MySQL] Executing: " + statement.toString());
  162.        
  163.         return statement.executeQuery();
  164.     }
  165.    
  166.     public int execute(PreparedStatement statement) throws SQLException {
  167.         LogSystem.get().debug("[MySQL] Executing: " + statement.toString());
  168.        
  169.         statement.executeUpdate();
  170.        
  171.         ResultSet result = statement.getGeneratedKeys();
  172.         int resultInt = -1;
  173.        
  174.         if(result.next()) {
  175.             resultInt = result.getInt(1);
  176.            
  177.             LogSystem.get().debug("[MySQL] Inserted with key: " + resultInt);
  178.         }
  179.        
  180.         statement.close();
  181.        
  182.         LogSystem.get().debug("[MySQL] Statement closed.");
  183.        
  184.         return resultInt;
  185.     }
  186.    
  187.     public int execute(Connection con, String query) throws SQLException {
  188.         LogSystem.get().debug("[MySQL] Executing: " + query);
  189.        
  190.         PreparedStatement statement = createStatement(con, query);
  191.        
  192.         statement.executeUpdate();
  193.        
  194.         ResultSet result = statement.getGeneratedKeys();
  195.         int resultInt = -1;
  196.        
  197.         if(result.next()) {
  198.             resultInt = result.getInt(1);
  199.            
  200.             LogSystem.get().debug("[MySQL] Inserted with key: " + resultInt);
  201.         }
  202.        
  203.         statement.close();
  204.        
  205.         LogSystem.get().debug("[MySQL] Statement closed.");
  206.        
  207.         return resultInt;
  208.     }
  209.    
  210.     public int[] executeBatch(PreparedStatement statement) throws SQLException{
  211.         LogSystem.get().debug("[MySQL] Executing batch...");
  212.        
  213.         int[] returnValue = statement.executeBatch();
  214.        
  215.         statement.close();
  216.        
  217.         LogSystem.get().debug("[MySQL] Statement closed.");
  218.        
  219.         return returnValue;
  220.     }
  221.    
  222.     public void commit(Connection con) throws SQLException{
  223.         con.commit();
  224.     }
  225.    
  226.     public void rollback(Connection con) throws SQLException{
  227.         con.rollback();
  228.     }
  229.    
  230.     public void closeAllIdleConnections() {
  231.         for(Connection con : connectionPoolQueue) {
  232.             try {
  233.                 con.close();
  234.             } catch (SQLException e) {}
  235.         }
  236.     }
  237.  
  238. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement