HHH-4027 - Remove current cache-jbosscache module content

git-svn-id: https://svn.jboss.org/repos/hibernate/core/trunk@17015 1b8cb986-b30d-0410-93ca-fae66ebed9b2
This commit is contained in:
Steve Ebersole 2009-07-07 16:26:49 +00:00
parent db35f58467
commit 640d95bbf6
11 changed files with 0 additions and 1519 deletions

View File

@ -1,85 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache;
import java.util.Properties;
import javax.transaction.TransactionManager;
import org.hibernate.transaction.TransactionManagerLookup;
import org.hibernate.transaction.TransactionManagerLookupFactory;
/**
* Support for JBossCache (TreeCache), where the cache instance is available
* via JNDI lookup.
*
* @author Steve Ebersole
*/
public class JndiBoundTreeCacheProvider extends AbstractJndiBoundCacheProvider {
private TransactionManager transactionManager;
/**
* Construct a Cache representing the "region" within in the underlying cache
* provider.
*
* @param regionName the name of the cache region
* @param properties configuration settings
*
* @throws CacheException
*/
public Cache buildCache(String regionName, Properties properties) throws CacheException {
return new TreeCache( getTreeCacheInstance(), regionName, transactionManager );
}
public void prepare(Properties properties) throws CacheException {
TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.getTransactionManagerLookup(properties);
if (transactionManagerLookup!=null) {
transactionManager = transactionManagerLookup.getTransactionManager(properties);
}
}
/**
* Generate a timestamp
*/
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
/**
* By default, should minimal-puts mode be enabled when using this cache.
* <p/>
* Since TreeCache is a clusterable cache and we are only getting a
* reference the instance from JNDI, safest to assume a clustered
* setup and return true here.
*
* @return True.
*/
public boolean isMinimalPutsEnabledByDefault() {
return true;
}
public org.jboss.cache.TreeCache getTreeCacheInstance() {
return ( org.jboss.cache.TreeCache ) super.getCache();
}
}

View File

