package org.apache.commons.jcs3.auxiliary.disk.jdbc; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import java.io.IOException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import javax.sql.DataSource; import org.apache.commons.jcs3.auxiliary.AuxiliaryCacheAttributes; import org.apache.commons.jcs3.auxiliary.disk.AbstractDiskCache; import org.apache.commons.jcs3.auxiliary.disk.jdbc.dsfactory.DataSourceFactory; import org.apache.commons.jcs3.engine.behavior.ICache; import org.apache.commons.jcs3.engine.behavior.ICacheElement; import org.apache.commons.jcs3.engine.logging.behavior.ICacheEvent; import org.apache.commons.jcs3.engine.logging.behavior.ICacheEventLogger; import org.apache.commons.jcs3.engine.stats.StatElement; import org.apache.commons.jcs3.engine.stats.behavior.IStatElement; import org.apache.commons.jcs3.engine.stats.behavior.IStats; import org.apache.commons.jcs3.log.Log; import org.apache.commons.jcs3.log.LogManager; /** * This is the jdbc disk cache plugin. *
* It expects a table created by the following script. The table name is configurable. *
** drop TABLE JCS_STORE; * CREATE TABLE JCS_STORE * ( * CACHE_KEY VARCHAR(250) NOT NULL, * REGION VARCHAR(250) NOT NULL, * ELEMENT BLOB, * CREATE_TIME TIMESTAMP, * UPDATE_TIME_SECONDS BIGINT, * MAX_LIFE_SECONDS BIGINT, * SYSTEM_EXPIRE_TIME_SECONDS BIGINT, * IS_ETERNAL CHAR(1), * PRIMARY KEY (CACHE_KEY, REGION) * ); **
* The cleanup thread will delete non eternal items where (now - create time) > max life seconds * * 1000 *
** To speed up the deletion the SYSTEM_EXPIRE_TIME_SECONDS is used instead. It is recommended that * an index be created on this column is you will have over a million records. *
*/ public class JDBCDiskCache* @param cattr the configuration object for this cache * @param dsFactory the DataSourceFactory for this cache * @param tableState an object to track table operations */ public JDBCDiskCache(final JDBCDiskCacheAttributes cattr, final DataSourceFactory dsFactory, final TableState tableState) { super( cattr ); setTableState( tableState ); setJdbcDiskCacheAttributes( cattr ); log.info( "jdbcDiskCacheAttributes = {0}", this::getJdbcDiskCacheAttributes); // This initializes the pool access. this.dsFactory = dsFactory; // Initialization finished successfully, so set alive to true. setAlive(true); } /** * Inserts or updates. By default it will try to insert. If the item exists we will get an * error. It will then update. This behavior is configurable. The cache can be configured to * check before inserting. *
* @param ce
*/
@Override
protected void processUpdate( final ICacheElement
* @param ce
* @param con
* @param element
*/
private void insertOrUpdate( final ICacheElement
* @param ce
* @param con
* @param element
* @return true if the insertion fails because the record exists.
*/
private boolean insertRow( final ICacheElement
* @param ce
* @param con
* @param element
*/
private void updateRow( final ICacheElement
* @param ce the cache element
* @param con a database connection
* @return boolean
*/
protected boolean doesElementExist( final ICacheElement
* @param key
* @return ICacheElement
* @see org.apache.commons.jcs3.auxiliary.disk.AbstractDiskCache#get(Object)
*/
@Override
protected ICacheElement
* @param pattern
* @return key,value map
*/
@Override
protected Map
* @param key
* @return boolean
*/
@Override
protected boolean processRemove( final K key )
{
// remove single item.
final String sqlSingle = String.format("delete from %s where REGION = ? and CACHE_KEY = ?",
getJdbcDiskCacheAttributes().getTableName());
// remove all keys of the same name group.
final String sqlPartial = String.format("delete from %s where REGION = ? and CACHE_KEY like ?",
getJdbcDiskCacheAttributes().getTableName());
try (Connection con = getDataSource().getConnection())
{
boolean partial = key.toString().endsWith(ICache.NAME_COMPONENT_DELIMITER);
String sql = partial ? sqlPartial : sqlSingle;
try (PreparedStatement psSelect = con.prepareStatement(sql))
{
psSelect.setString( 1, this.getCacheName() );
if ( partial )
{
psSelect.setString( 2, key.toString() + "%" );
}
else
{
psSelect.setString( 2, key.toString() );
}
psSelect.executeUpdate();
setAlive(true);
}
catch ( final SQLException e )
{
log.error( "Problem creating statement. sql [{0}]", sql, e );
setAlive(false);
}
}
catch ( final SQLException e )
{
log.error( "Problem updating cache.", e );
reset();
}
return false;
}
/**
* This should remove all elements. The auxiliary can be configured to forbid this behavior. If
* remove all is not allowed, the method balks.
*/
@Override
protected void processRemoveAll()
{
// it should never get here from the abstract disk cache.
if ( this.jdbcDiskCacheAttributes.isAllowRemoveAll() )
{
final String sql = String.format("delete from %s where REGION = ?",
getJdbcDiskCacheAttributes().getTableName());
try (Connection con = getDataSource().getConnection())
{
try (PreparedStatement psDelete = con.prepareStatement( sql ))
{
psDelete.setString( 1, this.getCacheName() );
setAlive(true);
psDelete.executeUpdate();
}
catch ( final SQLException e )
{
log.error( "Problem creating statement.", e );
setAlive(false);
}
}
catch ( final SQLException e )
{
log.error( "Problem removing all.", e );
reset();
}
}
else
{
log.info( "RemoveAll was requested but the request was not fulfilled: "
+ "allowRemoveAll is set to false." );
}
}
/**
* Removed the expired. (now - create time) > max life seconds * 1000
*
* @return the number deleted
*/
protected int deleteExpired()
{
int deleted = 0;
try (Connection con = getDataSource().getConnection())
{
// The shrinker thread might kick in before the table is created
// So check if the table exists first
final DatabaseMetaData dmd = con.getMetaData();
final ResultSet result = dmd.getTables(null, null,
getJdbcDiskCacheAttributes().getTableName(), null);
if (result.next())
{
getTableState().setState( TableState.DELETE_RUNNING );
final long now = System.currentTimeMillis() / 1000;
final String sql = String.format("delete from %s where IS_ETERNAL = ? and REGION = ?"
+ " and ? > SYSTEM_EXPIRE_TIME_SECONDS", getJdbcDiskCacheAttributes().getTableName());
try (PreparedStatement psDelete = con.prepareStatement( sql ))
{
psDelete.setString( 1, "F" );
psDelete.setString( 2, this.getCacheName() );
psDelete.setLong( 3, now );
setAlive(true);
deleted = psDelete.executeUpdate();
}
catch ( final SQLException e )
{
log.error( "Problem creating statement.", e );
setAlive(false);
}
logApplicationEvent( getAuxiliaryCacheAttributes().getName(), "deleteExpired",
"Deleted expired elements. URL: " + getDiskLocation() );
}
else
{
log.warn( "Trying to shrink non-existing table [{0}]",
getJdbcDiskCacheAttributes().getTableName() );
}
}
catch ( final SQLException e )
{
logError( getAuxiliaryCacheAttributes().getName(), "deleteExpired",
e.getMessage() + " URL: " + getDiskLocation() );
log.error( "Problem removing expired elements from the table.", e );
reset();
}
finally
{
getTableState().setState( TableState.FREE );
}
return deleted;
}
/**
* Typically this is used to handle errors by last resort, force content update, or removeall
*/
public void reset()
{
// nothing
}
/** Shuts down the pool */
@Override
public void processDispose()
{
final ICacheEvent
* @return The size value
*/
@Override
public int getSize()
{
int size = 0;
// region, key
final String selectString = String.format("select count(*) from %s where REGION = ?",
getJdbcDiskCacheAttributes().getTableName());
try (Connection con = getDataSource().getConnection())
{
try (PreparedStatement psSelect = con.prepareStatement( selectString ))
{
psSelect.setString( 1, this.getCacheName() );
try (ResultSet rs = psSelect.executeQuery())
{
if ( rs.next() )
{
size = rs.getInt( 1 );
}
}
}
}
catch ( final SQLException e )
{
log.error( "Problem getting size.", e );
}
return size;
}
/**
* Return the keys in this cache.
*
* @see org.apache.commons.jcs3.auxiliary.disk.AbstractDiskCache#getKeySet()
*/
@Override
public Set
* @return IStats
*/
@Override
public IStats getStatistics()
{
final IStats stats = super.getStatistics();
stats.setTypeName( "JDBC/Abstract Disk Cache" );
final List
* @return the table name or UNDEFINED
*/
protected String getTableName()
{
String name = "UNDEFINED";
if ( this.getJdbcDiskCacheAttributes() != null )
{
name = this.getJdbcDiskCacheAttributes().getTableName();
}
return name;
}
/**
* @param tableState The tableState to set.
*/
public void setTableState( final TableState tableState )
{
this.tableState = tableState;
}
/**
* @return Returns the tableState.
*/
public TableState getTableState()
{
return tableState;
}
/**
* This is used by the event logging.
*
* @return the location of the disk, either path or ip.
*/
@Override
protected String getDiskLocation()
{
return this.jdbcDiskCacheAttributes.getUrl();
}
/**
* Public so managers can access it.
* @return the dsFactory
* @throws SQLException if getting a data source fails
*/
public DataSource getDataSource() throws SQLException
{
return dsFactory.getDataSource();
}
/**
* For debugging.
*
* @return this.getStats();
*/
@Override
public String toString()
{
return this.getStats();
}
}