L2DatabaseFactory.java 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 com.l2jserver;
  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.l2jserver.gameserver.ThreadPoolManager;
  21. import com.mchange.v2.c3p0.ComboPooledDataSource;
  22. public class L2DatabaseFactory
  23. {
  24. static Logger _log = Logger.getLogger(L2DatabaseFactory.class.getName());
  25. public static enum ProviderType
  26. {
  27. MySql,
  28. MsSql
  29. }
  30. // =========================================================
  31. // Data Field
  32. private static L2DatabaseFactory _instance;
  33. private ProviderType _providerType;
  34. private ComboPooledDataSource _source;
  35. // =========================================================
  36. // Constructor
  37. public L2DatabaseFactory() throws SQLException
  38. {
  39. try
  40. {
  41. if (Config.DATABASE_MAX_CONNECTIONS < 2)
  42. {
  43. Config.DATABASE_MAX_CONNECTIONS = 2;
  44. _log.warning("A minimum of " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
  45. }
  46. _source = new ComboPooledDataSource();
  47. _source.setAutoCommitOnClose(true);
  48. _source.setInitialPoolSize(10);
  49. _source.setMinPoolSize(10);
  50. _source.setMaxPoolSize(Math.max(10, Config.DATABASE_MAX_CONNECTIONS));
  51. _source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
  52. _source.setAcquireRetryDelay(500); // 500 milliseconds wait before try to acquire connection again
  53. _source.setCheckoutTimeout(0); // 0 = wait indefinitely for new connection
  54. // if pool is exhausted
  55. _source.setAcquireIncrement(5); // if pool is exhausted, get 5 more connections at a time
  56. // cause there is a "long" delay on acquire connection
  57. // so taking more than one connection at once will make connection pooling
  58. // more effective.
  59. // this "connection_test_table" is automatically created if not already there
  60. _source.setAutomaticTestTable("connection_test_table");
  61. _source.setTestConnectionOnCheckin(false);
  62. // testing OnCheckin used with IdleConnectionTestPeriod is faster than testing on checkout
  63. _source.setIdleConnectionTestPeriod(3600); // test idle connection every 60 sec
  64. _source.setMaxIdleTime(Config.DATABASE_MAX_IDLE_TIME); // 0 = idle connections never expire
  65. // *THANKS* to connection testing configured above
  66. // but I prefer to disconnect all connections not used
  67. // for more than 1 hour
  68. // enables statement caching, there is a "semi-bug" in c3p0 0.9.0 but in 0.9.0.2 and later it's fixed
  69. _source.setMaxStatementsPerConnection(100);
  70. _source.setBreakAfterAcquireFailure(false); // never fail if any way possible
  71. // setting this to true will make
  72. // c3p0 "crash" and refuse to work
  73. // till restart thus making acquire
  74. // errors "FATAL" ... we don't want that
  75. // it should be possible to recover
  76. _source.setDriverClass(Config.DATABASE_DRIVER);
  77. _source.setJdbcUrl(Config.DATABASE_URL);
  78. _source.setUser(Config.DATABASE_LOGIN);
  79. _source.setPassword(Config.DATABASE_PASSWORD);
  80. /* Test the connection */
  81. _source.getConnection().close();
  82. if (Config.DEBUG)
  83. _log.fine("Database Connection Working");
  84. if (Config.DATABASE_DRIVER.toLowerCase().contains("microsoft"))
  85. _providerType = ProviderType.MsSql;
  86. else
  87. _providerType = ProviderType.MySql;
  88. }
  89. catch (SQLException x)
  90. {
  91. if (Config.DEBUG)
  92. _log.fine("Database Connection FAILED");
  93. // re-throw the exception
  94. throw x;
  95. }
  96. catch (Exception e)
  97. {
  98. if (Config.DEBUG)
  99. _log.fine("Database Connection FAILED");
  100. throw new SQLException("Could not init DB connection:" + e.getMessage());
  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)
  112. msSqlTop1 = " Top 1 ";
  113. if (getProviderType() == ProviderType.MySql)
  114. mySqlTop1 = " Limit 1 ";
  115. }
  116. String query = "SELECT " + msSqlTop1 + safetyString(fields) + " FROM " + tableName + " WHERE " + whereClause + mySqlTop1;
  117. return query;
  118. }
  119. public void shutdown()
  120. {
  121. try
  122. {
  123. _source.close();
  124. }
  125. catch (Exception e)
  126. {
  127. _log.log(Level.INFO, "", e);
  128. }
  129. try
  130. {
  131. _source = null;
  132. }
  133. catch (Exception e)
  134. {
  135. _log.log(Level.INFO, "", e);
  136. }
  137. }
  138. public final String safetyString(String... whatToCheck)
  139. {
  140. // NOTE: Use brace as a safty precaution just incase name is a reserved word
  141. final char braceLeft;
  142. final char braceRight;
  143. if (getProviderType() == ProviderType.MsSql)
  144. {
  145. braceLeft = '[';
  146. braceRight = ']';
  147. }
  148. else
  149. {
  150. braceLeft = '`';
  151. braceRight = '`';
  152. }
  153. int length = 0;
  154. for (String word : whatToCheck)
  155. {
  156. length += word.length() + 4;
  157. }
  158. final StringBuilder sbResult = new StringBuilder(length);
  159. for (String word : whatToCheck)
  160. {
  161. if (sbResult.length() > 0)
  162. {
  163. sbResult.append(", ");
  164. }
  165. sbResult.append(braceLeft);
  166. sbResult.append(word);
  167. sbResult.append(braceRight);
  168. }
  169. return sbResult.toString();
  170. }
  171. // =========================================================
  172. // Property - Public
  173. public static L2DatabaseFactory getInstance() throws SQLException
  174. {
  175. synchronized (L2DatabaseFactory.class)
  176. {
  177. if (_instance == null)
  178. {
  179. _instance = new L2DatabaseFactory();
  180. }
  181. }
  182. return _instance;
  183. }
  184. public Connection getConnection() //throws SQLException
  185. {
  186. Connection con = null;
  187. while (con == null)
  188. {
  189. try
  190. {
  191. con = _source.getConnection();
  192. if (Server.serverMode == Server.MODE_GAMESERVER)
  193. ThreadPoolManager.getInstance().scheduleGeneral(new ConnectionCloser(con, new RuntimeException()), 60000);
  194. }
  195. catch (SQLException e)
  196. {
  197. _log.log(Level.WARNING, "L2DatabaseFactory: getConnection() failed, trying again " + e.getMessage(), e);
  198. }
  199. }
  200. return con;
  201. }
  202. private class ConnectionCloser implements Runnable
  203. {
  204. private Connection c ;
  205. private RuntimeException exp;
  206. public ConnectionCloser(Connection con, RuntimeException e)
  207. {
  208. c = con;
  209. exp = e;
  210. }
  211. /* (non-Javadoc)
  212. * @see java.lang.Runnable#run()
  213. */
  214. @Override
  215. public void run()
  216. {
  217. try
  218. {
  219. if (!c.isClosed())
  220. {
  221. _log.log(Level.WARNING, "Unclosed connection! Trace: " + exp.getStackTrace()[1], exp);
  222. }
  223. }
  224. catch (SQLException e)
  225. {
  226. e.printStackTrace();
  227. }
  228. }
  229. }
  230. public static void close(Connection con)
  231. {
  232. if (con == null)
  233. return;
  234. try
  235. {
  236. con.close();
  237. }
  238. catch (SQLException e)
  239. {
  240. _log.log(Level.WARNING, "Failed to close database connection!", e);
  241. }
  242. }
  243. public int getBusyConnectionCount() throws SQLException
  244. {
  245. return _source.getNumBusyConnectionsDefaultUser();
  246. }
  247. public int getIdleConnectionCount() throws SQLException
  248. {
  249. return _source.getNumIdleConnectionsDefaultUser();
  250. }
  251. public final ProviderType getProviderType()
  252. {
  253. return _providerType;
  254. }
  255. }