@ -1,351 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Comparator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.optimistic.DataVersion;
import org.jboss.cache.config.Option;
import org.jboss.cache.lock.TimeoutException;
/**
* Represents a particular region within the given JBossCache TreeCache
* utilizing TreeCache's optimistic locking capabilities.
*
* @see OptimisticTreeCacheProvider for more details
*
* @author Steve Ebersole
*/
public class OptimisticTreeCache implements OptimisticCache, TransactionAwareCache {
// todo : eventually merge this with TreeCache and just add optional opt-lock support there.
private static final Logger log = LoggerFactory.getLogger( OptimisticTreeCache.class);
private static final String ITEM = "item";
private org.jboss.cache.TreeCache cache;
private final String regionName;
private final Fqn regionFqn;
private OptimisticCacheSource source;
public OptimisticTreeCache(org.jboss.cache.TreeCache cache, String regionName)
throws CacheException {
this.cache = cache;
this.regionName = regionName;
this.regionFqn = Fqn.fromString( regionName.replace( '.', '/' ) );
}
// OptimisticCache impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public void setSource(OptimisticCacheSource source) {
this.source = source;
}
public void writeInsert(Object key, Object value, Object currentVersion) {
writeUpdate( key, value, currentVersion, null );
}
public void writeUpdate(Object key, Object value, Object currentVersion, Object previousVersion) {
try {
Option option = new Option();
DataVersion dv = ( source != null && source.isVersioned() )
? new DataVersionAdapter( currentVersion, previousVersion, source.getVersionComparator(), source.toString() )
: NonLockingDataVersion.INSTANCE;
option.setDataVersion( dv );
cache.put( new Fqn( regionFqn, key ), ITEM, value, option );
}
catch ( Exception e ) {
throw new CacheException( e );
}
}
public void writeLoad(Object key, Object value, Object currentVersion) {
try {
Option option = new Option();
option.setFailSilently( true );
option.setDataVersion( NonLockingDataVersion.INSTANCE );
cache.remove( new Fqn( regionFqn, key ), "ITEM", option );
option = new Option();
option.setFailSilently( true );
DataVersion dv = ( source != null && source.isVersioned() )
? new DataVersionAdapter( currentVersion, currentVersion, source.getVersionComparator(), source.toString() )
: NonLockingDataVersion.INSTANCE;
option.setDataVersion( dv );
cache.put( new Fqn( regionFqn, key ), ITEM, value, option );
}
catch (Exception e) {
throw new CacheException(e);
}
}
// Cache impl ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
public Object get(Object key) throws CacheException {
try {
Option option = new Option();
option.setFailSilently( true );
// option.setDataVersion( NonLockingDataVersion.INSTANCE );
return cache.get( new Fqn( regionFqn, key ), ITEM, option );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public Object read(Object key) throws CacheException {
try {
return cache.get( new Fqn( regionFqn, key ), ITEM );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void update(Object key, Object value) throws CacheException {
try {
Option option = new Option();
option.setDataVersion( NonLockingDataVersion.INSTANCE );
cache.put( new Fqn( regionFqn, key ), ITEM, value, option );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void put(Object key, Object value) throws CacheException {
try {
log.trace( "performing put() into region [" + regionName + "]" );
// do the put outside the scope of the JTA txn
Option option = new Option();
option.setFailSilently( true );
option.setDataVersion( NonLockingDataVersion.INSTANCE );
cache.put( new Fqn( regionFqn, key ), ITEM, value, option );
}
catch (TimeoutException te) {
//ignore!
log.debug("ignoring write lock acquisition failure");
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void remove(Object key) throws CacheException {
try {
// tree cache in optimistic mode seems to have as very difficult
// time with remove calls on non-existent nodes (NPEs)...
if ( cache.get( new Fqn( regionFqn, key ), ITEM ) != null ) {
Option option = new Option();
option.setDataVersion( NonLockingDataVersion.INSTANCE );
cache.remove( new Fqn( regionFqn, key ), option );
}
else {
log.trace( "skipping remove() call as the underlying node did not seem to exist" );
}
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void clear() throws CacheException {
try {
Option option = new Option();
option.setDataVersion( NonLockingDataVersion.INSTANCE );
cache.remove( regionFqn, option );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void destroy() throws CacheException {
try {
Option option = new Option();
option.setCacheModeLocal( true );
option.setFailSilently( true );
option.setDataVersion( NonLockingDataVersion.INSTANCE );
cache.remove( regionFqn, option );
}
catch( Exception e ) {
throw new CacheException( e );
}
}
public void lock(Object key) throws CacheException {
throw new UnsupportedOperationException( "TreeCache is a fully transactional cache" + regionName );
}
public void unlock(Object key) throws CacheException {
throw new UnsupportedOperationException( "TreeCache is a fully transactional cache: " + regionName );
}
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
public int getTimeout() {
return 600; //60 seconds
}
public String getRegionName() {
return regionName;
}
public long getSizeInMemory() {
return -1;
}
public long getElementCountInMemory() {
try {
Set children = cache.getChildrenNames( regionFqn );
return children == null ? 0 : children.size();
}
catch (Exception e) {
throw new CacheException(e);
}
}
public long getElementCountOnDisk() {
return 0;
}
public Map toMap() {
try {
Map result = new HashMap();
Set childrenNames = cache.getChildrenNames( regionFqn );
if (childrenNames != null) {
Iterator iter = childrenNames.iterator();
while ( iter.hasNext() ) {
Object key = iter.next();
result.put(
key,
cache.get( new Fqn( regionFqn, key ), ITEM )
);
}
}
return result;
}
catch (Exception e) {
throw new CacheException(e);
}
}
public String toString() {
return "OptimisticTreeCache(" + regionName + ')';
}
public static class DataVersionAdapter implements DataVersion {
private final Object currentVersion;
private final Object previousVersion;
private final Comparator versionComparator;
private final String sourceIdentifer;
public DataVersionAdapter(Object currentVersion, Object previousVersion, Comparator versionComparator, String sourceIdentifer) {
this.currentVersion = currentVersion;
this.previousVersion = previousVersion;
this.versionComparator = versionComparator;
this.sourceIdentifer = sourceIdentifer;
log.trace( "created " + this );
}
/**
* newerThan() call is dispatched against the DataVersion currently
* associated with the node; the passed dataVersion param is the
* DataVersion associated with the data we are trying to put into
* the node.
* <p/>
* we are expected to return true in the case where we (the current
* node DataVersion) are newer that then incoming value. Returning
* true here essentially means that a optimistic lock failure has
* occured (because conversely, the value we are trying to put into
* the node is "older than" the value already there...)
*/
public boolean newerThan(DataVersion dataVersion) {
log.trace( "checking [" + this + "] against [" + dataVersion + "]" );
if ( dataVersion instanceof CircumventChecksDataVersion ) {
log.trace( "skipping lock checks..." );
return false;
}
else if ( dataVersion instanceof NonLockingDataVersion ) {
// can happen because of the multiple ways Cache.remove()
// can be invoked :(
log.trace( "skipping lock checks..." );
return false;
}
DataVersionAdapter other = ( DataVersionAdapter ) dataVersion;
if ( other.previousVersion == null ) {
log.warn( "Unexpected optimistic lock check on inserting data" );
// work around the "feature" where tree cache is validating the
// inserted node during the next transaction. no idea...
if ( this == dataVersion ) {
log.trace( "skipping lock checks due to same DV instance" );
return false;
}
}
return versionComparator.compare( currentVersion, other.previousVersion ) >= 1;
}
public String toString() {
return super.toString() + " [current=" + currentVersion + ", previous=" + previousVersion + ", src=" + sourceIdentifer + "]";
}
}
/**
* Used in regions where no locking should ever occur. This includes query-caches,
* update-timestamps caches, collection caches, and entity caches where the entity
* is not versioned.
*/
public static class NonLockingDataVersion implements DataVersion {
public static final DataVersion INSTANCE = new NonLockingDataVersion();
public boolean newerThan(DataVersion dataVersion) {
log.trace( "non locking lock check...");
return false;
}
}
/**
* Used to signal to a DataVersionAdapter to simply not perform any checks. This
* is currently needed for proper handling of remove() calls for entity cache regions
* (we do not know the version info...).
*/
public static class CircumventChecksDataVersion implements DataVersion {
public static final DataVersion INSTANCE = new CircumventChecksDataVersion();
public boolean newerThan(DataVersion dataVersion) {
throw new CacheException( "optimistic locking checks should never happen on CircumventChecksDataVersion" );
}
}
}

View File

@ -1,152 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache;
import java.util.Properties;
import javax.transaction.TransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.cfg.Environment;
import org.hibernate.transaction.TransactionManagerLookup;
import org.hibernate.transaction.TransactionManagerLookupFactory;
import org.jboss.cache.PropertyConfigurator;
/**
* Support for a standalone JBossCache TreeCache instance utilizing TreeCache's
* optimistic locking capabilities. This capability was added in JBossCache
* version 1.3.0; as such this provider will only work with that version or
* higher.
* <p/>
* The TreeCache instance is configured via a local config resource. The
* resource to be used for configuration can be controlled by specifying a value
* for the {@link #CONFIG_RESOURCE} config property.
*
* @author Steve Ebersole
*/
public class OptimisticTreeCacheProvider implements CacheProvider {
/**
* @deprecated use {@link Environment#CACHE_PROVIDER_CONFIG}
*/
public static final String CONFIG_RESOURCE = "hibernate.cache.opt_tree_cache.config";
public static final String DEFAULT_CONFIG = "treecache-optimistic.xml";
private static final String NODE_LOCKING_SCHEME = "OPTIMISTIC";
private static final Logger log = LoggerFactory.getLogger( OptimisticTreeCacheProvider.class );
private org.jboss.cache.TreeCache cache;
/**
* Construct and configure the Cache representation of a named cache region.
*
* @param regionName the name of the cache region
* @param properties configuration settings
* @return The Cache representation of the named cache region.
* @throws CacheException
* Indicates an error building the cache region.
*/
public Cache buildCache(String regionName, Properties properties) throws CacheException {
return new OptimisticTreeCache( cache, regionName );
}
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
/**
* Prepare the underlying JBossCache TreeCache instance.
*
* @param properties All current config settings.
* @throws CacheException
* Indicates a problem preparing cache for use.
*/
public void start(Properties properties) {
String resource = properties.getProperty( Environment.CACHE_PROVIDER_CONFIG );
if (resource == null) {
resource = properties.getProperty( CONFIG_RESOURCE );
}
if ( resource == null ) {
resource = DEFAULT_CONFIG;
}
log.debug( "Configuring TreeCache from resource [" + resource + "]" );
try {
cache = new org.jboss.cache.TreeCache();
PropertyConfigurator config = new PropertyConfigurator();
config.configure( cache, resource );
TransactionManagerLookup transactionManagerLookup =
TransactionManagerLookupFactory.getTransactionManagerLookup( properties );
if ( transactionManagerLookup == null ) {
throw new CacheException(
"JBossCache only supports optimisitc locking with a configured " +
"TransactionManagerLookup (" + Environment.TRANSACTION_MANAGER_STRATEGY + ")"
);
}
cache.setTransactionManagerLookup(
new TransactionManagerLookupAdaptor(
transactionManagerLookup,
properties
)
);
if ( ! NODE_LOCKING_SCHEME.equalsIgnoreCase( cache.getNodeLockingScheme() ) ) {
log.info( "Overriding node-locking-scheme to : " + NODE_LOCKING_SCHEME );
cache.setNodeLockingScheme( NODE_LOCKING_SCHEME );
}
cache.start();
}
catch ( Exception e ) {
throw new CacheException( e );
}
}
public void stop() {
if ( cache != null ) {
cache.stop();
cache.destroy();
cache = null;
}
}
public boolean isMinimalPutsEnabledByDefault() {
return true;
}
static final class TransactionManagerLookupAdaptor implements org.jboss.cache.TransactionManagerLookup {
private final TransactionManagerLookup tml;
private final Properties props;
TransactionManagerLookupAdaptor(TransactionManagerLookup tml, Properties props) {
this.tml = tml;
this.props = props;
}
public TransactionManager getTransactionManager() throws Exception {
return tml.getTransactionManager( props );
}
}
public org.jboss.cache.TreeCache getUnderlyingCache() {
return cache;
}
}

View File

@ -1,227 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.lock.TimeoutException;
/**
* Represents a particular region within the given JBossCache TreeCache.
*
* @author Gavin King
*/
public class TreeCache implements Cache, TransactionAwareCache {
private static final Logger log = LoggerFactory.getLogger(TreeCache.class);
private static final String ITEM = "item";
private org.jboss.cache.TreeCache cache;
private final String regionName;
private final Fqn regionFqn;
private final TransactionManager transactionManager;
public TreeCache(org.jboss.cache.TreeCache cache, String regionName, TransactionManager transactionManager)
throws CacheException {
this.cache = cache;
this.regionName = regionName;
this.regionFqn = Fqn.fromString( regionName.replace( '.', '/' ) );
this.transactionManager = transactionManager;
}
public Object get(Object key) throws CacheException {
Transaction tx = suspend();
try {
return read(key);
}
finally {
resume( tx );
}
}
public Object read(Object key) throws CacheException {
try {
return cache.get( new Fqn( regionFqn, key ), ITEM );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void update(Object key, Object value) throws CacheException {
try {
cache.put( new Fqn( regionFqn, key ), ITEM, value );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void put(Object key, Object value) throws CacheException {
Transaction tx = suspend();
try {
//do the failfast put outside the scope of the JTA txn
cache.putFailFast( new Fqn( regionFqn, key ), ITEM, value, 0 );
}
catch (TimeoutException te) {
//ignore!
log.debug("ignoring write lock acquisition failure");
}
catch (Exception e) {
throw new CacheException(e);
}
finally {
resume( tx );
}
}
private void resume(Transaction tx) {
try {
if (tx!=null) transactionManager.resume(tx);
}
catch (Exception e) {
throw new CacheException("Could not resume transaction", e);
}
}
private Transaction suspend() {
Transaction tx = null;
try {
if ( transactionManager!=null ) {
tx = transactionManager.suspend();
}
}
catch (SystemException se) {
throw new CacheException("Could not suspend transaction", se);
}
return tx;
}
public void remove(Object key) throws CacheException {
try {
cache.remove( new Fqn( regionFqn, key ) );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void clear() throws CacheException {
try {
cache.remove( regionFqn );
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void destroy() throws CacheException {
try {
// NOTE : evict() operates locally only (i.e., does not propogate
// to any other nodes in the potential cluster). This is
// exactly what is needed when we destroy() here; destroy() is used
// as part of the process of shutting down a SessionFactory; thus
// these removals should not be propogated
cache.evict( regionFqn );
}
catch( Exception e ) {
throw new CacheException( e );
}
}
public void lock(Object key) throws CacheException {
throw new UnsupportedOperationException( "TreeCache is a fully transactional cache" + regionName );
}
public void unlock(Object key) throws CacheException {
throw new UnsupportedOperationException( "TreeCache is a fully transactional cache: " + regionName );
}
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
public int getTimeout() {
return 600; //60 seconds
}
public String getRegionName() {
return regionName;
}
public long getSizeInMemory() {
return -1;
}
public long getElementCountInMemory() {
try {
Set children = cache.getChildrenNames( regionFqn );
return children == null ? 0 : children.size();
}
catch (Exception e) {
throw new CacheException(e);
}
}
public long getElementCountOnDisk() {
return 0;
}
public Map toMap() {
try {
Map result = new HashMap();
Set childrenNames = cache.getChildrenNames( regionFqn );
if (childrenNames != null) {
Iterator iter = childrenNames.iterator();
while ( iter.hasNext() ) {
Object key = iter.next();
result.put(
key,
cache.get( new Fqn( regionFqn, key ), ITEM )
);
}
}
return result;
}
catch (Exception e) {
throw new CacheException(e);
}
}
public String toString() {
return "TreeCache(" + regionName + ')';
}
}

View File

@ -1,131 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache;
import java.util.Properties;
import javax.transaction.TransactionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.transaction.TransactionManagerLookup;
import org.hibernate.transaction.TransactionManagerLookupFactory;
import org.hibernate.cfg.Environment;
import org.jboss.cache.PropertyConfigurator;
/**
* Support for a standalone JBossCache (TreeCache) instance. The JBossCache is configured
* via a local config resource.
*
* @author Gavin King
*/
public class TreeCacheProvider implements CacheProvider {
/**
* @deprecated use {@link org.hibernate.cfg.Environment#CACHE_PROVIDER_CONFIG}
*/
public static final String CONFIG_RESOURCE = "hibernate.cache.tree_cache.config";
public static final String DEFAULT_CONFIG = "treecache-optimistic.xml";
private static final Logger log = LoggerFactory.getLogger( TreeCacheProvider.class );
private org.jboss.cache.TreeCache cache;
private TransactionManager transactionManager;
/**
* Construct and configure the Cache representation of a named cache region.
*
* @param regionName the name of the cache region
* @param properties configuration settings
* @return The Cache representation of the named cache region.
* @throws CacheException Indicates an error building the cache region.
*/
public Cache buildCache(String regionName, Properties properties) throws CacheException {
return new TreeCache(cache, regionName, transactionManager);
}
public long nextTimestamp() {
return System.currentTimeMillis() / 100;
}
/**
* Prepare the underlying JBossCache TreeCache instance.
*
* @param properties All current config settings.
*
* @throws CacheException Indicates a problem preparing cache for use.
*/
public void start(Properties properties) {
String resource = properties.getProperty( Environment.CACHE_PROVIDER_CONFIG );
if ( resource == null ) {
resource = properties.getProperty( CONFIG_RESOURCE );
}
if ( resource == null ) {
resource = DEFAULT_CONFIG;
}
log.debug( "Configuring TreeCache from resource [" + resource + "]" );
try {
cache = new org.jboss.cache.TreeCache();
PropertyConfigurator config = new PropertyConfigurator();
config.configure( cache, resource );
TransactionManagerLookup transactionManagerLookup = TransactionManagerLookupFactory.getTransactionManagerLookup(properties);
if (transactionManagerLookup!=null) {
cache.setTransactionManagerLookup( new TransactionManagerLookupAdaptor(transactionManagerLookup, properties) );
transactionManager = transactionManagerLookup.getTransactionManager(properties);
}
cache.start();
}
catch (Exception e) {
throw new CacheException(e);
}
}
public void stop() {
if (cache!=null) {
cache.stop();
cache.destroy();
cache=null;
}
}
public boolean isMinimalPutsEnabledByDefault() {
return true;
}
static final class TransactionManagerLookupAdaptor implements org.jboss.cache.TransactionManagerLookup {
private final TransactionManagerLookup tml;
private final Properties props;
TransactionManagerLookupAdaptor(TransactionManagerLookup tml, Properties props) {
this.tml=tml;
this.props=props;
}
public TransactionManager getTransactionManager() throws Exception {
return tml.getTransactionManager(props);
}
}
public org.jboss.cache.TreeCache getUnderlyingCache() {
return cache;
}
}

View File

@ -1,131 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache;
import junit.framework.Test;
import junit.framework.Assert;
import org.jboss.cache.Fqn;
import org.jboss.cache.TreeCache;
import org.jboss.cache.config.Option;
import org.jboss.cache.optimistic.DataVersion;
import org.hibernate.cache.impl.bridge.RegionFactoryCacheProviderBridge;
import org.hibernate.cfg.Environment;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
import org.hibernate.test.cache.BaseCacheProviderTestCase;
import org.hibernate.test.tm.SimpleJtaTransactionManagerImpl;
/**
* @author Steve Ebersole
*/
public class OptimisticTreeCacheTest extends BaseCacheProviderTestCase {
public OptimisticTreeCacheTest(String x) {
super( x );
}
public static Test suite() {
return new FunctionalTestClassTestSuite( OptimisticTreeCacheTest.class );
}
public String getCacheConcurrencyStrategy() {
return "transactional";
}
protected Class getCacheProvider() {
return OptimisticTreeCacheProvider.class;
}
protected String getConfigResourceKey() {
return Environment.CACHE_PROVIDER_CONFIG;
}
protected String getConfigResourceLocation() {
return "treecache-optimistic.xml";
}
protected boolean useTransactionManager() {
return true;
}
public void testCacheLevelStaleWritesFail() throws Throwable {
Fqn fqn = new Fqn( "whatever" );
TreeCache treeCache = ( ( OptimisticTreeCacheProvider ) ( ( RegionFactoryCacheProviderBridge ) sfi().getSettings().getRegionFactory() ).getCacheProvider() ).getUnderlyingCache();
Long long1 = new Long(1);
Long long2 = new Long(2);
try {
System.out.println( "****************************************************************" );
SimpleJtaTransactionManagerImpl.getInstance().begin();
treeCache.put( fqn, "ITEM", long1, ManualDataVersion.gen( 1 ) );
SimpleJtaTransactionManagerImpl.getInstance().commit();
System.out.println( "****************************************************************" );
SimpleJtaTransactionManagerImpl.getInstance().begin();
treeCache.put( fqn, "ITEM", long2, ManualDataVersion.gen( 2 ) );
SimpleJtaTransactionManagerImpl.getInstance().commit();
try {
System.out.println( "****************************************************************" );
SimpleJtaTransactionManagerImpl.getInstance().begin();
treeCache.put( fqn, "ITEM", long1, ManualDataVersion.gen( 1 ) );
SimpleJtaTransactionManagerImpl.getInstance().commit();
Assert.fail( "stale write allowed" );
}
catch( Throwable ignore ) {
// expected behavior
SimpleJtaTransactionManagerImpl.getInstance().rollback();
}
Long current = ( Long ) treeCache.get( fqn, "ITEM" );
Assert.assertEquals( "unexpected current value", 2, current.longValue() );
}
finally {
try {
treeCache.remove( fqn, "ITEM" );
}
catch( Throwable ignore ) {
}
}
}
private static class ManualDataVersion implements DataVersion {
private final int version;
public ManualDataVersion(int version) {
this.version = version;
}
public boolean newerThan(DataVersion dataVersion) {
return this.version > ( ( ManualDataVersion ) dataVersion ).version;
}
public static Option gen(int version) {
ManualDataVersion mdv = new ManualDataVersion( version );
Option option = new Option();
option.setDataVersion( mdv );
return option;
}
}
}

View File

@ -1,64 +0,0 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors.  All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.cache;
import junit.framework.Test;
import org.hibernate.cfg.Environment;
import org.hibernate.junit.functional.FunctionalTestClassTestSuite;
import org.hibernate.test.cache.BaseCacheProviderTestCase;
/**
* @author Steve Ebersole
*/
public class PessimisticTreeCacheTest extends BaseCacheProviderTestCase {
public PessimisticTreeCacheTest(String x) {
super( x );
}
public static Test suite() {
return new FunctionalTestClassTestSuite( PessimisticTreeCacheTest.class );
}
public String getCacheConcurrencyStrategy() {
return "transactional";
}
protected Class getCacheProvider() {
return TreeCacheProvider.class;
}
protected String getConfigResourceKey() {
return Environment.CACHE_PROVIDER_CONFIG;
}
protected String getConfigResourceLocation() {
return "treecache-pessimistic.xml";
}
protected boolean useTransactionManager() {
return true;
}
}

View File

@ -1,32 +0,0 @@
################################################################################
# Hibernate, Relational Persistence for Idiomatic Java #
# #
# Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as #
# indicated by the @author tags or express copyright attribution #
# statements applied by the authors.  All third-party contributions are #
# distributed under license by Red Hat Middleware LLC. #
# #
# This copyrighted material is made available to anyone wishing to use, modify,#
# copy, or redistribute it subject to the terms and conditions of the GNU #
# Lesser General Public License, as published by the Free Software Foundation. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with this distribution; if not, write to: #
# Free Software Foundation, Inc. #
# 51 Franklin Street, Fifth Floor #
# Boston, MA 02110-1301 USA #
################################################################################
hibernate.dialect org.hibernate.dialect.HSQLDialect
hibernate.connection.driver_class org.hsqldb.jdbcDriver
hibernate.connection.url jdbc:hsqldb:mem:/test
hibernate.connection.username sa
hibernate.connection.password
hibernate.connection.pool_size 5
hibernate.cache.region_prefix hibernate.test

View File

@ -1,32 +0,0 @@
################################################################################
# Hibernate, Relational Persistence for Idiomatic Java #
# #
# Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as #
# indicated by the @author tags or express copyright attribution #
# statements applied by the authors.  All third-party contributions are #
# distributed under license by Red Hat Middleware LLC. #
# #
# This copyrighted material is made available to anyone wishing to use, modify,#
# copy, or redistribute it subject to the terms and conditions of the GNU #
# Lesser General Public License, as published by the Free Software Foundation. #
# #
# This program is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
# for more details. #
# #
# You should have received a copy of the GNU Lesser General Public License #
# along with this distribution; if not, write to: #
# Free Software Foundation, Inc. #
# 51 Franklin Street, Fifth Floor #
# Boston, MA 02110-1301 USA #
################################################################################
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=info, stdout
log4j.logger.org.hibernate.test=info

View File

@ -1,171 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
~ indicated by the @author tags or express copyright attribution
~ statements applied by the authors.  All third-party contributions are
~ distributed under license by Red Hat Middleware LLC.
~
~ This copyrighted material is made available to anyone wishing to use, modify,
~ copy, or redistribute it subject to the terms and conditions of the GNU
~ Lesser General Public License, as published by the Free Software Foundation.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this distribution; if not, write to:
~ Free Software Foundation, Inc.
~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA
-->
<!-- ===================================================================== -->
<!-- -->
<!-- Sample TreeCache Service Configuration -->
<!-- Recommended for use as Hibernate's 2nd Level Cache -->
<!-- For use with JBossCache >= 1.3.0 ONLY!!! -->
<!-- -->
<!-- ===================================================================== -->
<server>
<classpath codebase="./lib" archives="jboss-cache.jar, jgroups.jar"/>
<!-- ==================================================================== -->
<!-- Defines TreeCache configuration -->
<!-- ==================================================================== -->
<mbean code="org.jboss.cache.TreeCache"
name="jboss.cache:service=TreeCache">
<depends>jboss:service=Naming</depends>
<depends>jboss:service=TransactionManager</depends>
<!--
Configure the TransactionManager : no matter since Hibernate will plug in
an "adapter" to its own TransactionManagerLookup strategy here
-->
<attribute name="TransactionManagerLookupClass">org.jboss.cache.GenericTransactionManagerLookup</attribute>
<!--
Node locking scheme:
OPTIMISTIC
PESSIMISTIC (default)
-->
<attribute name="NodeLockingScheme">OPTIMISTIC</attribute>
<!--
Note that this attribute is IGNORED if your NodeLockingScheme above is OPTIMISTIC.
Isolation level : SERIALIZABLE
REPEATABLE_READ (default)
READ_COMMITTED
READ_UNCOMMITTED
NONE
-->
<attribute name="IsolationLevel">REPEATABLE_READ</attribute>
<!--
Valid modes are LOCAL
REPL_ASYNC
REPL_SYNC
INVALIDATION_ASYNC
INVALIDATION_SYNC
INVALIDATION_ASYNC is highly recommended as the mode for use
with clustered second-level caches.
-->
<attribute name="CacheMode">LOCAL</attribute>
<!--
Just used for async repl: use a replication queue
-->
<attribute name="UseReplQueue">false</attribute>
<!--
Replication interval for replication queue (in ms)
-->
<attribute name="ReplQueueInterval">0</attribute>
<!--
Max number of elements which trigger replication
-->
<attribute name="ReplQueueMaxElements">0</attribute>
<!-- Name of cluster. Needs to be the same for all clusters, in order
to find each other
-->
<attribute name="ClusterName">TreeCache-Cluster</attribute>
<!-- JGroups protocol stack properties. Can also be a URL,
e.g. file:/home/bela/default.xml
<attribute name="ClusterProperties"></attribute>
-->
<attribute name="ClusterConfig">
<config>
<!-- UDP: if you have a multihomed machine,
set the bind_addr attribute to the appropriate NIC IP address -->
<!-- UDP: On Windows machines, because of the media sense feature
being broken with multicast (even after disabling media sense)
set the loopback attribute to true -->
<UDP mcast_addr="228.1.2.3" mcast_port="48866"
ip_ttl="64" ip_mcast="true"
mcast_send_buf_size="150000" mcast_recv_buf_size="80000"
ucast_send_buf_size="150000" ucast_recv_buf_size="80000"
loopback="false"/>
<PING timeout="2000" num_initial_members="3"
up_thread="false" down_thread="false"/>
<MERGE2 min_interval="10000" max_interval="20000"/>
<!-- <FD shun="true" up_thread="true" down_thread="true" />-->
<FD_SOCK/>
<VERIFY_SUSPECT timeout="1500"
up_thread="false" down_thread="false"/>
<pbcast.NAKACK gc_lag="50" retransmit_timeout="600,1200,2400,4800"
max_xmit_size="8192" up_thread="false" down_thread="false"/>
<UNICAST timeout="600,1200,2400" window_size="100" min_threshold="10"
down_thread="false"/>
<pbcast.STABLE desired_avg_gossip="20000"
up_thread="false" down_thread="false"/>
<FRAG frag_size="8192"
down_thread="false" up_thread="false"/>
<pbcast.GMS join_timeout="5000" join_retry_timeout="2000"
shun="true" print_local_addr="true"/>
<pbcast.STATE_TRANSFER up_thread="true" down_thread="true"/>
</config>
</attribute>
<!--
Whether or not to fetch state on joining a cluster
NOTE this used to be called FetchStateOnStartup and has been renamed to be more descriptive.
-->
<attribute name="FetchInMemoryState">false</attribute>
<!--
Number of milliseconds to wait until all responses for a
synchronous call have been received.
-->
<attribute name="SyncReplTimeout">20000</attribute>
<!-- Max number of milliseconds to wait for a lock acquisition -->
<attribute name="LockAcquisitionTimeout">15000</attribute>
<!-- Name of the eviction policy class. -->
<attribute name="EvictionPolicyClass"></attribute>
<!--
Indicate whether to use marshalling or not. Set this to true if you are running under a scoped
class loader, e.g., inside an application server. Default is "false".
-->
<attribute name="UseMarshalling">false</attribute>
</mbean>
</server>

View File

@ -1,143 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ Copyright (c) 2007, Red Hat Middleware LLC or third-party contributors as
~ indicated by the @author tags or express copyright attribution
~ statements applied by the authors.  All third-party contributions are
~ distributed under license by Red Hat Middleware LLC.
~
~ This copyrighted material is made available to anyone wishing to use, modify,
~ copy, or redistribute it subject to the terms and conditions of the GNU
~ Lesser General Public License, as published by the Free Software Foundation.
~
~ This program is distributed in the hope that it will be useful,
~ but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
~ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
~ for more details.
~
~ You should have received a copy of the GNU Lesser General Public License
~ along with this distribution; if not, write to:
~ Free Software Foundation, Inc.
~ 51 Franklin Street, Fifth Floor
~ Boston, MA 02110-1301 USA
-->
<!-- ===================================================================== -->
<!-- -->
<!-- Sample TreeCache Service Configuration -->
<!-- -->
<!-- ===================================================================== -->
<server>
<classpath codebase="./lib" archives="jboss-cache.jar, jgroups.jar"/>
<!-- ==================================================================== -->
<!-- Defines TreeCache configuration -->
<!-- ==================================================================== -->
<mbean code="org.jboss.cache.TreeCache"
name="jboss.cache:service=TreeCache">
<depends>jboss:service=Naming</depends>
<depends>jboss:service=TransactionManager</depends>
<!--
TransactionManager configuration not required for Hibernate!
-->
<!--
Node isolation level : SERIALIZABLE
REPEATABLE_READ (default)
READ_COMMITTED
READ_UNCOMMITTED
NONE
-->
<attribute name="IsolationLevel">REPEATABLE_READ</attribute>
<!--
Valid modes are LOCAL
REPL_ASYNC
REPL_SYNC
-->
<attribute name="CacheMode">LOCAL</attribute>
<!-- Name of cluster. Needs to be the same for all clusters, in order
to find each other
-->
<attribute name="ClusterName">TreeCache-Cluster</attribute>
<!-- JGroups protocol stack properties. Can also be a URL,
e.g. file:/home/bela/default.xml
<attribute name="ClusterProperties"></attribute>
-->
<attribute name="ClusterConfig">
<config>
<!-- UDP: if you have a multihomed machine,
set the bind_addr attribute to the appropriate NIC IP address -->
<!-- UDP: On Windows machines, because of the media sense feature
being broken with multicast (even after disabling media sense)
set the loopback attribute to true -->
<UDP mcast_addr="228.1.2.3" mcast_port="45566"
ip_ttl="64" ip_mcast="true"
mcast_send_buf_size="150000" mcast_recv_buf_size="80000"
ucast_send_buf_size="150000" ucast_recv_buf_size="80000"
loopback="false"/>
<PING timeout="2000" num_initial_members="3"
up_thread="false" down_thread="false"/>
<MERGE2 min_interval="10000" max_interval="20000"/>
<FD shun="true" up_thread="true" down_thread="true"/>
<VERIFY_SUSPECT timeout="1500"
up_thread="false" down_thread="false"/>
<pbcast.NAKACK gc_lag="50" retransmit_timeout="600,1200,2400,4800"
up_thread="false" down_thread="false"/>
<pbcast.STABLE desired_avg_gossip="20000"
up_thread="false" down_thread="false"/>
<UNICAST timeout="600,1200,2400" window_size="100" min_threshold="10"
down_thread="false"/>
<FRAG frag_size="8192"
down_thread="false" up_thread="false"/>
<pbcast.GMS join_timeout="5000" join_retry_timeout="2000"
shun="true" print_local_addr="true"/>
<pbcast.STATE_TRANSFER up_thread="false" down_thread="false"/>
</config>
</attribute>
<!--
Max number of entries in the cache. If this is exceeded, the
eviction policy will kick some entries out in order to make
more room
-->
<attribute name="MaxCapacity">20000</attribute>
<!--
The max amount of time (in milliseconds) we wait until the
initial state (ie. the contents of the cache) are retrieved from
existing members in a clustered environment
-->
<attribute name="InitialStateRetrievalTimeout">20000</attribute>
<!--
Number of milliseconds to wait until all responses for a
synchronous call have been received.
-->
<attribute name="SyncReplTimeout">10000</attribute>
<!-- Max number of milliseconds to wait for a lock acquisition -->
<attribute name="LockAcquisitionTimeout">15000</attribute>
<!-- Max number of milliseconds we hold a lock (not currently
implemented) -->
<attribute name="LockLeaseTimeout">60000</attribute>
<!-- Name of the eviction policy class. Not supported now. -->
<attribute name="EvictionPolicyClass"></attribute>
</mbean>
</server>