L2DatabaseFactory.java 6.7 KB

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