JBossCache-1.4.1.SP14/0000755000175000017500000000000011350136226014104 5ustar twernertwernerJBossCache-1.4.1.SP14/src/0000755000175000017500000000000011350136224014671 5ustar twernertwernerJBossCache-1.4.1.SP14/src/org/0000755000175000017500000000000011350136224015460 5ustar twernertwernerJBossCache-1.4.1.SP14/src/org/jboss/0000755000175000017500000000000011350136224016600 5ustar twernertwernerJBossCache-1.4.1.SP14/src/org/jboss/cache/0000755000175000017500000000000011350136224017643 5ustar twernertwernerJBossCache-1.4.1.SP14/src/org/jboss/cache/TransactionTable.java0000755000175000017500000001603311350136224023751 0ustar twernertwerner/* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache; import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.cache.lock.IdentityLock; import org.jgroups.blocks.MethodCall; import javax.transaction.Transaction; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * Maintains the mapping between local (Transaction) and global transactions * (GlobalTransaction). Also keys modifications and undo-operations) under a * given TX. * * @author Bela Ban Apr 14, 2003 * @version $Revision: 4509 $ */ public class TransactionTable { /** Map, mapping between local (javax.transaction.Transaction) * and GlobalTransactions. New: a local TX can have a number of GTXs */ protected Map tx_map=new ConcurrentHashMap(); /** Map, mappings between GlobalTransactions and modifications */ protected Map txs=new ConcurrentHashMap(); /** our logger */ private static final Log log=LogFactory.getLog(TransactionTable.class); /** * Constructs a new table. */ public TransactionTable() { } /** * Returns the number of local transactions. */ public int getNumLocalTransactions() { return tx_map.size(); } /** * Returns the number of global transactions. */ public int getNumGlobalTransactions() { return txs.size(); } /** * Returns the global transaction associated with the local transaction. * Returns null if tx is null or it was not found. */ public GlobalTransaction get(Transaction tx) { if (tx == null) return null; return (GlobalTransaction) tx_map.get(tx); } /** * Returns the local transaction associated with a GlobalTransaction. Not * very efficient as the values have to be iterated over, don't use * frequently * * @param gtx The GlobalTransaction * @return Transaction. The local transaction associated with a given * GlobalTransaction). This will be null if no local transaction is * associated with a given GTX */ public Transaction getLocalTransaction(GlobalTransaction gtx) { Map.Entry entry; Transaction local_tx; GlobalTransaction global_tx; if(gtx == null) return null; for(Iterator it=tx_map.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); local_tx=(Transaction)entry.getKey(); global_tx=(GlobalTransaction)entry.getValue(); if(gtx.equals(global_tx)) { return local_tx; } } return null; } /** * Associates the global transaction with the local transaction. */ public void put(Transaction tx, GlobalTransaction gtx) { if(tx == null) { log.error("key (Transaction) is null"); return; } tx_map.put(tx, gtx); } /** * Returns the local transaction entry for the global transaction. * Returns null if tx is null or it was not found. */ public TransactionEntry get(GlobalTransaction gtx) { return gtx != null ? (TransactionEntry)txs.get(gtx) : null; } /** * Associates the global transaction with a transaction entry. */ public void put(GlobalTransaction tx, TransactionEntry entry) { if(tx == null) { log.error("key (GlobalTransaction) is null"); return; } txs.put(tx, entry); } /** * Removes a global transation, returns the old transaction entry. */ public TransactionEntry remove(GlobalTransaction tx) { return (TransactionEntry)txs.remove(tx); } /** * Removes a local transation, returns the global transaction entry. */ public GlobalTransaction remove(Transaction tx) { if(tx == null) return null; return (GlobalTransaction)tx_map.remove(tx); } /** * Adds a motification to the global transaction. */ public void addModification(GlobalTransaction gtx, MethodCall m) { TransactionEntry entry=get(gtx); if(entry == null) { log.error("transaction not found (gtx=" + gtx + ")"); return; } entry.addModification(m); } public void addCacheLoaderModification(GlobalTransaction gtx, MethodCall m) { TransactionEntry entry = get(gtx); if(entry == null) { log.error("transaction not found (gtx=" + gtx + ")"); return; } entry.addCacheLoaderModification(m); } /** * Adds an undo operation to the global transaction. */ public void addUndoOperation(GlobalTransaction gtx, MethodCall m) { TransactionEntry entry=get(gtx); if(entry == null) { log.error("transaction not found (gtx=" + gtx + ")"); return; } entry.addUndoOperation(m); } /** * Adds a lock to the global transaction. */ public void addLock(GlobalTransaction gtx, IdentityLock l) { TransactionEntry entry=get(gtx); if(entry == null) { log.error("transaction entry not found for (gtx=" + gtx + ")"); return; } entry.addLock(l); } /** * Adds a collection of locks to the global transaction. */ public void addLocks(GlobalTransaction gtx, Collection locks) { TransactionEntry entry=get(gtx); if(entry == null) { log.error("transaction entry not found for (gtx=" + gtx + ")"); return; } entry.addLocks(locks); } /** * Adds a node that has been removed to the global transaction */ public void addRemovedNode(GlobalTransaction gtx, Fqn fqn) { TransactionEntry entry=get(gtx); if(entry == null) { log.error("transaction entry not found for (gtx=" + gtx + ")"); return; } entry.addRemovedNode(fqn); } /** * Returns summary debug information. */ public String toString() { StringBuffer sb=new StringBuffer(); sb.append(tx_map.size()).append(" mappings, "); sb.append(txs.size()).append(" transactions"); return sb.toString(); } /** * Returns detailed debug information. */ public String toString(boolean print_details) { if(!print_details) return toString(); StringBuffer sb=new StringBuffer(); Map.Entry entry; sb.append("LocalTransactions: ").append(tx_map.size()).append("\n"); sb.append("GlobalTransactions: ").append(txs.size()).append("\n"); sb.append("tx_map:\n"); for(Iterator it=tx_map.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } sb.append("txs:\n"); for(Iterator it=txs.entrySet().iterator(); it.hasNext();) { entry=(Map.Entry)it.next(); sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } return sb.toString(); } } JBossCache-1.4.1.SP14/src/org/jboss/cache/GlobalTransaction.java0000755000175000017500000000603511350136224024123 0ustar twernertwerner/* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache; import org.jgroups.Address; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; /** * Uniquely identifies a transaction that spans all nodes in a cluster. This is used when * replicating all modifications in a transaction; the PREPARE and COMMIT (or ROLLBACK) * messages have to have a unique identifier to associate the changes with
* * @author Bela Ban Apr 12, 2003 * @author Manik Surtani (manik@jboss.org) * @version $Revision: 3104 $ */ public class GlobalTransaction implements Externalizable { Address addr=null; long id=-1; private static long sid=0; private transient boolean remote=false; private static final long serialVersionUID = 8011434781266976149L; // cash the hashcode private transient int hash_code=-1; // in the worst case, hashCode() returns 0, then increases, so we're safe here /** * empty ctor used by externalization */ public GlobalTransaction() { } private GlobalTransaction(Address addr) { this.addr=addr; id=newId(); } private static synchronized long newId() { return ++sid; } public static GlobalTransaction create(Address addr) { return new GlobalTransaction(addr); } public Object getAddress() { return addr; } public void setAddress(Address address) { addr = address; } public long getId() { return id; } public int hashCode() { if(hash_code == -1) { hash_code=(addr != null ? addr.hashCode() : 0) + (int)id; } return hash_code; } public boolean equals(Object other) { if (this == other) return true; if (!(other instanceof GlobalTransaction)) return false; GlobalTransaction otherGtx = (GlobalTransaction) other; return ((addr == null && otherGtx.addr == null) || (addr != null && otherGtx.addr != null && addr.compareTo(otherGtx.addr) == 0)) && id == otherGtx.id; } public String toString() { StringBuffer sb=new StringBuffer(); sb.append("GlobalTransaction:<").append(addr).append(">:").append(id); return sb.toString(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(addr); out.writeLong(id); // out.writeInt(hash_code); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { addr=(Address)in.readObject(); id=in.readLong(); // hash_code=in.readInt(); } /** * @return Returns the remote. */ public boolean isRemote() { return remote; } /** * @param remote The remote to set. */ public void setRemote(boolean remote) { this.remote = remote; } public void setId(long id) { this.id = id; } } JBossCache-1.4.1.SP14/src/org/jboss/cache/GenericTransactionManagerLookup.java0000755000175000017500000001146711350136224026771 0ustar twernertwernerpackage org.jboss.cache; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.cache.transaction.DummyTransactionManager; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.transaction.TransactionManager; import java.lang.reflect.Method; /** * A generic class that chooses the best-fit TransactionManager. Tries a number of well-known appservers * * @author Markus Plesser * @version $Id: GenericTransactionManagerLookup.java 203 2005-07-08 11:09:20Z bela $ */ public class GenericTransactionManagerLookup implements TransactionManagerLookup { /** * our logger */ private static Log log=LogFactory.getLog(GenericTransactionManagerLookup.class); /** * lookups performed? */ private static boolean lookupDone=false; /** * no lookup available? */ private static boolean lookupFailed=false; /** * the (final) used TransactionManager */ private static TransactionManager tm=null; /** * JNDI locations for TransactionManagers we know of */ private static String[][] knownJNDIManagers={ {"java:/TransactionManager", "JBoss, JRun4"}, {"java:comp/UserTransaction", "Resin, Orion, JOnAS (JOTM)"}, {"javax.transaction.TransactionManager", "BEA WebLogic"} }; /** * WebSphere 5.1 TransactionManagerFactory */ private static final String WS_FACTORY_CLASS_5_1="com.ibm.ws.Transaction.TransactionManagerFactory"; /** * WebSphere 5.0 TransactionManagerFactory */ private static final String WS_FACTORY_CLASS_5_0="com.ibm.ejs.jts.jta.TransactionManagerFactory"; /** * WebSphere 4.0 TransactionManagerFactory */ private static final String WS_FACTORY_CLASS_4="com.ibm.ejs.jts.jta.JTSXA"; /** * Get the systemwide used TransactionManager * * @return TransactionManager */ public TransactionManager getTransactionManager() { if(!lookupDone) doLookups(); if(tm != null) return tm; if(lookupFailed) { //fall back to a dummy from JBossCache tm=DummyTransactionManager.getInstance(); log.warn("Falling back to DummyTransactionManager from JBossCache"); } return tm; } /** * Try to figure out which TransactionManager to use */ private static void doLookups() { if(lookupFailed) return; InitialContext ctx; try { ctx=new InitialContext(); } catch(NamingException e) { log.error("Could not create an initial JNDI context!", e); lookupFailed=true; return; } //probe jndi lookups first Object jndiObject=null; for(int i=0; i < knownJNDIManagers.length; i++) { try { if(log.isDebugEnabled()) log.debug("Trying to lookup TransactionManager for " + knownJNDIManagers[i][1]); jndiObject=ctx.lookup(knownJNDIManagers[i][0]); } catch(NamingException e) { log.info("Failed to perform a lookup for [" + knownJNDIManagers[i][0] + " (" + knownJNDIManagers[i][1] + ")]"); } if(jndiObject instanceof TransactionManager) { tm=(TransactionManager)jndiObject; log.info("Found TransactionManager for " + knownJNDIManagers[i][1]); return; } } //try to find websphere lookups since we came here Class clazz; try { log.debug("Trying WebSphere 5.1: " + WS_FACTORY_CLASS_5_1); clazz=Class.forName(WS_FACTORY_CLASS_5_1); log.info("Found WebSphere 5.1: " + WS_FACTORY_CLASS_5_1); } catch(ClassNotFoundException ex) { try { log.debug("Trying WebSphere 5.0: " + WS_FACTORY_CLASS_5_0); clazz=Class.forName(WS_FACTORY_CLASS_5_0); log.info("Found WebSphere 5.0: " + WS_FACTORY_CLASS_5_0); } catch(ClassNotFoundException ex2) { try { log.debug("Trying WebSphere 4: " + WS_FACTORY_CLASS_4); clazz=Class.forName(WS_FACTORY_CLASS_4); log.info("Found WebSphere 4: " + WS_FACTORY_CLASS_4); } catch(ClassNotFoundException ex3) { log.info("Couldn't find any WebSphere TransactionManager factory class, neither for WebSphere version 5.1 nor 5.0 nor 4"); lookupFailed=true; return; } } } try { Class[] signature=null; Object[] args=null; Method method=clazz.getMethod("getTransactionManager", signature); tm=(TransactionManager)method.invoke(null, args); } catch(Exception ex) { log.error("Found WebSphere TransactionManager factory class [" + clazz.getName() + "], but couldn't invoke its static 'getTransactionManager' method", ex); } } } JBossCache-1.4.1.SP14/src/org/jboss/cache/OptimisticTransactionEntry.java0000755000175000017500000000265011350136224026070 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache; import org.jboss.cache.optimistic.TransactionWorkspace; import org.jboss.cache.optimistic.TransactionWorkspaceImpl; /** * Subclasses the {@link TransactionEntry} class to add a {@link TransactionWorkspace}. Used with optimistic locking * where each call is assigned a trasnaction and a transaction workspace. * * @author Manik Surtani (manik@jboss.org) * @author Steve Woodcock (stevew@jofti.com) */ public class OptimisticTransactionEntry extends TransactionEntry{ private TransactionWorkspace transactionWorkSpace = new TransactionWorkspaceImpl(); public OptimisticTransactionEntry() { } public String toString() { StringBuffer sb = new StringBuffer(super.toString()); sb.append("\nworkspace: ").append(transactionWorkSpace); return sb.toString(); } /** * @return Returns the transactionWorkSpace. */ public TransactionWorkspace getTransactionWorkSpace() { return transactionWorkSpace; } /** * @param transactionWorkSpace The transactionWorkSpace to set. */ public void setTransactionWorkSpace( TransactionWorkspace transactionWorkSpace) { this.transactionWorkSpace = transactionWorkSpace; } } JBossCache-1.4.1.SP14/src/org/jboss/cache/config/0000755000175000017500000000000011350136224021110 5ustar twernertwernerJBossCache-1.4.1.SP14/src/org/jboss/cache/config/Option.java0000755000175000017500000001121011350136224023221 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache.config; import org.jboss.cache.optimistic.DataVersion; /** * Used to override characteristics of specific calls to the cache. The javadocs of each of the setters below detail functionality and behaviour. * * @author Manik Surtani (manik@jboss.org) * @since 1.3.0 */ public class Option { private boolean failSilently; private boolean cacheModeLocal; private DataVersion dataVersion; private boolean suppressLocking; private boolean forceDataGravitation; private boolean skipDataGravitation; /** * * @since 1.4.0 */ public boolean isSuppressLocking() { return suppressLocking; } /** * Suppresses acquiring locks for the given invocation. Used with pessimistic locking only. Use with extreme care, may lead to a breach in data integrity! * @since 1.4.0 */ public void setSuppressLocking(boolean suppressLocking) { this.suppressLocking = suppressLocking; } /** * * @since 1.3.0 */ public boolean isFailSilently() { return failSilently; } /** * suppress any failures in your cache operation, including version mismatches with optimistic locking, timeouts obtaining locks, transaction rollbacks. If this is option is set, the method invocation will __never fail or throw an exception__, although it may not succeed. With this option enabled the call will not participate in any ongoing transactions even if a transaction is running. * @since 1.3.0 */ public void setFailSilently(boolean failSilently) { this.failSilently = failSilently; } /** * only applies to put() and remove() methods on the cache. * @since 1.3.0 */ public boolean isCacheModeLocal() { return cacheModeLocal; } /** * overriding CacheMode from REPL_SYNC, REPL_ASYNC, INVALIDATION_SYNC, INVALIDATION_ASYNC to LOCAL. Only applies to put() and remove() methods on the cache. * @since 1.3.0 * @param cacheModeLocal */ public void setCacheModeLocal(boolean cacheModeLocal) { this.cacheModeLocal = cacheModeLocal; } /** * * @since 1.3.0 */ public DataVersion getDataVersion() { return dataVersion; } /** * Passing in an {@link org.jboss.cache.optimistic.DataVersion} instance when using optimistic locking will override the default behaviour of internally generated version info and allow the caller to handle data versioning. * @since 1.3.0 */ public void setDataVersion(DataVersion dataVersion) { this.dataVersion = dataVersion; } /** * * @since 1.4.0 */ public boolean getForceDataGravitation() { return forceDataGravitation; } /** * Enables data gravitation calls if a cache miss is detected when using Buddy Replication. * Enabled only for a given invocation, and only useful if autoDataGravitation is set to false. * See Buddy Replication documentation for more details. * @since 1.4.0 */ public void setForceDataGravitation(boolean enableDataGravitation) { this.forceDataGravitation = enableDataGravitation; } /** * @return true if skipDataGravitation is set to true. * @since 1.4.1.SP6 */ public boolean isSkipDataGravitation() { return skipDataGravitation; } /** * Suppresses data gravitation when buddy replication is used. If true, overrides {@link #setForceDataGravitation(boolean)} * being set to true. Typically used to suppress gravitation calls when {@link org.jboss.cache.config.BuddyReplicationConfig#setAutoDataGravitation(boolean)} * is set to true. * * @param skipDataGravitation * @since 1.4.1.SP6 */ public void setSkipDataGravitation(boolean skipDataGravitation) { this.skipDataGravitation = skipDataGravitation; } public String toString() { return "Option{" + "failSilently=" + failSilently + ", cacheModeLocal=" + cacheModeLocal + ", dataVersion=" + dataVersion + ", suppressLocking=" + suppressLocking + ", forceDataGravitation=" + forceDataGravitation + ", skipDataGravitation=" + skipDataGravitation + '}'; } } JBossCache-1.4.1.SP14/src/org/jboss/cache/config/CacheLoaderConfig.java0000755000175000017500000001164411350136224025244 0ustar twernertwerner/* * JBoss, Home of Professional Open Source * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache.config; import org.jboss.cache.xml.XmlHelper; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.io.IOException; import java.io.ByteArrayInputStream; /** * Holds the configuration of the cache loader chain. ALL cache loaders should be defined using this class, adding * individual cache loaders to the chain by calling {@see CacheLoaderConfig#addIndividualCacheLoaderConfig} * * @author Manik Surtani (manik@jboss.org) */ public class CacheLoaderConfig { private boolean passivation; private String preload; private List cacheLoaderConfigs = new ArrayList(); private boolean shared; public String getPreload() { return preload; } public void setPreload(String preload) { this.preload = preload; } public void setPassivation(boolean passivation) { this.passivation = passivation; } public boolean isPassivation() { return passivation; } public void addIndividualCacheLoaderConfig(IndividualCacheLoaderConfig clc) { cacheLoaderConfigs.add(clc); } public List getIndividualCacheLoaderConfigs() { return cacheLoaderConfigs; } public IndividualCacheLoaderConfig getFirstCacheLoaderConfig() { if (cacheLoaderConfigs.size() == 0) return null; return (IndividualCacheLoaderConfig) cacheLoaderConfigs.get(0); } public boolean useChainingCacheLoader() { return !isPassivation() && cacheLoaderConfigs.size() > 1; } public String toString() { return new StringBuffer().append("CacheLoaderConfig{").append("shared=").append(shared).append(", passivation=").append(passivation).append(", preload='").append(preload).append('\'').append(", cacheLoaderConfigs.size()=").append(cacheLoaderConfigs.size()).append('}').toString(); } public void setShared(boolean shared) { this.shared = shared; } public boolean isShared() { return shared; } /** * Configuration object that holds the confguration of an individual cache loader. * * @author Manik Surtani (manik@jboss.org) */ public static class IndividualCacheLoaderConfig { private String className; private boolean async; private boolean ignoreModifications; private boolean fetchPersistentState; public boolean isPurgeOnStartup() { return purgeOnStartup; } private boolean purgeOnStartup; public boolean isFetchPersistentState() { return fetchPersistentState; } public void setFetchPersistentState(boolean fetchPersistentState) { this.fetchPersistentState = fetchPersistentState; } private Properties properties; public void setClassName(String className) { this.className = className; } public String getClassName() { return className; } public void setAsync(boolean async) { this.async = async; } public boolean isAsync() { return async; } public void setIgnoreModifications(boolean ignoreModifications) { this.ignoreModifications = ignoreModifications; } public boolean isIgnoreModifications() { return ignoreModifications; } public void setProperties(String properties) throws IOException { if (properties == null) return; // JBCACHE-531: escape all backslash characters // replace any "\" that is not preceded by a backslash with "\\" properties = XmlHelper.escapeBackslashes(properties); ByteArrayInputStream is = new ByteArrayInputStream(properties.trim().getBytes("ISO8859_1")); this.properties = new Properties(); this.properties.load(is); is.close(); } public void setProperties(Properties properties) { this.properties = properties; } public Properties getProperties() { return properties; } public String toString() { return new StringBuffer().append("IndividualCacheLoaderConfig{").append("className='").append(className).append('\'').append(", async=").append(async).append(", ignoreModifications=").append(ignoreModifications).append(", fetchPersistentState=").append(fetchPersistentState).append(", properties=").append(properties).append('}').toString(); } public void setPurgeOnStartup(boolean purgeOnStartup) { this.purgeOnStartup = purgeOnStartup; } } } JBossCache-1.4.1.SP14/src/org/jboss/cache/rpc/0000755000175000017500000000000011350136224020427 5ustar twernertwernerJBossCache-1.4.1.SP14/src/org/jboss/cache/rpc/RpcTreeCache.java0000755000175000017500000003217611350136224023576 0ustar twernertwernerpackage org.jboss.cache.rpc; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import org.jboss.cache.TreeCache; import org.jboss.cache.marshall.MethodCallFactory; import org.jgroups.Address; import org.jgroups.JChannel; import org.jgroups.blocks.MethodCall; /** * {@link TreeCache} extension that adds a general purpose RPC functionality * to allow clients to make/receive RPC calls over the same JGroups Channel * used by the cache. *

* Services wishing to receive remote calls should register a unique service * name and an object on which the remote calls for that service can be invoked. *

*

* Clients wishing to make RPC calls need to know the unique service name, which * they can pass to one of the flavors of callRemoteMethods. *

* * NOTE: The purpose of this class is to allow services that * want to use a TreeCache to avoid also having to use a HAPartition (and thus * potentially requiring a duplicate JGroups Channel). * * @deprecated This class will be removed when JGroups adds a multiplexing * capability. * * @author Brian Stansberry * @version $Revision$ */ public class RpcTreeCache extends TreeCache implements RpcTreeCacheMBean { /** The {@link #_dispatchRpcCall(String, MethodCall)} method */ public static final Method dispatchRpcCallMethod; static { try { dispatchRpcCallMethod=RpcTreeCache.class.getDeclaredMethod("_dispatchRpcCall", new Class[]{String.class, MethodCall.class}); } catch(NoSuchMethodException ex) { ex.printStackTrace(); throw new ExceptionInInitializerError(ex.toString()); } } /** Map of registered RPC handlers */ protected Map rpcHandlers = new HashMap(); /** * Creates a channel with the given properties. Connects to the channel, then creates a PullPushAdapter * and starts it */ public RpcTreeCache(String cluster_name, String props, long state_fetch_timeout) throws Exception { super(cluster_name, props, state_fetch_timeout); } /** * Default constructor. * * @throws Exception */ public RpcTreeCache() throws Exception { super(); } /** * Expects an already connected channel. Creates a PullPushAdapter and starts it */ public RpcTreeCache(JChannel channel) throws Exception { super(channel); } /** * Calls a remote method on nodes in the cluster, targeted at * objects registered under a given serviceName. * * * @param serviceName name of a callback handler that will have been * registered on the remote end via * {@link #registerRPCHandler(String, Object)}. * @param members Vector, each of whose members is the Address of one * the nodes in the cache's * {@link TreeCache#getMembers() member list}. * If null, the method will be invoked on * all members. * @param method method to execute * @param args method arguments * @param synchronous true if the call should block until * all members respond (or timeout); false * if the call should return immediately without * waiting for responses * @param exclude_self should the call be invoked on the callee? * @param timeout how long to wait for synchronous responses * @return List containing the responses that were received, or * null if the call is asynchronous. * Elements of the list will either be a returned value * or an exception if one was returned. Any * NoHandlerForRPCException returned will be removed. * * @throws Exception */ public List callRemoteMethods(String serviceName, Vector members, Method method, Object[] args, boolean synchronous, boolean exclude_self, long timeout) throws Exception { return callRemoteMethods(serviceName, members, MethodCallFactory.create(method, args), synchronous, exclude_self, timeout); } /** * Calls a remote method on nodes in the cluster, targeted at * objects registered under a given serviceName. *

* If the cache's cache mode is TreeCache.LOCAL * and parameter exclude_self is false * this request will be made directly to {@link #_dispatchRpcCall()}. *

* * @param serviceName name of a callback handler that will have been * registered on the remote end via * {@link #registerRPCHandler(String, Object)}. * @param members Vector, each of whose members is the Address of one * the nodes in the cache's * {@link TreeCache#getMembers() member list}. * If null, the method will be invoked on * all members. * @param method_call method call to execute * @param synchronous true if the call should block until * all members respond (or timeout); false * if the call should return immediately without * waiting for responses * @param exclude_self should the call be invoked on the callee? * @param timeout how long to wait for synchronous responses * @return List containing the responses that were received, or * null if the call is asynchronous. * Elements of the list will either be a returned value * or an exception if one was returned. Any * NoHandlerForRPCException returned will be removed. * * @throws Exception */ public List callRemoteMethods(String serviceName, Vector mbrs, MethodCall method_call, boolean synchronous, boolean exclude_self, long timeout) throws Exception { List responses = null; if (cache_mode == TreeCache.LOCAL) { // If cache mode is local, we have no channel // so we have to make local calls to our registered handler if (synchronous) { // For synchronous calls we have to return something responses = new ArrayList(); if (exclude_self == false) { // Make the call locally and add a valid response to result list Object resp = _dispatchRpcCall(serviceName, method_call); if ((resp instanceof NoHandlerForRPCException) == false) responses.add(_dispatchRpcCall(serviceName, method_call)); } // else just return an empty list } else if (exclude_self == false) { // Asynchronous, so we don't return anything, // but we still want to make the local call _dispatchRpcCall(serviceName, method_call); } } else { // Cache mode is not LOCAL // Need to make a call on the cluster // Wrap the ultimate target in a MethodCall pointing at // the _dispatchRpcCall method MethodCall wrapper = MethodCallFactory.create(dispatchRpcCallMethod, new Object[] { serviceName, method_call}); responses = callRemoteMethods(mbrs, wrapper, synchronous, exclude_self, timeout); // Remove any NoHandlerForRPCException // Its inefficient doing this here, but if we add it to // TreeCache.callRemoteMethods we slow down normal cache ops if (responses != null) { for (int i = 0; i < responses.size(); i++) { Object obj = responses.get(i); if (obj instanceof NoHandlerForRPCException) { responses.remove(i); i--; } } } } return responses; } /** * Calls a remote method on nodes in the cluster, targeted at * objects registered under a given serviceName. * * * @param serviceName name of a callback handler that will have been * registered on the remote end via * {@link #registerRPCHandler(String, Object)}. * @param members Vector, each of whose members is the Address of one * the nodes in the cache's * {@link TreeCache#getMembers() member list}. * If null, the method will be invoked on * all members. * @param method_name name of the method to execute * @param args method arguments * @param synchronous true if the call should block until * all members respond (or timeout); false * if the call should return immediately without * waiting for responses * @param exclude_self should the call be invoked on the callee? * @param timeout how long to wait for synchronous responses * @return List containing the responses that were received, or * null if the call is asynchronous. * Elements of the list will either be a returned value * or an exception if one was returned. Any * NoHandlerForRPCException returned will be removed. * * @throws NoHandlerForRPCException if no handler is registered on this node * under serviceName. * * @throws Exception */ public List callRemoteMethods(String serviceName, Vector members, String method_name, Class[] types, Object[] args, boolean synchronous, boolean exclude_self, long timeout) throws Exception { Object handler = rpcHandlers.get(serviceName); if (handler == null) { String msg = "No rpc handler registered under: " + serviceName; log.trace(msg); throw new NoHandlerForRPCException(msg); } Method method= handler.getClass().getDeclaredMethod(method_name, types); return callRemoteMethods(serviceName, members, method, args, synchronous, exclude_self, timeout); } /** * Registers the given object as the on which any MethodCall associated with * the given service should be invoked. * * @param serviceName name of a service that will be receiving RPC calls * @param handler object on which RPC calls for * serviceName can be invoked. * * @see #_dispatchRpcCall */ public void registerRPCHandler(String serviceName, Object handler) { rpcHandlers.put(serviceName, handler); } /** * Removes the given object as a handler for RPC calls for the given * service. * * @param serviceName name of a service that will be receiving RPC calls * @param handler object that was previously passed to * {@link #registerRPCHandler(String, Object)} for * serviceName. * @param handler */ public void unregisterRPCHandler(String serviceName, Object handler) { Object registered = rpcHandlers.remove(serviceName); if (handler != registered) { // Put it back rpcHandlers.put(serviceName, handler); } } /** * Looks up the RPC handler for serviceName and invokes * the method call on it. * * @param serviceName the service * @param call the call to invoke * @return the result of the call, or NoHandlerForRPCException * if no handler was registered for */ public Object _dispatchRpcCall(String serviceName, MethodCall call) { Object retval = null; Object handler = rpcHandlers.get(serviceName); if (handler == null) { String msg = "No rpc handler registered under: " + serviceName; log.trace(msg); return new NoHandlerForRPCException(msg, (Address) getLocalAddress()); } try { retval = call.invoke(handler); } catch (Throwable t) { log.trace("rpc call threw exception", t); retval = t; } return retval; } } JBossCache-1.4.1.SP14/src/org/jboss/cache/rpc/RpcTreeCacheMBean.java0000755000175000017500000001643511350136224024501 0ustar twernertwerner/* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache.rpc; import java.lang.reflect.Method; import java.util.List; import java.util.Vector; import org.jboss.cache.TreeCache; import org.jboss.cache.TreeCacheMBean; import org.jgroups.blocks.MethodCall; /** * MBean interface for the {@link RpcTreeCache}. * * @deprecated This class will be removed when JGroups adds a multiplexing * capability. * * @author Brian Stansberry * @version $Revision$ */ public interface RpcTreeCacheMBean extends TreeCacheMBean { /** * Calls a remote method on nodes in the cluster, targeted at * objects registered under a given serviceName. * * * @param serviceName name of a callback handler that will have been * registered on the remote end via * {@link #registerRPCHandler(String, Object)}. * @param members Vector, each of whose members is the Address of one * the nodes in the cache's * {@link TreeCache#getMembers() member list}. * If null, the method will be invoked on * all members. * @param method method to execute * @param args method arguments * @param synchronous true if the call should block until * all members respond (or timeout); false * if the call should return immediately without * waiting for responses * @param exclude_self should the call be invoked on the callee? * @param timeout how long to wait for synchronous responses * @return List containing the responses that were received, or * null if the call is asynchronous. * Elements of the list will either be a returned value * or an exception if one was returned. Any * NoHandlerForRPCException returned will be removed. * * @throws Exception */ public abstract List callRemoteMethods(String serviceName, Vector members, Method method, Object[] args, boolean synchronous, boolean exclude_self, long timeout) throws Exception; /** * Calls a remote method on nodes in the cluster, targeted at * objects registered under a given serviceName. *

* If the cache's cache mode is TreeCache.LOCAL * and parameter exclude_self is false * this request will be made directly to {@link #_dispatchRpcCall()}. *

* * @param serviceName name of a callback handler that will have been * registered on the remote end via * {@link #registerRPCHandler(String, Object)}. * @param members Vector, each of whose members is the Address of one * the nodes in the cache's * {@link TreeCache#getMembers() member list}. * If null, the method will be invoked on * all members. * @param method_call method call to execute * @param synchronous true if the call should block until * all members respond (or timeout); false * if the call should return immediately without * waiting for responses * @param exclude_self should the call be invoked on the callee? * @param timeout how long to wait for synchronous responses * @return List containing the responses that were received, or * null if the call is asynchronous. * Elements of the list will either be a returned value * or an exception if one was returned. Any * NoHandlerForRPCException returned will be removed. * * @throws Exception */ public abstract List callRemoteMethods(String serviceName, Vector mbrs, MethodCall method_call, boolean synchronous, boolean exclude_self, long timeout) throws Exception; /** * Calls a remote method on nodes in the cluster, targeted at * objects registered under a given serviceName. * * * @param serviceName name of a callback handler that will have been * registered on the remote end via * {@link #registerRPCHandler(String, Object)}. * @param members Vector, each of whose members is the Address of one * the nodes in the cache's * {@link TreeCache#getMembers() member list}. * If null, the method will be invoked on * all members. * @param method_name name of the method to execute * @param args method arguments * @param synchronous true if the call should block until * all members respond (or timeout); false * if the call should return immediately without * waiting for responses * @param exclude_self should the call be invoked on the callee? * @param timeout how long to wait for synchronous responses * @return List containing the responses that were received, or * null if the call is asynchronous. * Elements of the list will either be a returned value * or an exception if one was returned. Any * NoHandlerForRPCException returned will be removed. * * @throws NoHandlerForRPCException if no handler is registered on this node * under serviceName. * * @throws Exception */ public abstract List callRemoteMethods(String serviceName, Vector members, String method_name, Class[] types, Object[] args, boolean synchronous, boolean exclude_self, long timeout) throws Exception; /** * Registers the given object as the on which any MethodCall associated with * the given service should be invoked. * * @param serviceName name of a service that will be receiving RPC calls * @param handler object on which RPC calls for * serviceName can be invoked. * * @see #_dispatchRpcCall */ public abstract void registerRPCHandler(String serviceName, Object handler); /** * Removes the given object as a handler for RPC calls for the given * service. * * @param serviceName name of a service that will be receiving RPC calls * @param handler object that was previously passed to * {@link #registerRPCHandler(String, Object)} for * serviceName. * @param handler */ public abstract void unregisterRPCHandler(String serviceName, Object handler); }JBossCache-1.4.1.SP14/src/org/jboss/cache/rpc/NoHandlerForRPCException.java0000755000175000017500000000161111350136224026041 0ustar twernertwernerpackage org.jboss.cache.rpc; import org.jgroups.Address; /** * Exception returned when * {@link RpcTreeCache#_dispatchRpcCall(String, org.jgroups.blocks.MethodCall)} * is passed a call for an unregistered handler. * * @author Brian Stansberry * @version $Revision$ */ public class NoHandlerForRPCException extends Exception { /** The serialVersionUID */ private static final long serialVersionUID = 1L; private Address nodeAddress; public NoHandlerForRPCException(String msg) { super(msg); } public NoHandlerForRPCException(String message, Address failedNode) { super(message); this.nodeAddress = failedNode; } public Address getNodeAddress() { return nodeAddress; } public void setNodeAddress(Address failedNode) { this.nodeAddress = failedNode; } } JBossCache-1.4.1.SP14/src/org/jboss/cache/NodeNotExistsException.java0000755000175000017500000000132711350136224025141 0ustar twernertwerner// $Id: NodeNotExistsException.java 2073 2006-06-19 12:33:28Z $ /* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache; /** * Thrown when an operation is attempted on a non-existing node in the cache * * @author Bela Ban. * @version $Id: NodeNotExistsException.java 2073 2006-06-19 12:33:28Z $ */ public class NodeNotExistsException extends CacheException { public NodeNotExistsException() { super(); } public NodeNotExistsException(String msg) { super(msg); } public NodeNotExistsException(String msg, Throwable cause) { super(msg, cause); } } JBossCache-1.4.1.SP14/src/org/jboss/cache/TreeCache.java0000755000175000017500000064562011350136224022351 0ustar twernertwerner/* * JBoss, the OpenSource J2EE webOS * * Distributable under LGPL license. * See terms of license at gnu.org. */ package org.jboss.cache; import EDU.oswego.cs.dl.util.concurrent.ConcurrentHashMap; import EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArraySet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jboss.cache.buddyreplication.BuddyGroup; import org.jboss.cache.buddyreplication.BuddyManager; import org.jboss.cache.buddyreplication.BuddyNotInitException; import org.jboss.cache.config.CacheLoaderConfig; import org.jboss.cache.config.Option; import org.jboss.cache.eviction.EvictionPolicy; import org.jboss.cache.factories.InterceptorChainFactory; import org.jboss.cache.factories.NodeFactory; import org.jboss.cache.interceptors.Interceptor; import org.jboss.cache.loader.CacheLoader; import org.jboss.cache.loader.CacheLoaderManager; import org.jboss.cache.loader.ExtendedCacheLoader; import org.jboss.cache.loader.NodeData; import org.jboss.cache.lock.IdentityLock; import org.jboss.cache.lock.IsolationLevel; import org.jboss.cache.lock.LockStrategyFactory; import org.jboss.cache.lock.LockingException; import org.jboss.cache.lock.TimeoutException; import org.jboss.cache.marshall.JBCMethodCall; import org.jboss.cache.marshall.MethodCallFactory; import org.jboss.cache.marshall.MethodDeclarations; import org.jboss.cache.marshall.Region; import org.jboss.cache.marshall.RegionManager; import org.jboss.cache.marshall.RegionNameConflictException; import org.jboss.cache.marshall.RegionNotFoundException; import org.jboss.cache.marshall.TreeCacheMarshaller; import org.jboss.cache.marshall.VersionAwareMarshaller; import org.jboss.cache.optimistic.DataVersion; import org.jboss.cache.statetransfer.StateTransferFactory; import org.jboss.cache.statetransfer.StateTransferGenerator; import org.jboss.cache.statetransfer.StateTransferIntegrator; import org.jboss.cache.util.MBeanConfigurator; import org.jboss.invocation.MarshalledValueOutputStream; import org.jboss.system.ServiceMBeanSupport; import org.jgroups.Address; import org.jgroups.Channel; import org.jgroups.ChannelClosedException; import org.jgroups.ChannelNotConnectedException; import org.jgroups.JChannel; import org.jgroups.MembershipListener; import org.jgroups.Message; import org.jgroups.MessageListener; import org.jgroups.View; import org.jgroups.blocks.GroupRequest; import org.jgroups.blocks.MethodCall; import org.jgroups.blocks.RpcDispatcher; import org.jgroups.jmx.JmxConfigurator; import org.jgroups.stack.IpAddress; import org.jgroups.util.Rsp; import org.jgroups.util.RspList; import org.w3c.dom.Attr; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.NodeList; import javax.management.MBeanOperationInfo; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; import javax.management.ObjectName; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.NotSerializableException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.Vector; /** * A tree-like structure that is replicated across several members. Updates are * multicast to all group members reliably and in order. User has the * option to set transaction isolation levels and other options. * * @author Bela Ban * @author Ben Wang * @author Manik Surtani (manik@jboss.org) * @author Brian Stansberry * @author Daniel Huang (dhuang@jboss.org) * @author Galder Zamarreno * @version $Id: TreeCache.java 8082 2009-06-03 16:45:08Z dereed $ *

* @see JBossCache doc */ public class TreeCache extends ServiceMBeanSupport implements TreeCacheMBean, Cloneable, MembershipListener { private static final String CREATE_MUX_CHANNEL = "createMultiplexerChannel"; private static final String[] MUX_TYPES = {"java.lang.String", "java.lang.String"}; private static final String JBOSS_SERVER_DOMAIN = "jboss"; private static final String JGROUPS_JMX_DOMAIN = "jboss.jgroups"; private static final String CHANNEL_JMX_ATTRIBUTES = "type=channel,cluster="; private static final String PROTOCOL_JMX_ATTRIBUTES = "type=protocol,cluster="; private boolean forceAnycast = false; /** * Default replication version, from {@link Version#getVersionShort}. */ public static final short DEFAULT_REPLICATION_VERSION = Version.getVersionShort(); // Quite poor, but for now, root may be re-initialised when setNodeLockingOptimistic() is called. // this is because if node locking is optimistic, we need to use OptimisticTreeNodes rather than TreeNodes. // - MANIK /** * Root DataNode. */ protected DataNode root = NodeFactory.getInstance().createRootDataNode(NodeFactory.NODE_TYPE_TREENODE, this); /** * Set of TreeCacheListener. * * @see #addTreeCacheListener */ private final Set listeners = new CopyOnWriteArraySet(); // calling iterator on a ConcurrentHashMap is expensive due to synchronization - same problem // with calling isEmpty so hasListeners is an optimization to indicate whether or not listeners // is empty // /** * True if listeners are initialized. */ protected boolean hasListeners = false; // store this seperately from other listeners to avoid concurrency penalty of // iterating through ConcurrentHashMap - eviction listener is always there (or almost always) // and there are less frequently other listeners so optimization is justified // TreeCacheListener evictionPolicyListener = null; final static Object NULL = new Object(); /** * The JGroups JChannel in use. */ protected JChannel channel = null; /** * The JGroups multiplexer service name; null if the multiplexer isn't used */ protected String mux_serviceName = null; /** * The JGroups multiplexer stack name, default is "udp" */ protected String mux_stackName = "udp"; /** * Is this cache using a channel from the JGroups multiplexer */ protected boolean using_mux = false; /** * True if this TreeCache is the coordinator. */ protected boolean coordinator = false; /** * TreeCache log. */ protected final static Log log = LogFactory.getLog(TreeCache.class); /** * Default cluster name. */ protected String cluster_name = "TreeCache-Group"; /** * Default cluster properties. * * @see #getClusterProperties */ protected String cluster_props = null; /** * List of cluster group members. */ protected final Vector members = new Vector(); /** * JGroups RpcDispatcher in use. */ protected RpcDispatcher disp = null; /** * JGroups message listener. */ protected MessageListener ml = new MessageListenerAdaptor(log); /** * True if replication is queued. */ protected boolean use_repl_queue = false; /** * Maximum number of replicated elements to queue. */ protected int repl_queue_max_elements = 1000; /** * Replicated element queue interval. */ protected long repl_queue_interval = 5000; /** * True if MBean interceptors are used. * * @see #getUseInterceptorMbeans */ protected boolean use_interceptor_mbeans = true; /** * Maintains mapping of transactions (keys) and Modifications/Undo-Operations */ private final TransactionTable tx_table = new TransactionTable(); /** * HashMap, maintains locks acquired by threads (used when no TXs are used) */ private final Map lock_table = new ConcurrentHashMap(); protected boolean fetchInMemoryState = true; protected boolean usingEviction = false; // These are private as the setters ensure consistency between them // - Brian private short replication_version = DEFAULT_REPLICATION_VERSION; private String repl_version_string = Version.getVersionString(DEFAULT_REPLICATION_VERSION); protected long lock_acquisition_timeout = 10000; protected long state_fetch_timeout = lock_acquisition_timeout + 5000; protected long sync_repl_timeout = 15000; protected String eviction_policy_class = null; protected int cache_mode = LOCAL; protected boolean inactiveOnStartup = false; protected boolean isStandalone = false; /** * Set of Fqns of the topmost node of internal regions that should * not included in standard state transfers. */ protected Set internalFqns = new CopyOnWriteArraySet(); /** * True if state was initialized during start-up. */ protected boolean isStateSet = false; /** * An exception occuring upon fetch state. */ protected Exception setStateException; private final Object stateLock = new Object(); /** * Isolation level in use, default is {@link IsolationLevel#REPEATABLE_READ}. */ protected IsolationLevel isolationLevel = IsolationLevel.REPEATABLE_READ; /** * Require write locks on parents before adding or removing children. Default false. */ protected boolean lockParentForChildInsertRemove = false; /** * This ThreadLocal contains an {@see InvocationContext} object, which holds * invocation-specific details. */ private ThreadLocal invocationContextContainer = new ThreadLocal(); /** * Eviction policy configuration in xml Element */ protected Element evictConfig_ = null; protected String evictionInterceptorClass = "org.jboss.cache.interceptors.EvictionInterceptor"; /** * True if we use region based marshalling. Defaults to false. */ protected boolean useRegionBasedMarshalling = false; /** * Marshaller if register to handle marshalling */ protected VersionAwareMarshaller marshaller_ = null; /** * RegionManager used by marshaller and ExtendedCacheLoader */ protected RegionManager regionManager_ = null; /** * RegionManager used by cache eviction */ protected org.jboss.cache.eviction.RegionManager evictionRegionManager_ = null; /** * {@link #invokeMethod(MethodCall)} will dispatch to this chain of interceptors. * In the future, this will be replaced with JBossAop. This is a first step towards refactoring JBossCache. */ protected Interceptor interceptor_chain = null; /** * Method to acquire a TransactionManager. By default we use JBossTransactionManagerLookup. Has * to be set before calling {@link #start()} */ protected TransactionManagerLookup tm_lookup = null; /** * Class of the implementation of TransactionManagerLookup */ protected String tm_lookup_class = null; /** * Used to get the Transaction associated with the current thread */ protected TransactionManager tm = null; /** * The XML Element from which to configure the CacheLoader */ protected Element cacheLoaderConfig = null; protected CacheLoaderManager cacheLoaderManager; /** * for legacy use * */ protected CacheLoaderConfig cloaderConfig; /** * True if there is a synchronous commit phase, otherwise asynchronous commit. */ protected boolean sync_commit_phase = false; /** * True if there is a synchronous rollback phase, otherwise asynchronous rollback. */ protected boolean sync_rollback_phase = false; /** * @deprecated DO NOT USE THIS. IT IS HERE FOR EJB3 COMPILATION COMPATIBILITY WITH JBOSSCACHE1.3 */ protected EvictionPolicy eviction_policy_provider; /** * Queue used to replicate updates when mode is repl-async */ protected ReplicationQueue repl_queue = null; /** * @deprecated use {@link Fqn#SEPARATOR}. */ public static final String SEPARATOR = Fqn.SEPARATOR; /** * Entries in the cache are by default local and not replicated. */ public static final int LOCAL = 1; /** * Entries in the cache are by default replicated asynchronously. */ public static final int REPL_ASYNC = 2; /** * Entries in the cache are by default replicated synchronously. */ public static final int REPL_SYNC = 3; /** * Cache sends {@link #evict} calls to remote caches when a node is changed. * {@link #evict} calls are asynchronous. */ public static final int INVALIDATION_ASYNC = 4; /** * Cache sends {@link #evict} calls to remote caches when a node is changed. * {@link #evict} calls are synchronous. */ public static final int INVALIDATION_SYNC = 5; /** * Uninitialized node key. */ static public final String UNINITIALIZED = "jboss:internal:uninitialized"; /** * Determines whether to use optimistic locking or not. Disabled by default. */ protected boolean nodeLockingOptimistic = false; /** * _createService was called. */ protected boolean useCreateService = false; /** * Buddy replication configuration XML element */ protected Element buddyReplicationConfig; /** * Buddy Manager */ protected BuddyManager buddyManager; /** * Set of Fqns of nodes that are currently being processed by * activateReqion or inactivateRegion. Requests for these fqns * will be ignored by _getState(). */ protected final Set activationChangeNodes = new HashSet(); /** * The JGroups 2.4.1 or higher "callRemoteMethods" overload that * provides Anycast support. */ protected Method anycastMethod; /** Did we register our channel in JMX ourself? */ protected boolean channelRegistered; /** Did we register our channel's protocols in JMX ourself? */ protected boolean protocolsRegistered; /** * Creates a channel with the given cluster name, properties, and state fetch timeout. */ public TreeCache(String cluster_name, String props, long state_fetch_timeout) throws Exception { if (cluster_name != null) this.cluster_name = cluster_name; if (props != null) this.cluster_props = props; this.state_fetch_timeout = state_fetch_timeout; } /** * Constructs an uninitialized TreeCache. */ public TreeCache() throws Exception { } /** * Constructs a TreeCache with an already connected channel. */ public TreeCache(JChannel channel) throws Exception { this.channel = channel; } /** * Returns the TreeCache implementation version. */ public String getVersion() { return Version.printVersion(); } /** * Used internally by interceptors. * Don't use as client, this method will go away. */ public DataNode getRoot() { return root; } /** * Returns the local channel address. */ public Object getLocalAddress() { return channel != null ? channel.getLocalAddress() : null; } /** * Returns the members as a Vector. */ public Vector getMembers() { return members; } /** * Returns true if this node is the group coordinator. */ public boolean isCoordinator() { return coordinator; } /** * Returns the name of the replication cluster group. */ public String getClusterName() { return cluster_name; } /** * Sets the name of the replication cluster group. */ public void setClusterName(String name) { cluster_name = name; } /** * Returns the cluster properties as a String. * In the case of JGroups, returns the JGroup protocol stack specification. */ public String getClusterProperties() { return cluster_props; } /** * Sets the cluster properties. * To use the new properties, the cache must be restarted using * {@link #stop} and {@link #start}. * * @param cluster_props The properties for the cluster (JGroups) */ public void setClusterProperties(String cluster_props) { this.cluster_props = cluster_props; } public String getMultiplexerService() { return mux_serviceName; } public void setMultiplexerService(String serviceName) { mux_serviceName = serviceName; } public String getMultiplexerStack() { return mux_stackName; } public void setMultiplexerStack(String name) { mux_stackName = name; } /** * Gets whether this cache using a channel from the JGroups multiplexer. * Will not provide a meaningful result until after {@link #startService()} * is invoked. */ public boolean isUsingMultiplexer() { return using_mux; } public boolean isForceAnycast() { return forceAnycast; } public void setForceAnycast(boolean b) { forceAnycast = b; } /** * Returns the transaction table. */ public TransactionTable getTransactionTable() { return tx_table; } /** * Returns the lock table. */ public Map getLockTable() { return lock_table; } /** * Returns the contents of the TransactionTable as a string. */ public String dumpTransactionTable() { return tx_table.toString(true); } /** * Returns false. * * @deprecated */ public boolean getDeadlockDetection() { return false; } /** * Does nothing. * * @deprecated */ public void setDeadlockDetection(boolean dt) { log.warn("Using deprecated configuration element 'DeadlockDetection'. Will be ignored."); } /** * Returns the interceptor chain as a debug string. * Returns <empty> if not initialized. */ public String getInterceptorChain() { String retval = InterceptorChainFactory.printInterceptorChain(interceptor_chain); if (retval == null || retval.length() == 0) return ""; else return retval; } /** * Used for testing only - sets the interceptor chain. */ public void setInterceptorChain(Interceptor i) { interceptor_chain = i; } /** * Returns the list of interceptors. */ public List getInterceptors() { return InterceptorChainFactory.asList(interceptor_chain); } /** * Returns the cache loader configuration element. */ public Element getCacheLoaderConfiguration() { return cacheLoaderConfig; } /** * Sets the cache loader configuration element. */ public void setCacheLoaderConfiguration(Element cache_loader_config) { if (cloaderConfig != null) log.warn("Specified CacheLoaderConfig XML block will be ignored, because deprecated setters are used!"); this.cacheLoaderConfig = cache_loader_config; } /** * Returns the underlying cache loader in use. */ public CacheLoader getCacheLoader() { if (cacheLoaderManager == null) return null; return cacheLoaderManager.getCacheLoader(); } /** * Used for PojoCache. No-op here. * * @param config * @throws CacheException */ public void setPojoCacheConfig(Element config) throws CacheException { log.warn("setPojoCacheConfig(): You have a PojoCache config that is not used in TreeCache."); } public Element getPojoCacheConfig() { return null; } /** * Returns the MessageListener in use. */ public MessageListener getMessageListener() { return ml; } /** * Returns whether the entire tree is inactive upon startup, only responding * to replication messages after {@link #activateRegion(String)} is called * to activate one or more parts of the tree. *

* This property is only relevant if {@link #getUseMarshalling()} is * true. */ public boolean isInactiveOnStartup() { return inactiveOnStartup; } /** * Sets whether the entire tree is inactive upon startup, only responding * to replication messages after {@link #activateRegion(String)} is * called to activage one or more parts of the tree. *

* This property is only relevant if {@link #getUseMarshalling()} is * true. */ public void setInactiveOnStartup(boolean inactiveOnStartup) { this.inactiveOnStartup = inactiveOnStartup; } /** * Returns if sync commit phase is used. */ public boolean getSyncCommitPhase() { return sync_commit_phase; } /** * Sets if sync commit phase is used. */ public void setSyncCommitPhase(boolean sync_commit_phase) { this.sync_commit_phase = sync_commit_phase; } /** * Returns if sync rollback phase is used. */ public boolean getSyncRollbackPhase() { return sync_rollback_phase; } /** * Sets if sync rollback phase is used. */ public void setSyncRollbackPhase(boolean sync_rollback_phase) { this.sync_rollback_phase = sync_rollback_phase; } /** * Sets the eviction policy configuration element. */ public void setEvictionPolicyConfig(Element config) { evictConfig_ = config; if (log.isDebugEnabled()) log.debug("setEvictionPolicyConfig(): " + config); } /** * Returns the eviction policy configuration element. */ public Element getEvictionPolicyConfig() { return evictConfig_; } public String getEvictionInterceptorClass() { return this.evictionInterceptorClass; } public boolean isUsingEviction() { return this.usingEviction; } public void setIsUsingEviction(boolean usingEviction) { this.usingEviction = usingEviction; } /** * Converts a list of elements to a Java Groups property string. */ public void setClusterConfig(Element config) { StringBuffer buffer = new StringBuffer(); NodeList stack = config.getChildNodes(); int length = stack.getLength(); for (int s = 0; s < length; s++) { org.w3c.dom.Node node = stack.item(s); if (node.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) continue; Element tag = (Element) node; String protocol = tag.getTagName(); buffer.append(protocol); NamedNodeMap attrs = tag.getAttributes(); int attrLength = attrs.getLength(); if (attrLength > 0) buffer.append('('); for (int a = 0; a < attrLength; a++) { Attr attr = (Attr) attrs.item(a); String name = attr.getName(); String value = attr.getValue(); buffer.append(name); buffer.append('='); buffer.append(value); if (a < attrLength - 1) buffer.append(';'); } if (attrLength > 0) buffer.append(')'); buffer.append(':'); } // Remove the trailing ':' buffer.setLength(buffer.length() - 1); setClusterProperties(buffer.toString()); if (log.isDebugEnabled()) log.debug("setting cluster properties from xml to: " + cluster_props); } /** * Returns the max time to wait until the initial state is retrieved. * This is used in a replicating cache: when a new cache joins the cluster, * it needs to acquire the (replicated) state of the other members to * initialize itself. If no state has been received within timeout * milliseconds, the map will be not be initialized. * * @return long milliseconds to wait for the state; 0 means to wait forever */ public long getInitialStateRetrievalTimeout() { return state_fetch_timeout; } /** * Sets the initial state transfer timeout. * see #getInitialStateRetrievalTimeout() */ public void setInitialStateRetrievalTimeout(long timeout) { state_fetch_timeout = timeout; } /** * Returns the current caching mode. String values returned are: *