L2DatabaseFactory.java 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*
  2. * This program is free software: you can redistribute it and/or modify it under
  3. * the terms of the GNU General Public License as published by the Free Software
  4. * Foundation, either version 3 of the License, or (at your option) any later
  5. * version.
  6. *
  7. * This program is distributed in the hope that it will be useful, but WITHOUT
  8. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  9. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  10. * details.
  11. *
  12. * You should have received a copy of the GNU General Public License along with
  13. * this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. package net.sf.l2j;
  16. import java.sql.Connection;
  17. import java.sql.SQLException;
  18. import java.util.logging.Level;
  19. import java.util.logging.Logger;
  20. import com.mchange.v2.c3p0.ComboPooledDataSource;
  21. public class L2DatabaseFactory
  22. {
  23. static Logger _log = Logger.getLogger(L2DatabaseFactory.class.getName());
  24. public static enum ProviderType
  25. {
  26. MySql,
  27. MsSql
  28. }
  29. // =========================================================
  30. // Data Field
  31. private static L2DatabaseFactory _instance;
  32. private ProviderType _providerType;
  33. private ComboPooledDataSource _source;
  34. // =========================================================
  35. // Constructor
  36. public L2DatabaseFactory() throws SQLException
  37. {
  38. try
  39. {
  40. if (Config.DATABASE_MAX_CONNECTIONS < 2)
  41. {
  42. Config.DATABASE_MAX_CONNECTIONS = 2;
  43. _log.warning("at least " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
  44. }
  45. _source = new ComboPooledDataSource();
  46. _source.setAutoCommitOnClose(true);
  47. _source.setInitialPoolSize(10);
  48. _source.setMinPoolSize(10);
  49. _source.setMaxPoolSize(Config.DATABASE_MAX_CONNECTIONS);
  50. _source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
  51. _source.setAcquireRetryDelay(500); // 500 miliseconds wait before try to acquire connection again
  52. _source.setCheckoutTimeout(0); // 0 = wait indefinitely for new connection
  53. // if pool is exhausted
  54. _source.setAcquireIncrement(5); // if pool is exhausted, get 5 more connections at a time
  55. // cause there is a "long" delay on acquire connection
  56. // so taking more than one connection at once will make connection pooling
  57. // more effective.
  58. // this "connection_test_table" is automatically created if not already there
  59. _source.setAutomaticTestTable("connection_test_table");
  60. _source.setTestConnectionOnCheckin(false);
  61. // testing OnCheckin used with IdleConnectionTestPeriod is faster than testing on checkout
  62. _source.setIdleConnectionTestPeriod(3600); // test idle connection every 60 sec
  63. _source.setMaxIdleTime(0); // 0 = idle connections never expire
  64. // *THANKS* to connection testing configured above
  65. // but I prefer to disconnect all connections not used
  66. // for more than 1 hour
  67. // enables statement caching, there is a "semi-bug" in c3p0 0.9.0 but in 0.9.0.2 and later it's fixed
  68. _source.setMaxStatementsPerConnection(100);
  69. _source.setBreakAfterAcquireFailure(false); // never fail if any way possible
  70. // setting this to true will make
  71. // c3p0 "crash" and refuse to work
  72. // till restart thus making acquire
  73. // errors "FATAL" ... we don't want that
  74. // it should be possible to recover
  75. _source.setDriverClass(Config.DATABASE_DRIVER);
  76. _source.setJdbcUrl(Config.DATABASE_URL);
  77. _source.setUser(Config.DATABASE_LOGIN);
  78. _source.setPassword(Config.DATABASE_PASSWORD);
  79. /* Test the connection */
  80. _source.getConnection().close();
  81. if (Config.DEBUG) _log.fine("Database Connection Working");
  82. if (Config.DATABASE_DRIVER.toLowerCase().contains("microsoft"))
  83. _providerType = ProviderType.MsSql;
  84. else
  85. _providerType = ProviderType.MySql;
  86. }
  87. catch (SQLException x)
  88. {
  89. if (Config.DEBUG) _log.fine("Database Connection FAILED");
  90. // rethrow the exception
  91. throw x;
  92. }
  93. catch (Exception e)
  94. {
  95. if (Config.DEBUG) _log.fine("Database Connection FAILED");
  96. throw new SQLException("could not init DB connection:"+e);
  97. }
  98. }
  99. // =========================================================
  100. // Method - Public
  101. public final String prepQuerySelect(String[] fields, String tableName, String whereClause, boolean returnOnlyTopRecord)
  102. {
  103. String msSqlTop1 = "";
  104. String mySqlTop1 = "";
  105. if (returnOnlyTopRecord)
  106. {
  107. if (getProviderType() == ProviderType.MsSql) msSqlTop1 = " Top 1 ";
  108. if (getProviderType() == ProviderType.MySql) mySqlTop1 = " Limit 1 ";
  109. }
  110. String query = "SELECT " + msSqlTop1 + safetyString(fields) + " FROM " + tableName + " WHERE " + whereClause + mySqlTop1;
  111. return query;
  112. }
  113. public void shutdown()
  114. {
  115. try {
  116. _source.close();
  117. } catch (Exception e) {_log.log(Level.INFO, "", e);}
  118. try {
  119. _source = null;
  120. } catch (Exception e) {_log.log(Level.INFO, "", e);}
  121. }
  122. public final String safetyString(String... whatToCheck)
  123. {
  124. // NOTE: Use brace as a safty percaution just incase name is a reserved word
  125. String braceLeft = "`";
  126. String braceRight = "`";
  127. if (getProviderType() == ProviderType.MsSql)
  128. {
  129. braceLeft = "[";
  130. braceRight = "]";
  131. }
  132. String result = "";
  133. for(String word : whatToCheck)
  134. {
  135. if(result != "") result += ", ";
  136. result += braceLeft + word + braceRight;
  137. }
  138. return result;
  139. }
  140. // =========================================================
  141. // Property - Public
  142. public static L2DatabaseFactory getInstance() throws SQLException
  143. {
  144. if (_instance == null)
  145. {
  146. _instance = new L2DatabaseFactory();
  147. }
  148. return _instance;
  149. }
  150. public Connection getConnection() //throws SQLException
  151. {
  152. Connection con=null;
  153. while(con==null)
  154. {
  155. try
  156. {
  157. con=_source.getConnection();
  158. } catch (SQLException e)
  159. {
  160. _log.warning("L2DatabaseFactory: getConnection() failed, trying again "+e);
  161. }
  162. }
  163. return con;
  164. }
  165. public int getBusyConnectionCount() throws SQLException
  166. {
  167. return _source.getNumBusyConnectionsDefaultUser();
  168. }
  169. public int getIdleConnectionCount() throws SQLException
  170. {
  171. return _source.getNumIdleConnectionsDefaultUser();
  172. }
  173. public final ProviderType getProviderType() { return _providerType; }
  174. }