@Override public boolean isAvailable() { if (tableManager == null || connectionFactory == null) return false; Connection connection = null; try { connection = connectionFactory.getConnection(); return connection != null && connection.isValid(10); } catch (SQLException e) { return false; } finally { connectionFactory.releaseConnection(connection); } }
@Override public void close() { connectionFactory.stop(); }
@BeforeClass public void createConnection() throws Exception { JdbcStringBasedStoreConfigurationBuilder storeBuilder = TestCacheManagerFactory .getDefaultCacheConfiguration(false) .persistence() .addStore(JdbcStringBasedStoreConfigurationBuilder.class); UnitTestDatabaseManager.setDialect(storeBuilder); UnitTestDatabaseManager.buildTableManipulation(storeBuilder.table()); ConnectionFactoryConfiguration factoryConfiguration = UnitTestDatabaseManager.configureUniqueConnectionFactory(storeBuilder).create(); if (factoryConfiguration instanceof SimpleConnectionFactoryConfiguration) { SimpleConnectionFactoryConfiguration simpleConfiguration = (SimpleConnectionFactoryConfiguration) factoryConfiguration; connectionFactory = ConnectionFactory.getConnectionFactory(SimpleConnectionFactory.class); connectionFactory.start(simpleConfiguration, connectionFactory.getClass().getClassLoader()); connection = connectionFactory.getConnection(); } else if (factoryConfiguration instanceof PooledConnectionFactoryConfiguration) { PooledConnectionFactoryConfiguration pooledConfiguration = (PooledConnectionFactoryConfiguration) factoryConfiguration; connectionFactory = ConnectionFactory.getConnectionFactory(PooledConnectionFactory.class); connectionFactory.start(pooledConfiguration, connectionFactory.getClass().getClassLoader()); connection = connectionFactory.getConnection(); } tableManager = TableManagerFactory.getManager(connectionFactory, storeBuilder.create()); tableManager.setCacheName("aName"); }
@Override public void start() { if (configuration.manageConnectionFactory()) { ConnectionFactory factory = ConnectionFactory.getConnectionFactory(configuration.connectionFactory().connectionFactoryClass()); factory.start(configuration.connectionFactory(), factory.getClass().getClassLoader()); initializeConnectionFactory(factory); } try { Object mapper = Util.loadClassStrict(configuration.key2StringMapper(), globalConfiguration.classLoader()).newInstance(); if (mapper instanceof Key2StringMapper) key2StringMapper = (Key2StringMapper) mapper; } catch (Exception e) { log.errorf("Trying to instantiate %s, however it failed due to %s", configuration.key2StringMapper(), e.getClass().getName()); throw new IllegalStateException("This should not happen.", e); } if (trace) { log.tracef("Using key2StringMapper: %s", key2StringMapper.getClass().getName()); } if (configuration.preload()) { enforceTwoWayMapper("preload"); } if (isDistributedCache) { enforceTwoWayMapper("distribution/rehashing"); } }
private Connection getTxConnection(Transaction tx) { Connection connection = transactionConnectionMap.get(tx); if (connection == null) { connection = connectionFactory.getConnection(); transactionConnectionMap.put(tx, connection); } return connection; }
private void destroyTxConnection(Transaction tx) { Connection connection = transactionConnectionMap.remove(tx); if (connection != null) connectionFactory.releaseConnection(connection); }
public JdbcStoreReader(StoreProperties props) { this.props = props; this.marshaller = SerializationConfigUtil.getMarshaller(props); this.config = JdbcConfigurationUtil.getStoreConfig(props); this.connectionFactory = new PooledConnectionFactory(); String segmentCount = props.get(Element.SEGMENT_COUNT); this.metaData = new DbMetaData(config.dialect(), config.dbMajorVersion(), config.dbMinorVersion(), false, false, // If we don't have segments then disable it segmentCount == null || Integer.parseInt(segmentCount) <= 0); this.stringConfig = config.table(); this.binaryConfig = createBinaryTableConfig(); connectionFactory.start(config.connectionFactory(), JdbcStoreReader.class.getClassLoader()); }
AbstractJdbcEntryIterator(ConnectionFactory connectionFactory, TableManager tableManager, StreamingMarshaller marshaller) { this.connectionFactory = connectionFactory; this.tableManager = tableManager; this.marshaller = marshaller; PreparedStatement countPs = null; ResultSet countRs = null; try { conn = connectionFactory.getConnection(); countPs = conn.prepareStatement(tableManager.getCountNonExpiredRowsSql()); countPs.setLong(1, System.currentTimeMillis()); countRs = countPs.executeQuery(); countRs.next(); numberOfRows = countRs.getInt(1); ps = conn.prepareStatement(tableManager.getLoadAllRowsSql(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); ps.setFetchSize(tableManager.getFetchSize()); rs = ps.executeQuery(); } catch (SQLException e) { throw new PersistenceException("SQL error while fetching all StoredEntries", e); } finally { JdbcUtil.safeClose(countPs); JdbcUtil.safeClose(countRs); } }
@Override public void close() { JdbcUtil.safeClose(rs); JdbcUtil.safeClose(ps); connectionFactory.releaseConnection(conn); } }
@Override public void stop() throws PersistenceException { if (config.dropOnExit()) { Connection conn = null; try { conn = connectionFactory.getConnection(); dropTable(conn); } finally { connectionFactory.releaseConnection(conn); } } }
public void testForJdbcStringBasedCacheStore() throws Exception { CacheContainer cm = null; try { cm = TestCacheManagerFactory.fromXml("configs/string-based.xml"); Cache<String, String> first = cm.getCache("first"); Cache<String, String> second = cm.getCache("second"); StoreConfiguration firstCacheLoaderConfig = first.getCacheConfiguration().persistence().stores().get(0); StoreConfiguration secondCacheLoaderConfig = second.getCacheConfiguration().persistence().stores().get(0); assertEquals(JdbcStringBasedStoreConfiguration.class, firstCacheLoaderConfig.getClass()); assertEquals(JdbcStringBasedStoreConfiguration.class, secondCacheLoaderConfig.getClass()); JdbcStringBasedStore firstCs = (JdbcStringBasedStore) TestingUtil.getFirstLoader(first); JdbcStringBasedStore secondCs = (JdbcStringBasedStore) TestingUtil.getFirstLoader(second); assertTableExistence(firstCs.getConnectionFactory().getConnection(), firstCs.getTableManager().getIdentifierQuoteString(), "second", "first", "ISPN_STRING_TABLE"); assertNoOverlapingState(first, second, firstCs, secondCs); } finally { TestingUtil.killCacheManagers(cm); } }
@Override public void stop() { Throwable cause = null; try { tableManager.stop(); tableManager = null; } catch (Throwable t) { cause = t.getCause(); if (cause == null) cause = t; log.debug("Exception while stopping", t); } try { if (configuration.connectionFactory() instanceof ManagedConnectionFactory) { log.tracef("Stopping managed connection factory: %s", connectionFactory); connectionFactory.stop(); } } catch (Throwable t) { if (cause == null) { cause = t; } else { t.addSuppressed(cause); } log.debug("Exception while stopping", t); } if (cause != null) { throw new PersistenceException("Exceptions occurred while stopping store", cause); } }
@Override public void deleteBatch(Iterable<Object> keys) { Connection connection = null; try { connection = connectionFactory.getConnection(); try (PreparedStatement deleteBatch = connection.prepareStatement(tableManager.getDeleteRowSql())) { int batchSize = 0; for (Object key : keys) { String keyStr = key2Str(key); deleteBatch.setString(1, keyStr); deleteBatch.addBatch(); batchSize++; if (batchSize == configuration.maxBatchSize()) { batchSize = 0; deleteBatch.executeBatch(); deleteBatch.clearBatch(); } } if (batchSize != 0) deleteBatch.executeBatch(); } } catch (SQLException e) { throw log.sqlFailureDeletingBatch(keys, e); } finally { connectionFactory.releaseConnection(connection); } }
@Override public int size() { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = connectionFactory.getConnection(); String sql = tableManager.getCountNonExpiredRowsSql(); ps = conn.prepareStatement(sql); ps.setLong(1, timeService.wallClockTime()); rs = ps.executeQuery(); rs.next(); return rs.getInt(1); } catch (SQLException e) { log.sqlFailureIntegratingState(e); throw new PersistenceException("SQL failure while integrating state into store", e); } finally { JdbcUtil.safeClose(rs); JdbcUtil.safeClose(ps); connectionFactory.releaseConnection(conn); } }
@Override public boolean delete(Object key) { Connection connection = null; PreparedStatement ps = null; String keyStr = key2Str(key); try { String sql = tableManager.getDeleteRowSql(); if (trace) { log.tracef("Running sql '%s' on %s", sql, keyStr); } connection = connectionFactory.getConnection(); ps = connection.prepareStatement(sql); ps.setString(1, keyStr); return ps.executeUpdate() == 1; } catch (SQLException ex) { log.sqlFailureRemovingKeys(ex); throw new PersistenceException("Error while removing string keys from database", ex); } finally { JdbcUtil.safeClose(ps); connectionFactory.releaseConnection(connection); } }
@Override public void clear() { Connection conn = null; Statement statement = null; try { String sql = tableManager.getDeleteAllRowsSql(); conn = connectionFactory.getConnection(); statement = conn.createStatement(); int result = statement.executeUpdate(sql); if (log.isTraceEnabled()) { log.tracef("Successfully removed %d rows.", result); } } catch (SQLException ex) { log.failedClearingJdbcCacheStore(ex); throw new PersistenceException("Failed clearing cache store", ex); } finally { JdbcUtil.safeClose(statement); connectionFactory.releaseConnection(conn); } }
@Override public void write(MarshalledEntry entry) { Connection connection = null; String keyStr = key2Str(entry.getKey()); try { connection = connectionFactory.getConnection(); write(entry, connection, keyStr, getSegment(entry)); } catch (SQLException ex) { log.sqlFailureStoringKey(keyStr, ex); throw new PersistenceException(String.format("Error while storing string key to database; key: '%s'", keyStr), ex); } catch (InterruptedException e) { if (trace) { log.trace("Interrupted while marshalling to store"); } Thread.currentThread().interrupt(); } finally { connectionFactory.releaseConnection(connection); } }
@Override public int size(IntSet segments) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = connectionFactory.getConnection(); String sql = tableManager.getCountNonExpiredRowsSqlForSegments(segments.size()); ps = conn.prepareStatement(sql); int offset = 1; ps.setLong(offset, timeService.wallClockTime()); for (PrimitiveIterator.OfInt segIter = segments.iterator(); segIter.hasNext(); ) { ps.setInt(++offset, segIter.nextInt()); } rs = ps.executeQuery(); rs.next(); return rs.getInt(1); } catch (SQLException e) { log.sqlFailureIntegratingState(e); throw new PersistenceException("SQL failure while integrating state into store", e); } finally { JdbcUtil.safeClose(rs); JdbcUtil.safeClose(ps); connectionFactory.releaseConnection(conn); } }
connection = connectionFactory.getConnection(); try (PreparedStatement upsertBatch = connection.prepareStatement(tableManager.getUpsertRowSql())) { int batchSize = 0; throw log.sqlFailureWritingBatch(e); } finally { connectionFactory.releaseConnection(connection);
/** * Counts the number of rows in the given table. */ public static int rowCount(ConnectionFactory connectionFactory, TableName tableName) { Connection conn = null; PreparedStatement statement = null; ResultSet resultSet = null; try { conn = connectionFactory.getConnection(); String sql = "SELECT count(*) FROM " + tableName; statement = conn.prepareStatement(sql); resultSet = statement.executeQuery(); resultSet.next(); return resultSet.getInt(1); } catch (Exception ex) { throw new RuntimeException(ex); } finally { JdbcUtil.safeClose(resultSet); JdbcUtil.safeClose(statement); connectionFactory.releaseConnection(conn); } }