L2DatabaseFactory.java 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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.PreparedStatement;
  18. import java.sql.SQLException;
  19. import java.util.concurrent.Executors;
  20. import java.util.concurrent.ScheduledExecutorService;
  21. import java.util.concurrent.TimeUnit;
  22. import java.util.logging.Level;
  23. import java.util.logging.Logger;
  24. import com.l2jserver.gameserver.ThreadPoolManager;
  25. import com.mchange.v2.c3p0.ComboPooledDataSource;
  26. /**
  27. * This class manages the database connections.
  28. */
  29. public class L2DatabaseFactory
  30. {
  31. private static final Logger _log = Logger.getLogger(L2DatabaseFactory.class.getName());
  32. /**
  33. * The Enum ProviderType.
  34. */
  35. private static enum ProviderType
  36. {
  37. MySql,
  38. MsSql
  39. }
  40. private static L2DatabaseFactory _instance;
  41. private static volatile ScheduledExecutorService _executor;
  42. private ProviderType _providerType;
  43. private ComboPooledDataSource _source;
  44. /**
  45. * Instantiates a new l2 database factory.
  46. * @throws SQLException the SQL exception
  47. */
  48. public L2DatabaseFactory() throws SQLException
  49. {
  50. try
  51. {
  52. if (Config.DATABASE_MAX_CONNECTIONS < 2)
  53. {
  54. Config.DATABASE_MAX_CONNECTIONS = 2;
  55. _log.warning("A minimum of " + Config.DATABASE_MAX_CONNECTIONS + " db connections are required.");
  56. }
  57. _source = new ComboPooledDataSource();
  58. _source.setAutoCommitOnClose(true);
  59. _source.setInitialPoolSize(10);
  60. _source.setMinPoolSize(10);
  61. _source.setMaxPoolSize(Math.max(10, Config.DATABASE_MAX_CONNECTIONS));
  62. _source.setAcquireRetryAttempts(0); // try to obtain connections indefinitely (0 = never quit)
  63. _source.setAcquireRetryDelay(500); // 500 milliseconds wait before try to acquire connection again
  64. _source.setCheckoutTimeout(0); // 0 = wait indefinitely for new connection
  65. // if pool is exhausted
  66. _source.setAcquireIncrement(5); // if pool is exhausted, get 5 more connections at a time
  67. // cause there is a "long" delay on acquire connection
  68. // so taking more than one connection at once will make connection pooling
  69. // more effective.
  70. // this "connection_test_table" is automatically created if not already there
  71. _source.setAutomaticTestTable("connection_test_table");
  72. _source.setTestConnectionOnCheckin(false);
  73. // testing OnCheckin used with IdleConnectionTestPeriod is faster than testing on checkout
  74. _source.setIdleConnectionTestPeriod(3600); // test idle connection every 60 sec
  75. _source.setMaxIdleTime(Config.DATABASE_MAX_IDLE_TIME); // 0 = idle connections never expire
  76. // *THANKS* to connection testing configured above
  77. // but I prefer to disconnect all connections not used
  78. // for more than 1 hour
  79. // enables statement caching, there is a "semi-bug" in c3p0 0.9.0 but in 0.9.0.2 and later it's fixed
  80. _source.setMaxStatementsPerConnection(100);
  81. _source.setBreakAfterAcquireFailure(false); // never fail if any way possible
  82. // setting this to true will make
  83. // c3p0 "crash" and refuse to work
  84. // till restart thus making acquire
  85. // errors "FATAL" ... we don't want that
  86. // it should be possible to recover
  87. _source.setDriverClass(Config.DATABASE_DRIVER);
  88. _source.setJdbcUrl(Config.DATABASE_URL);
  89. _source.setUser(Config.DATABASE_LOGIN);
  90. _source.setPassword(Config.DATABASE_PASSWORD);
  91. /* Test the connection */
  92. _source.getConnection().close();
  93. if (Config.DEBUG)
  94. {
  95. _log.fine("Database Connection Working");
  96. }
  97. if (Config.DATABASE_DRIVER.toLowerCase().contains("microsoft"))
  98. {
  99. _providerType = ProviderType.MsSql;
  100. }
  101. else
  102. {
  103. _providerType = ProviderType.MySql;
  104. }
  105. }
  106. catch (SQLException x)
  107. {
  108. if (Config.DEBUG)
  109. {
  110. _log.fine("Database Connection FAILED");
  111. }
  112. // re-throw the exception
  113. throw x;
  114. }
  115. catch (Exception e)
  116. {
  117. if (Config.DEBUG)
  118. {
  119. _log.fine("Database Connection FAILED");
  120. }
  121. throw new SQLException("Could not init DB connection:" + e.getMessage());
  122. }
  123. }
  124. /**
  125. * Prepared query select.
  126. * @param fields the fields
  127. * @param tableName the table name
  128. * @param whereClause the where clause
  129. * @param returnOnlyTopRecord the return only top record
  130. * @return the string
  131. */
  132. public final String prepQuerySelect(String[] fields, String tableName, String whereClause, boolean returnOnlyTopRecord)
  133. {
  134. String msSqlTop1 = "";
  135. String mySqlTop1 = "";
  136. if (returnOnlyTopRecord)
  137. {
  138. if (getProviderType() == ProviderType.MsSql)
  139. {
  140. msSqlTop1 = " Top 1 ";
  141. }
  142. if (getProviderType() == ProviderType.MySql)
  143. {
  144. mySqlTop1 = " Limit 1 ";
  145. }
  146. }
  147. String query = "SELECT " + msSqlTop1 + safetyString(fields) + " FROM " + tableName + " WHERE " + whereClause + mySqlTop1;
  148. return query;
  149. }
  150. /**
  151. * Shutdown.
  152. */
  153. public void shutdown()
  154. {
  155. try
  156. {
  157. _source.close();
  158. }
  159. catch (Exception e)
  160. {
  161. _log.log(Level.INFO, "", e);
  162. }
  163. try
  164. {
  165. _source = null;
  166. }
  167. catch (Exception e)
  168. {
  169. _log.log(Level.INFO, "", e);
  170. }
  171. }
  172. /**
  173. * Safety string.
  174. * @param whatToCheck the what to check
  175. * @return the string
  176. */
  177. public final String safetyString(String... whatToCheck)
  178. {
  179. // NOTE: Use brace as a safety precaution just in case name is a reserved word
  180. final char braceLeft;
  181. final char braceRight;
  182. if (getProviderType() == ProviderType.MsSql)
  183. {
  184. braceLeft = '[';
  185. braceRight = ']';
  186. }
  187. else
  188. {
  189. braceLeft = '`';
  190. braceRight = '`';
  191. }
  192. int length = 0;
  193. for (String word : whatToCheck)
  194. {
  195. length += word.length() + 4;
  196. }
  197. final StringBuilder sbResult = new StringBuilder(length);
  198. for (String word : whatToCheck)
  199. {
  200. if (sbResult.length() > 0)
  201. {
  202. sbResult.append(", ");
  203. }
  204. sbResult.append(braceLeft);
  205. sbResult.append(word);
  206. sbResult.append(braceRight);
  207. }
  208. return sbResult.toString();
  209. }
  210. /**
  211. * Gets the single instance of L2DatabaseFactory.
  212. * @return single instance of L2DatabaseFactory
  213. * @throws SQLException the SQL exception
  214. */
  215. public static L2DatabaseFactory getInstance() throws SQLException
  216. {
  217. synchronized (L2DatabaseFactory.class)
  218. {
  219. if (_instance == null)
  220. {
  221. _instance = new L2DatabaseFactory();
  222. }
  223. }
  224. return _instance;
  225. }
  226. /**
  227. * Gets the connection.
  228. * @return the connection
  229. */
  230. public Connection getConnection()
  231. {
  232. Connection con = null;
  233. while (con == null)
  234. {
  235. try
  236. {
  237. con = _source.getConnection();
  238. if (Server.serverMode == Server.MODE_GAMESERVER)
  239. {
  240. ThreadPoolManager.getInstance().scheduleGeneral(new ConnectionCloser(con, new RuntimeException()), Config.CONNECTION_CLOSE_TIME);
  241. }
  242. else
  243. {
  244. getExecutor().schedule(new ConnectionCloser(con, new RuntimeException()), 60, TimeUnit.SECONDS);
  245. }
  246. }
  247. catch (SQLException e)
  248. {
  249. _log.log(Level.WARNING, "L2DatabaseFactory: getConnection() failed, trying again " + e.getMessage(), e);
  250. }
  251. }
  252. return con;
  253. }
  254. /**
  255. * The Class ConnectionCloser.
  256. */
  257. private static class ConnectionCloser implements Runnable
  258. {
  259. private static final Logger _log = Logger.getLogger(ConnectionCloser.class.getName());
  260. /** The connection. */
  261. private final Connection c;
  262. /** The exception. */
  263. private final RuntimeException exp;
  264. /**
  265. * Instantiates a new connection closer.
  266. * @param con the con
  267. * @param e the e
  268. */
  269. public ConnectionCloser(Connection con, RuntimeException e)
  270. {
  271. c = con;
  272. exp = e;
  273. }
  274. @Override
  275. public void run()
  276. {
  277. try
  278. {
  279. if (!c.isClosed())
  280. {
  281. _log.log(Level.WARNING, "Unclosed connection! Trace: " + exp.getStackTrace()[1], exp);
  282. }
  283. }
  284. catch (SQLException e)
  285. {
  286. _log.log(Level.WARNING, "", e);
  287. }
  288. }
  289. }
  290. /**
  291. * Close the connection.
  292. * @param con the con the connection
  293. * @deprecated now database connections are closed using try-with-resource.
  294. */
  295. @Deprecated
  296. public static void close(Connection con)
  297. {
  298. if (con == null)
  299. {
  300. return;
  301. }
  302. try
  303. {
  304. con.close();
  305. }
  306. catch (SQLException e)
  307. {
  308. _log.log(Level.WARNING, "Failed to close database connection!", e);
  309. }
  310. }
  311. /**
  312. * Gets the executor.
  313. * @return the executor
  314. */
  315. private static ScheduledExecutorService getExecutor()
  316. {
  317. if (_executor == null)
  318. {
  319. synchronized (L2DatabaseFactory.class)
  320. {
  321. if (_executor == null)
  322. {
  323. _executor = Executors.newSingleThreadScheduledExecutor();
  324. }
  325. }
  326. }
  327. return _executor;
  328. }
  329. /**
  330. * Gets the busy connection count.
  331. * @return the busy connection count
  332. * @throws SQLException the SQL exception
  333. */
  334. public int getBusyConnectionCount() throws SQLException
  335. {
  336. return _source.getNumBusyConnectionsDefaultUser();
  337. }
  338. /**
  339. * Gets the idle connection count.
  340. * @return the idle connection count
  341. * @throws SQLException the SQL exception
  342. */
  343. public int getIdleConnectionCount() throws SQLException
  344. {
  345. return _source.getNumIdleConnectionsDefaultUser();
  346. }
  347. /**
  348. * Gets the provider type.
  349. * @return the provider type
  350. */
  351. public final ProviderType getProviderType()
  352. {
  353. return _providerType;
  354. }
  355. /**
  356. * Designed to execute simple db operations like INSERT, UPDATE, DELETE.
  357. * @param query
  358. * @param params
  359. * @throws SQLException
  360. */
  361. public void executeQuery(String query, Object... params) throws SQLException
  362. {
  363. try (Connection con = getConnection();
  364. PreparedStatement st = con.prepareStatement(query))
  365. {
  366. for (int i = 0; i < params.length; i++)
  367. {
  368. st.setObject(i + 1, params[i]);
  369. }
  370. st.execute();
  371. }
  372. }
  373. }