public static Connection connectWithC3p0() { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (ClassNotFoundException cnfe) { System.err.println("Error: " + cnfe.getMessage()); } catch (InstantiationException ie) { System.err.println("Error: " + ie.getMessage()); } catch (IllegalAccessException iae) { System.err.println("Error: " + iae.getMessage()); } ComboPooledDataSource cpds = getC3p0(); try { if (con != null && !con.isClosed()) { con.close(); con = null; } con = cpds.getConnection(); } catch (SQLException ex) { ex.printStackTrace(); } System.out.println("Returning c3p0 Connection " + con); return con; }
/** * 从连接池中取出链接。 * * @return */ public synchronized Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { System.exit(0); } return null; }
/** 测试数据库连接池 */ private static void testConnection(ComboPooledDataSource dataSource) throws ServerInitException { try { Connection connection = dataSource.getConnection(); connection.close(); } catch (SQLException e) { throw new ServerInitException("初始化数据库连接池失败!", e); } }
/** * 获取连接 * * @return */ public final synchronized Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; }
// 获得连接 public static Connection getConnection() { Connection conn = null; try { conn = dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return conn; }
/** * Returns a new pooled SQL Connection object. * * @return */ public Connection openConnection() { if (!initDone) { init(); } try { return pool.getConnection(); } catch (Exception e) { throw new RuntimeException(e); } }
@Override public Connection getConnection() throws CacheLoaderException { try { logBefore(true); Connection connection = pooledDataSource.getConnection(); logAfter(connection, true); return connection; } catch (SQLException e) { throw new CacheLoaderException("Failed obtaining connection from PooledDataSource", e); } }
/** * 取得資料庫連結時的連線 * * @return Connection 連結對象 * @throws SQLException */ public Connection getConnection() { Connection con = null; while (con == null) { try { con = _source.getConnection(); } catch (SQLException e) { _log.warning("L1DatabaseFactory: getConnection() failed, trying again " + e); } } return Config.DETECT_DB_RESOURCE_LEAKS ? LeakCheckedConnection.create(con) : con; }
/** 存储过程执行(增删改),返回影响记录条数. */ public int spExecute(String sql) { Connection con = null; CallableStatement stat = null; try { con = cpds.getConnection(); stat = con.prepareCall(sql); int num = stat.executeUpdate(); return num; } catch (SQLException e) { throw new RuntimeException(e); } finally { close(stat, con, null); } }
public final Connection getConnection() { try { // log.debug("从连接池中获取连接开始!"+connMgmt.getClass().toString()+" // 内存块:"+connMgmt.toString()+"连接数:"+cds.getNumConnections()); Connection conn = cds.getConnection(); // log.debug("从连接池中获取到了连接!"+connMgmt.getClass().toString()+" // 内存块:"+connMgmt.toString()+"连接数:"+cds.getNumConnections()); return conn; } catch (SQLException e) { e.printStackTrace(); } return null; }
/** sql语句查询,返回指定类型查询结果(默认List<Map<String,Object>>). */ public Object query(String sql, String resultType) { Connection con = null; PreparedStatement stat = null; ResultSet rs = null; try { con = cpds.getConnection(); stat = con.prepareStatement(sql); rs = stat.executeQuery(); // 执行语句 return getResult(rs, resultType); // 封装结果 } catch (SQLException e) { throw new RuntimeException(e); } finally { close(stat, con, rs); } }
@Override public Connection getAnyConnection() throws SQLException { ComboPooledDataSource cpds = connProviderMap.get(CurrentTenantResolver.DEFAULT_TENANT_ID); logger.debug( "Get Default Connection:::Number of connections (max: busy - idle): {} : {} - {}", new int[] { cpds.getMaxPoolSize(), cpds.getNumBusyConnectionsAllUsers(), cpds.getNumIdleConnectionsAllUsers() }); if (cpds.getNumConnectionsAllUsers() == cpds.getMaxPoolSize()) { logger.warn("Maximum number of connections opened"); } if (cpds.getNumConnectionsAllUsers() == cpds.getMaxPoolSize() && cpds.getNumIdleConnectionsAllUsers() == 0) { logger.error("Connection pool empty!"); } return cpds.getConnection(); }
public Connection getConnection(AccessConfiguration configuration) throws DAOException { init(configuration); Connection connection = null; try { if (logger.isTraceEnabled()) logger.trace("Getting connection from pool "); if (logger.isTraceEnabled()) logger.trace(" getMaxPoolSize: " + cpds.getMaxPoolSize()); if (logger.isTraceEnabled()) logger.trace(" getNumConnections: " + cpds.getNumConnections()); if (logger.isTraceEnabled()) logger.trace(" getNumBusyConnections: " + cpds.getNumBusyConnections()); connection = cpds.getConnection(); if (logger.isTraceEnabled()) logger.trace("Opened connections: " + cpds.getNumConnections()); } catch (SQLException sqle) { close(connection); throw new DAOException( " getConnection: " + sqle + "\n\ndriver: " + configuration.getDriver() + " - uri: " + configuration.getUri() + " - login: "******" - password: "******"\n"); } if (connection == null) { throw new DAOException( "Connection is NULL !" + "\n\ndriver: " + configuration.getDriver() + " - uri: " + configuration.getUri() + " - login: "******" - password: "******"\n"); } return connection; }
/** * 資料庫連結的設定與配置 * * @throws SQLException */ public L1DatabaseFactory() throws SQLException { try { // DatabaseFactoryをL2Jから一部を除いて拝借 _source = new ComboPooledDataSource(); _source.setDriverClass(_driver); _source.setJdbcUrl(_url); _source.setUser(_user); _source.setPassword(_password); /* Test the connection */ _source.getConnection().close(); } catch (SQLException x) { _log.fine("Database Connection FAILED"); // rethrow the exception throw x; } catch (Exception e) { _log.fine("Database Connection FAILED"); throw new SQLException("could not init DB connection:" + e); } }
/** sql语句批量执行(增删改),返回影响记录总条数. */ public int execute(List<String> sqls) { Connection con = null; Statement stat = null; try { con = cpds.getConnection(); stat = con.createStatement(); for (String sql : sqls) { stat.addBatch(sql); } int[] is = stat.executeBatch(); int count = 0; for (int i : is) { count += i; } return count; } catch (SQLException e) { throw new RuntimeException(e); } finally { close(stat, con, null); } }
/** sql语句执行(增删改),返回指定类型查询结果(默认影响记录条数,可选pk-主键). */ public Object execute(String sql, String resultType) { Connection con = null; PreparedStatement stat = null; ResultSet rs = null; try { con = cpds.getConnection(); if ("pk".equals(resultType)) { stat = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stat.execute(); rs = stat.getGeneratedKeys(); return rs.next() ? rs.getObject(1) : null; } else { stat = con.prepareStatement(sql); return stat.executeUpdate(); } } catch (SQLException e) { throw new RuntimeException(e); } finally { close(stat, con, rs); } }
@Override public Connection getConnection(String tenantIdentifier) throws SQLException { ComboPooledDataSource cpds = connProviderMap.get(tenantIdentifier); logger.debug( "Get {} Connection:::Number of connections (max: busy - idle): {} : {} - {}", new Object[] { tenantIdentifier, cpds.getMaxPoolSize(), cpds.getNumBusyConnectionsAllUsers(), cpds.getNumIdleConnectionsAllUsers() }); if (cpds.getNumConnectionsAllUsers() == cpds.getMaxPoolSize()) { logger.warn("Maximum number of connections opened"); } if (cpds.getNumConnectionsAllUsers() == cpds.getMaxPoolSize() && cpds.getNumIdleConnectionsAllUsers() == 0) { logger.error("Connection pool empty!"); } return cpds.getConnection(); // return cpds.getConnection(tenantIdentifier, (String) props.get(tenantIdentifier)); }
public HappeningsTask(DatabaseAccess access, NationStates api, HealthMonitor health) { this.api = api; this.pool = access.getPool(); this.access = access; this.monitor = health; Connection conn = null; PreparedStatement state = null; ResultSet result = null; try { conn = pool.getConnection(); state = conn.prepareStatement("SELECT last_event_id FROM assembly.settings WHERE id = 1"); result = state.executeQuery(); result.next(); maxEventId = result.getInt(1); } catch (SQLException e) { throw new RuntimeException(e); } finally { DbUtils.closeQuietly(result); DbUtils.closeQuietly(state); DbUtils.closeQuietly(conn); } }
/** 文件保存,返回主键,sql中文件字段用?表示. */ public Object fileExecute(String sql, InputStream inputStream) { Connection con = null; PreparedStatement stat = null; ResultSet rs = null; try { con = cpds.getConnection(); stat = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); stat.setBinaryStream(1, inputStream, inputStream.available()); stat.execute(); rs = stat.getGeneratedKeys(); return rs.next() ? rs.getObject(1) : null; } catch (SQLException | IOException e) { throw new RuntimeException(e); } finally { try { inputStream.close(); // TODO 是否能自动关闭? } catch (IOException e) { throw new RuntimeException(e); } close(stat, con, rs); } }
@Test public void testComboPooledDataSource() throws Exception { String url = "jdbc:mysql://10.112.1.110:3306/test_mysql"; String driver = "com.mysql.jdbc.Driver"; String user = "******"; String passwd = "111111"; ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setDriverClass(driver); cpds.setJdbcUrl(url); cpds.setUser(user); cpds.setPassword(passwd); cpds.setMinPoolSize(5); cpds.setAcquireIncrement(5); cpds.setMaxPoolSize(30); cpds.setMaxIdleTime(60); Connection con = cpds.getConnection(); System.out.println("Get Connection Success!!! " + con); }
/** 构造. */ public DataBaseHandle( String driver, String url, String user, String password, Integer maxPoolSize) { try { // 创建连接池 cpds = new ComboPooledDataSource(); // 用户设置 cpds.setDriverClass(driver); // 驱动 cpds.setJdbcUrl(url); // 连接字符串 cpds.setUser(user); // 用户名 cpds.setPassword(password); // 密码 cpds.setMaxPoolSize(maxPoolSize); // 连接池中保留的最大连接数(默认:15) // 默认设置 cpds.setMinPoolSize(1); // 连接池中保留的最小连接数(默认:0) cpds.setInitialPoolSize(1); // 初始化时获取几个连接,取值应在minPoolSize与maxPoolSize之间(默认:3) cpds.setAcquireIncrement(1); // 当连接池中的连接耗尽的时候c3p0一次同时获取的连接数(默认:3) cpds.setCheckoutTimeout( 1000); // 当连接池用完时客户端调用getConnection()后等待获取新连接的时间,超时后将抛出SQLException,如设为0则无限期等待,单位毫秒(默认:0) cpds.setMaxIdleTime(25000); // 最大空闲时间,定义多少秒内未使用则连接被丢弃,若为0则永不丢弃(默认:0) cpds.setIdleConnectionTestPeriod(18000); // 隔多少秒检查所有连接池中的空闲连接,0表示不检查(默认:0) cpds.setDebugUnreturnedConnectionStackTraces( true); // 启用之后(true),对于每个从连接池拿出去的数据库连接,如果一段时间(unreturnedConnectionTimeout)内没有归还,C3P0就会强制关闭这个连接,并将获取连接时的stack trace,以抛出异常的方式显示出来(默认:false) cpds.setUnreturnedConnectionTimeout( 600); // 用于设置开启debugUnreturnedConnectionStackTraces后的超时时间(单位:秒) cpds.setTestConnectionOnCheckin(true); // 如果设为true那么在取得连接的同时将校验连接的有效性(默认:false) cpds.setMaxStatements( 100); // JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量,但由于预缓存的statements属于单个connection而不是整个连接池,所以设置这个参数需要考虑到多方面的因素。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭(默认:0) cpds.setAutomaticTestTable( "T_TEST_C3P0"); // c3p0将建一张名为T_TEST_C3P0的空表,并使用其自带的查询语句进行测试。如果定义了这个参数那么属性preferredTestQuery将被忽略。你不能在这张Test表上进行任何操作,它将只供c3p0测试使用(默认: null) // 取连接(测试) cpds.getConnection().close(); } catch (Throwable e) { throw new RuntimeException("连接池创建失败", e); } }
/** * Detects changes and reconfigures this dbConfig. Returns true if the database was configured * (Config info present. An exception is throwns if the config process fails. */ protected boolean configure() { // prefix used before all properties when loafing config. default is 'db' String propsPrefix; if (defaultDbConfigName.equals(dbConfigName)) { propsPrefix = "db"; } else { propsPrefix = "db_" + dbConfigName; } boolean dbConfigured = false; if (changed(propsPrefix)) { try { // We now know that we will either config the db, or fail with exception dbConfigured = true; Properties p = Play.configuration; if (datasource != null) { destroy(); } if (p.getProperty(propsPrefix, "").startsWith("java:")) { Context ctx = new InitialContext(); datasource = (DataSource) ctx.lookup(p.getProperty(propsPrefix)); } else { // Try the driver String driver = p.getProperty(propsPrefix + ".driver"); try { Driver d = (Driver) Class.forName(driver, true, Play.classloader).newInstance(); DriverManager.registerDriver(new ProxyDriver(d)); } catch (Exception e) { throw new Exception("Driver not found (" + driver + ")"); } // Try the connection Connection fake = null; try { if (p.getProperty(propsPrefix + ".user") == null) { fake = DriverManager.getConnection(p.getProperty(propsPrefix + ".url")); } else { fake = DriverManager.getConnection( p.getProperty(propsPrefix + ".url"), p.getProperty(propsPrefix + ".user"), p.getProperty(propsPrefix + ".pass")); } } finally { if (fake != null) { fake.close(); } } ComboPooledDataSource ds = new ComboPooledDataSource(); ds.setDriverClass(p.getProperty(propsPrefix + ".driver")); ds.setJdbcUrl(p.getProperty(propsPrefix + ".url")); ds.setUser(p.getProperty(propsPrefix + ".user")); ds.setPassword(p.getProperty(propsPrefix + ".pass")); ds.setAcquireRetryAttempts(10); ds.setCheckoutTimeout( Integer.parseInt(p.getProperty(propsPrefix + ".pool.timeout", "5000"))); ds.setBreakAfterAcquireFailure(false); ds.setMaxPoolSize(Integer.parseInt(p.getProperty(propsPrefix + ".pool.maxSize", "30"))); ds.setMinPoolSize(Integer.parseInt(p.getProperty(propsPrefix + ".pool.minSize", "1"))); ds.setMaxIdleTimeExcessConnections( Integer.parseInt( p.getProperty(propsPrefix + ".pool.maxIdleTimeExcessConnections", "0"))); ds.setIdleConnectionTestPeriod(10); ds.setTestConnectionOnCheckin(true); datasource = ds; url = ds.getJdbcUrl(); Connection c = null; try { c = ds.getConnection(); } finally { if (c != null) { c.close(); } } Logger.info("Connected to %s", ds.getJdbcUrl()); } destroyMethod = p.getProperty(propsPrefix + ".destroyMethod", ""); } catch (Exception e) { datasource = null; Logger.error( e, "Cannot connected to the database" + getConfigInfoString() + " : %s", e.getMessage()); if (e.getCause() instanceof InterruptedException) { throw new DatabaseException( "Cannot connected to the database" + getConfigInfoString() + ". Check the configuration.", e); } throw new DatabaseException( "Cannot connected to the database" + getConfigInfoString() + ", " + e.getMessage(), e); } } return dbConfigured; }
public static void main(String[] argv) { try { ComboPooledDataSource cpds = new ComboPooledDataSource(); cpds.setJdbcUrl(argv[0]); cpds.setUser(argv[1]); cpds.setPassword(argv[2]); cpds.setMinPoolSize(5); cpds.setAcquireIncrement(5); cpds.setMaxPoolSize(20); System.err.println("Initial..."); display(cpds); Thread.sleep(2000); HashSet hs = new HashSet(); for (int i = 0; i < 20; ++i) { Connection c = cpds.getConnection(); hs.add(c); System.err.println("Adding (" + (i + 1) + ") " + c); display(cpds); Thread.sleep(1000); // if (i == 9) // { // //System.err.println("hardReset()ing"); // //cpds.hardReset(); // System.err.println("softReset()ing"); // cpds.softReset(); // } } int count = 0; for (Iterator ii = hs.iterator(); ii.hasNext(); ) { Connection c = ((Connection) ii.next()); System.err.println("Removing " + ++count); ii.remove(); try { c.getMetaData().getTables(null, null, "PROBABLYNOT", new String[] {"TABLE"}); } catch (Exception e) { System.err.println(e); System.err.println(); continue; } finally { c.close(); } Thread.sleep(2000); display(cpds); } System.err.println( "Closing data source, \"forcing\" garbage collection, and sleeping for 5 seconds..."); cpds.close(); System.gc(); System.err.println("Main Thread: Sleeping for five seconds!"); Thread.sleep(5000); // System.gc(); // Thread.sleep(5000); System.err.println("Bye!"); } catch (Exception e) { e.printStackTrace(); } }
/** * Get Cached Connection * * @param connection info * @param autoCommit true if autocommit connection * @param transactionIsolation Connection transaction level * @return connection or null * @throws Exception */ @Override public Connection getCachedConnection( CConnection connection, boolean autoCommit, int transactionIsolation) throws Exception { Connection conn = null; Exception exception = null; try { if (m_ds == null) getDataSource(connection); // try { conn = m_ds.getConnection(); if (conn != null) { if (conn.getTransactionIsolation() != transactionIsolation) conn.setTransactionIsolation(transactionIsolation); if (conn.getAutoCommit() != autoCommit) conn.setAutoCommit(autoCommit); // conn.setDefaultRowPrefetch(20); // 10 default - reduces round // trips } } catch (Exception e) { exception = e; conn = null; if (DBException.isInvalidUserPassError(e)) { // log might cause infinite loop since it will try to acquire database connection again /* log.severe("Cannot connect to database: " + getConnectionURL(connection) + " - UserID=" + connection.getDbUid()); */ System.err.println( "Cannot connect to database: " + getConnectionURL(connection) + " - UserID=" + connection.getDbUid()); } } if (conn == null && exception != null) { // log might cause infinite loop since it will try to acquire database connection again /* log.log(Level.SEVERE, exception.toString()); log.fine(toString()); */ System.err.println(exception.toString()); } } catch (Exception e) { exception = e; } try { if (conn != null) { int numConnections = m_ds.getNumBusyConnections(); if (numConnections >= m_maxbusyconnections && m_maxbusyconnections > 0) { log.warning(getStatus()); // hengsin: make a best effort to reclaim leak connection Runtime.getRuntime().runFinalization(); } } } catch (Exception ex) { } if (exception != null) throw exception; return conn; } // getCachedConnection
public static Connection getConnection() throws SQLException { return ds.getConnection(); }
public void runImpl() { if (monitor != null) monitor.happeningHeartbeat(); HappeningData data; synchronized (api) { // Throttle the happening queries based on how many new happenings occurred last run if (lastRun + Duration.standardSeconds(10).getMillis() > System.currentTimeMillis()) { final int activity = this.highActivity.get(); if (newEvents >= 50 || activity > 0) { Logger.info("Very high happenings activity, running at 2s intervals"); this.highActivity.set(newEvents >= 50 ? 10 : activity - 1); } else { Logger.debug( "Skipping happening run, little activity, last run was " + (System.currentTimeMillis() - lastRun) + " ms ago"); return; } } lastRun = System.currentTimeMillis() + Duration.standardSeconds(1).getMillis(); newEvents = 0; Logger.info("Executing global happenings run. Max Event ID: " + maxEventId); try { data = api.getHappeningInfo(null, -1, maxEventId); } catch (RateLimitReachedException e) { Logger.warn("Happenings monitoring rate limited!"); return; } final int oldEventId = maxEventId; for (EventHappening happening : data.happenings) { if (maxEventId < happening.eventId) { maxEventId = happening.eventId; } if (oldEventId < happening.eventId) { newEvents++; } } } Connection conn = null; PreparedStatement happeningInsert = null; try { conn = pool.getConnection(); PreparedStatement state = conn.prepareStatement("UPDATE assembly.settings SET last_event_id = ? WHERE id = 1"); state.setInt(1, maxEventId); state.executeUpdate(); DbUtils.closeQuietly(state); happeningInsert = conn.prepareStatement( "INSERT INTO assembly.global_happenings (nation, happening, timestamp, type) VALUES (?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); for (EventHappening happening : data.happenings) { final String text = happening.text; final long timestamp = happening.timestamp * 1000; Matcher match = Utils.NATION_PATTERN.matcher(text); int nationId = -1; String nation = ""; if (match.find()) { String title = text.substring(match.start() + 2, match.end() - 2); nation = Utils.sanitizeName(title); nationId = access.getNationIdCache().get(nation); if (nationId == -1) { PreparedStatement insert = conn.prepareStatement( "INSERT INTO assembly.nation (name, title, full_name, region, first_seen, wa_member) VALUES (?, ?, ?, ?, ?, 2)", Statement.RETURN_GENERATED_KEYS); insert.setString(1, nation); insert.setString(2, title); insert.setString(3, WordUtils.capitalizeFully(nation.replaceAll("_", " "))); insert.setInt(4, -1); insert.setLong(5, happening.timestamp); insert.executeUpdate(); ResultSet keys = insert.getGeneratedKeys(); keys.next(); nationId = keys.getInt(1); access.getNationIdCache().put(nation, nationId); DbUtils.closeQuietly(keys); DbUtils.closeQuietly(insert); } } final int happeningType = HappeningType.match(text); final HappeningType type = HappeningType.getType(happeningType); if (happeningType == HappeningType.getType("ENDORSEMENT").getId()) { if (match.find()) { String title = text.substring(match.start() + 2, match.end() - 2); String otherNation = Utils.sanitizeName(title); addEndorsement(conn, access.getNationIdCache().get(otherNation), nationId); // Add *was endorsed by* to db happeningInsert.setInt(1, access.getNationIdCache().get(otherNation)); happeningInsert.setString( 2, "@@" + otherNation + "@@ was endorsed by @@" + nation + "@@."); happeningInsert.setLong(3, timestamp); happeningInsert.setInt(4, happeningType); happeningInsert.executeUpdate(); } } else if (happeningType == HappeningType.getType("WITHDREW_ENDORSEMENT").getId()) { if (match.find()) { String title = text.substring(match.start() + 2, match.end() - 2); String otherNation = Utils.sanitizeName(title); removeEndorsement(conn, access.getNationIdCache().get(otherNation), nationId); } } else if (happeningType == HappeningType.getType("LOST_ENDORSEMENT").getId()) { if (match.find()) { String title = text.substring(match.start() + 2, match.end() - 2); String otherNation = Utils.sanitizeName(title); removeEndorsement(conn, nationId, access.getNationIdCache().get(otherNation)); } } else if (happeningType == HappeningType.getType("RESIGNED_FROM_WORLD_ASSEMBLY").getId()) { resignFromWorldAssembly(conn, nationId, false); } else if (happeningType == HappeningType.getType("ADMITTED_TO_WORLD_ASSEMBLY").getId()) { joinWorldAssembly(conn, nationId); } else if (happeningType == HappeningType.getType("EJECTED_FOR_RULE_VIOLATIONS").getId()) { resignFromWorldAssembly(conn, nationId, true); } else if (happeningType == HappeningType.getType("ABOLISHED_REGIONAL_FLAG").getId()) { abolishRegionFlag(conn, access, text); } else if (happeningType == HappeningType.getType("RELOCATED").getId()) { relocateNation(conn, nationId, nation, text); } else if (updateCache.getIfPresent(nationId) == null && happeningType == HappeningType.getType("NEW_LEGISLATION").getId()) { setRegionUpdateTime(conn, nationId, timestamp); updateCache.put(nationId, true); } else if (nationId > -1 && (happeningType == HappeningType.getType("REFOUNDED").getId() || happeningType == HappeningType.getType("FOUNDED").getId())) { if (happeningType == HappeningType.getType("REFOUNDED").getId()) { // Ensure nation is dead access.markNationDead(nationId, conn); // Only erase flag if it was user uploaded PreparedStatement flag = conn.prepareStatement("SELECT flag FROM assembly.nation WHERE id = ?"); flag.setInt(1, nationId); ResultSet set = flag.executeQuery(); boolean eraseFlag = set.next() && set.getString(1).contains("/uploads/"); DbUtils.closeQuietly(set); DbUtils.closeQuietly(flag); PreparedStatement alive = conn.prepareStatement( "UPDATE assembly.nation SET alive = 1, wa_member = 2" + (eraseFlag ? ", flag = ?" : "") + " WHERE id = ?"); if (eraseFlag) { alive.setString(1, "http://nationstates.net/images/flags/Default.png"); alive.setInt(2, nationId); } else { alive.setInt(1, nationId); } alive.executeUpdate(); DbUtils.closeQuietly(alive); } // Update region Matcher regions = Utils.REGION_PATTERN.matcher(text); if (regions.find()) { final int regionId = access .getRegionIdCache() .get(text.substring(regions.start() + 2, regions.end() - 2)); if (regionId > -1) { PreparedStatement update = conn.prepareStatement( "UPDATE assembly.nation SET region = ?, wa_member = 2, puppet = ? WHERE id = ?"); update.setInt(1, regionId); update.setInt(2, puppetCache.getIfPresent(nation) != null ? 1 : 0); update.setInt(3, nationId); update.executeUpdate(); DbUtils.closeQuietly(update); if (puppetCache.getIfPresent(nation) != null) { String defaultSettings = "{\"settings\":{\"show_gameplay_news\":false,\"show_roleplay_news\":false,\"show_regional_news\":false,\"show_irc\":false,\"show_world_census\":false,\"show_regional_population\":false,},\"last_update\":" + System.currentTimeMillis() + "}"; PreparedStatement insert = conn.prepareStatement( "INSERT INTO assembly.ns_settings (id, settings, last_settings_update) VALUES (?, ?, ?)"); insert.setInt(1, nationId); insert.setString(2, defaultSettings); insert.setLong(3, System.currentTimeMillis()); insert.executeUpdate(); DbUtils.closeQuietly(insert); puppetCache.invalidate(nation); } } } } else if (nationId > -1 && happeningType == HappeningType.getType("CEASED_TO_EXIST").getId()) { access.markNationDead(nationId, conn); } happeningInsert.setInt(1, nationId); happeningInsert.setString(2, parseHappening(text)); happeningInsert.setLong(3, timestamp); happeningInsert.setInt(4, happeningType); happeningInsert.executeUpdate(); ResultSet keys = happeningInsert.getGeneratedKeys(); keys.next(); int happeningId = keys.getInt(1); if (type != null) { updateRegionHappenings(conn, access, nationId, happeningId, text, type); } DbUtils.closeQuietly(keys); } } catch (SQLException e) { Logger.error("Unable to update happenings", e); } catch (ExecutionException e) { Logger.error("Unable to update happenings", e); } finally { DbUtils.closeQuietly(happeningInsert); DbUtils.closeQuietly(conn); } }