L2DatabaseFactory.java 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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("A minimum of " + 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(Math.max(10, Config.DATABASE_MAX_CONNECTIONS));
  50. _source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
  51. _source.setAcquireRetryDelay(500); // 500 milliseconds 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(Config.DATABASE_MAX_IDLE_TIME); // 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)
  82. _log.fine("Database Connection Working");
  83. if (Config.DATABASE_DRIVER.toLowerCase().contains("microsoft"))
  84. _providerType = ProviderType.MsSql;
  85. else
  86. _providerType = ProviderType.MySql;
  87. }
  88. catch (SQLException x)
  89. {
  90. if (Config.DEBUG)
  91. _log.fine("Database Connection FAILED");
  92. // re-throw the exception
  93. throw x;
  94. }
  95. catch (Exception e)
  96. {
  97. if (Config.DEBUG)
  98. _log.fine("Database Connection FAILED");
  99. throw new SQLException("could not init DB connection:" + e);
  100. }
  101. }
  102. // =========================================================
  103. // Method - Public
  104. public final String prepQuerySelect(String[] fields, String tableName, String whereClause, boolean returnOnlyTopRecord)
  105. {
  106. String msSqlTop1 = "";
  107. String mySqlTop1 = "";
  108. if (returnOnlyTopRecord)
  109. {
  110. if (getProviderType() == ProviderType.MsSql)
  111. msSqlTop1 = " Top 1 ";
  112. if (getProviderType() == ProviderType.MySql)
  113. mySqlTop1 = " Limit 1 ";
  114. }
  115. String query = "SELECT " + msSqlTop1 + safetyString(fields) + " FROM " + tableName + " WHERE " + whereClause + mySqlTop1;
  116. return query;
  117. }
  118. public void shutdown()
  119. {
  120. try
  121. {
  122. _source.close();
  123. }
  124. catch (Exception e)
  125. {
  126. _log.log(Level.INFO, "", e);
  127. }
  128. try
  129. {
  130. _source = null;
  131. }
  132. catch (Exception e)
  133. {
  134. _log.log(Level.INFO, "", e);
  135. }
  136. }
  137. public final String safetyString(String... whatToCheck)
  138. {
  139. // NOTE: Use brace as a safty precaution just incase name is a reserved word
  140. final char braceLeft;
  141. final char braceRight;
  142. if (getProviderType() == ProviderType.MsSql)
  143. {
  144. braceLeft = '[';
  145. braceRight = ']';
  146. }
  147. else
  148. {
  149. braceLeft = '`';
  150. braceRight = '`';
  151. }
  152. int length = 0;
  153. for (String word : whatToCheck)
  154. {
  155. length += word.length() + 4;
  156. }
  157. final StringBuilder sbResult = new StringBuilder(length);
  158. for (String word : whatToCheck)
  159. {
  160. if (sbResult.length() > 0)
  161. {
  162. sbResult.append(", ");
  163. }
  164. sbResult.append(braceLeft);
  165. sbResult.append(word);
  166. sbResult.append(braceRight);
  167. }
  168. return sbResult.toString();
  169. }
  170. // =========================================================
  171. // Property - Public
  172. public static L2DatabaseFactory getInstance() throws SQLException
  173. {
  174. synchronized (L2DatabaseFactory.class)
  175. {
  176. if (_instance == null)
  177. {
  178. _instance = new L2DatabaseFactory();
  179. }
  180. }
  181. return _instance;
  182. }
  183. public Connection getConnection() //throws SQLException
  184. {
  185. Connection con = null;
  186. while (con == null)
  187. {
  188. try
  189. {
  190. con = _source.getConnection();
  191. }
  192. catch (SQLException e)
  193. {
  194. _log.warning("L2DatabaseFactory: getConnection() failed, trying again " + e);
  195. }
  196. }
  197. return con;
  198. }
  199. public int getBusyConnectionCount() throws SQLException
  200. {
  201. return _source.getNumBusyConnectionsDefaultUser();
  202. }
  203. public int getIdleConnectionCount() throws SQLException
  204. {
  205. return _source.getNumIdleConnectionsDefaultUser();
  206. }
  207. public final ProviderType getProviderType()
  208. {
  209. return _providerType;
  210. }
  211. }