JBoss Cache SVN: r6902 - core/branches/flat.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-10 08:52:50 -0400 (Fri, 10 Oct 2008)
New Revision: 6902
Modified:
core/branches/flat/pom.xml
Log:
Updated JGroups
Modified: core/branches/flat/pom.xml
===================================================================
--- core/branches/flat/pom.xml 2008-10-10 09:43:27 UTC (rev 6901)
+++ core/branches/flat/pom.xml 2008-10-10 12:52:50 UTC (rev 6902)
@@ -27,7 +27,7 @@
<dependency>
<groupId>jgroups</groupId>
<artifactId>jgroups</artifactId>
- <version>2.6.4.GA</version>
+ <version>2.6.5.GA</version>
</dependency>
<!-- For the JTA 1.1 API; consuming projects can safely
@@ -405,7 +405,7 @@
<dependency>
<groupId>jgroups</groupId>
<artifactId>jgroups</artifactId>
- <version>2.6.4.GA</version>
+ <version>2.6.5.GA</version>
</dependency>
<!-- Replaces javax.transaction/jta -->
<dependency>
17 years, 2 months
JBoss Cache SVN: r6901 - in core/branches/flat/src: main/java/org/jboss/starobrno/commands/read and 10 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-10 05:43:27 -0400 (Fri, 10 Oct 2008)
New Revision: 6901
Added:
core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheAPITest.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheSPITest.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/AbstractBatchTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithTM.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithoutTM.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockAssert.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockTestBase.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/ReadCommittedLockTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/RepeatableReadLockTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/WriteSkewTest.java
Modified:
core/branches/flat/src/main/java/org/jboss/cache/transaction/DummyBaseTransactionManager.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContext.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/TxInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java
Log:
Fixed stuff
Modified: core/branches/flat/src/main/java/org/jboss/cache/transaction/DummyBaseTransactionManager.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/transaction/DummyBaseTransactionManager.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/cache/transaction/DummyBaseTransactionManager.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -21,6 +21,9 @@
*/
package org.jboss.cache.transaction;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.InvalidTransactionException;
@@ -41,6 +44,8 @@
{
static ThreadLocal<Transaction> thread_local = new ThreadLocal<Transaction>();
private static final long serialVersionUID = -6716097342564237376l;
+ private static final Log log = LogFactory.getLog(DummyBaseTransactionManager.class);
+ private static final boolean trace = log.isTraceEnabled();
/**
* Starts a new transaction, and associate it with the calling thread.
@@ -214,6 +219,7 @@
{
Transaction retval = getTransaction();
setTransaction(null);
+ if (trace) log.trace("Suspending tx " + retval);
return retval;
}
@@ -233,6 +239,7 @@
*/
public void resume(Transaction tx) throws InvalidTransactionException, IllegalStateException, SystemException
{
+ if (trace) log.trace("Resuming tx " + tx);
setTransaction(tx);
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -76,4 +76,12 @@
{
return (key != null ? key.hashCode() : 0);
}
+
+
+ public String toString()
+ {
+ return getClass().getSimpleName() + "{" +
+ "key=" + key +
+ '}';
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -61,7 +61,7 @@
MVCCEntry entry = ctx.lookupEntry(key);
if (entry == null || entry.isNullEntry())
{
- if (trace) log.trace("Node not found");
+ if (trace) log.trace("Entry not found");
return null;
}
if (entry.isDeleted())
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -62,12 +62,4 @@
{
return METHOD_ID;
}
-
-
- public String toString()
- {
- return "AbstractDataCommand{" +
- "key=" + key +
- '}';
- }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -79,7 +79,7 @@
MVCCEntry mvccEntry;
if (forceWriteLock)
{
- if (trace) log.trace("Forcing lock on reading key " + key);
+ if (trace) log.trace("Forcing lock on reading");
return wrapEntryForWriting(ctx, key, false, false);
}
else if ((mvccEntry = ctx.lookupEntry(key)) == null)
@@ -88,12 +88,12 @@
// simple implementation. Peek the node, wrap it, put wrapped node in the context.
Object value = container.get(key);
mvccEntry = entryFactory.createWrappedEntry(key, value, false);
- if (mvccEntry != null && putInContext) ctx.putLookedUpEntry(mvccEntry);
+ if (mvccEntry != null && putInContext) ctx.putLookedUpEntry(key, mvccEntry);
return mvccEntry;
}
else
{
- if (trace) log.trace("Key " + key + " is already in context.");
+ if (trace) log.trace("Key is already in context");
return mvccEntry;
}
}
@@ -110,7 +110,7 @@
// create a copy of the underlying node
mvccEntry.copyForUpdate(container, writeSkewCheck);
}
- if (trace) log.trace("Retrieving wrapped node " + key);
+ if (trace) log.trace("Exists in context.");
if (mvccEntry.isDeleted() && createIfAbsent)
{
if (trace) log.trace("Node is deleted in current scope. Need to un-delete.");
@@ -124,21 +124,23 @@
Object value = container.get(key);
if (value != null)
{
+ if (trace) log.trace("Retrieved from container.");
// exists in cache! Just acquire lock if needed, and wrap.
// do we need a lock?
boolean needToCopy = false;
if (acquireLock(ctx, key)) needToCopy = true;
mvccEntry = entryFactory.createWrappedEntry(key, value, false);
- ctx.putLookedUpEntry(mvccEntry);
+ ctx.putLookedUpEntry(key, mvccEntry);
if (needToCopy) mvccEntry.copyForUpdate(container, writeSkewCheck);
}
else if (createIfAbsent) // else, do we need to create one?
{
+ if (trace) log.trace("Creating new entry.");
// now to lock and create the node. Lock first to prevent concurrent creation!
acquireLock(ctx, key);
mvccEntry = entryFactory.createWrappedEntry(key, value, true);
mvccEntry.setCreated(true);
- ctx.putLookedUpEntry(mvccEntry);
+ ctx.putLookedUpEntry(key, mvccEntry);
mvccEntry.copyForUpdate(container, writeSkewCheck);
}
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -202,4 +202,17 @@
else
unsetFlag(DELETED);
}
+
+ public String toString()
+ {
+ return getClass().getSimpleName() + "(" + System.identityHashCode(this) + "){" +
+ "key=" + key +
+ ", value=" + value +
+ ", oldValue=" + oldValue +
+ ", isCreated=" + isCreated() +
+ ", isChanged=" + isChanged() +
+ ", isDeleted=" + isDeleted() +
+ ", isValid=" + isValid() +
+ '}';
+ }
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -24,7 +24,6 @@
import org.jboss.starobrno.container.MVCCEntry;
import java.util.Map;
-import java.util.Set;
/**
* // TODO: MANIK: Document this
@@ -38,9 +37,9 @@
Map<Object, MVCCEntry> getLookedUpEntries();
- void putLookedUpEntry(MVCCEntry e);
+ void putLookedUpEntry(Object key, MVCCEntry e);
- void putLookedUpEntries(Set<MVCCEntry> lookedUpEntries);
+ void putLookedUpEntries(Map<Object, MVCCEntry> lookedUpEntries);
void clearLookedUpEntries();
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContext.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContext.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContext.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -21,7 +21,6 @@
*/
package org.jboss.starobrno.context;
-import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.config.Option;
import org.jboss.starobrno.transaction.GlobalTransaction;
@@ -84,10 +83,6 @@
long getLockAcquisitionTimeout(long timeout);
- void setCommand(VisitableCommand cacheCommand);
-
- VisitableCommand getCommand();
-
boolean isValidTransaction();
void throwIfNeeded(Throwable e) throws Throwable;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -24,7 +24,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.util.Immutables;
-import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.config.Option;
import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.transaction.GlobalTransaction;
@@ -36,7 +35,6 @@
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
-import java.util.Set;
/**
* // TODO: MANIK: Document this
@@ -51,13 +49,11 @@
private Transaction transaction;
private GlobalTransaction globalTransaction;
- protected TransactionContext transactionContext;
+ protected volatile TransactionContext transactionContext;
private Option optionOverrides;
// defaults to true.
private boolean originLocal = true;
private boolean localRollbackOnly;
- @Deprecated
- private VisitableCommand command;
/**
* LinkedHashSet of locks acquired by the invocation. We use a LinkedHashSet because we need efficient Set semantics
@@ -80,8 +76,14 @@
*/
public MVCCEntry lookupEntry(Object k)
{
- if (transactionContext != null) return transactionContext.lookupEntry(k);
- return lookedUpEntries == null ? null : lookedUpEntries.get(k);
+ if (transactionContext != null)
+ {
+ return transactionContext.lookupEntry(k);
+ }
+ else
+ {
+ return lookedUpEntries == null ? null : lookedUpEntries.get(k);
+ }
}
/**
@@ -90,21 +92,20 @@
* If a transaction is in progress, implementations should delegate to {@link org.jboss.cache.transaction.MVCCTransactionContext#putLookedUpNode(Fqn, NodeSPI)}
* <p/>
*
- * @param f fqn to add
- * @param n node to add
+ * @param key
*/
- public void putLookedUpEntry(MVCCEntry e)
+ public void putLookedUpEntry(Object key, MVCCEntry e)
{
if (transactionContext != null)
- transactionContext.putLookedUpEntry(e);
+ transactionContext.putLookedUpEntry(key, e);
else
{
if (lookedUpEntries == null) lookedUpEntries = new HashMap<Object, MVCCEntry>(4);
- lookedUpEntries.put(e.getKey(), e);
+ lookedUpEntries.put(key, e);
}
}
- public void putLookedUpEntries(Set<MVCCEntry> lookedUpEntries)
+ public void putLookedUpEntries(Map<Object, MVCCEntry> lookedUpEntries)
{
if (transactionContext != null)
transactionContext.putLookedUpEntries(lookedUpEntries);
@@ -113,20 +114,15 @@
if (this.lookedUpEntries == null)
this.lookedUpEntries = new HashMap<Object, MVCCEntry>();
- for (MVCCEntry e : lookedUpEntries) this.lookedUpEntries.put(e.getKey(), e);
+ this.lookedUpEntries.putAll(lookedUpEntries);
}
}
/**
* Clears the registry of looked up nodes.
- * <p/>
- * If a transaction is in progress, implementations should delegate to {@link org.jboss.cache.transaction.MVCCTransactionContext#clearLookedUpNodes()}.
*/
public void clearLookedUpEntries()
{
-// if (transactionContext != null)
-// transactionContext.clearLookedUpEntries();
-// else if (lookedUpEntries != null) lookedUpEntries.clear();
if (lookedUpEntries != null) lookedUpEntries.clear();
}
@@ -452,7 +448,6 @@
optionOverrides = null;
originLocal = true;
invocationLocks = null;
- command = null;
if (lookedUpEntries != null)
{
lookedUpEntries.clear();
@@ -498,31 +493,6 @@
}
/**
- * This is only used for backward compatibility with old interceptors implementation and should <b>NOT</b> be
- * use by any new custom interceptors. The commands is now passed in as the second param in each implementing
- * handlers (handler = method in ChainedInterceptor class)
- *
- * @param cacheCommand command to set
- */
- @Deprecated
- @SuppressWarnings("deprecation")
- public void setCommand(VisitableCommand cacheCommand)
- {
- this.command = cacheCommand;
- }
-
- /**
- * @return command that is in scope
- * @see #setCommand(org.jboss.cache.commands.VisitableCommand)
- */
- @Deprecated
- @SuppressWarnings("deprecation")
- public VisitableCommand getCommand()
- {
- return command;
- }
-
- /**
* @return true if there is current transaction associated with the invocation, and this transaction is in a valid state.
*/
public boolean isValidTransaction()
@@ -555,7 +525,6 @@
protected void doCopy(InvocationContext c)
{
InvocationContextImpl copy = (InvocationContextImpl) c;
- copy.command = command;
copy.globalTransaction = globalTransaction;
copy.invocationLocks = invocationLocks == null ? null : new LinkedHashSet(invocationLocks);
copy.localRollbackOnly = localRollbackOnly;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -37,7 +37,6 @@
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.Set;
/**
* A transaction context specially geared to dealing with MVCC.
@@ -116,12 +115,11 @@
* would delegate to this method if a transaction is in scope.
* <p/>
*
- * @param f fqn to add
- * @param n node to add
+ * @param key
*/
- public void putLookedUpEntry(MVCCEntry entry)
+ public void putLookedUpEntry(Object key, MVCCEntry entry)
{
- lookedUpEntries.put(entry.getKey(), entry);
+ lookedUpEntries.put(key, entry);
}
/**
@@ -162,9 +160,9 @@
lookedUpEntries.clear();
}
- public void putLookedUpEntries(Set<MVCCEntry> entries)
+ public void putLookedUpEntries(Map<Object, MVCCEntry> entries)
{
- for (MVCCEntry e : entries) lookedUpEntries.put(e.getKey(), e);
+ lookedUpEntries.putAll(entries);
}
public void addModification(VisitableCommand command)
@@ -291,7 +289,7 @@
public String toString()
{
StringBuilder sb = new StringBuilder();
- sb.append("TransactionEntry\nmodificationList: ").append(modificationList);
+ sb.append("TransactionContext (" + System.identityHashCode(this) + ") nmodificationList: ").append(modificationList);
return sb.toString();
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -259,7 +259,6 @@
@SuppressWarnings("deprecation")
public Object invoke(InvocationContext ctx, VisitableCommand command)
{
- ctx.setCommand(command);
try
{
return command.acceptVisitor(ctx, firstInChain);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -60,7 +60,7 @@
@Override
public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
{
- return handleAll(ctx, command, ctx.getGlobalTransaction(), false);
+ return handleAll(ctx, command, ctx.getGlobalTransaction(), true);
}
@Override
@@ -102,7 +102,7 @@
@Override
public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
{
- return handleAll(ctx, command, null, false);
+ return handleAll(ctx, command, null, true);
}
@SuppressWarnings("deprecation")
@@ -199,9 +199,6 @@
}
}
- // reset the context to prevent leakage of internals
- ctx.setCommand(null);
-
// TODO: Calling ctx.reset() here breaks stuff. Check whether this is just becuse UTs expect stuff in the ctx or whether this really breaks functionality.
// ctx.reset();
// instead, for now, just wipe contents of the looked up node map
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -226,7 +226,7 @@
Set<Object> keysToRemove = new HashSet<Object>();
for (MVCCEntry e : ctx.getLookedUpEntries().values())
{
- if (e.isChanged()) keysToRemove.add(e.getKey());
+ if (!e.isChanged()) keysToRemove.add(e.getKey());
}
for (Object k : keysToRemove) ctx.removeKeyLocked(k);
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/TxInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/TxInterceptor.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/TxInterceptor.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -482,16 +482,7 @@
{
GlobalTransaction gtx = ctx.getGlobalTransaction();
Object result;
- VisitableCommand originalCommand = ctx.getCommand();
- ctx.setCommand(command);
- try
- {
- result = invokeNextInterceptor(ctx, command);
- }
- finally
- {
- ctx.setCommand(originalCommand);
- }
+ result = invokeNextInterceptor(ctx, command);
if (log.isDebugEnabled()) log.debug("Finished local commit/rollback method for " + gtx);
return result;
}
@@ -605,16 +596,7 @@
Transaction currentTransaction = txManager.getTransaction();
if (currentTransaction != null && ltx != null && currentTransaction.equals(ltx))
{
- VisitableCommand originalCommand = ctx.getCommand();
- ctx.setCommand(prepareCommand);
- try
- {
- result = invokeNextInterceptor(ctx, prepareCommand);
- }
- finally
- {
- ctx.setCommand(originalCommand);
- }
+ result = invokeNextInterceptor(ctx, prepareCommand);
}
else
{
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java 2008-10-10 08:18:13 UTC (rev 6900)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -35,7 +35,6 @@
import org.jboss.starobrno.CacheException;
import org.jboss.starobrno.CacheSPI;
import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.annotations.Destroy;
import org.jboss.starobrno.factories.annotations.Inject;
@@ -638,10 +637,7 @@
{
InvocationContext currentIC = cache.getInvocationContext();
backup.clearLookedUpEntries();
- for (MVCCEntry me : currentIC.getLookedUpEntries().values())
- {
- backup.putLookedUpEntry(me);
- }
+ backup.putLookedUpEntries(currentIC.getLookedUpEntries());
cache.setInvocationContext(backup);
}
@@ -658,10 +654,7 @@
cache.setInvocationContext(null);
// get a new Invocation Context
InvocationContext newContext = cache.getInvocationContext();
- for (MVCCEntry me : ctx.getLookedUpEntries().values())
- {
- newContext.putLookedUpEntry(me);
- }
+ newContext.putLookedUpEntries(ctx.getLookedUpEntries());
return ctx;
}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheAPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheAPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheAPITest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,154 @@
+package org.jboss.starobrno.api;
+
+import org.jboss.cache.CacheFactory;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.transaction.GenericTransactionManagerLookup;
+import org.jboss.starobrno.CacheSPI;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.config.ConfigurationException;
+import org.jboss.starobrno.util.TestingUtil;
+import static org.testng.AssertJUnit.assertEquals;
+import static org.testng.AssertJUnit.assertNull;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Tests the {@link org.jboss.cache.Cache} public API at a high level
+ *
+ * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
+ */
+
+@Test(groups = {"functional", "pessimistic"})
+public class CacheAPITest
+{
+ private CacheSPI<String, String> cache;
+ final List<String> events = new ArrayList<String>();
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+ // start a single cache instance
+ CacheFactory<String, String> cf = new DefaultCacheFactory<String, String>();
+ cache = (CacheSPI<String, String>) cf.createCache("configs/local-tx.xml", false);
+ cache.getConfiguration().setEvictionConfig(null);
+ configure(cache.getConfiguration());
+ cache.start();
+ events.clear();
+ }
+
+ protected void configure(Configuration c)
+ {
+ }
+
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown()
+ {
+ TestingUtil.killCaches(cache);
+ }
+
+ /**
+ * Tests that the configuration contains the values expected, as well as immutability of certain elements
+ */
+ public void testConfiguration()
+ {
+ Configuration c = cache.getConfiguration();
+ assertEquals(Configuration.CacheMode.LOCAL, c.getCacheMode());
+ assertEquals(GenericTransactionManagerLookup.class.getName(), c.getTransactionManagerLookupClass());
+
+ // note that certain values should be immutable. E.g., CacheMode cannot be changed on the fly.
+ try
+ {
+ c.setCacheMode(Configuration.CacheMode.REPL_SYNC);
+ assert false : "Should have thrown an Exception";
+ }
+ catch (ConfigurationException e)
+ {
+ // expected
+ }
+
+ // others should be changeable though.
+ c.setLockAcquisitionTimeout(100);
+ }
+
+ public void testGetMembersInLocalMode()
+ {
+ assert cache.getRPCManager() == null : "Cache members should be null if running in LOCAL mode";
+ }
+
+ /**
+ * All cache operations should happen on a {@link Node} - I.e., you look up a {@link Node} and perform data operations
+ * on this {@link Node}. For convenience and familiarity with JBoss Cache 1.x, we provide some helpers in {@link Cache}
+ * which dives you direct data access to nodes.
+ * <p/>
+ * This test exercises these.
+ */
+ public void testConvenienceMethods()
+ {
+ String key = "key", value = "value";
+ Map<String, String> data = new HashMap<String, String>();
+ data.put(key, value);
+
+ assertNull(cache.get(key));
+
+ cache.put(key, value);
+
+ assertEquals(value, cache.get(key));
+
+ cache.remove(key);
+
+ assertNull(cache.get(key));
+
+ cache.putAll(data);
+
+ assertEquals(value, cache.get(key));
+ }
+
+ /**
+ * Tests basic eviction
+ */
+ public void testEvict()
+ {
+ String key1 = "keyOne", key2 = "keyTwo", value = "value";
+
+ cache.put(key1, value);
+ cache.put(key2, value);
+
+ assert cache.containsKey(key1);
+ assert cache.containsKey(key2);
+ assert cache.size() == 2;
+
+ // evict two
+ cache.evict(key2);
+
+ assert cache.containsKey(key1);
+ assert !cache.containsKey(key2);
+ assert cache.size() == 1;
+
+ cache.evict(key1);
+
+ assert !cache.containsKey(key1);
+ assert !cache.containsKey(key2);
+ assert cache.size() == 0;
+ }
+
+ public void testStopClearsData() throws Exception
+ {
+ String key = "key", value = "value";
+ cache.put(key, value);
+ assert cache.get(key).equals(value);
+ assert 1 == cache.size();
+ cache.stop();
+
+ cache.start();
+
+ assert !cache.containsKey(key);
+ assert cache.isEmpty();
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheSPITest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheSPITest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/CacheSPITest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,97 @@
+package org.jboss.starobrno.api;
+
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.starobrno.CacheSPI;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.config.Configuration.CacheMode;
+import org.jboss.starobrno.util.TestingUtil;
+import org.jboss.starobrno.util.internals.ViewChangeListener;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+@Test(groups = {"functional", "pessimistic"})
+public class CacheSPITest
+{
+ private CacheSPI<Object, Object> cache1;
+ private CacheSPI<Object, Object> cache2;
+
+ @BeforeMethod(alwaysRun = true)
+ public void setUp() throws Exception
+ {
+
+ Configuration conf1 = new Configuration();
+ conf1.setCacheMode(CacheMode.REPL_SYNC);
+
+ Configuration conf2 = conf1.clone();
+
+ cache1 = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(conf1, false);
+ cache2 = (CacheSPI<Object, Object>) new DefaultCacheFactory<Object, Object>().createCache(conf2, false);
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws Exception
+ {
+ if (cache1 != null)
+ {
+ try
+ {
+ cache1.stop();
+ }
+ catch (Exception e)
+ {
+ }
+ }
+
+ if (cache2 != null)
+ {
+ try
+ {
+ cache2.stop();
+ }
+ catch (Exception e)
+ {
+ }
+ }
+ }
+
+ public void testGetMembers() throws Exception
+ {
+ cache1.start();
+ List memb1 = cache1.getRPCManager().getMembers();
+ assert 1 == memb1.size();
+
+ Object coord = memb1.get(0);
+
+ cache2.start();
+ memb1 = cache1.getRPCManager().getMembers();
+ TestingUtil.blockUntilViewsReceived(5000, false, cache1, cache2);
+ List memb2 = cache2.getRPCManager().getMembers();
+ assert 2 == memb1.size();
+ assert memb1 == memb2;
+
+ cache1.stop();
+ TestingUtil.blockUntilViewsReceived(5000, false, cache2);
+ memb2 = cache2.getRPCManager().getMembers();
+ assert 1 == memb2.size();
+ assert !coord.equals(memb2.get(0));
+ }
+
+ public void testIsCoordinator() throws Exception
+ {
+ cache1.start();
+ assert cache1.getRPCManager().isCoordinator();
+
+ cache2.start();
+ assert cache1.getRPCManager().isCoordinator();
+ assert !cache2.getRPCManager().isCoordinator();
+ ViewChangeListener viewChangeListener = new ViewChangeListener(cache2);
+ cache1.stop();
+ // wait till cache2 gets the view change notification
+ assert viewChangeListener.waitForViewChange(60, TimeUnit.SECONDS) : "Should have received a view change!";
+ assert cache2.getRPCManager().isCoordinator();
+ }
+}
\ No newline at end of file
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/AbstractBatchTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/AbstractBatchTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/AbstractBatchTest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,24 @@
+package org.jboss.starobrno.api.batch;
+
+import org.jboss.starobrno.Cache;
+
+import java.util.concurrent.atomic.AtomicReference;
+
+public abstract class AbstractBatchTest
+{
+ protected String getOnDifferentThread(final Cache<String, String> cache, final String key) throws InterruptedException
+ {
+ final AtomicReference<String> ref = new AtomicReference<String>();
+ Thread t = new Thread()
+ {
+ public void run()
+ {
+ ref.set(cache.get(key));
+ }
+ };
+
+ t.start();
+ t.join();
+ return ref.get();
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithTM.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithTM.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithTM.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,123 @@
+package org.jboss.starobrno.api.batch;
+
+import org.jboss.cache.CacheFactory;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.transaction.DummyTransactionManagerLookup;
+import org.jboss.starobrno.Cache;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import javax.transaction.TransactionManager;
+
+
+@Test(groups = {"functional", "transaction"})
+public class BatchWithTM extends AbstractBatchTest
+{
+ public void testBatchWithOngoingTM() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache();
+ TransactionManager tm = getTransactionManager(cache);
+ tm.begin();
+ cache.put("k", "v");
+ cache.startBatch();
+ cache.put("k2", "v2");
+ tm.commit();
+
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
+
+ cache.endBatch(false); // should be a no op
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchWithoutOngoingTMSuspension() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache();
+ TransactionManager tm = getTransactionManager(cache);
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+ cache.startBatch();
+ cache.put("k", "v");
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+ cache.put("k2", "v2");
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+
+ try
+ {
+ tm.commit(); // should have no effect
+ }
+ catch (Exception e)
+ {
+ // the TM may barf here ... this is OK.
+ }
+
+ assert tm.getTransaction() == null : "Should have no ongoing txs";
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+
+ cache.endBatch(true); // should be a no op
+
+ assert "v".equals(getOnDifferentThread(cache, "k"));
+ assert "v2".equals(getOnDifferentThread(cache, "k2"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchRollback() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache();
+ TransactionManager tm = getTransactionManager(cache);
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.put("k2", "v2");
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+
+ cache.endBatch(false);
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ private TransactionManager getTransactionManager(Cache<String, String> c)
+ {
+ return c.getConfiguration().getRuntimeConfig().getTransactionManager();
+ }
+
+ private Cache<String, String> createCache()
+ {
+ CacheFactory<String, String> cf = new DefaultCacheFactory<String, String>();
+ Configuration c = new Configuration();
+ c.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ c.setInvocationBatchingEnabled(true);
+ assert c.getTransactionManagerLookupClass() != null : "Should have a transaction manager lookup class attached!!";
+ return cf.createCache(c);
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithoutTM.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithoutTM.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/BatchWithoutTM.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,144 @@
+package org.jboss.starobrno.api.batch;
+
+import org.jboss.cache.CacheFactory;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.starobrno.Cache;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.config.ConfigurationException;
+import org.jboss.starobrno.util.TestingUtil;
+import org.testng.annotations.Test;
+
+@Test(groups = "functional")
+public class BatchWithoutTM extends AbstractBatchTest
+{
+ public void testBatchWithoutCfg()
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(false);
+ try
+ {
+ cache.startBatch();
+ assert false : "Should have failed";
+ }
+ catch (ConfigurationException good)
+ {
+ // do nothing
+ }
+
+ try
+ {
+ cache.endBatch(true);
+ assert false : "Should have failed";
+ }
+ catch (ConfigurationException good)
+ {
+ // do nothing
+ }
+
+ try
+ {
+ cache.endBatch(false);
+ assert false : "Should have failed";
+ }
+ catch (ConfigurationException good)
+ {
+ // do nothing
+ }
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testEndBatchWithoutStartBatch()
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.endBatch(true);
+ cache.endBatch(false);
+ // should not fail.
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testStartBatchIdempotency()
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.startBatch(); // again
+ cache.put("k2", "v2");
+ cache.endBatch(true);
+
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchVisibility() throws InterruptedException
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.startBatch();
+ cache.put("k", "v");
+ assert getOnDifferentThread(cache, "k") == null : "Other thread should not see batch update till batch completes!";
+
+ cache.endBatch(true);
+
+ assert "v".equals(getOnDifferentThread(cache, "k"));
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ public void testBatchRollback() throws Exception
+ {
+ Cache<String, String> cache = null;
+ try
+ {
+ cache = createCache(true);
+ cache.startBatch();
+ cache.put("k", "v");
+ cache.put("k2", "v2");
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+
+ cache.endBatch(false);
+
+ assert getOnDifferentThread(cache, "k") == null;
+ assert getOnDifferentThread(cache, "k2") == null;
+ }
+ finally
+ {
+ TestingUtil.killCaches(cache);
+ }
+ }
+
+ private Cache<String, String> createCache(boolean enableBatch)
+ {
+ CacheFactory<String, String> cf = new DefaultCacheFactory<String, String>();
+ Configuration c = new Configuration();
+ c.setInvocationBatchingEnabled(enableBatch);
+ return cf.createCache(c);
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockAssert.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockAssert.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockAssert.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,35 @@
+package org.jboss.starobrno.api.mvcc;
+
+import org.jboss.cache.util.concurrent.locks.LockContainer;
+import org.jboss.starobrno.invocation.InvocationContextContainer;
+import org.jboss.starobrno.lock.LockManager;
+import org.jboss.starobrno.util.TestingUtil;
+
+/**
+ * Helper class to assert lock status in MVCC
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class LockAssert
+{
+ public static void assertLocked(Object key, LockManager lockManager, InvocationContextContainer icc)
+ {
+ assert lockManager.isLocked(key) : key + " not locked!";
+// assert icc.get().getKeysLocked().contains(key) : "Lock not recorded for " + key;
+ }
+
+ public static void assertNotLocked(Object key, InvocationContextContainer icc)
+ {
+ // can't rely on the negative test since other nodes may share the same lock with lock striping.
+// assert !lockManager.isLocked(fqn) : fqn + " is locked!";
+ assert !icc.get().getKeysLocked().contains(key) : key + " lock recorded!";
+ }
+
+ public static void assertNoLocks(LockManager lockManager, InvocationContextContainer icc)
+ {
+ LockContainer lc = (LockContainer) TestingUtil.extractField(lockManager, "lockContainer");
+ assert lc.getNumLocksHeld() == 0 : "Stale locks exist! NumLocksHeld is " + lc.getNumLocksHeld() + " and lock info is " + lockManager.printLockInfo();
+ assert icc.get().getKeysLocked().isEmpty() : "Stale (?) locks recorded! " + icc.get().getKeysLocked();
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockTestBase.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockTestBase.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/LockTestBase.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,301 @@
+package org.jboss.starobrno.api.mvcc;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.lock.IsolationLevel;
+import org.jboss.cache.lock.TimeoutException;
+import org.jboss.cache.transaction.DummyTransactionManagerLookup;
+import org.jboss.starobrno.Cache;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.invocation.InvocationContextContainer;
+import org.jboss.starobrno.lock.LockManager;
+import org.jboss.starobrno.util.TestingUtil;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+import java.util.Collections;
+
+/**
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+@Test(groups = {"functional", "mvcc"})
+public abstract class LockTestBase
+{
+ protected Cache<String, String> cache;
+ protected TransactionManager tm;
+ protected LockManager lockManager;
+ protected InvocationContextContainer icc;
+ protected boolean repeatableRead = true;
+ protected boolean lockParentForChildInsertRemove = false;
+ private Log log = LogFactory.getLog(LockTestBase.class);
+
+
+ @BeforeMethod
+ public void setUp()
+ {
+ cache = new DefaultCacheFactory<String, String>().createCache(new Configuration(), false);
+ cache.getConfiguration().setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ cache.getConfiguration().setIsolationLevel(repeatableRead ? IsolationLevel.REPEATABLE_READ : IsolationLevel.READ_COMMITTED);
+ cache.getConfiguration().setLockParentForChildInsertRemove(lockParentForChildInsertRemove);
+ // reduce lock acquisition timeout so this doesn't take forever to run
+ cache.getConfiguration().setLockAcquisitionTimeout(200); // 200 ms
+ cache.start();
+ lockManager = TestingUtil.extractComponentRegistry(cache).getComponent(LockManager.class);
+ icc = TestingUtil.extractComponentRegistry(cache).getComponent(InvocationContextContainer.class);
+ tm = TestingUtil.extractComponentRegistry(cache).getComponent(TransactionManager.class);
+ }
+
+ @AfterMethod
+ public void tearDown()
+ {
+ log.debug("**** - STARTING TEARDOWN - ****");
+ TestingUtil.killCaches(cache);
+ }
+
+ protected void assertLocked(Object key)
+ {
+ LockAssert.assertLocked(key, lockManager, icc);
+ }
+
+ protected void assertNotLocked(Object key)
+ {
+ LockAssert.assertNotLocked(key, icc);
+ }
+
+ protected void assertNoLocks()
+ {
+ LockAssert.assertNoLocks(lockManager, icc);
+ }
+
+ public void testLocksOnPutKeyVal() throws Exception
+ {
+ tm.begin();
+ cache.put("k", "v");
+ assertLocked("k");
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.begin();
+ assert cache.get("k").equals("v");
+ assertNotLocked("k");
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.begin();
+ cache.remove("k");
+ assertLocked("k");
+ tm.commit();
+
+ assertNoLocks();
+ }
+
+ public void testLocksOnPutData() throws Exception
+ {
+ tm.begin();
+ cache.putAll(Collections.singletonMap("k", "v"));
+ assertLocked("k");
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ assertNoLocks();
+ tm.commit();
+
+ assertNoLocks();
+ }
+
+ public void testLocksOnEvictNode() throws Exception
+ {
+ // init some data on a node
+ cache.putAll(Collections.singletonMap("k", "v"));
+
+ assert "v".equals(cache.get("k"));
+
+ tm.begin();
+ cache.evict("k");
+ assertLocked("k");
+ tm.commit();
+ assert !cache.containsKey("k") : "Should not exist";
+ assertNoLocks();
+ }
+
+ public void testLocksOnRemoveNonexistentNode() throws Exception
+ {
+ assert !cache.containsKey("k") : "Should not exist";
+
+ tm.begin();
+ cache.remove("k");
+ assertLocked("k");
+ tm.commit();
+ assert !cache.containsKey("k") : "Should not exist";
+ assertNoLocks();
+ }
+
+ public void testLocksOnEvictNonexistentNode() throws Exception
+ {
+ assert !cache.containsKey("k") : "Should not exist";
+
+ tm.begin();
+ cache.evict("k");
+ assertLocked("k");
+ tm.commit();
+ assert !cache.containsKey("k") : "Should not exist";
+ assertNoLocks();
+ }
+
+ public void testLocksOnRemoveData() throws Exception
+ {
+ // init some data on a node
+ cache.put("k", "v");
+ cache.put("k2", "v2");
+
+ assert "v".equals(cache.get("k"));
+ assert "v2".equals(cache.get("k2"));
+
+ // remove
+ tm.begin();
+ cache.clear();
+ assertLocked("k");
+ assertLocked("k2");
+ tm.commit();
+
+ assert cache.isEmpty();
+ assertNoLocks();
+ }
+
+ public void testWriteDoesntBlockRead() throws Exception
+ {
+ cache.put("k", "v");
+
+ // start a write.
+ tm.begin();
+ cache.put("k2", "v2");
+ assertLocked("k2");
+ Transaction write = tm.suspend();
+
+ // now start a read and confirm that the write doesn't block it.
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ assert null == cache.get("k2") : "Should not see uncommitted changes";
+ Transaction read = tm.suspend();
+
+ // commit the write
+ tm.resume(write);
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.resume(read);
+ if (repeatableRead)
+ assert null == cache.get("k2") : "Should have repeatable read";
+ else
+ assert "v2".equals(cache.get("k2")) : "Read committed should see committed changes";
+ tm.commit();
+ assertNoLocks();
+ }
+
+ public void testWriteDoesntBlockReadNonexistent() throws Exception
+ {
+ // start a write.
+ tm.begin();
+ cache.put("k", "v");
+ assertLocked("k");
+ Transaction write = tm.suspend();
+
+ // now start a read and confirm that the write doesn't block it.
+ tm.begin();
+ assert null == cache.get("k") : "Should not see uncommitted changes";
+ Transaction read = tm.suspend();
+
+ // commit the write
+ tm.resume(write);
+ tm.commit();
+
+ assertNoLocks();
+
+ tm.resume(read);
+ if (repeatableRead)
+ {
+ assert null == cache.get("k") : "Should have repeatable read";
+ }
+ else
+ {
+ assert "v".equals(cache.get("k")) : "Read committed should see committed changes";
+ }
+ tm.commit();
+ assertNoLocks();
+ }
+
+ public void testConcurrentWriters() throws Exception
+ {
+ tm.begin();
+ cache.put("k", "v");
+ Transaction t1 = tm.suspend();
+
+ tm.begin();
+ try
+ {
+ cache.put("k", "v");
+ assert false : "Should fail lock acquisition";
+ }
+ catch (TimeoutException expected)
+ {
+// expected.printStackTrace(); // for debugging
+ }
+ tm.commit();
+ tm.resume(t1);
+ tm.commit();
+ assertNoLocks();
+ }
+
+ public void testRollbacks() throws Exception
+ {
+ cache.put("k", "v");
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.put("k", "v2");
+ tm.rollback();
+
+ tm.resume(reader);
+ Object value = cache.get("k");
+ assert "v".equals(value) : "Expecting 'v' but was " + value;
+ tm.commit();
+
+ // even after commit
+ assert "v".equals(cache.get("k"));
+ assertNoLocks();
+ }
+
+ public void testRollbacksOnNullNode() throws Exception
+ {
+ tm.begin();
+ assert null == cache.get("k");
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.put("k", "v");
+ assert "v".equals(cache.get("k"));
+ tm.rollback();
+
+ tm.resume(reader);
+ assert null == cache.get("k") : "Expecting null but was " + cache.get("k");
+ tm.commit();
+
+ // even after commit
+ assert null == cache.get("k");
+ assertNoLocks();
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/CacheAPIMVCCTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/CacheAPIMVCCTest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,20 @@
+package org.jboss.starobrno.api.mvcc.read_committed;
+
+import org.jboss.cache.lock.IsolationLevel;
+import org.jboss.starobrno.api.CacheAPITest;
+import org.jboss.starobrno.config.Configuration;
+import org.testng.annotations.Test;
+
+/**
+ * MVCC version of {@link org.jboss.cache.api.CacheAPITest}
+ */
+@Test(groups = {"functional", "mvcc"})
+public class CacheAPIMVCCTest extends CacheAPITest
+{
+ @Override
+ protected void configure(Configuration c)
+ {
+ super.configure(c);
+ c.setIsolationLevel(IsolationLevel.READ_COMMITTED);
+ }
+}
\ No newline at end of file
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/ReadCommittedLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/ReadCommittedLockTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/ReadCommittedLockTest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,13 @@
+package org.jboss.starobrno.api.mvcc.read_committed;
+
+import org.jboss.starobrno.api.mvcc.LockTestBase;
+import org.testng.annotations.Test;
+
+@Test(groups = {"functional", "mvcc"})
+public class ReadCommittedLockTest extends LockTestBase
+{
+ public ReadCommittedLockTest()
+ {
+ repeatableRead = false;
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/CacheAPIMVCCTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/CacheAPIMVCCTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/CacheAPIMVCCTest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,20 @@
+package org.jboss.starobrno.api.mvcc.repeatable_read;
+
+import org.jboss.cache.lock.IsolationLevel;
+import org.jboss.starobrno.api.CacheAPITest;
+import org.jboss.starobrno.config.Configuration;
+import org.testng.annotations.Test;
+
+/**
+ * MVCC version of {@link org.jboss.cache.api.CacheAPITest}
+ */
+@Test(groups = {"functional", "mvcc"})
+public class CacheAPIMVCCTest extends CacheAPITest
+{
+ @Override
+ protected void configure(Configuration c)
+ {
+ super.configure(c);
+ c.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
+ }
+}
\ No newline at end of file
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/RepeatableReadLockTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/RepeatableReadLockTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/RepeatableReadLockTest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,90 @@
+package org.jboss.starobrno.api.mvcc.repeatable_read;
+
+import org.jboss.starobrno.api.mvcc.LockTestBase;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+
+@Test(groups = {"functional", "mvcc"})
+public class RepeatableReadLockTest extends LockTestBase
+{
+ public RepeatableReadLockTest()
+ {
+ repeatableRead = true;
+ }
+
+ public void testRepeatableReadWithRemove() throws Exception
+ {
+ cache.put("k", "v");
+
+ tm.begin();
+ assert cache.get("k") != null;
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ assert cache.remove("k") != null;
+ assert cache.get("k") == null;
+ tm.commit();
+
+ assert cache.get("k") == null;
+
+ tm.resume(reader);
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assert cache.get("k") == null;
+ assertNoLocks();
+ }
+
+ public void testRepeatableReadWithEvict() throws Exception
+ {
+ cache.put("k", "v");
+
+ tm.begin();
+ assert cache.get("k") != null;
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.evict("k");
+ assert cache.get("k") == null;
+ tm.commit();
+
+ assert cache.get("k") == null;
+
+ tm.resume(reader);
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assert cache.get("k") == null;
+ assertNoLocks();
+ }
+
+ public void testRepeatableReadWithNull() throws Exception
+ {
+ assert cache.get("k") == null;
+
+ tm.begin();
+ assert cache.get("k") == null;
+ Transaction reader = tm.suspend();
+
+ tm.begin();
+ cache.put("k", "v");
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ tm.commit();
+
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+
+ tm.resume(reader);
+ Object o = cache.get("k");
+ assert o == null : "found value " + o;
+ tm.commit();
+
+ assert cache.get("k") != null;
+ assert "v".equals(cache.get("k"));
+ assertNoLocks();
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/WriteSkewTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/WriteSkewTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/WriteSkewTest.java 2008-10-10 09:43:27 UTC (rev 6901)
@@ -0,0 +1,191 @@
+package org.jboss.starobrno.api.mvcc.repeatable_read;
+
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.cache.lock.IsolationLevel;
+import org.jboss.cache.transaction.DummyTransactionManagerLookup;
+import org.jboss.starobrno.Cache;
+import org.jboss.starobrno.api.mvcc.LockAssert;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.invocation.InvocationContextContainer;
+import org.jboss.starobrno.lock.LockManager;
+import org.jboss.starobrno.util.TestingUtil;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import javax.transaction.SystemException;
+import javax.transaction.TransactionManager;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+
+@Test(groups = {"functional", "mvcc"})
+public class WriteSkewTest
+{
+ protected Cache<String, String> cache;
+ protected TransactionManager tm;
+ protected LockManager lockManager;
+ protected InvocationContextContainer icc;
+ protected boolean repeatableRead = true;
+
+ @BeforeMethod
+ public void setUp()
+ {
+ cache = new DefaultCacheFactory<String, String>().createCache(new Configuration(), false);
+ cache.getConfiguration().setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ cache.getConfiguration().setIsolationLevel(repeatableRead ? IsolationLevel.REPEATABLE_READ : IsolationLevel.READ_COMMITTED);
+ // reduce lock acquisition timeout so this doesn't take forever to run
+ cache.getConfiguration().setLockAcquisitionTimeout(200); // 200 ms
+ }
+
+ @AfterMethod
+ public void tearDown()
+ {
+ TestingUtil.killCaches(cache);
+ }
+
+ private void postStart()
+ {
+ lockManager = TestingUtil.extractComponentRegistry(cache).getComponent(LockManager.class);
+ icc = TestingUtil.extractComponentRegistry(cache).getComponent(InvocationContextContainer.class);
+ tm = TestingUtil.extractComponentRegistry(cache).getComponent(TransactionManager.class);
+ }
+
+ protected void assertNoLocks()
+ {
+ LockAssert.assertNoLocks(lockManager, icc);
+ }
+
+ public void testDontCheckWriteSkew() throws Exception
+ {
+ cache.getConfiguration().setWriteSkewCheck(false);
+ cache.start();
+ postStart();
+ doTest(true);
+ }
+
+ public void testCheckWriteSkew() throws Exception
+ {
+ cache.getConfiguration().setWriteSkewCheck(true);
+ cache.start();
+ postStart();
+ doTest(false);
+ }
+
+ private void doTest(final boolean allowWriteSkew) throws Exception
+ {
+ if (repeatableRead)
+ {
+ cache.put("k", "v");
+ final Set<Exception> w1exceptions = new HashSet<Exception>();
+ final Set<Exception> w2exceptions = new HashSet<Exception>();
+ final CountDownLatch w1Signal = new CountDownLatch(1);
+ final CountDownLatch w2Signal = new CountDownLatch(1);
+ final CountDownLatch threadSignal = new CountDownLatch(2);
+
+ Thread w1 = new Thread("Writer-1")
+ {
+ public void run()
+ {
+ boolean didCoundDown = false;
+ try
+ {
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ threadSignal.countDown();
+ didCoundDown = true;
+ w1Signal.await();
+ cache.put("k", "v2");
+ tm.commit();
+ }
+ catch (Exception e)
+ {
+ w1exceptions.add(e);
+ }
+ finally
+ {
+ if (!didCoundDown) threadSignal.countDown();
+ }
+ }
+ };
+
+ Thread w2 = new Thread("Writer-2")
+ {
+ public void run()
+ {
+ boolean didCoundDown = false;
+ try
+ {
+ tm.begin();
+ assert "v".equals(cache.get("k"));
+ threadSignal.countDown();
+ didCoundDown = true;
+ w2Signal.await();
+ cache.put("k", "v3");
+ tm.commit();
+ }
+ catch (Exception e)
+ {
+ w2exceptions.add(e);
+ // the exception will be thrown when doing a cache.put(). We should make sure we roll back the tx to release locks.
+ if (!allowWriteSkew)
+ {
+ try
+ {
+ tm.rollback();
+ }
+ catch (SystemException e1)
+ {
+ // do nothing.
+ }
+ }
+ }
+ finally
+ {
+ if (!didCoundDown) threadSignal.countDown();
+ }
+ }
+ };
+
+ w1.start();
+ w2.start();
+
+ threadSignal.await();
+ // now. both txs have read.
+ // let tx1 start writing
+ w1Signal.countDown();
+ w1.join();
+
+ w2Signal.countDown();
+ w2.join();
+
+ if (allowWriteSkew)
+ {
+ // should have no exceptions!!
+ throwExceptions(w1exceptions, w2exceptions);
+ assert w2exceptions.size() == 0;
+ assert w1exceptions.size() == 0;
+ assert "v3".equals(cache.get("k")) : "W2 should have overwritten W1's work!";
+ }
+ else
+ {
+ // there should be a single exception from w2.
+ assert w2exceptions.size() == 1;
+ throwExceptions(w1exceptions);
+ assert w1exceptions.size() == 0;
+ assert "v2".equals(cache.get("k")) : "W2 should NOT have overwritten W1's work!";
+ }
+
+ assertNoLocks();
+ }
+ }
+
+ private void throwExceptions(Collection<Exception>... exceptions) throws Exception
+ {
+ for (Collection<Exception> ce : exceptions)
+ {
+ for (Exception e : ce) throw e;
+ }
+ }
+}
17 years, 2 months
JBoss Cache SVN: r6900 - in core/branches/flat/src/main/java/org/jboss/cache: marshall and 1 other directory.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-10 04:18:13 -0400 (Fri, 10 Oct 2008)
New Revision: 6900
Removed:
core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValue.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueMap.java
Log:
Removed junk
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java 2008-10-09 16:51:41 UTC (rev 6899)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java 2008-10-10 08:18:13 UTC (rev 6900)
@@ -1,240 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.DataContainer;
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.commands.read.GetKeyValueCommand;
-import org.jboss.cache.commands.write.EvictCommand;
-import org.jboss.cache.commands.write.PutDataMapCommand;
-import org.jboss.cache.commands.write.PutForExternalReadCommand;
-import org.jboss.cache.commands.write.PutKeyValueCommand;
-import org.jboss.cache.interceptors.base.JmxStatsCommandInterceptor;
-import org.jboss.cache.jmx.annotations.ManagedAttribute;
-import org.jboss.cache.jmx.annotations.ManagedOperation;
-import org.jboss.starobrno.factories.annotations.Inject;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Captures cache management statistics
- *
- * @author Jerry Gauthier
- * @version $Id$
- */
-public class CacheMgmtInterceptor extends JmxStatsCommandInterceptor
-{
- private long hitTimes = 0;
- private long missTimes = 0;
- private long storeTimes = 0;
- private long hits = 0;
- private long misses = 0;
- private long stores = 0;
- private long evictions = 0;
- private long start = System.currentTimeMillis();
- private long reset = start;
-
- private DataContainer dataContainer;
-
- @Inject
- public void setDependencies(DataContainer dataContainer)
- {
- this.dataContainer = dataContainer;
- }
-
- @Override
- public Object visitEvictFqnCommand(InvocationContext ctx, EvictCommand command) throws Throwable
- {
- Object returnValue = invokeNextInterceptor(ctx, command);
- evictions++;
- return returnValue;
- }
-
- @Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
- long t1 = System.currentTimeMillis();
- Object retval = invokeNextInterceptor(ctx, command);
- long t2 = System.currentTimeMillis();
- if (retval == null)
- {
- missTimes = missTimes + (t2 - t1);
- misses++;
- }
- else
- {
- hitTimes = hitTimes + (t2 - t1);
- hits++;
- }
- return retval;
- }
-
- @Override
- public Object visitPutDataMapCommand(InvocationContext ctx, PutDataMapCommand command) throws Throwable
- {
- Map data = command.getData();
- long t1 = System.currentTimeMillis();
- Object retval = invokeNextInterceptor(ctx, command);
- long t2 = System.currentTimeMillis();
-
- if (data != null && data.size() > 0)
- {
- storeTimes = storeTimes + (t2 - t1);
- stores = stores + data.size();
- }
- return retval;
- }
-
-
- @Override
- public Object visitPutForExternalReadCommand(InvocationContext ctx, PutForExternalReadCommand command) throws Throwable
- {
- return visitPutKeyValueCommand(ctx, command);
- }
-
- @Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- long t1 = System.currentTimeMillis();
- Object retval = invokeNextInterceptor(ctx, command);
- long t2 = System.currentTimeMillis();
- storeTimes = storeTimes + (t2 - t1);
- stores++;
- return retval;
- }
-
- @ManagedAttribute(description = "number of cache attribute hits")
- public long getHits()
- {
- return hits;
- }
-
- @ManagedAttribute(description = "number of cache attribute misses")
- public long getMisses()
- {
- return misses;
- }
-
- @ManagedAttribute(description = "number of cache attribute put operations")
- public long getStores()
- {
- return stores;
- }
-
- @ManagedAttribute(description = "number of cache eviction operations")
- public long getEvictions()
- {
- return evictions;
- }
-
- @ManagedAttribute(description = "hit/miss ratio for the cache")
- public double getHitMissRatio()
- {
- double total = hits + misses;
- if (total == 0)
- return 0;
- return (hits / total);
- }
-
- @ManagedAttribute(description = "read/writes ratio for the cache")
- public double getReadWriteRatio()
- {
- if (stores == 0)
- return 0;
- return (((double) (hits + misses) / (double) stores));
- }
-
- @ManagedAttribute(description = "average number of milliseconds for a read operation")
- public long getAverageReadTime()
- {
- long total = hits + misses;
- if (total == 0)
- return 0;
- return (hitTimes + missTimes) / total;
- }
-
- @ManagedAttribute(description = "average number of milliseconds for a write operation")
- public long getAverageWriteTime()
- {
- if (stores == 0)
- return 0;
- return (storeTimes) / stores;
- }
-
- @ManagedAttribute(description = "number of cache eviction operations")
- public int getNumberOfAttributes()
- {
- return dataContainer.getNumberOfAttributes();
- }
-
- @ManagedAttribute
- public int getNumberOfNodes()
- {
- return dataContainer.getNumberOfNodes();
- }
-
- @ManagedAttribute(description = "seconds since cache started")
- public long getElapsedTime()
- {
- return (System.currentTimeMillis() - start) / 1000;
- }
-
- @ManagedAttribute(description = "number of seconds since the cache statistics were last reset")
- public long getTimeSinceReset()
- {
- return (System.currentTimeMillis() - reset) / 1000;
- }
-
- @ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>();
- retval.put("Hits", hits);
- retval.put("Misses", misses);
- retval.put("Stores", stores);
- retval.put("Evictions", evictions);
- retval.put("NumberOfAttributes", dataContainer.getNumberOfAttributes());
- retval.put("NumberOfNodes", dataContainer.getNumberOfNodes());
- retval.put("ElapsedTime", getElapsedTime());
- retval.put("TimeSinceReset", getTimeSinceReset());
- retval.put("AverageReadTime", getAverageReadTime());
- retval.put("AverageWriteTime", getAverageWriteTime());
- retval.put("HitMissRatio", getHitMissRatio());
- retval.put("ReadWriteRatio", getReadWriteRatio());
- return retval;
- }
-
- @ManagedOperation
- public void resetStatistics()
- {
- hits = 0;
- misses = 0;
- stores = 0;
- evictions = 0;
- hitTimes = 0;
- missTimes = 0;
- storeTimes = 0;
- reset = System.currentTimeMillis();
- }
-}
-
Deleted: core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValue.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValue.java 2008-10-09 16:51:41 UTC (rev 6899)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValue.java 2008-10-10 08:18:13 UTC (rev 6900)
@@ -1,229 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.marshall;
-
-import org.jboss.starobrno.CacheException;
-import org.jboss.util.stream.MarshalledValueInputStream;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.NotSerializableException;
-import java.io.ObjectInput;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Arrays;
-
-/**
- * Wrapper that wraps cached data, providing lazy deserialization using the calling thread's context class loader.
- * <p/>
- * The {@link org.jboss.cache.interceptors.MarshalledValueInterceptor} handles transparent
- * wrapping/unwrapping of cached data.
- * <p/>
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @see org.jboss.cache.interceptors.MarshalledValueInterceptor
- * @since 2.1.0
- */
-public class MarshalledValue implements Externalizable
-{
- protected Object instance;
- protected byte[] raw;
- private int cachedHashCode = 0;
- // by default equals() will test on the istance rather than the byte array if conversion is required.
- private transient boolean equalityPreferenceForInstance = true;
-
- public MarshalledValue(Object instance) throws NotSerializableException
- {
- if (instance == null) throw new NullPointerException("Null values cannot be wrapped as MarshalledValues!");
-
- if (instance instanceof Serializable)
- this.instance = instance;
- else
- throw new NotSerializableException("Marshalled values can only wrap Objects that are serializable! Instance of " + instance.getClass() + " won't Serialize.");
- }
-
- public MarshalledValue()
- {
- // empty ctor for serialization
- }
-
- public void setEqualityPreferenceForInstance(boolean equalityPreferenceForInstance)
- {
- this.equalityPreferenceForInstance = equalityPreferenceForInstance;
- }
-
- public synchronized void serialize()
- {
- if (raw == null)
- {
- try
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(baos);
- oos.writeObject(instance);
- oos.close();
- baos.close();
- // Do NOT set instance to null over here, since it may be used elsewhere (e.g., in a cache listener).
- // this will be compacted by the MarshalledValueInterceptor when the call returns.
-// instance = null;
- raw = baos.toByteArray();
- }
- catch (Exception e)
- {
- throw new CacheException("Unable to marshall value " + instance, e);
- }
- }
- }
-
- public synchronized void deserialize()
- {
- if (instance == null)
- {
- try
- {
- ByteArrayInputStream bais = new ByteArrayInputStream(raw);
- // use a MarshalledValueInputStream since it needs to be aware of any context class loaders on the current thread.
- ObjectInputStream ois = new MarshalledValueInputStream(bais);
- instance = ois.readObject();
- ois.close();
- bais.close();
-// raw = null;
- }
- catch (Exception e)
- {
- throw new CacheException("Unable to unmarshall value", e);
- }
- }
- }
-
- /**
- * Compacts the references held by this class to a single reference. If only one representation exists this method
- * is a no-op unless the 'force' parameter is used, in which case the reference held is forcefully switched to the
- * 'preferred representation'.
- * <p/>
- * Either way, a call to compact() will ensure that only one representation is held.
- * <p/>
- *
- * @param preferSerializedRepresentation if true and both representations exist, the serialized representation is favoured. If false, the deserialized representation is preferred.
- * @param force ensures the preferred representation is maintained and the other released, even if this means serializing or deserializing.
- */
- public void compact(boolean preferSerializedRepresentation, boolean force)
- {
- // reset the equalityPreference
- equalityPreferenceForInstance = true;
- if (force)
- {
- if (preferSerializedRepresentation && raw == null) serialize();
- else if (!preferSerializedRepresentation && instance == null) deserialize();
- }
-
- if (instance != null && raw != null)
- {
- // need to lose one representation!
-
- if (preferSerializedRepresentation)
- {
- instance = null;
- }
- else
- {
- raw = null;
- }
- }
- }
-
- public void writeExternal(ObjectOutput out) throws IOException
- {
- if (raw == null) serialize();
- out.writeInt(raw.length);
- out.write(raw);
- out.writeInt(hashCode());
- }
-
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
- int size = in.readInt();
- raw = new byte[size];
- cachedHashCode = 0;
- in.readFully(raw);
- cachedHashCode = in.readInt();
- }
-
- public Object get() throws IOException, ClassNotFoundException
- {
- if (instance == null) deserialize();
- return instance;
- }
-
- @Override
- public boolean equals(Object o)
- {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
-
- MarshalledValue that = (MarshalledValue) o;
-
- // if both versions are serialized or deserialized, just compare the relevant representations.
- if (raw != null && that.raw != null) return Arrays.equals(raw, that.raw);
- if (instance != null && that.instance != null) return instance.equals(that.instance);
-
- // if conversion of one representation to the other is necessary, then see which we prefer converting.
- if (equalityPreferenceForInstance)
- {
- if (instance == null) deserialize();
- if (that.instance == null) that.deserialize();
- return instance.equals(that.instance);
- }
- else
- {
- if (raw == null) serialize();
- if (that.raw == null) that.serialize();
- return Arrays.equals(raw, that.raw);
- }
- }
-
- @Override
- public int hashCode()
- {
- if (cachedHashCode == 0)
- {
- // always calculate the hashcode based on the instance since this is where we're getting the equals()
- if (instance == null) deserialize();
- cachedHashCode = instance.hashCode();
- if (cachedHashCode == 0) // degenerate case
- {
- cachedHashCode = 0xFEED;
- }
- }
- return cachedHashCode;
- }
-
- @Override
- public String toString()
- {
- return "MarshalledValue(cachedHashCode=" + cachedHashCode + "; serialized=" + (raw != null) + ")";
- }
-}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java 2008-10-09 16:51:41 UTC (rev 6899)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java 2008-10-10 08:18:13 UTC (rev 6900)
@@ -1,55 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.marshall;
-
-import org.jboss.cache.Fqn;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.transaction.GlobalTransaction;
-import org.jgroups.Address;
-
-/**
- * Common functionality used by the {@link org.jboss.cache.interceptors.MarshalledValueInterceptor} and the {@link MarshalledValueMap}.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @see MarshalledValue
- * @see org.jboss.cache.interceptors.MarshalledValueInterceptor
- * @see org.jboss.cache.marshall.MarshalledValueMap
- * @since 2.1.0
- */
-public class MarshalledValueHelper
-{
- /**
- * Tests whether the type should be excluded from MarshalledValue wrapping.
- *
- * @param type type to test. Should not be null.
- * @return true if it should be excluded from MarshalledValue wrapping.
- */
- public static boolean isTypeExcluded(Class type)
- {
- return type.equals(String.class) || type.isPrimitive() ||
- type.equals(Void.class) || type.equals(Boolean.class) || type.equals(Character.class) ||
- type.equals(Byte.class) || type.equals(Short.class) || type.equals(Integer.class) ||
- type.equals(Long.class) || type.equals(Float.class) || type.equals(Double.class) ||
- (type.isArray() && isTypeExcluded(type.getComponentType())) || type.equals(Fqn.class) || type.equals(GlobalTransaction.class) || type.equals(Address.class) ||
- ReplicableCommand.class.isAssignableFrom(type) || type.equals(MarshalledValue.class);
- }
-}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueMap.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueMap.java 2008-10-09 16:51:41 UTC (rev 6899)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueMap.java 2008-10-10 08:18:13 UTC (rev 6900)
@@ -1,181 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.marshall;
-
-import net.jcip.annotations.Immutable;
-import org.jboss.starobrno.CacheException;
-
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A Map that is able to wrap/unwrap MarshalledValues in keys or values. Note that calling keySet(), entrySet() or values()
- * could be expensive if this map is large!!
- * <p/>
- * Also note that this is an immutable Map.
- * <p/>
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @see MarshalledValue
- * @since 2.1.0
- */
-@Immutable
-public class MarshalledValueMap implements Map, Externalizable
-{
- Map delegate;
- Map<Object, Object> unmarshalled;
-
- public MarshalledValueMap()
- {
- // for externalization
- }
-
- public MarshalledValueMap(Map delegate)
- {
- this.delegate = delegate;
- }
-
- @SuppressWarnings("unchecked")
- protected synchronized Map getUnmarshalledMap()
- {
- if (unmarshalled == null) unmarshalled = unmarshalledMap(delegate.entrySet());
- return unmarshalled;
- }
-
- public int size()
- {
- return delegate.size();
- }
-
- public boolean isEmpty()
- {
- return delegate.isEmpty();
- }
-
- public boolean containsKey(Object key)
- {
- return getUnmarshalledMap().containsKey(key);
- }
-
- public boolean containsValue(Object value)
- {
- return getUnmarshalledMap().containsValue(value);
- }
-
- public Object get(Object key)
- {
- return getUnmarshalledMap().get(key);
- }
-
- public Object put(Object key, Object value)
- {
- throw new UnsupportedOperationException("This is an immutable map!");
- }
-
- public Object remove(Object key)
- {
- throw new UnsupportedOperationException("This is an immutable map!");
- }
-
- public void putAll(Map t)
- {
- throw new UnsupportedOperationException("This is an immutable map!");
- }
-
- public void clear()
- {
- throw new UnsupportedOperationException("This is an immutable map!");
- }
-
- public Set keySet()
- {
- return getUnmarshalledMap().keySet();
- }
-
- public Collection values()
- {
- return getUnmarshalledMap().values();
- }
-
- public Set entrySet()
- {
- return getUnmarshalledMap().entrySet();
- }
-
- @SuppressWarnings("unchecked")
- protected Map unmarshalledMap(Set entries)
- {
- if (entries == null || entries.isEmpty()) return Collections.emptyMap();
- Map map = new HashMap(entries.size());
- for (Object e : entries)
- {
- Map.Entry entry = (Map.Entry) e;
- map.put(getUnmarshalledValue(entry.getKey()), getUnmarshalledValue(entry.getValue()));
- }
- return map;
- }
-
- private Object getUnmarshalledValue(Object o)
- {
- try
- {
- return o instanceof MarshalledValue ? ((MarshalledValue) o).get() : o;
- }
- catch (Exception e)
- {
- throw new CacheException("Unable to unmarshall value", e);
- }
- }
-
- @Override
- public boolean equals(Object other)
- {
- if (other instanceof Map)
- {
- return getUnmarshalledMap().equals(other);
- }
- return false;
- }
-
- @Override
- public int hashCode()
- {
- return getUnmarshalledMap().hashCode();
- }
-
- public void writeExternal(ObjectOutput out) throws IOException
- {
- out.writeObject(delegate);
- }
-
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
- {
- delegate = (Map) in.readObject();
- }
-}
17 years, 2 months
JBoss Cache SVN: r6899 - in core/branches/flat/src: main/java/org/jboss/cache/commands/read and 19 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-09 12:51:41 -0400 (Thu, 09 Oct 2008)
New Revision: 6899
Added:
core/branches/flat/src/test/java/org/jboss/starobrno/api/
core/branches/flat/src/test/java/org/jboss/starobrno/api/batch/
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/read_committed/
core/branches/flat/src/test/java/org/jboss/starobrno/api/mvcc/repeatable_read/
core/branches/flat/src/test/java/org/jboss/starobrno/tx/
core/branches/flat/src/test/java/org/jboss/starobrno/tx/LocalModeTxTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/util/internals/
core/branches/flat/src/test/java/org/jboss/starobrno/util/internals/ViewChangeListener.java
Removed:
core/branches/flat/src/main/java/org/jboss/cache/DataContainerImpl.java
core/branches/flat/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java
core/branches/flat/src/main/java/org/jboss/cache/mvcc/
Modified:
core/branches/flat/src/main/java/org/jboss/cache/AbstractNodeFactory.java
core/branches/flat/src/main/java/org/jboss/cache/NodeFactory.java
core/branches/flat/src/main/java/org/jboss/cache/commands/read/GetChildrenNamesCommand.java
core/branches/flat/src/main/java/org/jboss/cache/commands/write/EvictCommand.java
core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java
core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
core/branches/flat/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
core/branches/flat/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java
core/branches/flat/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java
core/branches/flat/src/main/java/org/jboss/cache/util/CachePrinter.java
core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/config/Configuration.java
core/branches/flat/src/main/java/org/jboss/starobrno/config/parsing/XmlConfigurationParser.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java
core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java
Log:
More fixed
Modified: core/branches/flat/src/main/java/org/jboss/cache/AbstractNodeFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/AbstractNodeFactory.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/AbstractNodeFactory.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -25,7 +25,6 @@
import org.jboss.cache.interceptors.InterceptorChain;
import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.invocation.NodeInvocationDelegate;
-import org.jboss.cache.mvcc.ReadCommittedNode;
import org.jboss.starobrno.config.Configuration;
import org.jboss.starobrno.factories.ComponentRegistry;
import org.jboss.starobrno.factories.annotations.Inject;
@@ -113,7 +112,7 @@
throw new UnsupportedOperationException("Unsupported in this implementation (" + getClass().getSimpleName() + ")!");
}
- public ReadCommittedNode createWrappedNode(InternalNode<K, V> node, InternalNode<K, V> parent)
+ public Object createWrappedNode(InternalNode<K, V> node, InternalNode<K, V> parent)
{
throw new UnsupportedOperationException("Unsupported in this implementation (" + getClass().getSimpleName() + ")!");
}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/DataContainerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/DataContainerImpl.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/DataContainerImpl.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -1,777 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.buddyreplication.BuddyFqnTransformer;
-import org.jboss.cache.lock.LockManager;
-import org.jboss.cache.marshall.NodeData;
-import org.jboss.starobrno.CacheException;
-import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.config.Configuration.NodeLockingScheme;
-import org.jboss.starobrno.factories.annotations.Inject;
-import org.jboss.starobrno.factories.annotations.NonVolatile;
-import org.jboss.starobrno.factories.annotations.Start;
-import org.jboss.starobrno.factories.annotations.Stop;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A container for the root node in the cache, which also provides helpers for efficiently accessing nodes, walking trees, etc.
- *
- * @author Mircea.Markus(a)jboss.com
- * @since 2.2
- */
-@NonVolatile
-public class DataContainerImpl implements DataContainer
-{
- private static final Log log = LogFactory.getLog(DataContainerImpl.class);
- private static boolean trace = log.isTraceEnabled();
-
- /**
- * Root node.
- */
- private volatile NodeSPI root;
- private volatile InternalNode rootInternal;
-
- /**
- * Set<Fqn> of Fqns of the topmost node of internal regions that should
- * not included in standard state transfers.
- */
- private final Set<Fqn> internalFqns = new HashSet<Fqn>();
- private NodeFactory nodeFactory;
- private LockManager lockManager;
- private BuddyFqnTransformer buddyFqnTransformer;
- private Configuration config;
- private boolean usingMvcc;
- private static final InternalNode[] NULL_ARRAY = {null, null};
-
- @Inject
- public void injectDependencies(NodeFactory nodeFactory, LockManager lockManager, BuddyFqnTransformer transformer, Configuration configuration)
- {
- setDependencies(nodeFactory, lockManager);
-
- // We need to create a root node even at this stage since certain components rely on this being available before
- // start() is called.
- // TODO: Investigate which components rely on this being available before start(), and why!
- //TODO - remove setDependencies method at this point
- createRootNode();
- this.buddyFqnTransformer = transformer;
- config = configuration;
- }
-
- public void setDependencies(NodeFactory nodeFactory, LockManager lockManager)
- {
- this.nodeFactory = nodeFactory;
- this.lockManager = lockManager;
- }
-
- @Start(priority = 12)
- public void createRootNode()
- {
- usingMvcc = config != null && config.getNodeLockingScheme() == NodeLockingScheme.MVCC;
- if (trace) log.trace("Starting data container. Using MVCC? " + usingMvcc);
- // create a new root temporarily.
- NodeSPI tempRoot = nodeFactory.createRootNode();
- // if we don't already have a root or the new (temp) root is of a different class (optimistic vs pessimistic) to
- // the current root, then we use the new one.
-
- Class currentRootType = root == null ? null : root.getDelegationTarget().getClass();
- Class tempRootType = tempRoot.getDelegationTarget().getClass();
-
- if (!tempRootType.equals(currentRootType))
- {
- if (trace) log.trace("Setting root node to an instance of " + tempRootType);
- setRoot(tempRoot);
- }
-
- if (usingMvcc && rootInternal == null) setRoot(root); // sets the "internal root"
-
- if (root != null) root.setChildrenLoaded(true);
- if (rootInternal != null) rootInternal.setChildrenLoaded(true);
- }
-
- @Stop(priority = 100)
- public void stop()
- {
- // empty in-memory state
- if (root != null)
- {
- root.clearDataDirect();
- root.removeChildrenDirect();
- }
- else if (rootInternal != null)
- {
- rootInternal.clear();
- rootInternal.removeChildren();
- }
- }
-
- @Deprecated
- public NodeSPI getRoot()
- {
- return root;
- }
-
- /**
- * Sets the root node reference to the node passed in.
- *
- * @param root node
- */
- public void setRoot(Object root)
- {
- if (root == null) throw new CacheException("Attempting to set a null node as a root node!");
- // Mega-Ugh!
- if (usingMvcc && root instanceof InternalNode)
- {
- if (log.isDebugEnabled()) log.debug("Setting rootInternal to " + root);
- rootInternal = (InternalNode) root;
- this.root = null;
- }
- else
- {
- this.root = (NodeSPI) root;
- if (usingMvcc)
- {
- if (log.isDebugEnabled()) log.debug("Setting rootInternal to " + this.root.getDelegationTarget());
- rootInternal = this.root.getDelegationTarget();
- this.root = null;
- }
- }
- }
-
- public boolean isResident(Fqn fqn)
- {
- if (usingMvcc)
- {
- InternalNode in = peekInternalNode(fqn, false);
- return in != null && in.isResident();
- }
- else
- {
- NodeSPI<?, ?> nodeSPI = peek(fqn, false, false);
- return nodeSPI != null && nodeSPI.isResident();
- }
- }
-
- public void registerInternalFqn(Fqn fqn)
- {
- internalFqns.add(fqn);
- }
-
- public NodeSPI peek(Fqn fqn)
- {
- return peek(fqn, false, false);
- }
-
- public NodeSPI peek(Fqn fqn, boolean includeDeletedNodes)
- {
- return peek(fqn, includeDeletedNodes, false);
- }
-
- public NodeSPI peek(Fqn fqn, boolean includeDeletedNodes, boolean includeInvalidNodes)
- {
- if (fqn == null || fqn.size() == 0) return getRoot();
- NodeSPI n = getRoot();
- int fqnSize = fqn.size();
- for (int i = 0; i < fqnSize; i++)
- {
- Object obj = fqn.get(i);
- n = n.getChildDirect(obj);
- if (n == null)
- {
- return null;
- }
- else if (!includeDeletedNodes && n.isDeleted())
- {
- return null;
- }
- else if (!includeInvalidNodes && !n.isValid())
- {
- return null;
- }
- }
- return n;
- }
-
- public boolean exists(Fqn fqn)
- {
- return usingMvcc ? peekInternalNode(fqn, false) != null : peek(fqn, false, false) != null;
- }
-
- public boolean hasChildren(Fqn fqn)
- {
- if (fqn == null) return false;
-
- if (usingMvcc)
- {
- InternalNode in = peekInternalNode(fqn, false);
- return in != null && in.hasChildren();
- }
- else
- {
- NodeSPI n = peek(fqn);
- return n != null && n.hasChildrenDirect();
- }
- }
-
- public List<NodeData> buildNodeData(List<NodeData> list, NodeSPI node, boolean mapSafe)
- {
- if (usingMvcc)
- return buildNodeData(list, node.getDelegationTarget(), node.getData(), mapSafe);
- else
- return buildNodeDataLegacy(list, node, mapSafe);
- }
-
- private List<NodeData> buildNodeData(List<NodeData> list, InternalNode<?, ?> node, Map dataInNode, boolean mapSafe)
- {
- NodeData data = new NodeData(buddyFqnTransformer.getActualFqn(node.getFqn()), dataInNode, mapSafe);
- list.add(data);
- for (InternalNode childNode : node.getChildrenMap().values())
- {
- buildNodeData(list, childNode, childNode.getData(), true);
- }
- return list;
- }
-
- @Deprecated
- private List<NodeData> buildNodeDataLegacy(List<NodeData> list, NodeSPI node, boolean mapSafe)
- {
- NodeData data = new NodeData(buddyFqnTransformer.getActualFqn(node.getFqn()), node.getDataDirect(), mapSafe);
- list.add(data);
- for (Object childNode : node.getChildrenDirect())
- {
- buildNodeData(list, (NodeSPI) childNode, true);
- }
- return list;
- }
-
- public List<Fqn> getNodesForEviction(Fqn fqn, boolean recursive)
- {
- List<Fqn> result = new ArrayList<Fqn>();
- if (usingMvcc)
- {
- InternalNode node = peekInternalNode(fqn, false);
- if (recursive)
- {
- if (node != null) recursiveAddEvictionNodes(node, result);
- }
- else
- {
- if (node == null)
- {
- result.add(fqn);
- return result;
- }
- if (fqn.isRoot())
- {
- for (Object childName : node.getChildrenNames())
- {
- if (!node.isResident()) result.add(Fqn.fromRelativeElements(fqn, childName));
- }
- }
- else if (!node.isResident())
- {
- result.add(fqn);
- }
- }
- return result;
- }
- else
- {
- NodeSPI node = peek(fqn, false);
- if (recursive)
- {
- if (node != null) recursiveAddEvictionNodes(node, result);
- }
- else
- {
- if (node == null)
- {
- result.add(fqn);
- return result;
- }
- if (fqn.isRoot())
- {
- for (Object childName : node.getChildrenNamesDirect())
- {
- if (!node.isResident()) result.add(Fqn.fromRelativeElements(fqn, childName));
- }
- }
- else if (!node.isResident())
- {
- result.add(fqn);
- }
- }
- return result;
- }
- }
-
- private void recursiveAddEvictionNodes(NodeSPI<?, ?> node, List<Fqn> result)
- {
- for (NodeSPI<?, ?> child : node.getChildrenDirect())
- {
- recursiveAddEvictionNodes(child, result);
- }
- Fqn fqn = node.getFqn();
- if (!fqn.isRoot() && !node.isResident())
- {
- result.add(fqn);
- }
- }
-
- private void recursiveAddEvictionNodes(InternalNode<?, ?> node, List<Fqn> result)
- {
- for (InternalNode child : node.getChildren())
- {
- recursiveAddEvictionNodes(child, result);
- }
- Fqn fqn = node.getFqn();
- if (!fqn.isRoot() && !node.isResident())
- {
- result.add(fqn);
- }
- }
-
- @Override
- public String toString()
- {
- return toString(false);
- }
-
- public Set<Fqn> getInternalFqns()
- {
- return Collections.unmodifiableSet(internalFqns);
- }
-
- /**
- * Returns a debug string with optional details of contents.
- *
- * @param details if true, details are printed
- * @return detailed contents of the container
- */
- @SuppressWarnings("deprecation")
- public String toString(boolean details)
- {
- StringBuilder sb = new StringBuilder();
- int indent = 0;
-
- if (!details)
- {
- sb.append(getClass().getName()).append(" [").append(getNumberOfNodes()).append(" nodes, ");
- sb.append(getNumberOfLocksHeld()).append(" locks]");
- }
- else
- {
- if (root == null)
- return sb.toString();
- for (Object n : root.getChildrenDirect())
- {
- ((NodeSPI) n).print(sb, indent);
- sb.append("\n");
- }
- }
- return sb.toString();
- }
-
- public int getNumberOfLocksHeld()
- {
- return numLocks(root);
- }
-
- private int numLocks(NodeSPI n)
- {
- int num = 0;
- if (n != null)
- {
- if (lockManager.isLocked(n))
- {
- num++;
- }
- for (Object cn : n.getChildrenDirect(true))
- {
- num += numLocks((NodeSPI) cn);
- }
- }
- return num;
- }
-
- public int getNumberOfNodes()
- {
- if (!usingMvcc) return numNodes(root) - 1;
- return numNodesMvcc(rootInternal) - 1;
- }
-
- private int numNodesMvcc(InternalNode node)
- {
- int count = 1; //for 'node'
- if (node != null)
- {
- Set<InternalNode> children = node.getChildren();
- for (InternalNode child : children)
- {
- count += numNodesMvcc((InternalNode) child);
- }
- }
- return count;
- }
-
- private int numNodes(NodeSPI n)
- {
- int count = 1;// for n
- if (n != null)
- {
- for (Object child : n.getChildrenDirect())
- {
- count += numNodes((NodeSPI) child);
- }
- }
- return count;
- }
-
- /**
- * Prints information about the contents of the nodes in the cache's current
- * in-memory state. Does not load any previously evicted nodes from a
- * cache loader, so evicted nodes will not be included.
- *
- * @return details
- */
- public String printDetails()
- {
- StringBuilder sb = new StringBuilder();
- if (root == null)
- rootInternal.printDetails(sb, 0);
- else
- root.printDetails(sb, 0);
- sb.append("\n");
- return sb.toString();
- }
-
-
- /**
- * Returns lock information.
- *
- * @return lock info
- */
- public String printLockInfo()
- {
- return lockManager.printLockInfo(root);
- }
-
- public int getNumberOfAttributes(Fqn fqn)
- {
- return usingMvcc ? numAttributes(peekInternalNode(fqn, false)) : numAttributes(peek(fqn));
- }
-
- private int numAttributes(NodeSPI n)
- {
- int count = 0;
- for (Object child : n.getChildrenDirect())
- {
- count += numAttributes((NodeSPI) child);
- }
- count += n.getDataDirect().size();
- return count;
- }
-
- private int numAttributesMvcc(InternalNode n)
- {
- int count = 0;
- for (Object child : n.getChildren())
- {
- count += numAttributesMvcc((InternalNode) child);
- }
- count += n.getData().size();
- return count;
- }
-
- private int numAttributes(InternalNode n)
- {
- int count = 0;
- for (Object child : n.getChildren())
- {
- count += numAttributes((NodeSPI) child);
- }
- count += n.getData().size();
- return count;
- }
-
- public int getNumberOfAttributes()
- {
- return usingMvcc ? numAttributesMvcc(rootInternal) : numAttributes(root);
- }
-
- public boolean removeFromDataStructure(Fqn f, boolean skipMarkerCheck)
- {
- return usingMvcc ? removeMvcc(f, skipMarkerCheck) : removeLegacy(f, skipMarkerCheck);
- }
-
- private boolean removeMvcc(Fqn f, boolean skipMarkerCheck)
- {
- InternalNode n = peekInternalNode(f, true);
- if (n == null)
- {
- return false;
- }
-
- if (trace) log.trace("Performing a real remove for node " + f + ", marked for removal.");
- if (skipMarkerCheck || n.isRemoved())
- {
- if (n.getFqn().isRoot())
- {
- // do not actually delete; just remove deletion marker
- n.setRemoved(true);
-
- // mark the node to be removed (and all children) as invalid so anyone holding a direct reference to it will
- // be aware that it is no longer valid.
- n.setValid(false, true);
- n.setValid(true, false);
-
- // but now remove all children, since the call has been to remove("/")
- n.removeChildren();
- return true;
- }
- else
- {
- // mark the node to be removed (and all children) as invalid so anyone holding a direct reference to it will
- // be aware that it is no longer valid.
- n.setValid(false, true);
- InternalNode parent = peekInternalNode(f.getParent(), true);
- return parent.removeChild(n.getFqn().getLastElement());
- }
- }
- else
- {
- if (log.isDebugEnabled()) log.debug("Node " + f + " NOT marked for removal as expected, not removing!");
- return false;
- }
- }
-
-
- private boolean removeLegacy(Fqn f, boolean skipMarkerCheck)
- {
- NodeSPI n = peek(f, true);
- if (n == null)
- {
- return false;
- }
-
- if (trace) log.trace("Performing a real remove for node " + f + ", marked for removal.");
- if (skipMarkerCheck || n.isDeleted())
- {
- if (n.getFqn().isRoot())
- {
- // do not actually delete; just remove deletion marker
- n.markAsDeleted(true);
-
- // mark the node to be removed (and all children) as invalid so anyone holding a direct reference to it will
- // be aware that it is no longer valid.
- n.setValid(false, true);
- n.setValid(true, false);
-
- // but now remove all children, since the call has been to remove("/")
- n.removeChildrenDirect();
- return true;
- }
- else
- {
- // mark the node to be removed (and all children) as invalid so anyone holding a direct reference to it will
- // be aware that it is no longer valid.
- n.setValid(false, true);
- NodeSPI parent = peek(f.getParent(), true);
- return parent.removeChildDirect(n.getFqn().getLastElement());
- }
- }
- else
- {
- if (log.isDebugEnabled()) log.debug("Node " + f + " NOT marked for removal as expected, not removing!");
- return false;
- }
- }
-
- public void evict(Fqn fqn, boolean recursive)
- {
- List<Fqn> toEvict = getNodesForEviction(fqn, recursive);
- for (Fqn aFqn : toEvict)
- {
- evict(aFqn);
- }
- }
-
- public boolean evict(Fqn fqn)
- {
- if (!exists(fqn)) return true;
- if (hasChildren(fqn))
- {
- if (trace)
- log.trace("removing DATA as node has children: evict(" + fqn + ")");
- if (usingMvcc)
- removeData(fqn);
- else
- removeDataLegacy(fqn);
- return false;
- }
- else
- {
- if (trace) log.trace("removing NODE as it is a leaf: evict(" + fqn + ")");
- if (usingMvcc)
- removeNode(fqn);
- else
- removeNodeLegacy(fqn);
- return true;
- }
- }
-
- private void removeNodeLegacy(Fqn fqn)
- {
- NodeSPI targetNode = peek(fqn, false, true);
- if (targetNode == null) return;
- NodeSPI parentNode = targetNode.getParentDirect();
- targetNode.setValid(false, false);
- if (parentNode != null)
- {
- parentNode.removeChildDirect(fqn.getLastElement());
- parentNode.setChildrenLoaded(false);
- }
- }
-
- private void removeNode(Fqn fqn)
- {
- InternalNode targetNode = peekInternalNode(fqn, true);
- if (targetNode == null) return;
- InternalNode parentNode = peekInternalNode(fqn.getParent(), true);
- targetNode.setValid(false, false);
- if (parentNode != null)
- {
- parentNode.removeChild(fqn.getLastElement());
- parentNode.setChildrenLoaded(false);
- }
- }
-
- private void removeDataLegacy(Fqn fqn)
- {
- NodeSPI n = peek(fqn);
- if (n == null)
- {
- log.warn("node " + fqn + " not found");
- return;
- }
- n.clearDataDirect();
- n.setDataLoaded(false);
- }
-
- private void removeData(Fqn fqn)
- {
- InternalNode n = peekInternalNode(fqn, false);
- if (n == null)
- {
- log.warn("node " + fqn + " not found");
- return;
- }
- n.clear();
- n.setDataLoaded(false);
- }
-
- public Object[] createNodes(Fqn fqn)
- {
- List<NodeSPI> result = new ArrayList<NodeSPI>(fqn.size());
- Fqn tmpFqn = Fqn.ROOT;
-
- int size = fqn.size();
-
- // root node
- NodeSPI n = root;
- for (int i = 0; i < size; i++)
- {
- Object childName = fqn.get(i);
- tmpFqn = Fqn.fromRelativeElements(tmpFqn, childName);
-
- NodeSPI childNode;
- Map children = n.getChildrenMapDirect();
- childNode = (NodeSPI) children.get(childName);
-
- if (childNode == null)
- {
- childNode = n.addChildDirect(Fqn.fromElements(childName));
- result.add(childNode);
- }
-
- n = childNode;
- }
- return new Object[]{result, n};
- }
-
- public InternalNode peekInternalNode(Fqn fqn, boolean includeInvalidNodes)
- {
- if (fqn == null || fqn.size() == 0) return rootInternal;
- InternalNode n = rootInternal;
- int fqnSize = fqn.size();
- for (int i = 0; i < fqnSize; i++)
- {
- Object obj = fqn.get(i);
- n = n.getChild(obj);
- if (n == null)
- {
- return null;
- }
- else if (!includeInvalidNodes && !n.isValid())
- {
- return null;
- }
- }
- return n;
- }
-
- public InternalNode[] peekInternalNodeAndDirectParent(Fqn fqn, boolean includeInvalidNodes)
- {
- if (fqn == null || fqn.size() == 0) return new InternalNode[]{rootInternal, null};
- InternalNode n = rootInternal;
- InternalNode directParent = null;
- int fqnSize = fqn.size();
- for (int i = 0; i < fqnSize; i++)
- {
- directParent = n;
- Object obj = fqn.get(i);
- n = directParent.getChild(obj);
- if (n == null)
- {
- return NULL_ARRAY;
- }
- else if (!includeInvalidNodes && !n.isValid())
- {
- return NULL_ARRAY;
- }
- }
- return new InternalNode[]{n, directParent};
- }
-
- public void setBuddyFqnTransformer(BuddyFqnTransformer buddyFqnTransformer)
- {
- this.buddyFqnTransformer = buddyFqnTransformer;
- }
-}
Modified: core/branches/flat/src/main/java/org/jboss/cache/NodeFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/NodeFactory.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/NodeFactory.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -21,7 +21,6 @@
*/
package org.jboss.cache;
-import org.jboss.cache.mvcc.ReadCommittedNode;
import java.util.Map;
@@ -34,7 +33,7 @@
*/
public interface NodeFactory<K, V>
{
- ReadCommittedNode createWrappedNode(InternalNode<K, V> node, InternalNode<K, V> parent);
+ Object createWrappedNode(InternalNode<K, V> node, InternalNode<K, V> parent);
/**
* Creates a new node and populates its attributes.
Modified: core/branches/flat/src/main/java/org/jboss/cache/commands/read/GetChildrenNamesCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/commands/read/GetChildrenNamesCommand.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/commands/read/GetChildrenNamesCommand.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -1,24 +1,24 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
package org.jboss.cache.commands.read;
import org.apache.commons.logging.Log;
@@ -28,10 +28,8 @@
import org.jboss.cache.InvocationContext;
import org.jboss.cache.NodeSPI;
import org.jboss.cache.commands.Visitor;
-import org.jboss.cache.mvcc.ReadCommittedNode;
import java.util.Collection;
-import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
@@ -69,12 +67,13 @@
@SuppressWarnings("unchecked")
public Object perform(InvocationContext ctx)
{
- ReadCommittedNode n = (ReadCommittedNode) (fqn == null ? null : ctx.lookUpNode(fqn));
- if (n == null || n.isDeleted()) return null;
- Map<Object, InternalNode<?, ?>> childrenMap = n.getDelegationTarget().getChildrenMap();
- Collection<InternalNode> children = (Collection<InternalNode>) (childrenMap.isEmpty() ? Collections.emptySet() : childrenMap.values());
-
- return getCorrectedChildNames(children, ctx);
+// ReadCommittedNode n = (ReadCommittedNode) (fqn == null ? null : ctx.lookUpNode(fqn));
+// if (n == null || n.isDeleted()) return null;
+// Map<Object, InternalNode<?, ?>> childrenMap = n.getDelegationTarget().getChildrenMap();
+// Collection<InternalNode> children = (Collection<InternalNode>) (childrenMap.isEmpty() ? Collections.emptySet() : childrenMap.values());
+//
+// return getCorrectedChildNames(children, ctx);
+ return null;
}
/**
@@ -104,11 +103,11 @@
{
Fqn childFqn = n.getKey();
- if (childFqn.isDirectChildOf(fqn))
- {
- ReadCommittedNode childNode = (ReadCommittedNode) n.getValue();
- if (childNode.isCreated()) childNames.add(childFqn.getLastElement());
- }
+// if (childFqn.isDirectChildOf(fqn))
+// {
+// ReadCommittedNode childNode = (ReadCommittedNode) n.getValue();
+// if (childNode.isCreated()) childNames.add(childFqn.getLastElement());
+// }
}
return childNames;
}
Modified: core/branches/flat/src/main/java/org/jboss/cache/commands/write/EvictCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/commands/write/EvictCommand.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/commands/write/EvictCommand.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -30,7 +30,6 @@
import org.jboss.cache.NodeSPI;
import org.jboss.cache.commands.Visitor;
import org.jboss.cache.commands.read.AbstractDataCommand;
-import org.jboss.cache.mvcc.ReadCommittedNode;
import org.jboss.cache.notifications.Notifier;
import java.util.Collection;
@@ -159,12 +158,14 @@
private InternalNode lookupInAllScopes(InvocationContext ctx, Fqn fqn)
{
+ return null;
+ /*
ReadCommittedNode nodeSPI = (ReadCommittedNode) lookupForEviction(ctx, fqn);
if (nodeSPI == null)
{
return dataContainer.peekInternalNode(fqn, true);
}
- return nodeSPI.getDelegationTarget();
+ return nodeSPI.getDelegationTarget();*/
}
protected NodeSPI lookupForEviction(InvocationContext ctx, Fqn fqn)
Modified: core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheLoaderInterceptor.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -44,8 +44,6 @@
import org.jboss.cache.jmx.annotations.ManagedOperation;
import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.loader.CacheLoaderManager;
-import org.jboss.cache.mvcc.MVCCNodeHelper;
-import org.jboss.cache.mvcc.NullMarkerNode;
import org.jboss.cache.notifications.Notifier;
import org.jboss.cache.transaction.TransactionTable;
import org.jboss.starobrno.CacheException;
@@ -80,9 +78,7 @@
protected boolean isActivation = false;
// protected boolean usingVersionedInvalidation = false;
- protected MVCCNodeHelper helper;
-
/**
* True if CacheStoreInterceptor is in place.
* This allows us to skip loading keys for remove(Fqn, key) and put(Fqn, key).
@@ -92,7 +88,7 @@
@Inject
protected void injectDependencies(TransactionTable txTable, CacheLoaderManager clm, Configuration configuration,
- DataContainer dataContainer, Notifier notifier, MVCCNodeHelper helper)
+ DataContainer dataContainer, Notifier notifier)
{
this.txTable = txTable;
this.clm = clm;
@@ -100,7 +96,6 @@
// usingVersionedInvalidation = mode.isInvalidation();
this.dataContainer = dataContainer;
this.notifier = notifier;
- this.helper = helper;
}
@Start
@@ -259,12 +254,12 @@
private void loadIfNeeded(InvocationContext ctx, Fqn fqn, Object key, boolean allKeys, boolean initNode, boolean acquireWriteLock, boolean recursive, boolean isMove, boolean bypassLoadingData, boolean shouldLoadIfNodeIsNull) throws Throwable
{
- NodeSPI n = helper.wrapNodeForReading(ctx, fqn, true);
- if (n instanceof NullMarkerNode)
- {
- ctx.getLookedUpNodes().remove(fqn);
- n = null;
- }
+ NodeSPI n = null;//helper.wrapNodeForReading(ctx, fqn, true);
+// if (n instanceof NullMarkerNode)
+// {
+// ctx.getLookedUpNodes().remove(fqn);
+// n = null;
+// }
boolean mustLoad = mustLoad(n, key, allKeys || isMove, shouldLoadIfNodeIsNull);
if (trace) log.trace("load element " + fqn + " mustLoad=" + mustLoad);
@@ -274,7 +269,7 @@
if (acquireWriteLock || initNode)
{
boolean isNew = n == null;
- n = helper.wrapNodeForWriting(ctx, fqn, true, false, true, false, true); // won't create any nodes but will acquire locks.
+// n = helper.wrapNodeForWriting(ctx, fqn, true, false, true, false, true); // won't create any nodes but will acquire locks.
if (isNew && n != null) n.setDataLoaded(false);
}
@@ -283,7 +278,7 @@
if (n == null && loader.exists(fqn))
{
// just create a dummy node in memory
- n = helper.wrapNodeForWriting(ctx, fqn, true, true, true, false, false);
+// n = helper.wrapNodeForWriting(ctx, fqn, true, true, true, false, false);
n.setDataLoaded(false);
}
if (!bypassLoadingData)
@@ -348,7 +343,7 @@
// Create if node had not been created already
if (node == null)
{
- NodeSPI temp = helper.wrapNodeForWriting(ctxt, fqn, true, true, true, false, false);
+ NodeSPI temp = null;//helper.wrapNodeForWriting(ctxt, fqn, true, true, true, false, false);
node = temp.getDelegationTarget();
}
@@ -358,7 +353,7 @@
Fqn childFqn = Fqn.fromRelativeElements(fqn, name);
// create child if it didn't exist
- NodeSPI child = helper.wrapNodeForWriting(ctxt, childFqn, true, true, true, false, false);
+ NodeSPI child = null;//helper.wrapNodeForWriting(ctxt, childFqn, true, true, true, false, false);
if (child.isCreated()) child.setDataLoaded(false);
if ((isMove || isActivation) && recursive)
{
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/InvocationContextInterceptor.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -1,262 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.RPCManager;
-import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.commands.read.ExistsCommand;
-import org.jboss.cache.commands.tx.CommitCommand;
-import org.jboss.cache.commands.tx.PrepareCommand;
-import org.jboss.cache.commands.tx.RollbackCommand;
-import org.jboss.cache.commands.write.ClearDataCommand;
-import org.jboss.cache.commands.write.PutDataMapCommand;
-import org.jboss.cache.commands.write.PutForExternalReadCommand;
-import org.jboss.cache.commands.write.PutKeyValueCommand;
-import org.jboss.cache.commands.write.RemoveKeyCommand;
-import org.jboss.cache.commands.write.RemoveNodeCommand;
-import org.jboss.cache.transaction.GlobalTransaction;
-import org.jboss.cache.transaction.TransactionTable;
-import org.jboss.starobrno.config.Option;
-import org.jboss.starobrno.factories.annotations.Inject;
-
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-
-/**
- * Always place this interceptor at the start of the interceptor chain to ensure invocation contexts and set up and cleaned up correctly.
- *
- * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
- */
-public class InvocationContextInterceptor extends BaseTransactionalContextInterceptor
-{
- private RPCManager rpcManager;
-
- @Inject
- public void setDependencies(RPCManager rpcManager)
- {
- this.rpcManager = rpcManager;
- }
-
- @Override
- public Object visitPutDataMapCommand(InvocationContext ctx, PutDataMapCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), false);
- }
-
- @Override
- public Object visitExistsNodeCommand(InvocationContext ctx, ExistsCommand command) throws Throwable
- {
- return handleAll(ctx, command, null, false);
- }
-
- @Override
- public Object visitPutForExternalReadCommand(InvocationContext ctx, PutForExternalReadCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), false);
- }
-
- @Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), false);
- }
-
- @Override
- public Object visitRemoveNodeCommand(InvocationContext ctx, RemoveNodeCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), false);
- }
-
- @Override
- public Object visitClearDataCommand(InvocationContext ctx, ClearDataCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), false);
- }
-
- @Override
- public Object visitRemoveKeyCommand(InvocationContext ctx, RemoveKeyCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), false);
- }
-
- @Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), true);
- }
-
- @Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), true);
- }
-
- @Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- return handleAll(ctx, command, command.getGlobalTransaction(), true);
- }
-
- @Override
- public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- return handleAll(ctx, command, null, false);
- }
-
- @SuppressWarnings("deprecation")
- private Object handleAll(InvocationContext ctx, VisitableCommand command, GlobalTransaction gtx, boolean scrubContextOnCompletion) throws Throwable
- {
- Option optionOverride = ctx.getOptionOverrides();
- boolean suppressExceptions = false;
- Transaction suspendedTransaction = null;
- boolean resumeSuspended = false;
-
- if (trace) log.trace("Invoked with command " + command + " and InvocationContext [" + ctx + "]");
-
- try
- {
- if (txManager != null)
- {
- Transaction tx = getTransaction();
- GlobalTransaction realGtx = getGlobalTransaction(tx, gtx);
- if (tx == null && realGtx != null && realGtx.isRemote()) tx = txTable.getLocalTransaction(gtx);
- setTransactionalContext(tx, realGtx, null, ctx);
- }
- else
- {
- setTransactionalContext(null, null, null, ctx);
- }
-
- if (optionOverride != null)
- {
- if (optionOverride.isFailSilently())
- {
- log.debug("FAIL_SILENTLY Option is present - suspending any ongoing transaction.");
- suppressExceptions = true;
- if (ctx.getTransaction() != null)
- {
- suspendedTransaction = txManager.suspend();
- setTransactionalContext(null, null, null, ctx);
- if (trace) log.trace("Suspending transaction " + suspendedTransaction);
- resumeSuspended = true;
- }
- else
- {
- if (trace) log.trace("No ongoing transaction to suspend");
- }
- }
- }
-
- Object retval;
- try
- {
- return invokeNextInterceptor(ctx, command);
- }
- catch (Throwable th)
- {
- retval = th;
- // if fail silently return a null
- if (suppressExceptions) return null;
- Throwable t = (Throwable) retval;
- if (t instanceof RuntimeException && t.getCause() != null)
- {
- throw t.getCause();
- }
- else
- {
- throw t;
- }
- }
- // assume we're the first interceptor in the chain. Handle the exception-throwing.
- }
- finally
- {
- // TODO: scope upgrading should happen transparently
- /*
- * we should scrub txs after every call to prevent race conditions
- * basically any other call coming in on the same thread and hijacking any running tx's
- * was highlighted in JBCACHE-606
- */
- if (scrubContextOnCompletion) setTransactionalContext(null, null, null, ctx);
-
- // clean up any invocation-scope options set up
- if (trace) log.trace("Resetting invocation-scope options");
- ctx.getOptionOverrides().reset();
-
- // if this is a prepare, opt prepare or
-
- if (resumeSuspended)
- {
- txManager.resume(suspendedTransaction);
- }
- else
- {
- if (ctx.getTransaction() != null && (TransactionTable.isValid(ctx.getTransaction())))
- {
- copyInvocationScopeOptionsToTxScope(ctx);
- }
- }
-
- // reset the context to prevent leakage of internals
- ctx.setCommand(null);
- ctx.setMethodCall(null);
-
- // TODO: Calling ctx.reset() here breaks stuff. Check whether this is just becuse UTs expect stuff in the ctx or whether this really breaks functionality.
-// ctx.reset();
- // instead, for now, just wipe contents of the looked up node map
- ctx.clearLookedUpNodes();
- }
- }
-
- private GlobalTransaction getGlobalTransaction(Transaction tx, GlobalTransaction gtx)
- {
- if (gtx == null) gtx = txTable.getCurrentTransaction(tx, false);
- if (gtx != null) gtx.setRemote(isRemoteGlobalTx(gtx));
- return gtx;
- }
-
- private Transaction getTransaction() throws SystemException
- {
- // this creates a context if one did not exist.
- if (txManager == null)
- {
- if (trace) log.trace("no transaction manager configured, setting tx as null.");
- return null;
- }
- else
- {
- return txManager.getTransaction();
- }
- }
-
- /**
- * Tests if a global transaction originated from a different cache in the cluster
- *
- * @param gtx
- * @return true if the gtx is remote, false if it originated locally.
- */
- private boolean isRemoteGlobalTx(GlobalTransaction gtx)
- {
- return gtx != null && (gtx.getAddress() != null) && (!gtx.getAddress().equals(rpcManager.getLocalAddress()));
- }
-}
Modified: core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -34,7 +34,6 @@
import org.jboss.cache.Region;
import org.jboss.cache.RegionManager;
import org.jboss.cache.Version;
-import org.jboss.starobrno.batch.BatchContainer;
import org.jboss.cache.buddyreplication.BuddyManager;
import org.jboss.cache.buddyreplication.GravitateResult;
import org.jboss.cache.commands.CommandsFactory;
@@ -55,21 +54,19 @@
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.marshall.Marshaller;
-import org.jboss.cache.mvcc.MVCCNodeHelper;
import org.jboss.cache.notifications.Notifier;
import org.jboss.cache.statetransfer.StateTransferManager;
import org.jboss.cache.transaction.GlobalTransaction;
import org.jboss.cache.transaction.TransactionTable;
import org.jboss.cache.util.Immutables;
import org.jboss.starobrno.CacheException;
+import org.jboss.starobrno.batch.BatchContainer;
import org.jboss.starobrno.config.Configuration;
-import org.jboss.starobrno.config.Configuration.NodeLockingScheme;
import org.jboss.starobrno.config.ConfigurationException;
import org.jboss.starobrno.config.Option;
import org.jboss.starobrno.factories.ComponentRegistry;
import org.jboss.starobrno.factories.annotations.Inject;
import org.jboss.starobrno.factories.annotations.NonVolatile;
-import org.jboss.starobrno.factories.annotations.Start;
import org.jgroups.Address;
import javax.transaction.Transaction;
@@ -103,7 +100,6 @@
private Marshaller marshaller;
private DataContainer dataContainer;
private CommandsFactory commandsFactory;
- private MVCCNodeHelper mvccHelper;
private boolean usingMvcc;
private BatchContainer batchContainer;
@@ -111,7 +107,7 @@
public void initialize(StateTransferManager stateTransferManager, CacheLoaderManager cacheLoaderManager, Notifier notifier,
TransactionManager transactionManager, BuddyManager buddyManager, TransactionTable transactionTable,
RPCManager rpcManager, RegionManager regionManager, Marshaller marshaller,
- CommandsFactory commandsFactory, DataContainer dataContainer, MVCCNodeHelper mvccHelper, BatchContainer batchContainer)
+ CommandsFactory commandsFactory, DataContainer dataContainer, BatchContainer batchContainer)
{
this.stateTransferManager = stateTransferManager;
this.cacheLoaderManager = cacheLoaderManager;
@@ -124,16 +120,9 @@
this.marshaller = marshaller;
this.dataContainer = dataContainer;
this.commandsFactory = commandsFactory;
- this.mvccHelper = mvccHelper;
this.batchContainer = batchContainer;
}
- @Start
- private void setNodeLockingScheme()
- {
- usingMvcc = configuration.getNodeLockingScheme() == NodeLockingScheme.MVCC;
- }
-
private void reset()
{
this.usingMvcc = false;
@@ -317,15 +306,15 @@
@SuppressWarnings("unchecked")
private NodeSPI<K, V> mvccPeek(Fqn f)
{
- NodeSPI<K, V> n;
- try
- {
- n = mvccHelper.wrapNodeForReading(getInvocationContext(), f, false);
- }
- catch (InterruptedException e)
- {
- throw new CacheException(e);
- }
+ NodeSPI<K, V> n = null;
+// try
+// {
+// n = mvccHelper.wrapNodeForReading(getInvocationContext(), f, false);
+// }
+// catch (InterruptedException e)
+// {
+// throw new CacheException(e);
+// }
if (n == null || n.isNullNode()) return null;
return n;
}
Modified: core/branches/flat/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/jmx/CacheJmxWrapper.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -322,11 +322,6 @@
return getConfiguration().getRuntimeConfig().getMuxChannelFactory();
}
- public String getNodeLockingScheme()
- {
- return getConfiguration().getNodeLockingSchemeString();
- }
-
public long getReplQueueInterval()
{
return getConfiguration().getReplQueueInterval();
@@ -513,11 +508,6 @@
getConfiguration().getRuntimeConfig().setMuxChannelFactory(factory);
}
- public void setNodeLockingScheme(String nodeLockingScheme)
- {
- getConfiguration().setNodeLockingSchemeString(nodeLockingScheme);
- }
-
public void setReplQueueInterval(long interval)
{
getConfiguration().setReplQueueInterval(interval);
Modified: core/branches/flat/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/jmx/LegacyConfiguration.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -300,10 +300,6 @@
void setTransactionManager(TransactionManager manager);
- void setNodeLockingScheme(String nodeLockingScheme);
-
- String getNodeLockingScheme();
-
/**
* Gets whether the entire tree is inactive upon startup, only responding
* to replication messages after activateRegion is
Modified: core/branches/flat/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/jmx/ResourceDMBean.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -1,24 +1,24 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
package org.jboss.cache.jmx;
import org.apache.commons.logging.Log;
@@ -89,11 +89,7 @@
attrInfo = new MBeanAttributeInfo[atts.size()];
int i = 0;
- if (log.isInfoEnabled())
- {
- log.trace("Processing class " + instance.getClass());
- log.trace("Number of attributes: " + atts.size());
- }
+
MBeanAttributeInfo info;
for (AttributeEntry entry : atts.values())
{
@@ -178,15 +174,7 @@
if (name == null || name.length() == 0)
throw new NullPointerException("Invalid attribute requested " + name);
- if (log.isDebugEnabled())
- {
- log.debug("getAttribute called for " + name);
- }
Attribute attr = getNamedAttribute(name);
- if (log.isDebugEnabled())
- {
- log.debug("getAttribute value found " + attr.getValue());
- }
return attr.getValue();
}
@@ -223,11 +211,6 @@
{
Attribute attr = (Attribute) list.get(i);
- if (log.isDebugEnabled())
- {
- log.debug("Attribute name " + attr.getName() + " new value is " + attr.getValue());
- }
-
if (setNamedAttribute(attr))
{
results.add(attr);
@@ -236,7 +219,7 @@
{
if (log.isWarnEnabled())
{
- log.debug("Failed to update attribute name " + attr.getName()
+ log.warn("Failed to update attribute name " + attr.getName()
+ " with value "
+ attr.getValue());
}
@@ -367,11 +350,6 @@
}
}
- if (log.isDebugEnabled())
- {
- log.debug("@Attr found for method " + method.getName() + " and registered as " + attributeName);
- }
-
AttributeEntry ae = atts.get(attributeName);
//is it a read method?
if (!writeAttribute)
@@ -457,10 +435,6 @@
if (!isAlreadyExposed)
{
ops.add(new MBeanOperationInfo(op != null ? op.description() : "", method));
- if (log.isDebugEnabled())
- {
- log.debug("@Operation found for method " + method.getName());
- }
}
}
}
@@ -508,10 +482,6 @@
false);
atts.put(fieldName, new FieldAttributeEntry(info, field));
- if (log.isDebugEnabled())
- {
- log.debug("@Attr found for field " + field.getName());
- }
}
}
}
Modified: core/branches/flat/src/main/java/org/jboss/cache/util/CachePrinter.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/util/CachePrinter.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/cache/util/CachePrinter.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -24,7 +24,6 @@
import org.jboss.cache.CacheSPI_Legacy;
import org.jboss.cache.Cache_Legacy;
import org.jboss.cache.DataContainer;
-import org.jboss.cache.DataContainerImpl;
import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.invocation.CacheInvocationDelegate;
@@ -57,9 +56,7 @@
*/
public static String printCacheLockingInfo(Cache_Legacy c)
{
- // internal cast
- DataContainerImpl cd = (DataContainerImpl) ((CacheInvocationDelegate) c).getDataContainer();
- return cd.printLockInfo();
+ return "Fix me";
}
public static String printCacheInterceptors(CacheSPI_Legacy<?, ?> cache)
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -69,16 +69,20 @@
protected InterceptorChain invoker;
protected Configuration config;
protected Notifier notifier;
- private BatchContainer batchContainer;
+ protected BatchContainer batchContainer;
protected ComponentRegistry componentRegistry;
+ protected TransactionManager transactionManager;
+
@Inject
private void injectDependencies(InvocationContextContainer invocationContextContainer,
CommandsFactory commandsFactory,
InterceptorChain interceptorChain,
Configuration configuration,
Notifier notifier,
- ComponentRegistry componentRegistry)
+ ComponentRegistry componentRegistry,
+ TransactionManager transactionManager,
+ BatchContainer batchContainer)
{
this.invocationContextContainer = invocationContextContainer;
this.commandsFactory = commandsFactory;
@@ -86,6 +90,8 @@
this.config = configuration;
this.notifier = notifier;
this.componentRegistry = componentRegistry;
+ this.transactionManager = transactionManager;
+ this.batchContainer = batchContainer;
}
public V putIfAbsent(K key, V value)
@@ -248,7 +254,7 @@
public TransactionManager getTransactionManager()
{
- return null; //TODO: Autogenerated. Implement me properly
+ return transactionManager;
}
public List<CommandInterceptor> getInterceptorChain()
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -94,7 +94,7 @@
public EvictCommand buildEvictCommand(Object key)
{
- return new EvictCommand();
+ return new EvictCommand(key);
}
public PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, Address localAddress, boolean onePhaseCommit)
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -33,6 +33,11 @@
{
public static final int METHOD_ID = 3000;
+ public EvictCommand(Object key)
+ {
+ this.key = key;
+ }
+
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
{
return visitor.visitEvictCommand(ctx, this);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -57,7 +57,7 @@
for (Entry<Object, Object> e : map.entrySet())
{
MVCCEntry me = ctx.lookupEntry(e.getKey());
- if (e != null) e.setValue(me.getValue());
+ if (me != null) me.setValue(e.getValue());
}
return null;
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/config/Configuration.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/config/Configuration.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/config/Configuration.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -135,19 +135,6 @@
}
/**
- * Cache node locking scheme.
- */
- public static enum NodeLockingScheme
- {
- /**
- * Data is locked using the MVCC locking scheme. This is the default locking scheme in JBoss Cache 3.0.0.
- *
- * @see <a href="http://wiki.jboss.org/wiki/JBossCacheMVCC">http://wiki.jboss.org/wiki/JBossCacheMVCC</a>
- */
- MVCC
- }
-
- /**
* Default replication version, from {@link Version#getVersionShort}.
*/
public static final short DEFAULT_REPLICATION_VERSION = Version.getVersionShort();
@@ -189,7 +176,6 @@
private boolean syncRollbackPhase = false;
private BuddyReplicationConfig buddyReplicationConfig;
- private NodeLockingScheme nodeLockingScheme = NodeLockingScheme.MVCC;
private String muxStackName = null;
private boolean usingMultiplexer = false;
private transient RuntimeConfig runtimeConfig;
@@ -208,18 +194,15 @@
private void correctIsolationLevels()
{
// ensure the correct isolation level upgrades and/or downgrades are performed.
- if (nodeLockingScheme == NodeLockingScheme.MVCC)
+ switch (isolationLevel)
{
- switch (isolationLevel)
- {
- case NONE:
- case READ_UNCOMMITTED:
- isolationLevel = IsolationLevel.READ_COMMITTED;
- break;
- case SERIALIZABLE:
- isolationLevel = IsolationLevel.REPEATABLE_READ;
- break;
- }
+ case NONE:
+ case READ_UNCOMMITTED:
+ isolationLevel = IsolationLevel.READ_COMMITTED;
+ break;
+ case SERIALIZABLE:
+ isolationLevel = IsolationLevel.REPEATABLE_READ;
+ break;
}
}
@@ -444,13 +427,6 @@
this.buddyReplicationConfig = config;
}
- public void setNodeLockingScheme(NodeLockingScheme nodeLockingScheme)
- {
- testImmutability("nodeLockingScheme");
- testImmutability("nodeLockingOptimistic");
- this.nodeLockingScheme = nodeLockingScheme;
- }
-
public void setUseReplQueue(boolean useReplQueue)
{
testImmutability("useReplQueue");
@@ -469,26 +445,6 @@
this.stateRetrievalTimeout = stateRetrievalTimeout;
}
- public void setNodeLockingScheme(String nodeLockingScheme)
- {
- testImmutability("nodeLockingScheme");
- if (nodeLockingScheme == null)
- {
- throw new ConfigurationException("Node locking scheme cannot be null", "NodeLockingScheme");
- }
- this.nodeLockingScheme = NodeLockingScheme.valueOf(uc(nodeLockingScheme));
- }
-
- public String getNodeLockingSchemeString()
- {
- return nodeLockingScheme == null ? null : nodeLockingScheme.toString();
- }
-
- public void setNodeLockingSchemeString(String nodeLockingScheme)
- {
- setNodeLockingScheme(nodeLockingScheme);
- }
-
private static String uc(String s)
{
return s.toUpperCase(Locale.ENGLISH);
@@ -758,11 +714,6 @@
return buddyReplicationConfig;
}
- public NodeLockingScheme getNodeLockingScheme()
- {
- return nodeLockingScheme;
- }
-
public long getStateRetrievalTimeout()
{
return stateRetrievalTimeout;
@@ -898,7 +849,6 @@
if (marshallerClass != null ? !marshallerClass.equals(that.marshallerClass) : that.marshallerClass != null)
return false;
if (muxStackName != null ? !muxStackName.equals(that.muxStackName) : that.muxStackName != null) return false;
- if (nodeLockingScheme != that.nodeLockingScheme) return false;
if (runtimeConfig != null ? !runtimeConfig.equals(that.runtimeConfig) : that.runtimeConfig != null) return false;
if (shutdownHookBehavior != that.shutdownHookBehavior) return false;
if (transactionManagerLookupClass != null ? !transactionManagerLookupClass.equals(that.transactionManagerLookupClass) : that.transactionManagerLookupClass != null)
@@ -936,7 +886,6 @@
result = 31 * result + (syncCommitPhase ? 1 : 0);
result = 31 * result + (syncRollbackPhase ? 1 : 0);
result = 31 * result + (buddyReplicationConfig != null ? buddyReplicationConfig.hashCode() : 0);
- result = 31 * result + (nodeLockingScheme != null ? nodeLockingScheme.hashCode() : 0);
result = 31 * result + (muxStackName != null ? muxStackName.hashCode() : 0);
result = 31 * result + (usingMultiplexer ? 1 : 0);
result = 31 * result + (runtimeConfig != null ? runtimeConfig.hashCode() : 0);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/config/parsing/XmlConfigurationParser.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/config/parsing/XmlConfigurationParser.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/config/parsing/XmlConfigurationParser.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -374,7 +374,6 @@
String lockAcquisitionTimeout = getAttributeValue(element, "lockAcquisitionTimeout");
if (existsAttribute(lockAcquisitionTimeout)) config.setLockAcquisitionTimeout(getLong(lockAcquisitionTimeout));
String nodeLockingScheme = getAttributeValue(element, "nodeLockingScheme");
- if (existsAttribute(nodeLockingScheme)) config.setNodeLockingScheme(nodeLockingScheme);
String writeSkewCheck = getAttributeValue(element, "writeSkewCheck");
if (existsAttribute(writeSkewCheck)) config.setWriteSkewCheck(getBoolean(writeSkewCheck));
String concurrencyLevel = getAttributeValue(element, "concurrencyLevel");
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -23,7 +23,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.jboss.cache.mvcc.RepeatableReadNode;
import org.jboss.starobrno.CacheException;
import static org.jboss.starobrno.container.ReadCommittedEntry.Flags.CHANGED;
@@ -35,7 +34,7 @@
*/
public class RepeatableReadEntry extends ReadCommittedEntry
{
- private static final Log log = LogFactory.getLog(RepeatableReadNode.class);
+ private static final Log log = LogFactory.getLog(RepeatableReadEntry.class);
public RepeatableReadEntry(Object key, Object value)
{
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -124,9 +124,10 @@
*/
public void clearLookedUpEntries()
{
- if (transactionContext != null)
- transactionContext.clearLookedUpEntries();
- else if (lookedUpEntries != null) lookedUpEntries.clear();
+// if (transactionContext != null)
+// transactionContext.clearLookedUpEntries();
+// else if (lookedUpEntries != null) lookedUpEntries.clear();
+ if (lookedUpEntries != null) lookedUpEntries.clear();
}
/**
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InvocationContextInterceptor.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -30,6 +30,7 @@
import org.jboss.starobrno.commands.write.PutKeyValueCommand;
import org.jboss.starobrno.commands.write.PutMapCommand;
import org.jboss.starobrno.commands.write.RemoveCommand;
+import org.jboss.starobrno.commands.write.ReplaceCommand;
import org.jboss.starobrno.config.Option;
import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.annotations.Inject;
@@ -75,6 +76,12 @@
}
@Override
+ public Object visitReplaceCommand(InvocationContext ctx, ReplaceCommand command) throws Throwable
+ {
+ return handleAll(ctx, command, ctx.getGlobalTransaction(), false);
+ }
+
+ @Override
public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
{
return handleAll(ctx, command, command.getGlobalTransaction(), true);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -164,7 +164,8 @@
public Object handlePutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
{
entryWrapper.wrapEntryForWriting(ctx, command.getKey(), true, false);
- return invokeNextInterceptor(ctx, command);
+ Object o = invokeNextInterceptor(ctx, command);
+ return o;
}
@Override
@@ -219,6 +220,7 @@
{
if (useReadCommitted)
{
+ if (trace) log.trace("Wiping unnecessary entries from context");
// wipe all unchanged entries from context, to force subsequent reads to go to the container,
// hence providing R_C semantics.
Set<Object> keysToRemove = new HashSet<Object>();
@@ -277,7 +279,10 @@
if (ctx.getTransactionContext() != null)
{
List<Object> locks = ctx.getTransactionContext().getKeysLocked();
- if (!locks.isEmpty()) cleanupLocks(locks, ctx, ctx.getGlobalTransaction(), commit);
+ if (!locks.isEmpty())
+ cleanupLocks(locks, ctx, ctx.getGlobalTransaction(), commit);
+ else if (trace)
+ log.trace("At transaction boundary (" + (commit ? "commit" : "rollback") + "), and we have no locks in context!");
}
else
{
Modified: core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java 2008-10-09 13:45:15 UTC (rev 6898)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -25,12 +25,6 @@
import org.jboss.starobrno.manager.CacheManager;
import org.testng.annotations.Test;
-/**
- * // TODO: MANIK: Document this
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @since 3.0
- */
@Test(groups = "functional")
public class BasicTest
{
@@ -67,14 +61,4 @@
cm.stop();
}
}
-
- public void concurrentMapMethodTest()
- {
-
- }
-
- public void transactionalTest()
- {
-
- }
}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/tx/LocalModeTxTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/tx/LocalModeTxTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/tx/LocalModeTxTest.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -0,0 +1,90 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.tx;
+
+import org.jboss.cache.transaction.DummyTransactionManagerLookup;
+import org.jboss.starobrno.CacheSPI;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.manager.CacheManager;
+import org.jboss.starobrno.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+@Test(groups = "functional")
+public class LocalModeTxTest
+{
+ private CacheSPI<String, String> createCache()
+ {
+ Configuration cfg = new Configuration();
+ cfg.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
+ CacheManager cm = new CacheManager(cfg);
+ return (CacheSPI<String, String>) cm.createCache("test");
+ }
+
+ public void testTxCommit1() throws Exception
+ {
+ CacheSPI c = null;
+ try
+ {
+ c = createCache();
+ TransactionManager tm = c.getTransactionManager();
+ tm.begin();
+ c.put("key", "value");
+ Transaction t = tm.suspend();
+ assert c.isEmpty();
+ tm.resume(t);
+ tm.commit();
+ assert !c.isEmpty();
+ }
+ finally
+ {
+ TestingUtil.killCaches(c);
+ }
+ }
+
+ public void testTxCommit2() throws Exception
+ {
+ CacheSPI c = null;
+ try
+ {
+ c = createCache();
+ TransactionManager tm = c.getTransactionManager();
+ c.put("key", "old");
+ tm.begin();
+ assert c.get("key").equals("old");
+ c.put("key", "value");
+ assert c.get("key").equals("value");
+ Transaction t = tm.suspend();
+ assert c.get("key").equals("old");
+ tm.resume(t);
+ tm.commit();
+ assert c.get("key").equals("value");
+ assert !c.isEmpty();
+ }
+ finally
+ {
+ TestingUtil.killCaches(c);
+ }
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/util/internals/ViewChangeListener.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/util/internals/ViewChangeListener.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/util/internals/ViewChangeListener.java 2008-10-09 16:51:41 UTC (rev 6899)
@@ -0,0 +1,55 @@
+package org.jboss.starobrno.util.internals;
+
+import org.jboss.cache.notifications.annotation.CacheListener;
+import org.jboss.cache.notifications.annotation.ViewChanged;
+import org.jboss.cache.notifications.event.ViewChangedEvent;
+import org.jboss.starobrno.Cache;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * A class that registers a cache listener with a given cache, and waits for a view change on the cache.
+ * <p/>
+ * Sample usage:
+ * <pre>
+ * Cache c = getCache();
+ * ViewChangeListener vcl = new ViewChangeListener(c);
+ * assert vcl.waitForViewChange(60, TimeUnit.SECONDS); // will block for up to 60 seconds for a view change on cache c
+ * </pre>
+ */
+@CacheListener
+public class ViewChangeListener
+{
+ CountDownLatch latch;
+
+ /**
+ * Constructs a view change listener
+ *
+ * @param cache cache to listen on for view change events
+ */
+ public ViewChangeListener(Cache cache)
+ {
+ this.latch = new CountDownLatch(1);
+ cache.addCacheListener(this);
+ }
+
+ @ViewChanged
+ public void handleViewChange(ViewChangedEvent e)
+ {
+ if (!e.isPre()) latch.countDown();
+ }
+
+ /**
+ * Waits for up to millis milliseconds for a view change to be received.
+ *
+ * @param timeout length of time to wait for a view change
+ * @param unit time unit to use
+ * @return true if a view change is received, false otherwise.
+ * @throws InterruptedException
+ */
+ public boolean waitForViewChange(long timeout, TimeUnit unit) throws InterruptedException
+ {
+ return latch.await(timeout, unit);
+ }
+}
\ No newline at end of file
17 years, 2 months
JBoss Cache SVN: r6898 - in core/branches/flat/src/main/java/org/jboss: cache/interceptors and 9 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-09 09:45:15 -0400 (Thu, 09 Oct 2008)
New Revision: 6898
Added:
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/CacheMgmtInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/MarshalledValueInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/NotificationInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/base/JmxStatsCommandInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/marshall/
core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValue.java
core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueHelper.java
core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueMap.java
Removed:
core/branches/flat/src/main/java/org/jboss/cache/interceptors/CallInterceptor.java
core/branches/flat/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java
core/branches/flat/src/main/java/org/jboss/cache/interceptors/MarshalledValueInterceptor.java
core/branches/flat/src/main/java/org/jboss/cache/interceptors/NotificationInterceptor.java
core/branches/flat/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
Modified:
core/branches/flat/src/main/java/org/jboss/cache/UnversionedNode.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java
core/branches/flat/src/main/java/org/jboss/cache/notifications/NotifierImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/factories/InterceptorChainFactory.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java
Log:
More interceptors migrated
Modified: core/branches/flat/src/main/java/org/jboss/cache/UnversionedNode.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/UnversionedNode.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/UnversionedNode.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -24,11 +24,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import static org.jboss.cache.AbstractNode.NodeFlags.*;
-import org.jboss.cache.marshall.MarshalledValue;
import org.jboss.cache.util.FastCopyHashMap;
import org.jboss.cache.util.Immutables;
import org.jboss.cache.util.concurrent.SelfInitializingConcurrentHashMap;
import org.jboss.starobrno.CacheException;
+import org.jboss.starobrno.marshall.MarshalledValue;
import java.util.Collections;
import java.util.HashMap;
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/CallInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/CallInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/CallInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -1,182 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.commands.WriteCommand;
-import org.jboss.cache.commands.tx.CommitCommand;
-import org.jboss.cache.commands.tx.PrepareCommand;
-import org.jboss.cache.commands.tx.RollbackCommand;
-import org.jboss.cache.commands.write.ClearDataCommand;
-import org.jboss.cache.commands.write.MoveCommand;
-import org.jboss.cache.commands.write.PutDataMapCommand;
-import org.jboss.cache.commands.write.PutForExternalReadCommand;
-import org.jboss.cache.commands.write.PutKeyValueCommand;
-import org.jboss.cache.commands.write.RemoveKeyCommand;
-import org.jboss.cache.commands.write.RemoveNodeCommand;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
-import org.jboss.cache.transaction.GlobalTransaction;
-import org.jboss.starobrno.factories.annotations.Start;
-
-import javax.transaction.Transaction;
-
-/**
- * Always at the end of the chain, directly in front of the cache. Simply calls into the cache using reflection.
- * If the call resulted in a modification, add the Modification to the end of the modification list
- * keyed by the current transaction.
- * <p/>
- * Although always added to the end of an optimistically locked chain as well, calls should not make it down to
- * this interceptor unless it is a call the OptimisticNodeInterceptor knows nothing about.
- *
- * @author Bela Ban
- * @version $Id$
- */
-public class CallInterceptor extends CommandInterceptor
-{
- private boolean notOptimisticLocking;
-
- @Start
- protected void start()
- {
- notOptimisticLocking = true;
- }
-
- @Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- if (trace) log.trace("Suppressing invocation of method handlePrepareCommand.");
- return null;
- }
-
- @Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- if (trace) log.trace("Suppressing invocation of method handleCommitCommand.");
- return null;
- }
-
- @Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- if (trace) log.trace("Suppressing invocation of method handleRollbackCommand.");
- return null;
- }
-
- @Override
- public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- if (trace) log.trace("Executing command: " + command + ".");
- return invokeCommand(ctx, command);
- }
-
- private Object invokeCommand(InvocationContext ctx, ReplicableCommand command)
- throws Throwable
- {
- Object retval;
- try
- {
- retval = command.perform(ctx);
- }
- catch (Throwable t)
- {
- Transaction tx = ctx.getTransaction();
- if (ctx.isValidTransaction())
- {
- tx.setRollbackOnly();
- }
- throw t;
- }
- return retval;
- }
-
- @Override
- public Object visitPutDataMapCommand(InvocationContext ctx, PutDataMapCommand command) throws Throwable
- {
- return handleAlterCacheMethod(ctx, command);
- }
-
- @Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- return handleAlterCacheMethod(ctx, command);
- }
-
- @Override
- public Object visitPutForExternalReadCommand(InvocationContext ctx, PutForExternalReadCommand command) throws Throwable
- {
- return handleAlterCacheMethod(ctx, command);
- }
-
- @Override
- public Object visitRemoveNodeCommand(InvocationContext ctx, RemoveNodeCommand command) throws Throwable
- {
- return handleAlterCacheMethod(ctx, command);
- }
-
- @Override
- public Object visitClearDataCommand(InvocationContext ctx, ClearDataCommand command) throws Throwable
- {
- return handleAlterCacheMethod(ctx, command);
- }
-
- @Override
- public Object visitRemoveKeyCommand(InvocationContext ctx, RemoveKeyCommand command) throws Throwable
- {
- return handleAlterCacheMethod(ctx, command);
- }
-
- @Override
- public Object visitMoveCommand(InvocationContext ctx, MoveCommand command) throws Throwable
- {
- return handleAlterCacheMethod(ctx, command);
- }
-
- /**
- * only add the modification to the modification list if we are using pessimistic locking.
- * Optimistic locking calls *should* not make it this far down the interceptor chain, but just
- * in case a method has been invoked that the OptimisticNodeInterceptor knows nothing about, it will
- * filter down here.
- */
- private Object handleAlterCacheMethod(InvocationContext ctx, WriteCommand command)
- throws Throwable
- {
- Object result = invokeCommand(ctx, command);
- if (notOptimisticLocking && ctx.isValidTransaction())
- {
- GlobalTransaction gtx = ctx.getGlobalTransaction();
- if (gtx == null)
- {
- if (log.isDebugEnabled())
- {
- log.debug("didn't find GlobalTransaction for " + ctx.getTransaction() + "; won't add modification to transaction list");
- }
- }
- else
- {
- ctx.getTransactionContext().addModification(command);
- }
- }
- return result;
- }
-}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/MVCCLockingInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -1,402 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.DataContainer;
-import org.jboss.cache.Fqn;
-import org.jboss.cache.InternalNode;
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.NodeSPI;
-import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.commands.read.ExistsCommand;
-import org.jboss.cache.commands.read.GetChildrenNamesCommand;
-import org.jboss.cache.commands.read.GetDataMapCommand;
-import org.jboss.cache.commands.read.GetKeyValueCommand;
-import org.jboss.cache.commands.read.GetKeysCommand;
-import org.jboss.cache.commands.read.GetNodeCommand;
-import org.jboss.cache.commands.read.GravitateDataCommand;
-import org.jboss.cache.commands.tx.CommitCommand;
-import org.jboss.cache.commands.tx.PrepareCommand;
-import org.jboss.cache.commands.tx.RollbackCommand;
-import org.jboss.cache.commands.write.ClearDataCommand;
-import org.jboss.cache.commands.write.EvictCommand;
-import org.jboss.cache.commands.write.InvalidateCommand;
-import org.jboss.cache.commands.write.MoveCommand;
-import org.jboss.cache.commands.write.PutDataMapCommand;
-import org.jboss.cache.commands.write.PutForExternalReadCommand;
-import org.jboss.cache.commands.write.PutKeyValueCommand;
-import org.jboss.cache.commands.write.RemoveKeyCommand;
-import org.jboss.cache.commands.write.RemoveNodeCommand;
-import org.jboss.cache.interceptors.base.PrePostProcessingCommandInterceptor;
-import org.jboss.cache.lock.LockManager;
-import org.jboss.cache.mvcc.MVCCNodeHelper;
-import org.jboss.starobrno.factories.annotations.Inject;
-
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Map;
-
-/**
- * Interceptor to implement <a href="http://wiki.jboss.org/wiki/JBossCacheMVCC">MVCC</a> functionality.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @see <a href="http://wiki.jboss.org/wiki/JBossCacheMVCC">MVCC designs</a>
- * @since 3.0
- */
-public class MVCCLockingInterceptor extends PrePostProcessingCommandInterceptor
-{
- LockManager lockManager;
- DataContainer dataContainer;
- MVCCNodeHelper helper;
-
- @Inject
- public void setDependencies(LockManager lockManager, DataContainer dataContainer, MVCCNodeHelper helper)
- {
- this.lockManager = lockManager;
- this.dataContainer = dataContainer;
- this.helper = helper;
- }
-
- @Override
- protected boolean doBeforeCall(InvocationContext ctx, VisitableCommand command)
- {
- if (ctx.getOptionOverrides().isSuppressLocking())
- {
- if (log.isWarnEnabled()) log.warn("Lock suppression not supported with MVCC!");
- }
- return true;
- }
-
- @Override
- public Object handlePutDataMapCommand(InvocationContext ctx, PutDataMapCommand command) throws Throwable
- {
- helper.wrapNodeForWriting(ctx, command.getFqn(), true, true, false, false, false); // get the node and stick it in the context.
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handlePutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- helper.wrapNodeForWriting(ctx, command.getFqn(), true, true, false, false, false); // get the node and stick it in the context.
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handlePutForExternalReadCommand(InvocationContext ctx, PutForExternalReadCommand command) throws Throwable
- {
- helper.wrapNodeForWriting(ctx, command.getFqn(), true, true, false, false, false); // get the node and stick it in the context.
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleRemoveNodeCommand(InvocationContext ctx, RemoveNodeCommand command) throws Throwable
- {
- helper.wrapNodesRecursivelyForRemoval(ctx, command.getFqn());
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleClearDataCommand(InvocationContext ctx, ClearDataCommand command) throws Throwable
- {
- helper.wrapNodeForWriting(ctx, command.getFqn(), true, false, false, false, false);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleEvictFqnCommand(InvocationContext ctx, EvictCommand command) throws Throwable
- {
- // set lock acquisition timeout to 0 - we need to fail fast.
- ctx.getOptionOverrides().setLockAcquisitionTimeout(0);
- if (command.isRecursive())
- {
- handleRecursiveEvict(ctx, command);
- }
- else
- {
- handleNonrecursiveEvict(ctx, command);
- }
-
- return invokeNextInterceptor(ctx, command);
- }
-
- @SuppressWarnings("unchecked")
- private void handleRecursiveEvict(InvocationContext ctx, EvictCommand command) throws InterruptedException
- {
- List<Fqn> fqnsToEvict;
- if (command.getFqn().isRoot())
- {
- // if this is the root node, do not attempt to lock this for writing but instead just get all direct children of root.
- Map<Object, InternalNode> children = dataContainer.peekInternalNode(Fqn.ROOT, false).getChildrenMap();
- if (!children.isEmpty())
- {
- fqnsToEvict = new LinkedList<Fqn>();
- // lock recursively.
- for (InternalNode child : children.values())
- fqnsToEvict.addAll(helper.wrapNodesRecursivelyForRemoval(ctx, child.getFqn()));
- }
- else
- {
- fqnsToEvict = Collections.emptyList();
- }
- }
- else
- {
- // lock current node recursively.
- fqnsToEvict = helper.wrapNodesRecursivelyForRemoval(ctx, command.getFqn());
- }
-
- // set these in the evict command so that the command is aware of what needs to be evicted.
- command.setNodesToEvict(fqnsToEvict);
- }
-
- @SuppressWarnings("unchecked")
- private void handleNonrecursiveEvict(InvocationContext ctx, EvictCommand command) throws InterruptedException
- {
- if (command.getFqn().isRoot())
- {
- // if this is the root node, do not attempt to lock this for writing but instead just get all direct children of root.
- Map<Object, InternalNode> children = dataContainer.peekInternalNode(Fqn.ROOT, false).getChildrenMap();
- if (!children.isEmpty())
- {
- for (InternalNode child : children.values())
- helper.wrapNodeForWriting(ctx, child.getFqn(), true, false, false, true, true);
- }
- }
- else
- {
- // just wrap the node for writing. Do not create if absent.
- helper.wrapNodeForWriting(ctx, command.getFqn(), true, false, false, true, true);
- }
- }
-
- @Override
- public Object handleInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable
- {
- // this should be handled the same as a recursive evict command.
- ctx.getOptionOverrides().setLockAcquisitionTimeout(0);
- if (!command.getFqn().isRoot()) helper.wrapNodesRecursivelyForRemoval(ctx, command.getFqn());
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleRemoveKeyCommand(InvocationContext ctx, RemoveKeyCommand command) throws Throwable
- {
- helper.wrapNodeForWriting(ctx, command.getFqn(), true, false, false, false, false);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleGetDataMapCommand(InvocationContext ctx, GetDataMapCommand command) throws Throwable
- {
- helper.wrapNodeForReading(ctx, command.getFqn(), true);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleExistsNodeCommand(InvocationContext ctx, ExistsCommand command) throws Throwable
- {
- helper.wrapNodeForReading(ctx, command.getFqn(), true);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
- helper.wrapNodeForReading(ctx, command.getFqn(), true);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleGetNodeCommand(InvocationContext ctx, GetNodeCommand command) throws Throwable
- {
- helper.wrapNodeForReading(ctx, command.getFqn(), true);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleGetKeysCommand(InvocationContext ctx, GetKeysCommand command) throws Throwable
- {
- helper.wrapNodeForReading(ctx, command.getFqn(), true);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleGetChildrenNamesCommand(InvocationContext ctx, GetChildrenNamesCommand command) throws Throwable
- {
- helper.wrapNodeForReading(ctx, command.getFqn(), true);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleMoveCommand(InvocationContext ctx, MoveCommand command) throws Throwable
- {
- // Nodes we need to get WLs for:
-
- // 1) node we are moving FROM, and its parent and ALL children. Same as removeNode.
- List<Fqn> nodeAndChildren = helper.wrapNodesRecursivelyForRemoval(ctx, command.getFqn());
-
- Fqn newParent = command.getTo();
- Fqn oldParent = command.getFqn().getParent();
-
- // 2) The new parent.
- helper.wrapNodeForWriting(ctx, newParent, true, true, false, false, false);
-
- if (!oldParent.equals(newParent))
- {
- // the nodeAndChildren list contains all child nodes, including the node itself.
- // 3) now obtain locks on the new places these new nodes will occupy.
- for (Fqn f : nodeAndChildren)
- {
- Fqn newChildFqn = f.replaceAncestor(oldParent, newParent);
- helper.wrapNodeForWriting(ctx, newChildFqn, true, true, true, false, false);
- }
- }
-
- // now pass up the chain.
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleGravitateDataCommand(InvocationContext ctx, GravitateDataCommand command) throws Throwable
- {
- helper.wrapNodeForReading(ctx, command.getFqn(), true);
- return invokeNextInterceptor(ctx, command);
- }
-
- @Override
- public Object handleRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- Object retval = null;
- try
- {
- retval = invokeNextInterceptor(ctx, command);
- }
- finally
- {
- transactionalCleanup(false, ctx);
- }
- return retval;
- }
-
- @Override
- public Object handleCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- Object retval = null;
- try
- {
- retval = invokeNextInterceptor(ctx, command);
- }
- finally
- {
- transactionalCleanup(true, ctx);
- }
- return retval;
- }
-
- @Override
- public Object handlePrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- Object retval = null;
- try
- {
- retval = invokeNextInterceptor(ctx, command);
- }
- finally
- {
- if (command.isOnePhaseCommit()) transactionalCleanup(true, ctx);
- }
- return retval;
- }
-
- @SuppressWarnings("unchecked")
- protected void doAfterCall(InvocationContext ctx, VisitableCommand command)
- {
- // for non-transactional stuff.
- if (ctx.getTransactionContext() == null)
- {
- List<Fqn> locks;
- if (!(locks = ctx.getLocks()).isEmpty())
- {
- cleanupLocks(locks, ctx, Thread.currentThread(), true);
- }
- else
- {
- if (trace) log.trace("Nothing to do since there are no modifications in scope.");
- }
- }
- else
- {
- if (trace) log.trace("Nothing to do since there is a transaction in scope.");
- }
- }
-
- private void cleanupLocks(List<Fqn> locks, InvocationContext ctx, Object owner, boolean commit)
- {
- // clean up.
- // unlocking needs to be done in reverse order.
- ListIterator<Fqn> it = locks.listIterator(locks.size());
-
- if (commit)
- {
- while (it.hasPrevious())
- {
- Fqn f = it.previous();
- NodeSPI rcn = ctx.lookUpNode(f);
- // could be null with read-committed
- if (rcn != null) rcn.commitUpdate(ctx, dataContainer);
- // and then unlock
- if (trace) log.trace("Releasing lock on [" + f + "] for owner " + owner);
- lockManager.unlock(f, owner);
- }
- }
- else
- {
- while (it.hasPrevious())
- {
- Fqn f = it.previous();
- NodeSPI rcn = ctx.lookUpNode(f);
- // could be null with read-committed
- if (rcn != null) rcn.rollbackUpdate();
- // and then unlock
- if (trace) log.trace("Releasing lock on [" + f + "] for owner " + owner);
- lockManager.unlock(f, owner);
- }
- }
- ctx.clearLocks();
- }
-
- @SuppressWarnings("unchecked")
- private void transactionalCleanup(boolean commit, InvocationContext ctx)
- {
- if (ctx.getTransactionContext() != null)
- {
- List<Fqn> locks = ctx.getTransactionContext().getLocks();
- if (!locks.isEmpty()) cleanupLocks(locks, ctx, ctx.getGlobalTransaction(), commit);
- }
- else
- {
- throw new IllegalStateException("Attempting to do a commit or rollback but there is no transactional context in scope. " + ctx);
- }
- }
-}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/MarshalledValueInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/MarshalledValueInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/MarshalledValueInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -1,210 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.commands.read.GetChildrenNamesCommand;
-import org.jboss.cache.commands.read.GetDataMapCommand;
-import org.jboss.cache.commands.read.GetKeyValueCommand;
-import org.jboss.cache.commands.read.GetKeysCommand;
-import org.jboss.cache.commands.read.GetNodeCommand;
-import org.jboss.cache.commands.write.ClearDataCommand;
-import org.jboss.cache.commands.write.PutDataMapCommand;
-import org.jboss.cache.commands.write.PutForExternalReadCommand;
-import org.jboss.cache.commands.write.PutKeyValueCommand;
-import org.jboss.cache.commands.write.RemoveKeyCommand;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
-import org.jboss.cache.marshall.MarshalledValue;
-import org.jboss.cache.marshall.MarshalledValueHelper;
-import org.jboss.cache.marshall.MarshalledValueMap;
-
-import java.io.IOException;
-import java.io.NotSerializableException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Interceptor that handles the wrapping and unwrapping of cached data using {@link org.jboss.cache.marshall.MarshalledValue}s.
- * Known "excluded" types are not wrapped/unwrapped, which at this time include {@link String}, Java primitives
- * and their Object wrappers, as well as arrays of excluded types.
- * <p/>
- * The {@link org.jboss.cache.marshall.MarshalledValue} wrapper handles lazy deserialization from byte array representations.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @see org.jboss.cache.marshall.MarshalledValue
- * @since 2.1.0
- */
-public class MarshalledValueInterceptor extends CommandInterceptor
-{
-
- @Override
- public Object visitPutDataMapCommand(InvocationContext ctx, PutDataMapCommand command) throws Throwable
- {
- Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
- command.setData(wrapMap(command.getData(), marshalledValues, ctx));
- Object retVal = invokeNextInterceptor(ctx, command);
- return compactAndProcessRetVal(command, marshalledValues, retVal);
- }
-
- @Override
- public Object visitGetDataMapCommand(InvocationContext ctx, GetDataMapCommand command) throws Throwable
- {
- Object retVal = invokeNextInterceptor(ctx, command);
- if (retVal instanceof Map)
- {
- if (trace) log.trace("Return value is a Map and we're retrieving data. Wrapping as a MarshalledValueMap.");
- Map retValMap = (Map) retVal;
- if (!retValMap.isEmpty()) retVal = new MarshalledValueMap(retValMap);
- }
- return retVal;
- }
-
- @Override
- public Object visitPutForExternalReadCommand(InvocationContext ctx, PutForExternalReadCommand command) throws Throwable
- {
- return visitPutKeyValueCommand(ctx, command);
- }
-
- @Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
- if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
- {
- Object newKey = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
- command.setKey(newKey);
- }
- if (!MarshalledValueHelper.isTypeExcluded(command.getValue().getClass()))
- {
- Object value = createAndAddMarshalledValue(command.getValue(), marshalledValues, ctx);
- command.setValue(value);
- }
- Object retVal = invokeNextInterceptor(ctx, command);
- return compactAndProcessRetVal(command, marshalledValues, retVal);
- }
-
- @Override
- public Object visitGetNodeCommand(InvocationContext ctx, GetNodeCommand command) throws Throwable
- {
- Object retVal = invokeNextInterceptor(ctx, command);
- return processRetVal(retVal);
- }
-
- @Override
- public Object visitClearDataCommand(InvocationContext ctx, ClearDataCommand command) throws Throwable
- {
- Object retVal = invokeNextInterceptor(ctx, command);
- return processRetVal(retVal);
- }
-
- @Override
- public Object visitRemoveKeyCommand(InvocationContext ctx, RemoveKeyCommand command) throws Throwable
- {
- Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
- if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
- {
- Object value = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
- command.setKey(value);
- }
- Object retVal = invokeNextInterceptor(ctx, command);
- return compactAndProcessRetVal(command, marshalledValues, retVal);
- }
-
- @Override
- public Object visitGetChildrenNamesCommand(InvocationContext ctx, GetChildrenNamesCommand command) throws Throwable
- {
- Object retVal = invokeNextInterceptor(ctx, command);
- return processRetVal(retVal);
- }
-
- @Override
- public Object visitGetKeysCommand(InvocationContext ctx, GetKeysCommand command) throws Throwable
- {
- Object retVal = invokeNextInterceptor(ctx, command);
- return processRetVal(retVal);
- }
-
- @Override
- public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
- {
- Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
- if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
- {
- Object value = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
- command.setKey(value);
- }
- Object retVal = invokeNextInterceptor(ctx, command);
- return compactAndProcessRetVal(command, marshalledValues, retVal);
- }
-
- private Object compactAndProcessRetVal(ReplicableCommand command, Set<MarshalledValue> marshalledValues, Object retVal)
- throws IOException, ClassNotFoundException
- {
- if (trace) log.trace("Compacting MarshalledValues created");
- for (MarshalledValue mv : marshalledValues) mv.compact(false, false);
-
- return processRetVal(retVal);
- }
-
- private Object processRetVal(Object retVal)
- throws IOException, ClassNotFoundException
- {
- if (retVal instanceof MarshalledValue)
- {
- if (trace) log.trace("Return value is a MarshalledValue. Unwrapping.");
- retVal = ((MarshalledValue) retVal).get();
- }
- return retVal;
- }
-
- @SuppressWarnings("unchecked")
- protected Map wrapMap(Map<Object, Object> m, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException
- {
- if (m == null)
- {
- if (trace) log.trace("Map is nul; returning an empty map.");
- return Collections.emptyMap();
- }
- if (trace) log.trace("Wrapping map contents of argument " + m);
- Map copy = new HashMap();
- for (Map.Entry me : m.entrySet())
- {
- Object key = me.getKey();
- Object value = me.getValue();
- copy.put((key == null || MarshalledValueHelper.isTypeExcluded(key.getClass())) ? key : createAndAddMarshalledValue(key, marshalledValues, ctx),
- (value == null || MarshalledValueHelper.isTypeExcluded(value.getClass())) ? value : createAndAddMarshalledValue(value, marshalledValues, ctx));
- }
- return copy;
- }
-
- protected MarshalledValue createAndAddMarshalledValue(Object toWrap, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException
- {
- MarshalledValue mv = new MarshalledValue(toWrap);
- marshalledValues.add(mv);
- if (!ctx.isOriginLocal()) mv.setEqualityPreferenceForInstance(false);
- return mv;
- }
-}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/NotificationInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/NotificationInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/NotificationInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -1,71 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.commands.tx.CommitCommand;
-import org.jboss.cache.commands.tx.PrepareCommand;
-import org.jboss.cache.commands.tx.RollbackCommand;
-import org.jboss.cache.notifications.Notifier;
-import org.jboss.starobrno.factories.annotations.Inject;
-
-/**
- * The interceptor in charge of firing off notifications to cache listeners
- *
- * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
- * @since 2.0.0
- */
-public class NotificationInterceptor extends BaseTransactionalContextInterceptor
-{
- private Notifier notifier;
-
- @Inject
- public void injectDependencies(Notifier notifier)
- {
- this.notifier = notifier;
- }
-
- @Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- Object retval = invokeNextInterceptor(ctx, command);
- if (command.isOnePhaseCommit()) notifier.notifyTransactionCompleted(ctx.getTransaction(), true, ctx);
-
- return retval;
- }
-
- @Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- Object retval = invokeNextInterceptor(ctx, command);
- notifier.notifyTransactionCompleted(ctx.getTransaction(), true, ctx);
- return retval;
- }
-
- @Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- Object retval = invokeNextInterceptor(ctx, command);
- notifier.notifyTransactionCompleted(ctx.getTransaction(), false, ctx);
- return retval;
- }
-}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/TxInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -1,1145 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.RPCManager;
-import org.jboss.cache.ReplicationException;
-import org.jboss.cache.commands.AbstractVisitor;
-import org.jboss.cache.commands.CommandsFactory;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.commands.WriteCommand;
-import org.jboss.cache.commands.tx.CommitCommand;
-import org.jboss.cache.commands.tx.PrepareCommand;
-import org.jboss.cache.commands.tx.RollbackCommand;
-import org.jboss.cache.commands.write.ClearDataCommand;
-import org.jboss.cache.commands.write.InvalidateCommand;
-import org.jboss.cache.commands.write.PutDataMapCommand;
-import org.jboss.cache.commands.write.PutKeyValueCommand;
-import org.jboss.cache.commands.write.RemoveKeyCommand;
-import org.jboss.cache.commands.write.RemoveNodeCommand;
-import org.jboss.cache.invocation.InvocationContextContainer;
-import org.jboss.cache.jmx.annotations.ManagedAttribute;
-import org.jboss.cache.jmx.annotations.ManagedOperation;
-import org.jboss.cache.lock.LockManager;
-import org.jboss.cache.notifications.Notifier;
-import org.jboss.cache.transaction.GlobalTransaction;
-import org.jboss.cache.transaction.TransactionContext;
-import org.jboss.cache.transaction.TransactionTable;
-import org.jboss.cache.util.concurrent.ConcurrentHashSet;
-import org.jboss.starobrno.CacheException;
-import org.jboss.starobrno.config.Option;
-import org.jboss.starobrno.factories.ComponentRegistry;
-import org.jboss.starobrno.factories.annotations.Inject;
-import org.jboss.starobrno.factories.context.ContextFactory;
-
-import javax.transaction.InvalidTransactionException;
-import javax.transaction.Status;
-import javax.transaction.Synchronization;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * This interceptor is the new default at the head of all interceptor chains,
- * and makes transactional attributes available to all interceptors in the chain.
- * This interceptor is also responsible for registering for synchronisation on
- * transaction completion.
- *
- * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
- * @author <a href="mailto:stevew@jofti.com">Steve Woodcock (stevew(a)jofti.com)</a>
- */
-public class TxInterceptor extends BaseTransactionalContextInterceptor
-{
- protected CommandsFactory commandsFactory;
- protected RPCManager rpcManager;
- private Notifier notifier;
- private InvocationContextContainer invocationContextContainer;
- private ComponentRegistry componentRegistry;
- private ContextFactory contextFactory;
-
- /**
- * List <Transaction>that we have registered for
- */
- private final Set<Transaction> transactions = new ConcurrentHashSet<Transaction>();
- private final Map<Transaction, GlobalTransaction> rollbackTransactions = new ConcurrentHashMap<Transaction, GlobalTransaction>(16);
- private long prepares = 0;
- private long commits = 0;
- private long rollbacks = 0;
- protected boolean optimistic = false;
- private LockManager lockManager;
- private boolean statsEnabled;
-
- @Inject
- public void intialize(RPCManager rpcManager, ContextFactory contextFactory,
- Notifier notifier, InvocationContextContainer icc,
- CommandsFactory factory, ComponentRegistry componentRegistry, LockManager lockManager)
- {
- this.contextFactory = contextFactory;
- this.commandsFactory = factory;
- this.rpcManager = rpcManager;
- this.notifier = notifier;
- this.invocationContextContainer = icc;
- this.componentRegistry = componentRegistry;
- this.lockManager = lockManager;
- setStatisticsEnabled(configuration.getExposeManagementStatistics());
- }
-
- @Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- Object result = null;
-
- // this is a prepare, commit, or rollback.
- if (log.isDebugEnabled()) log.debug("Got gtx from invocation context " + ctx.getGlobalTransaction());
- try
- {
- if (ctx.getGlobalTransaction().isRemote())
- {
- result = handleRemotePrepare(ctx, command);
- if (getStatisticsEnabled()) prepares++;
- }
- else
- {
- if (trace) log.trace("received my own message (discarding it)");
- result = null;
- }
- }
- catch (Throwable e)
- {
- ctx.throwIfNeeded(e);
- }
-
- return result;
- }
-
- @Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- if (!ctx.getGlobalTransaction().isRemote())
- {
- if (trace) log.trace("received my own message (discarding it)");
- return null;
- }
- try
- {
- if (trace) log.trace("(" + rpcManager.getLocalAddress() + ") call on command [" + command + "]");
- GlobalTransaction gtx = ctx.getGlobalTransaction();
- Transaction ltx = txTable.getLocalTransaction(gtx, true);
- // disconnect if we have a current tx associated
- Transaction currentTx = txManager.getTransaction();
- boolean resumeCurrentTxOnCompletion = false;
- try
- {
- if (!ltx.equals(currentTx))
- {
- currentTx = txManager.suspend();
- resumeCurrentTxOnCompletion = true;
- txManager.resume(ltx);
- // make sure we set this in the ctx
- ctx.setTransaction(ltx);
- }
- if (log.isDebugEnabled()) log.debug(" executing commit() with local TX " + ltx + " under global tx " + gtx);
- txManager.commit();
- if (getStatisticsEnabled()) commits++;
- }
- finally
- {
- //resume the old transaction if we suspended it
- if (resumeCurrentTxOnCompletion)
- {
- resumeTransactionOnCompletion(ctx, currentTx);
- }
- // remove from local lists.
- transactions.remove(ltx);
- // this tx has completed. Clean up in the tx table.
- txTable.remove(gtx, ltx);
- }
- if (log.isDebugEnabled()) log.debug("Finished remote rollback method for " + gtx);
- }
- catch (Throwable throwable)
- {
- ctx.throwIfNeeded(throwable);
- }
-
- return null;
- }
-
- @Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- if (!ctx.getGlobalTransaction().isRemote())
- {
- if (trace) log.trace("received my own message (discarding it)");
- return null;
- }
- try
- {
- if (trace) log.trace("(" + rpcManager.getLocalAddress() + ") call on command [" + command + "]");
- GlobalTransaction gtx = ctx.getGlobalTransaction();
- Transaction ltx = txTable.getLocalTransaction(gtx);
- if (ltx == null)
- {
- log.warn("No local transaction for this remotely originating rollback. Possibly rolling back before a prepare call was broadcast?");
- txTable.remove(gtx);
- return null;
- }
- // disconnect if we have a current tx associated
- Transaction currentTx = txManager.getTransaction();
- boolean resumeCurrentTxOnCompletion = false;
- try
- {
- if (!ltx.equals(currentTx))
- {
- currentTx = txManager.suspend();
- resumeCurrentTxOnCompletion = true;
- txManager.resume(ltx);
- // make sure we set this in the ctx
- ctx.setTransaction(ltx);
- }
- if (log.isDebugEnabled()) log.debug("executing with local TX " + ltx + " under global tx " + gtx);
- txManager.rollback();
- if (getStatisticsEnabled()) rollbacks++;
- }
- finally
- {
- //resume the old transaction if we suspended it
- if (resumeCurrentTxOnCompletion)
- {
- resumeTransactionOnCompletion(ctx, currentTx);
- }
-
- // remove from local lists.
- transactions.remove(ltx);
-
- // this tx has completed. Clean up in the tx table.
- txTable.remove(gtx, ltx);
- }
- if (log.isDebugEnabled()) log.debug("Finished remote commit/rollback method for " + gtx);
- }
- catch (Throwable throwable)
- {
- ctx.throwIfNeeded(throwable);
- }
-
- return null;
- }
-
- @Override
- public Object visitInvalidateCommand(InvocationContext ctx, InvalidateCommand command) throws Throwable
- {
- return invokeNextInterceptor(ctx, command);
- }
-
- /**
- * Tests if we already have a tx running. If so, register a sync handler for this method invocation.
- * if not, create a local tx if we're using opt locking.
- *
- * @throws Throwable
- */
- @Override
- public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- try
- {
- return attachGtxAndPassUpChain(ctx, command);
- }
- catch (Throwable throwable)
- {
- ctx.throwIfNeeded(throwable);
- return null;
- }
- }
-
- protected Object attachGtxAndPassUpChain(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- Transaction tx = ctx.getTransaction();
- if (tx != null) attachGlobalTransaction(ctx, tx, command);
- return invokeNextInterceptor(ctx, command);
- }
-
- // ------------------------------------------------------------------------
- // JMX statistics
- // ------------------------------------------------------------------------
-
- // --------------------------------------------------------------
-
- /**
- * Handles a remotely originating prepare call, by creating a local transaction for the remote global transaction
- * and replaying modifications in this new local transaction.
- *
- * @param ctx invocation context
- * @param command prepare command
- * @return result of the prepare, typically a null.
- * @throws Throwable in the event of problems.
- */
- private Object handleRemotePrepare(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- // the InvocationContextInterceptor would have set this for us
- GlobalTransaction gtx = ctx.getGlobalTransaction();
-
- // Is there a local transaction associated with GTX? (not the current tx associated with the thread, which may be
- // in the invocation context
- Transaction ltx = txTable.getLocalTransaction(gtx);
- Transaction currentTx = txManager.getTransaction();
-
- Object retval = null;
- boolean success = false;
- try
- {
- if (ltx == null)
- {
- if (currentTx != null) txManager.suspend();
- // create a new local transaction
- ltx = createLocalTx();
- // associate this with a global tx
- txTable.put(ltx, gtx);
- if (trace) log.trace("Created new tx for gtx " + gtx);
-
- if (log.isDebugEnabled())
- log.debug("Started new local tx as result of remote prepare: local tx=" + ltx + " (status=" + ltx.getStatus() + "), gtx=" + gtx);
- }
- else
- {
- //this should be valid
- if (!TransactionTable.isValid(ltx))
- throw new CacheException("Transaction " + ltx + " not in correct state to be prepared");
-
- //associate this thread with the local transaction associated with the global transaction, IF the localTx is NOT the current tx.
- if (currentTx == null || !ltx.equals(currentTx))
- {
- if (trace) log.trace("Suspending current tx " + currentTx);
- txManager.suspend();
- txManager.resume(ltx);
- }
- }
- if (trace) log.trace("Resuming existing tx " + ltx + ", global tx=" + gtx);
-
- // at this point we have a non-null ltx
-
- // Asssociate the local TX with the global TX. Create new
- // transactionContext for TX in txTable, the modifications
- // below will need this transactionContext to add their modifications
- // under the GlobalTx key
- TransactionContext transactionContext = txTable.get(gtx);
- if (transactionContext == null)
- {
- // create a new transaction transactionContext
- if (log.isDebugEnabled()) log.debug("creating new tx transactionContext");
-// transactionContext = contextFactory.createTransactionContext(ltx);
- throw new RuntimeException("Delete this class!");
-// txTable.put(gtx, transactionContext);
- }
-
- setTransactionalContext(ltx, gtx, transactionContext, ctx);
-
- // register a sync handler for this tx.
- registerHandler(ltx, new RemoteSynchronizationHandler(gtx, ltx, transactionContext), ctx);
-
- success = false;
-
- // replay modifications
- replayModifications(ctx, ltx, command);
-
- success = true; // no exceptions were thrown above!!
-
- // now pass the prepare command up the chain as well.
- if (command.isOnePhaseCommit())
- {
- if (trace)
- log.trace("Using one-phase prepare. Not propagating the prepare call up the stack until called to do so by the sync handler.");
- }
- else
- {
- // now pass up the prepare method itself.
- invokeNextInterceptor(ctx, command);
- }
- // JBCACHE-361 Confirm that the transaction is ACTIVE
- assertTxIsStillValid(ltx);
- }
- finally
- {
- // if we are running a one-phase commit, perform a commit or rollback now.
- if (trace) log.trace("Are we running a 1-phase commit? " + command.isOnePhaseCommit());
-
- if (command.isOnePhaseCommit())
- {
- try
- {
- if (success)
- {
- ltx.commit();
- }
- else
- {
- ltx.rollback();
- }
- }
- catch (Throwable t)
- {
- log.error("Commit/rollback failed.", t);
- if (success)
- {
- // try another rollback...
- try
- {
- log.info("Attempting anotehr rollback");
- //invokeOnePhaseCommitMethod(globalTransaction, modifications.size() > 0, false);
- ltx.rollback();
- }
- catch (Throwable t2)
- {
- log.error("Unable to rollback", t2);
- }
- }
- }
- finally
- {
- transactions.remove(ltx);// JBAS-298
- }
- }
-
- txManager.suspend();// suspends ltx - could be null
- // resume whatever else we had going.
- if (currentTx != null) txManager.resume(currentTx);
- if (log.isDebugEnabled()) log.debug("Finished remote prepare " + gtx);
- }
-
- return retval;
- }
-
- private ReplicableCommand attachGlobalTransaction(InvocationContext ctx, Transaction tx, VisitableCommand command) throws Throwable
- {
- if (trace)
- {
- log.trace(" local transaction exists - registering global tx if not present for " + Thread.currentThread());
- }
- if (trace)
- {
- GlobalTransaction tempGtx = txTable.get(tx);
- log.trace("Associated gtx in txTable is " + tempGtx);
- }
-
- // register a sync handler for this tx - only if the globalTransaction is not remotely initiated.
- GlobalTransaction gtx = registerTransaction(tx, ctx);
- if (gtx != null)
- {
- command = replaceGtx(command, gtx);
- }
- else
- {
- // get the current globalTransaction from the txTable.
- gtx = txTable.get(tx);
- }
-
- // make sure we attach this globalTransaction to the invocation context.
- ctx.setGlobalTransaction(gtx);
-
- return command;
- }
-
- /**
- * Replays modifications
- */
- protected void replayModifications(InvocationContext ctx, Transaction ltx, PrepareCommand command) throws Throwable
- {
- try
- {
- // replay modifications
- for (WriteCommand modification : command.getModifications())
- {
- invokeNextInterceptor(ctx, modification);
- assertTxIsStillValid(ltx);
- }
- }
- catch (Throwable th)
- {
- log.error("prepare failed!", th);
- throw th;
- }
- }
-
- private void resumeTransactionOnCompletion(InvocationContext ctx, Transaction currentTx)
- throws SystemException, InvalidTransactionException
- {
- if (trace) log.trace("Resuming suspended transaction " + currentTx);
- txManager.suspend();
- if (currentTx != null)
- {
- txManager.resume(currentTx);
- ctx.setTransaction(currentTx);
- }
- }
-
- /**
- * Handles a commit or a rollback. Called by the synch handler. Simply tests that we are in the correct tx and
- * passes the meth call up the interceptor chain.
- *
- * @throws Throwable
- */
- @SuppressWarnings("deprecation")
- private Object handleCommitRollback(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- GlobalTransaction gtx = ctx.getGlobalTransaction();
- Object result;
- VisitableCommand originalCommand = ctx.getCommand();
- ctx.setCommand(command);
- try
- {
- result = invokeNextInterceptor(ctx, command);
- }
- finally
- {
- ctx.setCommand(originalCommand);
- ctx.setMethodCall(null);
- }
- if (log.isDebugEnabled()) log.debug("Finished local commit/rollback method for " + gtx);
- return result;
- }
-
- // --------------------------------------------------------------
- // Transaction phase runners
- // --------------------------------------------------------------
-
- protected PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, boolean onePhaseCommit)
- {
- return commandsFactory.buildPrepareCommand(gtx, modifications, rpcManager.getLocalAddress(), onePhaseCommit);
- }
-
- /**
- * creates a commit()
- */
- protected void runCommitPhase(InvocationContext ctx, GlobalTransaction gtx, List modifications, boolean onePhaseCommit)
- {
- try
- {
- VisitableCommand commitCommand = onePhaseCommit ? buildPrepareCommand(gtx, modifications, true) : commandsFactory.buildCommitCommand(gtx);
-
- if (trace) log.trace("Running commit for " + gtx);
-
- handleCommitRollback(ctx, commitCommand);
- }
- catch (Throwable e)
- {
- log.warn("Commit failed. Clearing stale locks.");
- try
- {
- cleanupStaleLocks(ctx);
- }
- catch (RuntimeException re)
- {
- log.error("Unable to clear stale locks", re);
- throw re;
- }
- catch (Throwable e2)
- {
- log.error("Unable to clear stale locks", e2);
- throw new RuntimeException(e2);
- }
- if (e instanceof RuntimeException)
- throw (RuntimeException) e;
- else
- throw new RuntimeException("Commit failed.", e);
- }
- }
-
- protected void cleanupStaleLocks(InvocationContext ctx) throws Throwable
- {
- TransactionContext transactionContext = ctx.getTransactionContext();
- if (transactionContext != null) lockManager.unlock(ctx);
- }
-
- /**
- * creates a rollback()
- */
- protected void runRollbackPhase(InvocationContext ctx, GlobalTransaction gtx, Transaction tx)
- {
- try
- {
- // JBCACHE-457
- VisitableCommand rollbackCommand = commandsFactory.buildRollbackCommand(gtx);
- if (trace) log.trace(" running rollback for " + gtx);
-
- //JBCACHE-359 Store a lookup for the globalTransaction so a listener
- // callback can find it
- rollbackTransactions.put(tx, gtx);
-
- handleCommitRollback(ctx, rollbackCommand);
- }
- catch (Throwable e)
- {
- log.warn("Rollback had a problem", e);
- }
- finally
- {
- rollbackTransactions.remove(tx);
- }
- }
-
- private boolean isOnePhaseCommit()
- {
- if (!configuration.getCacheMode().isSynchronous() && !optimistic)
- {
- // this is a REPL_ASYNC call - do 1-phase commit. break!
- if (trace) log.trace("This is a REPL_ASYNC call (1 phase commit) - do nothing for beforeCompletion()");
- return true;
- }
- return false;
- }
-
- /**
- * Handles a local prepare - invoked by the sync handler. Tests if the current tx matches the gtx passed in to the
- * method call and passes the prepare() call up the chain.
- */
- @SuppressWarnings("deprecation")
- public Object runPreparePhase(InvocationContext ctx, GlobalTransaction gtx, List<WriteCommand> modifications) throws Throwable
- {
- // running a 2-phase commit.
- VisitableCommand prepareCommand = buildPrepareCommand(gtx, modifications, false);
-
- Object result;
-
- // Is there a local transaction associated with GTX ?
- Transaction ltx = ctx.getTransaction();
-
- //if ltx is not null and it is already running
- Transaction currentTransaction = txManager.getTransaction();
- if (currentTransaction != null && ltx != null && currentTransaction.equals(ltx))
- {
- VisitableCommand originalCommand = ctx.getCommand();
- ctx.setCommand(prepareCommand);
- try
- {
- result = invokeNextInterceptor(ctx, prepareCommand);
- }
- finally
- {
- ctx.setCommand(originalCommand);
- ctx.setMethodCall(null);
- }
- }
- else
- {
- log.warn("Local transaction does not exist or does not match expected transaction " + gtx);
- throw new CacheException(" local transaction " + ltx + " does not exist or does not match expected transaction " + gtx);
- }
- return result;
- }
-
- // --------------------------------------------------------------
- // Private helper methods
- // --------------------------------------------------------------
-
- protected void assertTxIsStillValid(Transaction tx)
- {
- if (!TransactionTable.isActive(tx))
- {
- try
- {
- throw new ReplicationException("prepare() failed -- local transaction status is not STATUS_ACTIVE; is " + tx.getStatus());
- }
- catch (SystemException e)
- {
- throw new ReplicationException("prepare() failed -- local transaction status is not STATUS_ACTIVE; Unable to retrieve transaction status.");
- }
- }
- }
-
- /**
- * Creates a gtx (if one doesnt exist), a sync handler, and registers the tx.
- */
- private GlobalTransaction registerTransaction(Transaction tx, InvocationContext ctx) throws Exception
- {
- GlobalTransaction gtx;
-
- if (TransactionTable.isValid(tx) && transactions.add(tx))
- {
- gtx = txTable.getCurrentTransaction(tx, true);
- TransactionContext transactionContext;
- if (ctx.getGlobalTransaction() == null)
- {
- ctx.setGlobalTransaction(gtx);
- transactionContext = txTable.get(gtx);
- ctx.setTransactionContext(transactionContext);
- }
- else
- {
- transactionContext = ctx.getTransactionContext();
- }
- if (gtx.isRemote())
- {
- // should be no need to register a handler since this a remotely initiated globalTransaction
- if (trace) log.trace("is a remotely initiated gtx so no need to register a tx for it");
- }
- else
- {
- if (trace) log.trace("Registering sync handler for tx " + tx + ", gtx " + gtx);
-
- // see the comment in the LocalSyncHandler for the last isOriginLocal param.
- LocalSynchronizationHandler myHandler = new LocalSynchronizationHandler(gtx, tx, transactionContext, !ctx.isOriginLocal());
- registerHandler(tx, myHandler, ctx);
- }
- }
- else if ((gtx = rollbackTransactions.get(tx)) != null)
- {
- if (trace) log.trace("Transaction " + tx + " is already registered and is rolling back.");
- }
- else
- {
- if (trace) log.trace("Transaction " + tx + " is already registered.");
- }
- return gtx;
- }
-
- /**
- * Registers a sync hander against a tx.
- */
- private void registerHandler(Transaction tx, Synchronization handler, InvocationContext ctx) throws Exception
- {
- OrderedSynchronizationHandler orderedHandler = ctx.getTransactionContext().getOrderedSynchronizationHandler(); //OrderedSynchronizationHandler.getInstance(tx);
-
- if (trace) log.trace("registering for TX completion: SynchronizationHandler(" + handler + ")");
-
- orderedHandler.registerAtHead(handler);// needs to be invoked first on TX commit
-
- notifier.notifyTransactionRegistered(tx, ctx);
- }
-
- /**
- * Replaces the global transaction in a VisitableCommand with a new global transaction passed in.
- */
- private VisitableCommand replaceGtx(VisitableCommand command, final GlobalTransaction gtx) throws Throwable
- {
- command.acceptVisitor(null, new AbstractVisitor()
- {
- @Override
- public Object visitPutDataMapCommand(InvocationContext ctx, PutDataMapCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- @Override
- public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- @Override
- public Object visitClearDataCommand(InvocationContext ctx, ClearDataCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- @Override
- public Object visitRemoveNodeCommand(InvocationContext ctx, RemoveNodeCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- @Override
- public Object visitRemoveKeyCommand(InvocationContext ctx, RemoveKeyCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- @Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- @Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- @Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- command.setGlobalTransaction(gtx);
- return null;
- }
-
- });
- return command;
- }
-
- /**
- * Creates and starts a local tx
- *
- * @throws Exception
- */
- protected Transaction createLocalTx() throws Exception
- {
- if (trace)
- {
- log.trace("Creating transaction for thread " + Thread.currentThread());
- }
- Transaction localTx;
- if (txManager == null) throw new Exception("Failed to create local transaction; TransactionManager is null");
- txManager.begin();
- localTx = txManager.getTransaction();
- return localTx;
- }
-
- // ------------------------------------------------------------------------
- // Synchronization classes
- // ------------------------------------------------------------------------
-
- // this controls the whole transaction
-
- private class RemoteSynchronizationHandler implements Synchronization
- {
- Transaction tx = null;
- GlobalTransaction gtx = null;
- List<WriteCommand> modifications = null;
- TransactionContext transactionContext = null;
- protected InvocationContext ctx; // the context for this call.
-
- RemoteSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext entry)
- {
- this.gtx = gtx;
- this.tx = tx;
- this.transactionContext = entry;
- }
-
- public void beforeCompletion()
- {
- if (trace) log.trace("Running beforeCompletion on gtx " + gtx);
-
- if (transactionContext == null)
- {
- log.error("Transaction has a null transaction entry - beforeCompletion() will fail.");
- throw new IllegalStateException("cannot find transaction entry for " + gtx);
- }
-
- modifications = transactionContext.getModifications();
- ctx = invocationContextContainer.get();
- setTransactionalContext(tx, gtx, transactionContext, ctx);
-
- if (ctx.isOptionsUninitialised() && transactionContext.getOption() != null)
- ctx.setOptionOverrides(transactionContext.getOption());
-
- assertCanContinue();
-
- ctx.setOriginLocal(false);
- }
-
- // this should really not be done here -
- // it is supposed to be post commit not actually run the commit
- public void afterCompletion(int status)
- {
- // could happen if a rollback is called and beforeCompletion() doesn't get called.
- if (ctx == null)
- {
- ctx = invocationContextContainer.get();
- setTransactionalContext(tx, gtx, transactionContext, ctx);
-
- if (ctx.isOptionsUninitialised() && transactionContext != null && transactionContext.getOption() != null)
- {
- // use the options from the transaction entry instead
- ctx.setOptionOverrides(transactionContext.getOption());
- }
- }
-
- try
- {
- assertCanContinue();
-
- try
- {
- if (txManager.getTransaction() != null && !txManager.getTransaction().equals(tx)) txManager.resume(tx);
- }
- catch (Exception e)
- {
- log.error("afterCompletion error: " + status, e);
- }
-
- if (trace) log.trace("calling aftercompletion for " + gtx);
-
- // set any transaction wide options as current for this thread.
- if (transactionContext != null)
- {
- // this should ideally be set in beforeCompletion(), after compacting the list.
- if (modifications == null) modifications = transactionContext.getModifications();
- ctx.setOptionOverrides(transactionContext.getOption());
- }
- if (tx != null) transactions.remove(tx);
-
- switch (status)
- {
- case Status.STATUS_COMMITTED:
- boolean onePhaseCommit = isOnePhaseCommit();
- if (log.isDebugEnabled()) log.debug("Running commit phase. One phase? " + onePhaseCommit);
- runCommitPhase(ctx, gtx, modifications, onePhaseCommit);
- log.debug("Finished commit phase");
- break;
- case Status.STATUS_UNKNOWN:
- log.warn("Received JTA STATUS_UNKNOWN in afterCompletion()! XA resources may not be in sync. The app should manually clean up resources at this point.");
- case Status.STATUS_MARKED_ROLLBACK:
- case Status.STATUS_ROLLEDBACK:
- log.debug("Running rollback phase");
- runRollbackPhase(ctx, gtx, tx);
- log.debug("Finished rollback phase");
- break;
-
- default:
- throw new IllegalStateException("illegal status: " + status);
- }
- }
- catch (Exception th)
- {
- log.trace("Caught exception ", th);
-
- }
- finally
- {
- // clean up the tx table
- txTable.remove(gtx);
- txTable.remove(tx);
- setTransactionalContext(null, null, null, ctx);
- cleanupInternalState();
- }
- }
-
- private void assertCanContinue()
- {
- if (!componentRegistry.invocationsAllowed(true) && (ctx.getOptionOverrides() == null || !ctx.getOptionOverrides().isSkipCacheStatusCheck()))
- throw new IllegalStateException("Cache not in STARTED state!");
- }
-
- /**
- * Cleans out (nullifies) member variables held by the sync object for easier gc. Could be (falsely) seen as a mem
- * leak if the TM implementation hangs on to the synchronizations for an unnecessarily long time even after the tx
- * completes. See JBCACHE-1007.
- */
- private void cleanupInternalState()
- {
- tx = null;
- gtx = null;
- modifications = null;
- if (transactionContext != null) transactionContext.reset();
- transactionContext = null;
- }
-
- @Override
- public String toString()
- {
- return "TxInterceptor.RemoteSynchronizationHandler(gtx=" + gtx + ", tx=" + getTxAsString() + ")";
- }
-
- protected String getTxAsString()
- {
- // JBCACHE-1114 -- don't call toString() on tx or it can lead to stack overflow
- if (tx == null)
- return null;
-
- return tx.getClass().getName() + "@" + System.identityHashCode(tx);
- }
- }
-
- private class LocalSynchronizationHandler extends RemoteSynchronizationHandler
- {
- private boolean localRollbackOnly = true;
- // a VERY strange situation where a tx has remote origins, but since certain buddy group org methods perform local
- // cleanups even when remotely triggered, and optimistic locking is used, you end up with an implicit local tx.
- // This is STILL remotely originating though and this needs to be made explicit here.
- // this can be checked by inspecting the InvocationContext.isOriginLocal() at the time of registering the sync.
- private boolean remoteLocal = false;
- private Option originalOptions, transactionalOptions;
-
- /**
- * A Synchronization for locally originating txs.
- * <p/>
- * a VERY strange situation where a tx has remote origins, but since certain buddy group org methods perform local
- * cleanups even when remotely triggered, and optimistic locking is used, you end up with an implicit local tx.
- * This is STILL remotely originating though and this needs to be made explicit here.
- * this can be checked by inspecting the InvocationContext.isOriginLocal() at the time of registering the sync.
- *
- * @param gtx
- * @param tx
- * @param remoteLocal
- */
- LocalSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext transactionContext, boolean remoteLocal)
- {
- super(gtx, tx, transactionContext);
- this.remoteLocal = remoteLocal;
- }
-
- @Override
- public void beforeCompletion()
- {
- super.beforeCompletion();
- ctx.setOriginLocal(!remoteLocal); // this is the LOCAL sync handler after all!
- // fetch the modifications before the transaction is committed
- // (and thus removed from the txTable)
- setTransactionalContext(tx, gtx, transactionContext, ctx);
- if (!transactionContext.hasModifications())
- {
- if (trace) log.trace("No modifications in this tx. Skipping beforeCompletion()");
- modifications = Collections.emptyList();
- return;
- }
- else
- {
- modifications = transactionContext.getModifications();
- }
-
- // set any transaction wide options as current for this thread, caching original options that would then be reset
- originalOptions = ctx.getOptionOverrides();
- transactionalOptions = transactionContext.getOption();
- ctx.setOptionOverrides(transactionalOptions);
-
- try
- {
- switch (tx.getStatus())
- {
- // if we are active or preparing then we can go ahead
- case Status.STATUS_ACTIVE:
- case Status.STATUS_PREPARING:
- // run a prepare call.
-
- Object result = isOnePhaseCommit() ? null : runPreparePhase(ctx, gtx, modifications);
-
- if (result instanceof Throwable)
- {
- if (log.isDebugEnabled())
- log.debug("Transaction needs to be rolled back - the cache returned an instance of Throwable for this prepare call (tx=" + tx + " and gtx=" + gtx + ")", (Throwable) result);
- tx.setRollbackOnly();
- throw (Throwable) result;
- }
- break;
- default:
- throw new CacheException("transaction " + tx + " in status " + tx.getStatus() + " unable to start transaction");
- }
- }
- catch (Throwable t)
- {
- if (log.isWarnEnabled()) log.warn("Caught exception, will now set transaction to roll back", t);
- try
- {
- tx.setRollbackOnly();
- }
- catch (SystemException se)
- {
- throw new RuntimeException("setting tx rollback failed ", se);
- }
- if (t instanceof RuntimeException)
- throw (RuntimeException) t;
- else
- throw new RuntimeException("", t);
- }
- finally
- {
- localRollbackOnly = false;
- setTransactionalContext(null, null, null, ctx);
- ctx.setOptionOverrides(originalOptions);
- }
- }
-
- @Override
- public void afterCompletion(int status)
- {
- // could happen if a rollback is called and beforeCompletion() doesn't get called.
- if (ctx == null) ctx = invocationContextContainer.get();
- ctx.setLocalRollbackOnly(localRollbackOnly);
- setTransactionalContext(tx, gtx, transactionContext, ctx);
- if (transactionalOptions != null) ctx.setOptionOverrides(transactionalOptions);
- try
- {
- super.afterCompletion(status);
- }
- finally
- {
- ctx.setOptionOverrides(originalOptions);
- }
- }
-
- @Override
- public String toString()
- {
- return "TxInterceptor.LocalSynchronizationHandler(gtx=" + gtx + ", tx=" + getTxAsString() + ")";
- }
- }
-
- @ManagedOperation
- public void resetStatistics()
- {
- prepares = 0;
- commits = 0;
- rollbacks = 0;
- }
-
- @ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>(3);
- retval.put("Prepares", prepares);
- retval.put("Commits", commits);
- retval.put("Rollbacks", rollbacks);
- return retval;
- }
-
- @ManagedAttribute
- public boolean getStatisticsEnabled()
- {
- return this.statsEnabled;
- }
-
- @ManagedAttribute
- public void setStatisticsEnabled(boolean enabled)
- {
- this.statsEnabled = enabled;
- }
-
- @ManagedAttribute(description = "number of transaction prepares")
- public long getPrepares()
- {
- return prepares;
- }
-
- @ManagedAttribute(description = "number of transaction commits")
- public long getCommits()
- {
- return commits;
- }
-
- @ManagedAttribute(description = "number of transaction rollbacks")
- public long getRollbacks()
- {
- return rollbacks;
- }
-}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -31,6 +31,7 @@
import org.jboss.starobrno.commands.CommandsFactory;
import org.jboss.starobrno.commands.ReplicableCommand;
import org.jboss.starobrno.factories.annotations.Inject;
+import org.jboss.starobrno.marshall.MarshalledValue;
import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jgroups.Address;
import org.jgroups.stack.IpAddress;
Modified: core/branches/flat/src/main/java/org/jboss/cache/notifications/NotifierImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/notifications/NotifierImpl.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/cache/notifications/NotifierImpl.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -26,7 +26,6 @@
import org.jboss.cache.Fqn;
import org.jboss.cache.InvocationContext;
import org.jboss.cache.buddyreplication.BuddyGroup;
-import org.jboss.cache.marshall.MarshalledValueMap;
import org.jboss.cache.notifications.annotation.*;
import org.jboss.cache.notifications.event.*;
import org.jboss.cache.util.Immutables;
@@ -40,6 +39,7 @@
import org.jboss.starobrno.factories.annotations.NonVolatile;
import org.jboss.starobrno.factories.annotations.Start;
import org.jboss.starobrno.factories.annotations.Stop;
+import org.jboss.starobrno.marshall.MarshalledValueMap;
import org.jgroups.View;
import javax.transaction.Transaction;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -50,6 +50,16 @@
{
}
+ public Object getValue()
+ {
+ return value;
+ }
+
+ public void setValue(Object value)
+ {
+ this.value = value;
+ }
+
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
{
return visitor.visitPutKeyValueCommand(ctx, this);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -57,7 +57,7 @@
for (Entry<Object, Object> e : map.entrySet())
{
MVCCEntry me = ctx.lookupEntry(e.getKey());
- if (e != null) e.setValue(e.getValue());
+ if (e != null) e.setValue(me.getValue());
}
return null;
}
@@ -67,6 +67,11 @@
return map;
}
+ public void setMap(Map<Object, Object> map)
+ {
+ this.map = map;
+ }
+
public int getCommandId()
{
return METHOD_ID;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/factories/InterceptorChainFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/factories/InterceptorChainFactory.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/factories/InterceptorChainFactory.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -26,10 +26,14 @@
import org.jboss.starobrno.config.ConfigurationException;
import org.jboss.starobrno.config.CustomInterceptorConfig;
import org.jboss.starobrno.factories.annotations.DefaultFactoryFor;
+import org.jboss.starobrno.interceptors.BatchingInterceptor;
+import org.jboss.starobrno.interceptors.CacheMgmtInterceptor;
import org.jboss.starobrno.interceptors.CallInterceptor;
import org.jboss.starobrno.interceptors.InterceptorChain;
import org.jboss.starobrno.interceptors.InvocationContextInterceptor;
import org.jboss.starobrno.interceptors.LockingInterceptor;
+import org.jboss.starobrno.interceptors.MarshalledValueInterceptor;
+import org.jboss.starobrno.interceptors.NotificationInterceptor;
import org.jboss.starobrno.interceptors.TxInterceptor;
import org.jboss.starobrno.interceptors.base.CommandInterceptor;
@@ -83,33 +87,30 @@
{
boolean invocationBatching = configuration.isInvocationBatchingEnabled();
// load the icInterceptor first
- // TODO: Uncomment once the BatchingInterceptor has been moved to Starobrno
-// CommandInterceptor first = invocationBatching ? createInterceptor(BatchingInterceptor.class) : createInterceptor(InvocationContextInterceptor.class);
- CommandInterceptor first = createInterceptor(InvocationContextInterceptor.class);
+ CommandInterceptor first = invocationBatching ? createInterceptor(BatchingInterceptor.class) : createInterceptor(InvocationContextInterceptor.class);
+
InterceptorChain interceptorChain = new InterceptorChain(first);
// add the interceptor chain to the registry first, since some interceptors may ask for it.
componentRegistry.registerComponent(interceptorChain, InterceptorChain.class);
// NOW add the ICI if we are using batching!
-// if (invocationBatching)
-// interceptorChain.appendIntereceptor(createInterceptor(InvocationContextInterceptor.class));
+ if (invocationBatching)
+ interceptorChain.appendIntereceptor(createInterceptor(InvocationContextInterceptor.class));
// load the cache management interceptor next
- // TODO: Uncomment once the CacheMGMT has been moved to Starobrno
+ if (configuration.getExposeManagementStatistics())
+ interceptorChain.appendIntereceptor(createInterceptor(CacheMgmtInterceptor.class));
-// if (configuration.getExposeManagementStatistics())
-// interceptorChain.appendIntereceptor(createInterceptor(CacheMgmtInterceptor.class));
-
// load the tx interceptor
interceptorChain.appendIntereceptor(createInterceptor(TxInterceptor.class));
- // TODO: Uncomment once the MarshalledValue, Notification has been moved to Starobrno
-// if (configuration.isUseLazyDeserialization())
-// interceptorChain.appendIntereceptor(createInterceptor(MarshalledValueInterceptor.class));
-// interceptorChain.appendIntereceptor(createInterceptor(NotificationInterceptor.class));
+ if (configuration.isUseLazyDeserialization())
+ interceptorChain.appendIntereceptor(createInterceptor(MarshalledValueInterceptor.class));
+ interceptorChain.appendIntereceptor(createInterceptor(NotificationInterceptor.class));
+
// TODO: Uncomment once the Repl and Inval interceptors has been moved to Starobrno
// switch (configuration.getCacheMode())
// {
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -21,11 +21,11 @@
*/
package org.jboss.starobrno.interceptors;
-import org.jboss.cache.InvocationContext;
import org.jboss.starobrno.batch.BatchContainer;
-import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.starobrno.commands.VisitableCommand;
+import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.annotations.Inject;
+import org.jboss.starobrno.interceptors.base.CommandInterceptor;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/CacheMgmtInterceptor.java (from rev 6896, core/branches/flat/src/main/java/org/jboss/cache/interceptors/CacheMgmtInterceptor.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/CacheMgmtInterceptor.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/CacheMgmtInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -0,0 +1,225 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.interceptors;
+
+import org.jboss.starobrno.commands.read.GetKeyValueCommand;
+import org.jboss.starobrno.commands.write.EvictCommand;
+import org.jboss.starobrno.commands.write.PutKeyValueCommand;
+import org.jboss.starobrno.commands.write.PutMapCommand;
+import org.jboss.starobrno.container.DataContainer;
+import org.jboss.starobrno.context.InvocationContext;
+import org.jboss.starobrno.factories.annotations.Inject;
+import org.jboss.starobrno.interceptors.base.JmxStatsCommandInterceptor;
+import org.jboss.starobrno.jmx.annotations.ManagedAttribute;
+import org.jboss.starobrno.jmx.annotations.ManagedOperation;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Captures cache management statistics
+ *
+ * @author Jerry Gauthier
+ * @version $Id$
+ */
+public class CacheMgmtInterceptor extends JmxStatsCommandInterceptor
+{
+ private long hitTimes = 0;
+ private long missTimes = 0;
+ private long storeTimes = 0;
+ private long hits = 0;
+ private long misses = 0;
+ private long stores = 0;
+ private long evictions = 0;
+ private long start = System.currentTimeMillis();
+ private long reset = start;
+
+ private DataContainer dataContainer;
+
+ @Inject
+ public void setDependencies(DataContainer dataContainer)
+ {
+ this.dataContainer = dataContainer;
+ }
+
+ @Override
+ public Object visitEvictCommand(InvocationContext ctx, EvictCommand command) throws Throwable
+ {
+ Object returnValue = invokeNextInterceptor(ctx, command);
+ evictions++;
+ return returnValue;
+ }
+
+ @Override
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
+ {
+ long t1 = System.currentTimeMillis();
+ Object retval = invokeNextInterceptor(ctx, command);
+ long t2 = System.currentTimeMillis();
+ if (retval == null)
+ {
+ missTimes = missTimes + (t2 - t1);
+ misses++;
+ }
+ else
+ {
+ hitTimes = hitTimes + (t2 - t1);
+ hits++;
+ }
+ return retval;
+ }
+
+ @Override
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
+ {
+ Map data = command.getMap();
+ long t1 = System.currentTimeMillis();
+ Object retval = invokeNextInterceptor(ctx, command);
+ long t2 = System.currentTimeMillis();
+
+ if (data != null && data.size() > 0)
+ {
+ storeTimes = storeTimes + (t2 - t1);
+ stores = stores + data.size();
+ }
+ return retval;
+ }
+
+ @Override
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
+ {
+ long t1 = System.currentTimeMillis();
+ Object retval = invokeNextInterceptor(ctx, command);
+ long t2 = System.currentTimeMillis();
+ storeTimes = storeTimes + (t2 - t1);
+ stores++;
+ return retval;
+ }
+
+ @ManagedAttribute(description = "number of cache attribute hits")
+ public long getHits()
+ {
+ return hits;
+ }
+
+ @ManagedAttribute(description = "number of cache attribute misses")
+ public long getMisses()
+ {
+ return misses;
+ }
+
+ @ManagedAttribute(description = "number of cache attribute put operations")
+ public long getStores()
+ {
+ return stores;
+ }
+
+ @ManagedAttribute(description = "number of cache eviction operations")
+ public long getEvictions()
+ {
+ return evictions;
+ }
+
+ @ManagedAttribute(description = "hit/miss ratio for the cache")
+ public double getHitMissRatio()
+ {
+ double total = hits + misses;
+ if (total == 0)
+ return 0;
+ return (hits / total);
+ }
+
+ @ManagedAttribute(description = "read/writes ratio for the cache")
+ public double getReadWriteRatio()
+ {
+ if (stores == 0)
+ return 0;
+ return (((double) (hits + misses) / (double) stores));
+ }
+
+ @ManagedAttribute(description = "average number of milliseconds for a read operation")
+ public long getAverageReadTime()
+ {
+ long total = hits + misses;
+ if (total == 0)
+ return 0;
+ return (hitTimes + missTimes) / total;
+ }
+
+ @ManagedAttribute(description = "average number of milliseconds for a write operation")
+ public long getAverageWriteTime()
+ {
+ if (stores == 0)
+ return 0;
+ return (storeTimes) / stores;
+ }
+
+ @ManagedAttribute(description = "number of entries in the cache")
+ public int getNumberOfEntries()
+ {
+ return dataContainer.size();
+ }
+
+ @ManagedAttribute(description = "seconds since cache started")
+ public long getElapsedTime()
+ {
+ return (System.currentTimeMillis() - start) / 1000;
+ }
+
+ @ManagedAttribute(description = "number of seconds since the cache statistics were last reset")
+ public long getTimeSinceReset()
+ {
+ return (System.currentTimeMillis() - reset) / 1000;
+ }
+
+ @ManagedOperation
+ public Map<String, Object> dumpStatistics()
+ {
+ Map<String, Object> retval = new HashMap<String, Object>();
+ retval.put("Hits", hits);
+ retval.put("Misses", misses);
+ retval.put("Stores", stores);
+ retval.put("Evictions", evictions);
+ retval.put("NumberOfEntries", dataContainer.size());
+ retval.put("ElapsedTime", getElapsedTime());
+ retval.put("TimeSinceReset", getTimeSinceReset());
+ retval.put("AverageReadTime", getAverageReadTime());
+ retval.put("AverageWriteTime", getAverageWriteTime());
+ retval.put("HitMissRatio", getHitMissRatio());
+ retval.put("ReadWriteRatio", getReadWriteRatio());
+ return retval;
+ }
+
+ @ManagedOperation
+ public void resetStatistics()
+ {
+ hits = 0;
+ misses = 0;
+ stores = 0;
+ evictions = 0;
+ hitTimes = 0;
+ missTimes = 0;
+ storeTimes = 0;
+ reset = System.currentTimeMillis();
+ }
+}
+
Property changes on: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/CacheMgmtInterceptor.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/MarshalledValueInterceptor.java (from rev 6896, core/branches/flat/src/main/java/org/jboss/cache/interceptors/MarshalledValueInterceptor.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/MarshalledValueInterceptor.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/MarshalledValueInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -0,0 +1,155 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.interceptors;
+
+import org.jboss.starobrno.commands.read.GetKeyValueCommand;
+import org.jboss.starobrno.commands.write.PutKeyValueCommand;
+import org.jboss.starobrno.commands.write.PutMapCommand;
+import org.jboss.starobrno.commands.write.RemoveCommand;
+import org.jboss.starobrno.context.InvocationContext;
+import org.jboss.starobrno.interceptors.base.CommandInterceptor;
+import org.jboss.starobrno.marshall.MarshalledValue;
+import org.jboss.starobrno.marshall.MarshalledValueHelper;
+
+import java.io.IOException;
+import java.io.NotSerializableException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Interceptor that handles the wrapping and unwrapping of cached data using {@link MarshalledValue}s.
+ * Known "excluded" types are not wrapped/unwrapped, which at this time include {@link String}, Java primitives
+ * and their Object wrappers, as well as arrays of excluded types.
+ * <p/>
+ * The {@link MarshalledValue} wrapper handles lazy deserialization from byte array representations.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @see MarshalledValue
+ * @since 2.1.0
+ */
+public class MarshalledValueInterceptor extends CommandInterceptor
+{
+ @Override
+ public Object visitPutMapCommand(InvocationContext ctx, PutMapCommand command) throws Throwable
+ {
+ Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
+
+ command.setMap(wrapMap(command.getMap(), marshalledValues, ctx));
+ Object retVal = invokeNextInterceptor(ctx, command);
+ return compactAndProcessRetVal(marshalledValues, retVal);
+ }
+
+ @Override
+ public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable
+ {
+ Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
+ if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
+ {
+ Object newKey = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
+ command.setKey(newKey);
+ }
+ if (!MarshalledValueHelper.isTypeExcluded(command.getValue().getClass()))
+ {
+ Object value = createAndAddMarshalledValue(command.getValue(), marshalledValues, ctx);
+ command.setValue(value);
+ }
+ Object retVal = invokeNextInterceptor(ctx, command);
+ return compactAndProcessRetVal(marshalledValues, retVal);
+ }
+
+ @Override
+ public Object visitRemoveCommand(InvocationContext ctx, RemoveCommand command) throws Throwable
+ {
+ Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
+ if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
+ {
+ Object value = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
+ command.setKey(value);
+ }
+ Object retVal = invokeNextInterceptor(ctx, command);
+ return compactAndProcessRetVal(marshalledValues, retVal);
+ }
+
+ @Override
+ public Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable
+ {
+ Set<MarshalledValue> marshalledValues = new HashSet<MarshalledValue>();
+ if (!MarshalledValueHelper.isTypeExcluded(command.getKey().getClass()))
+ {
+ Object value = createAndAddMarshalledValue(command.getKey(), marshalledValues, ctx);
+ command.setKey(value);
+ }
+ Object retVal = invokeNextInterceptor(ctx, command);
+ return compactAndProcessRetVal(marshalledValues, retVal);
+ }
+
+ private Object compactAndProcessRetVal(Set<MarshalledValue> marshalledValues, Object retVal)
+ throws IOException, ClassNotFoundException
+ {
+ if (trace) log.trace("Compacting MarshalledValues created");
+ for (MarshalledValue mv : marshalledValues) mv.compact(false, false);
+
+ return processRetVal(retVal);
+ }
+
+ private Object processRetVal(Object retVal)
+ throws IOException, ClassNotFoundException
+ {
+ if (retVal instanceof MarshalledValue)
+ {
+ if (trace) log.trace("Return value is a MarshalledValue. Unwrapping.");
+ retVal = ((MarshalledValue) retVal).get();
+ }
+ return retVal;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected Map wrapMap(Map<Object, Object> m, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException
+ {
+ if (m == null)
+ {
+ if (trace) log.trace("Map is nul; returning an empty map.");
+ return Collections.emptyMap();
+ }
+ if (trace) log.trace("Wrapping map contents of argument " + m);
+ Map copy = new HashMap();
+ for (Map.Entry me : m.entrySet())
+ {
+ Object key = me.getKey();
+ Object value = me.getValue();
+ copy.put((key == null || MarshalledValueHelper.isTypeExcluded(key.getClass())) ? key : createAndAddMarshalledValue(key, marshalledValues, ctx),
+ (value == null || MarshalledValueHelper.isTypeExcluded(value.getClass())) ? value : createAndAddMarshalledValue(value, marshalledValues, ctx));
+ }
+ return copy;
+ }
+
+ protected MarshalledValue createAndAddMarshalledValue(Object toWrap, Set<MarshalledValue> marshalledValues, InvocationContext ctx) throws NotSerializableException
+ {
+ MarshalledValue mv = new MarshalledValue(toWrap);
+ marshalledValues.add(mv);
+ if (!ctx.isOriginLocal()) mv.setEqualityPreferenceForInstance(false);
+ return mv;
+ }
+}
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/NotificationInterceptor.java (from rev 6896, core/branches/flat/src/main/java/org/jboss/cache/interceptors/NotificationInterceptor.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/NotificationInterceptor.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/NotificationInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -0,0 +1,71 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.interceptors;
+
+import org.jboss.starobrno.commands.tx.CommitCommand;
+import org.jboss.starobrno.commands.tx.PrepareCommand;
+import org.jboss.starobrno.commands.tx.RollbackCommand;
+import org.jboss.starobrno.context.InvocationContext;
+import org.jboss.starobrno.factories.annotations.Inject;
+import org.jboss.starobrno.notifications.Notifier;
+
+/**
+ * The interceptor in charge of firing off notifications to cache listeners
+ *
+ * @author <a href="mailto:manik@jboss.org">Manik Surtani</a>
+ * @since 2.0.0
+ */
+public class NotificationInterceptor extends BaseTransactionalContextInterceptor
+{
+ private Notifier notifier;
+
+ @Inject
+ public void injectDependencies(Notifier notifier)
+ {
+ this.notifier = notifier;
+ }
+
+ @Override
+ public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
+ {
+ Object retval = invokeNextInterceptor(ctx, command);
+ if (command.isOnePhaseCommit()) notifier.notifyTransactionCompleted(ctx.getTransaction(), true, ctx);
+
+ return retval;
+ }
+
+ @Override
+ public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
+ {
+ Object retval = invokeNextInterceptor(ctx, command);
+ notifier.notifyTransactionCompleted(ctx.getTransaction(), true, ctx);
+ return retval;
+ }
+
+ @Override
+ public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
+ {
+ Object retval = invokeNextInterceptor(ctx, command);
+ notifier.notifyTransactionCompleted(ctx.getTransaction(), false, ctx);
+ return retval;
+ }
+}
Property changes on: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/NotificationInterceptor.java
___________________________________________________________________
Name: svn:keywords
+ Author Date Id Revision
Name: svn:eol-style
+ native
Added: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/base/JmxStatsCommandInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/base/JmxStatsCommandInterceptor.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/base/JmxStatsCommandInterceptor.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -0,0 +1,87 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.interceptors.base;
+
+import org.jboss.cache.jmx.JmxStatisticsExposer;
+import org.jboss.starobrno.factories.annotations.Start;
+import org.jboss.starobrno.jmx.annotations.ManagedAttribute;
+
+import java.util.Collections;
+import java.util.Map;
+
+/**
+ * Base class for all the interceptors exposing management statistics.
+ *
+ * @author Mircea.Markus(a)jboss.com
+ * @since 3.0
+ */
+public class JmxStatsCommandInterceptor extends CommandInterceptor implements JmxStatisticsExposer
+{
+ private boolean statsEnabled = false;
+
+ @Start
+ public void checkStatisticsUsed()
+ {
+ setStatisticsEnabled(configuration.getExposeManagementStatistics());
+ }
+
+ /**
+ * Returns whether an interceptor's statistics are
+ * being captured.
+ *
+ * @return true if statistics are captured
+ */
+ @ManagedAttribute
+ public boolean getStatisticsEnabled()
+ {
+ return statsEnabled;
+ }
+
+ /**
+ * @param enabled whether gathering statistics for JMX are enabled.
+ */
+ @ManagedAttribute
+ public void setStatisticsEnabled(boolean enabled)
+ {
+ statsEnabled = enabled;
+ }
+
+ /**
+ * Returns a map of statistics. This is a default implementation which returns an empty map and should be overridden
+ * if it is to be meaningful.
+ *
+ * @return an empty map
+ */
+ public Map<String, Object> dumpStatistics()
+ {
+ return Collections.emptyMap();
+ }
+
+ /**
+ * Resets statistics gathered. Is a no-op, and should be overridden if it is to be meaningful.
+ */
+ public void resetStatistics()
+ {
+ }
+
+
+}
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValue.java (from rev 6896, core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValue.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValue.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValue.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -0,0 +1,229 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.marshall;
+
+import org.jboss.starobrno.CacheException;
+import org.jboss.util.stream.MarshalledValueInputStream;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.NotSerializableException;
+import java.io.ObjectInput;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+import java.util.Arrays;
+
+/**
+ * Wrapper that wraps cached data, providing lazy deserialization using the calling thread's context class loader.
+ * <p/>
+ * The {@link org.jboss.starobrno.interceptors.MarshalledValueInterceptor} handles transparent
+ * wrapping/unwrapping of cached data.
+ * <p/>
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @see org.jboss.starobrno.interceptors.MarshalledValueInterceptor
+ * @since 2.1.0
+ */
+public class MarshalledValue implements Externalizable
+{
+ protected Object instance;
+ protected byte[] raw;
+ private int cachedHashCode = 0;
+ // by default equals() will test on the istance rather than the byte array if conversion is required.
+ private transient boolean equalityPreferenceForInstance = true;
+
+ public MarshalledValue(Object instance) throws NotSerializableException
+ {
+ if (instance == null) throw new NullPointerException("Null values cannot be wrapped as MarshalledValues!");
+
+ if (instance instanceof Serializable)
+ this.instance = instance;
+ else
+ throw new NotSerializableException("Marshalled values can only wrap Objects that are serializable! Instance of " + instance.getClass() + " won't Serialize.");
+ }
+
+ public MarshalledValue()
+ {
+ // empty ctor for serialization
+ }
+
+ public void setEqualityPreferenceForInstance(boolean equalityPreferenceForInstance)
+ {
+ this.equalityPreferenceForInstance = equalityPreferenceForInstance;
+ }
+
+ public synchronized void serialize()
+ {
+ if (raw == null)
+ {
+ try
+ {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(instance);
+ oos.close();
+ baos.close();
+ // Do NOT set instance to null over here, since it may be used elsewhere (e.g., in a cache listener).
+ // this will be compacted by the MarshalledValueInterceptor when the call returns.
+// instance = null;
+ raw = baos.toByteArray();
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to marshall value " + instance, e);
+ }
+ }
+ }
+
+ public synchronized void deserialize()
+ {
+ if (instance == null)
+ {
+ try
+ {
+ ByteArrayInputStream bais = new ByteArrayInputStream(raw);
+ // use a MarshalledValueInputStream since it needs to be aware of any context class loaders on the current thread.
+ ObjectInputStream ois = new MarshalledValueInputStream(bais);
+ instance = ois.readObject();
+ ois.close();
+ bais.close();
+// raw = null;
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to unmarshall value", e);
+ }
+ }
+ }
+
+ /**
+ * Compacts the references held by this class to a single reference. If only one representation exists this method
+ * is a no-op unless the 'force' parameter is used, in which case the reference held is forcefully switched to the
+ * 'preferred representation'.
+ * <p/>
+ * Either way, a call to compact() will ensure that only one representation is held.
+ * <p/>
+ *
+ * @param preferSerializedRepresentation if true and both representations exist, the serialized representation is favoured. If false, the deserialized representation is preferred.
+ * @param force ensures the preferred representation is maintained and the other released, even if this means serializing or deserializing.
+ */
+ public void compact(boolean preferSerializedRepresentation, boolean force)
+ {
+ // reset the equalityPreference
+ equalityPreferenceForInstance = true;
+ if (force)
+ {
+ if (preferSerializedRepresentation && raw == null) serialize();
+ else if (!preferSerializedRepresentation && instance == null) deserialize();
+ }
+
+ if (instance != null && raw != null)
+ {
+ // need to lose one representation!
+
+ if (preferSerializedRepresentation)
+ {
+ instance = null;
+ }
+ else
+ {
+ raw = null;
+ }
+ }
+ }
+
+ public void writeExternal(ObjectOutput out) throws IOException
+ {
+ if (raw == null) serialize();
+ out.writeInt(raw.length);
+ out.write(raw);
+ out.writeInt(hashCode());
+ }
+
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+ {
+ int size = in.readInt();
+ raw = new byte[size];
+ cachedHashCode = 0;
+ in.readFully(raw);
+ cachedHashCode = in.readInt();
+ }
+
+ public Object get() throws IOException, ClassNotFoundException
+ {
+ if (instance == null) deserialize();
+ return instance;
+ }
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ MarshalledValue that = (MarshalledValue) o;
+
+ // if both versions are serialized or deserialized, just compare the relevant representations.
+ if (raw != null && that.raw != null) return Arrays.equals(raw, that.raw);
+ if (instance != null && that.instance != null) return instance.equals(that.instance);
+
+ // if conversion of one representation to the other is necessary, then see which we prefer converting.
+ if (equalityPreferenceForInstance)
+ {
+ if (instance == null) deserialize();
+ if (that.instance == null) that.deserialize();
+ return instance.equals(that.instance);
+ }
+ else
+ {
+ if (raw == null) serialize();
+ if (that.raw == null) that.serialize();
+ return Arrays.equals(raw, that.raw);
+ }
+ }
+
+ @Override
+ public int hashCode()
+ {
+ if (cachedHashCode == 0)
+ {
+ // always calculate the hashcode based on the instance since this is where we're getting the equals()
+ if (instance == null) deserialize();
+ cachedHashCode = instance.hashCode();
+ if (cachedHashCode == 0) // degenerate case
+ {
+ cachedHashCode = 0xFEED;
+ }
+ }
+ return cachedHashCode;
+ }
+
+ @Override
+ public String toString()
+ {
+ return "MarshalledValue(cachedHashCode=" + cachedHashCode + "; serialized=" + (raw != null) + ")";
+ }
+}
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueHelper.java (from rev 6896, core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueHelper.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueHelper.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueHelper.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -0,0 +1,54 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.marshall;
+
+import org.jboss.starobrno.commands.ReplicableCommand;
+import org.jboss.starobrno.transaction.GlobalTransaction;
+import org.jgroups.Address;
+
+/**
+ * Common functionality used by the {@link org.jboss.starobrno.interceptors.MarshalledValueInterceptor} and the {@link MarshalledValueMap}.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @see MarshalledValue
+ * @see org.jboss.starobrno.interceptors.MarshalledValueInterceptor
+ * @see MarshalledValueMap
+ * @since 2.1.0
+ */
+public class MarshalledValueHelper
+{
+ /**
+ * Tests whether the type should be excluded from MarshalledValue wrapping.
+ *
+ * @param type type to test. Should not be null.
+ * @return true if it should be excluded from MarshalledValue wrapping.
+ */
+ public static boolean isTypeExcluded(Class type)
+ {
+ return type.equals(String.class) || type.isPrimitive() ||
+ type.equals(Void.class) || type.equals(Boolean.class) || type.equals(Character.class) ||
+ type.equals(Byte.class) || type.equals(Short.class) || type.equals(Integer.class) ||
+ type.equals(Long.class) || type.equals(Float.class) || type.equals(Double.class) ||
+ (type.isArray() && isTypeExcluded(type.getComponentType())) || type.equals(GlobalTransaction.class) || type.equals(Address.class) ||
+ ReplicableCommand.class.isAssignableFrom(type) || type.equals(MarshalledValue.class);
+ }
+}
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueMap.java (from rev 6896, core/branches/flat/src/main/java/org/jboss/cache/marshall/MarshalledValueMap.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueMap.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/marshall/MarshalledValueMap.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -0,0 +1,181 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.marshall;
+
+import net.jcip.annotations.Immutable;
+import org.jboss.starobrno.CacheException;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * A Map that is able to wrap/unwrap MarshalledValues in keys or values. Note that calling keySet(), entrySet() or values()
+ * could be expensive if this map is large!!
+ * <p/>
+ * Also note that this is an immutable Map.
+ * <p/>
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @see MarshalledValue
+ * @since 2.1.0
+ */
+@Immutable
+public class MarshalledValueMap implements Map, Externalizable
+{
+ Map delegate;
+ Map<Object, Object> unmarshalled;
+
+ public MarshalledValueMap()
+ {
+ // for externalization
+ }
+
+ public MarshalledValueMap(Map delegate)
+ {
+ this.delegate = delegate;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected synchronized Map getUnmarshalledMap()
+ {
+ if (unmarshalled == null) unmarshalled = unmarshalledMap(delegate.entrySet());
+ return unmarshalled;
+ }
+
+ public int size()
+ {
+ return delegate.size();
+ }
+
+ public boolean isEmpty()
+ {
+ return delegate.isEmpty();
+ }
+
+ public boolean containsKey(Object key)
+ {
+ return getUnmarshalledMap().containsKey(key);
+ }
+
+ public boolean containsValue(Object value)
+ {
+ return getUnmarshalledMap().containsValue(value);
+ }
+
+ public Object get(Object key)
+ {
+ return getUnmarshalledMap().get(key);
+ }
+
+ public Object put(Object key, Object value)
+ {
+ throw new UnsupportedOperationException("This is an immutable map!");
+ }
+
+ public Object remove(Object key)
+ {
+ throw new UnsupportedOperationException("This is an immutable map!");
+ }
+
+ public void putAll(Map t)
+ {
+ throw new UnsupportedOperationException("This is an immutable map!");
+ }
+
+ public void clear()
+ {
+ throw new UnsupportedOperationException("This is an immutable map!");
+ }
+
+ public Set keySet()
+ {
+ return getUnmarshalledMap().keySet();
+ }
+
+ public Collection values()
+ {
+ return getUnmarshalledMap().values();
+ }
+
+ public Set entrySet()
+ {
+ return getUnmarshalledMap().entrySet();
+ }
+
+ @SuppressWarnings("unchecked")
+ protected Map unmarshalledMap(Set entries)
+ {
+ if (entries == null || entries.isEmpty()) return Collections.emptyMap();
+ Map map = new HashMap(entries.size());
+ for (Object e : entries)
+ {
+ Map.Entry entry = (Map.Entry) e;
+ map.put(getUnmarshalledValue(entry.getKey()), getUnmarshalledValue(entry.getValue()));
+ }
+ return map;
+ }
+
+ private Object getUnmarshalledValue(Object o)
+ {
+ try
+ {
+ return o instanceof MarshalledValue ? ((MarshalledValue) o).get() : o;
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to unmarshall value", e);
+ }
+ }
+
+ @Override
+ public boolean equals(Object other)
+ {
+ if (other instanceof Map)
+ {
+ return getUnmarshalledMap().equals(other);
+ }
+ return false;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return getUnmarshalledMap().hashCode();
+ }
+
+ public void writeExternal(ObjectOutput out) throws IOException
+ {
+ out.writeObject(delegate);
+ }
+
+ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException
+ {
+ delegate = (Map) in.readObject();
+ }
+}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java 2008-10-09 13:22:09 UTC (rev 6897)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java 2008-10-09 13:45:15 UTC (rev 6898)
@@ -25,7 +25,6 @@
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.buddyreplication.BuddyGroup;
-import org.jboss.cache.marshall.MarshalledValueMap;
import org.jboss.cache.notifications.IncorrectCacheListenerException;
import org.jboss.cache.notifications.annotation.*;
import org.jboss.cache.notifications.event.*;
@@ -43,6 +42,7 @@
import org.jboss.starobrno.factories.annotations.NonVolatile;
import org.jboss.starobrno.factories.annotations.Start;
import org.jboss.starobrno.factories.annotations.Stop;
+import org.jboss.starobrno.marshall.MarshalledValueMap;
import org.jboss.starobrno.notifications.event.NodeModifiedEvent;
import org.jgroups.View;
17 years, 2 months
JBoss Cache SVN: r6897 - in core/branches/flat/src: main/java/org/jboss/starobrno/commands/read and 9 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-09 09:22:09 -0400 (Thu, 09 Oct 2008)
New Revision: 6897
Added:
core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntry.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/NullMarkerEntry.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java
core/branches/flat/src/test/java/org/jboss/starobrno/profiling/
core/branches/flat/src/test/java/org/jboss/starobrno/profiling/MemConsumptionTest.java
core/branches/flat/src/test/java/org/jboss/starobrno/util/
core/branches/flat/src/test/java/org/jboss/starobrno/util/TestingUtil.java
Removed:
core/branches/flat/src/main/java/org/jboss/starobrno/DataContainer.java
core/branches/flat/src/main/java/org/jboss/starobrno/RPCManager.java
core/branches/flat/src/main/java/org/jboss/starobrno/ReplicationException.java
core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/UnsortedDataContainer.java
core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/
Modified:
core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
core/branches/flat/src/main/java/org/jboss/starobrno/CacheSPI.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ClearCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/DataContainer.java
core/branches/flat/src/main/java/org/jboss/starobrno/container/UnsortedDataContainer.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java
core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactory.java
core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactoryImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java
core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java
Log:
Working mem tests
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -24,10 +24,10 @@
import org.jboss.cache.CacheStatus;
import org.jboss.cache.buddyreplication.BuddyManager;
import org.jboss.cache.buddyreplication.GravitateResult;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.marshall.Marshaller;
import org.jboss.cache.statetransfer.StateTransferManager;
+import org.jboss.starobrno.batch.BatchContainer;
import org.jboss.starobrno.commands.CommandsFactory;
import org.jboss.starobrno.commands.read.GetKeyValueCommand;
import org.jboss.starobrno.commands.read.SizeCommand;
@@ -44,11 +44,12 @@
import org.jboss.starobrno.factories.annotations.Inject;
import org.jboss.starobrno.factories.annotations.NonVolatile;
import org.jboss.starobrno.interceptors.InterceptorChain;
+import org.jboss.starobrno.interceptors.base.CommandInterceptor;
import org.jboss.starobrno.invocation.InvocationContextContainer;
import org.jboss.starobrno.notifications.Notifier;
+import org.jboss.starobrno.remoting.RPCManager;
import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jboss.starobrno.transaction.TransactionTable;
-import org.jboss.starobrno.batch.BatchContainer;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
@@ -295,7 +296,7 @@
return null; //TODO: Autogenerated. Implement me properly
}
- public Object getRPCManager()
+ public RPCManager getRPCManager()
{
return null; //TODO: Autogenerated. Implement me properly
}
@@ -305,7 +306,7 @@
return null; //TODO: Autogenerated. Implement me properly
}
- public org.jboss.cache.notifications.Notifier getNotifier()
+ public Notifier getNotifier()
{
return null; //TODO: Autogenerated. Implement me properly
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/CacheSPI.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/CacheSPI.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/CacheSPI.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -24,14 +24,14 @@
import net.jcip.annotations.ThreadSafe;
import org.jboss.cache.buddyreplication.BuddyManager;
import org.jboss.cache.buddyreplication.GravitateResult;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
-import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.loader.CacheLoaderManager;
import org.jboss.cache.marshall.Marshaller;
-import org.jboss.cache.notifications.Notifier;
import org.jboss.cache.statetransfer.StateTransferManager;
import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.ComponentRegistry;
+import org.jboss.starobrno.interceptors.base.CommandInterceptor;
+import org.jboss.starobrno.notifications.Notifier;
+import org.jboss.starobrno.remoting.RPCManager;
import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jboss.starobrno.transaction.TransactionTable;
@@ -168,7 +168,7 @@
*
* @return the {@link org.jboss.cache.RPCManager} configured.
*/
- Object getRPCManager();
+ RPCManager getRPCManager();
/**
* Retrieves the current StateTransferManager instance associated with the current Cache instance.
Deleted: core/branches/flat/src/main/java/org/jboss/starobrno/DataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/DataContainer.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/DataContainer.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -1,48 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno;
-
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * // TODO: MANIK: Document this
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @since 3.0
- */
-public interface DataContainer<K, V>
-{
- Set<Entry<K, V>> getEntries();
-
- Entry<K, V> getEntry(K k);
-
- void putEntry(Entry<K, V> entry);
-
- boolean exists(Entry<K, V> entry);
-
- int size();
-
- void clear();
-
- void removeEntry(K key);
-}
Deleted: core/branches/flat/src/main/java/org/jboss/starobrno/RPCManager.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/RPCManager.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/RPCManager.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -1,154 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno;
-
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.Fqn;
-import org.jgroups.Address;
-import org.jgroups.Channel;
-import org.jgroups.blocks.RspFilter;
-
-import java.util.List;
-import java.util.Vector;
-
-/**
- * Provides a mechanism for communicating with other caches in the cluster. For now this is based on JGroups as an underlying
- * transport, and in future more transport options may become available.
- * <p/>
- * Implementations have a simple lifecycle:
- * <ul>
- * <li>start() - starts the underlying channel based on configuration options injected, and connects the channel</li>
- * <li>disconnect() - disconnects the channel</li>
- * <li>stop() - stops the dispatcher and releases resources</li>
- * </ul>
- *
- * @author Manik Surtani
- * @since 2.1.0
- */
-public interface RPCManager
-{
- /**
- * Disconnects and closes the underlying JGroups channel.
- */
- void disconnect();
-
- /**
- * Stops the RPCDispatcher and frees resources. Closes and disconnects the underlying JGroups channel if this is
- * still open/connected.
- */
- void stop();
-
- /**
- * Starts the RPCManager by connecting the underlying JGroups channel (if configured for replication). Connecting
- * the channel may also involve state transfer (if configured) so the interceptor chain should be started and
- * available before this method is called.
- */
- void start();
-
- /**
- * Invokes an RPC call on other caches in the cluster.
- *
- * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the entire cluster.
- * @param cacheCommand the cache command to invoke
- * @param mode the group request mode to use. See {@link org.jgroups.blocks.GroupRequest}.
- * @param timeout a timeout after which to throw a replication exception.
- * @param responseFilter a response filter with which to filter out failed/unwanted/invalid responses.
- * @param useOutOfBandMessage if true, the message is put on JGroups' OOB queue. See JGroups docs for more info.
- * @return a list of responses from each member contacted.
- * @throws Exception in the event of problems.
- */
- List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand cacheCommand, int mode, long timeout, RspFilter responseFilter, boolean useOutOfBandMessage) throws Exception;
-
- /**
- * Invokes an RPC call on other caches in the cluster.
- *
- * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the entire cluster.
- * @param cacheCommand the cache command to invoke
- * @param mode the group request mode to use. See {@link org.jgroups.blocks.GroupRequest}.
- * @param timeout a timeout after which to throw a replication exception.
- * @param useOutOfBandMessage if true, the message is put on JGroups' OOB queue. See JGroups docs for more info.
- * @return a list of responses from each member contacted.
- * @throws Exception in the event of problems.
- */
- List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand cacheCommand, int mode, long timeout, boolean useOutOfBandMessage) throws Exception;
-
- /**
- * Invokes an RPC call on other caches in the cluster.
- *
- * @param recipients a list of Addresses to invoke the call on. If this is null, the call is broadcast to the entire cluster.
- * @param cacheCommand the cache command to invoke
- * @param synchronous if true, sets group request mode to {@link org.jgroups.blocks.GroupRequest#GET_ALL}, and if false sets it to {@link org.jgroups.blocks.GroupRequest#GET_NONE}.
- * @param timeout a timeout after which to throw a replication exception.
- * @param useOutOfBandMessage if true, the message is put on JGroups' OOB queue. See JGroups docs for more info.
- * @return a list of responses from each member contacted.
- * @throws Exception in the event of problems.
- */
- List<Object> callRemoteMethods(Vector<Address> recipients, ReplicableCommand cacheCommand, boolean synchronous, long timeout, boolean useOutOfBandMessage) throws Exception;
-
- /**
- * @return true if the current Channel is the coordinator of the cluster.
- */
- boolean isCoordinator();
-
- /**
- * @return the Address of the current coordinator.
- */
- Address getCoordinator();
-
- /**
- * Retrieves the local JGroups channel's address
- *
- * @return an Address
- */
- Address getLocalAddress();
-
- /**
- * Returns a defensively copied list of members in the current cluster view.
- */
- List<Address> getMembers();
-
- /**
- * Retrieves partial state from remote instances.
- *
- * @param sources sources to consider for a state transfer
- * @param sourceTarget Fqn on source to retrieve state for
- * @param integrationTarget integration point on local cache to apply state
- * @throws Exception in the event of problems
- */
- void fetchPartialState(List<Address> sources, Fqn sourceTarget, Fqn integrationTarget) throws Exception;
-
- /**
- * Retrieves partial state from remote instances.
- *
- * @param sources sources to consider for a state transfer
- * @param subtree Fqn subtree to retrieve. Will be integrated at the same point.
- * @throws Exception in the event of problems
- */
- void fetchPartialState(List<Address> sources, Fqn subtree) throws Exception;
-
- /**
- * Retrieves the Channel
- *
- * @return a channel
- */
- Channel getChannel();
-}
\ No newline at end of file
Deleted: core/branches/flat/src/main/java/org/jboss/starobrno/ReplicationException.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/ReplicationException.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/ReplicationException.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -1,57 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno;
-
-/**
- * Thrown when a replication problem occurred
- */
-public class ReplicationException extends CacheException
-{
-
- private static final long serialVersionUID = 33172388691879866L;
-
- public ReplicationException()
- {
- super();
- }
-
- public ReplicationException(Throwable cause)
- {
- super(cause);
- }
-
- public ReplicationException(String msg)
- {
- super(msg);
- }
-
- public ReplicationException(String msg, Throwable cause)
- {
- super(msg, cause);
- }
-
- @Override
- public String toString()
- {
- return super.toString();
- }
-}
\ No newline at end of file
Deleted: core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -1,1041 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno;
-
-import org.jboss.cache.util.concurrent.ConcurrentHashSet;
-import org.jboss.starobrno.commands.CommandsFactory;
-import org.jboss.starobrno.commands.ReplicableCommand;
-import org.jboss.starobrno.commands.VisitableCommand;
-import org.jboss.starobrno.commands.tx.CommitCommand;
-import org.jboss.starobrno.commands.tx.PrepareCommand;
-import org.jboss.starobrno.commands.tx.RollbackCommand;
-import org.jboss.starobrno.config.Option;
-import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.context.TransactionContext;
-import org.jboss.starobrno.factories.ComponentRegistry;
-import org.jboss.starobrno.factories.annotations.Inject;
-import org.jboss.starobrno.factories.context.ContextFactory;
-import org.jboss.starobrno.interceptors.BaseTransactionalContextInterceptor;
-import org.jboss.starobrno.invocation.InvocationContextContainer;
-import org.jboss.starobrno.jmx.annotations.ManagedAttribute;
-import org.jboss.starobrno.jmx.annotations.ManagedOperation;
-import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.notifications.Notifier;
-import org.jboss.starobrno.transaction.GlobalTransaction;
-import org.jboss.starobrno.transaction.OrderedSynchronizationHandler;
-import org.jboss.starobrno.transaction.TransactionTable;
-
-import javax.transaction.*;
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * This interceptor is the new default at the head of all interceptor chains,
- * and makes transactional attributes available to all interceptors in the chain.
- * This interceptor is also responsible for registering for synchronisation on
- * transaction completion.
- *
- * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik(a)jboss.org)</a>
- * @author <a href="mailto:stevew@jofti.com">Steve Woodcock (stevew(a)jofti.com)</a>
- */
-public class TxInterceptor extends BaseTransactionalContextInterceptor
-{
- protected CommandsFactory commandsFactory;
- protected RPCManager rpcManager;
- private Notifier notifier;
- private InvocationContextContainer invocationContextContainer;
- private ComponentRegistry componentRegistry;
- private ContextFactory contextFactory;
-
- /**
- * List <Transaction>that we have registered for
- */
- private final Set<Transaction> transactions = new ConcurrentHashSet<Transaction>();
- private final Map<Transaction, GlobalTransaction> rollbackTransactions = new ConcurrentHashMap<Transaction, GlobalTransaction>(16);
- private long prepares = 0;
- private long commits = 0;
- private long rollbacks = 0;
- protected boolean optimistic = false;
- private LockManager lockManager;
- private boolean statsEnabled;
-
- @Inject
- public void intialize(RPCManager rpcManager, ContextFactory contextFactory,
- Notifier notifier, InvocationContextContainer icc,
- CommandsFactory factory, ComponentRegistry componentRegistry, LockManager lockManager)
- {
- this.contextFactory = contextFactory;
- this.commandsFactory = factory;
- this.rpcManager = rpcManager;
- this.notifier = notifier;
- this.invocationContextContainer = icc;
- this.componentRegistry = componentRegistry;
- this.lockManager = lockManager;
- setStatisticsEnabled(configuration.isExposeManagementStatistics());
- }
-
- @Override
- public Object visitPrepareCommand(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- Object result = null;
-
- // this is a prepare, commit, or rollback.
- if (log.isDebugEnabled()) log.debug("Got gtx from invocation context " + ctx.getGlobalTransaction());
- try
- {
- if (ctx.getGlobalTransaction().isRemote())
- {
- result = handleRemotePrepare(ctx, command);
- if (getStatisticsEnabled()) prepares++;
- }
- else
- {
- if (trace) log.trace("received my own message (discarding it)");
- result = null;
- }
- }
- catch (Throwable e)
- {
- ctx.throwIfNeeded(e);
- }
-
- return result;
- }
-
- @Override
- public Object visitCommitCommand(InvocationContext ctx, CommitCommand command) throws Throwable
- {
- if (!ctx.getGlobalTransaction().isRemote())
- {
- if (trace) log.trace("received my own message (discarding it)");
- return null;
- }
- try
- {
- if (trace) log.trace("(" + rpcManager.getLocalAddress() + ") call on command [" + command + "]");
- GlobalTransaction gtx = ctx.getGlobalTransaction();
- Transaction ltx = txTable.getLocalTransaction(gtx, true);
- // disconnect if we have a current tx associated
- Transaction currentTx = txManager.getTransaction();
- boolean resumeCurrentTxOnCompletion = false;
- try
- {
- if (!ltx.equals(currentTx))
- {
- currentTx = txManager.suspend();
- resumeCurrentTxOnCompletion = true;
- txManager.resume(ltx);
- // make sure we set this in the ctx
- ctx.setTransaction(ltx);
- }
- if (log.isDebugEnabled()) log.debug(" executing commit() with local TX " + ltx + " under global tx " + gtx);
- txManager.commit();
- if (getStatisticsEnabled()) commits++;
- }
- finally
- {
- //resume the old transaction if we suspended it
- if (resumeCurrentTxOnCompletion)
- {
- resumeTransactionOnCompletion(ctx, currentTx);
- }
- // remove from local lists.
- transactions.remove(ltx);
- // this tx has completed. Clean up in the tx table.
- txTable.remove(gtx, ltx);
- }
- if (log.isDebugEnabled()) log.debug("Finished remote rollback method for " + gtx);
- }
- catch (Throwable throwable)
- {
- ctx.throwIfNeeded(throwable);
- }
- return null;
- }
-
- @Override
- public Object visitRollbackCommand(InvocationContext ctx, RollbackCommand command) throws Throwable
- {
- if (!ctx.getGlobalTransaction().isRemote())
- {
- if (trace) log.trace("received my own message (discarding it)");
- return null;
- }
- try
- {
- if (trace) log.trace("(" + rpcManager.getLocalAddress() + ") call on command [" + command + "]");
- GlobalTransaction gtx = ctx.getGlobalTransaction();
- Transaction ltx = txTable.getLocalTransaction(gtx);
- if (ltx == null)
- {
- log.warn("No local transaction for this remotely originating rollback. Possibly rolling back before a prepare call was broadcast?");
- txTable.remove(gtx);
- return null;
- }
- // disconnect if we have a current tx associated
- Transaction currentTx = txManager.getTransaction();
- boolean resumeCurrentTxOnCompletion = false;
- try
- {
- if (!ltx.equals(currentTx))
- {
- currentTx = txManager.suspend();
- resumeCurrentTxOnCompletion = true;
- txManager.resume(ltx);
- // make sure we set this in the ctx
- ctx.setTransaction(ltx);
- }
- if (log.isDebugEnabled()) log.debug("executing with local TX " + ltx + " under global tx " + gtx);
- txManager.rollback();
- if (getStatisticsEnabled()) rollbacks++;
- }
- finally
- {
- //resume the old transaction if we suspended it
- if (resumeCurrentTxOnCompletion)
- {
- resumeTransactionOnCompletion(ctx, currentTx);
- }
-
- // remove from local lists.
- transactions.remove(ltx);
-
- // this tx has completed. Clean up in the tx table.
- txTable.remove(gtx, ltx);
- }
- if (log.isDebugEnabled()) log.debug("Finished remote commit/rollback method for " + gtx);
- }
- catch (Throwable throwable)
- {
- ctx.throwIfNeeded(throwable);
- }
-
- return null;
- }
-
- @Override
- public Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- try
- {
- return attachGtxAndPassUpChain(ctx, command);
- }
- catch (Throwable throwable)
- {
- ctx.throwIfNeeded(throwable);
- return null;
- }
- }
-
- protected Object attachGtxAndPassUpChain(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- Transaction tx = ctx.getTransaction();
- if (tx != null) attachGlobalTransaction(ctx, tx, command);
- return invokeNextInterceptor(ctx, command);
- }
-
- // ------------------------------------------------------------------------
- // JMX statistics
- // ------------------------------------------------------------------------
-
- // --------------------------------------------------------------
-
- /**
- * Handles a remotely originating prepare call, by creating a local transaction for the remote global transaction
- * and replaying modifications in this new local transaction.
- *
- * @param ctx invocation context
- * @param command prepare command
- * @return result of the prepare, typically a null.
- * @throws Throwable in the event of problems.
- */
- private Object handleRemotePrepare(InvocationContext ctx, PrepareCommand command) throws Throwable
- {
- // the InvocationContextInterceptor would have set this for us
- GlobalTransaction gtx = ctx.getGlobalTransaction();
-
- // Is there a local transaction associated with GTX? (not the current tx associated with the thread, which may be
- // in the invocation context
- Transaction ltx = txTable.getLocalTransaction(gtx);
- Transaction currentTx = txManager.getTransaction();
-
- Object retval = null;
- boolean success = false;
- try
- {
- if (ltx == null)
- {
- if (currentTx != null) txManager.suspend();
- // create a new local transaction
- ltx = createLocalTx();
- // associate this with a global tx
- txTable.put(ltx, gtx);
- if (trace) log.trace("Created new tx for gtx " + gtx);
-
- if (log.isDebugEnabled())
- log.debug("Started new local tx as result of remote prepare: local tx=" + ltx + " (status=" + ltx.getStatus() + "), gtx=" + gtx);
- }
- else
- {
- //this should be valid
- if (!TransactionTable.isValid(ltx))
- throw new CacheException("Transaction " + ltx + " not in correct state to be prepared");
-
- //associate this thread with the local transaction associated with the global transaction, IF the localTx is NOT the current tx.
- if (currentTx == null || !ltx.equals(currentTx))
- {
- if (trace) log.trace("Suspending current tx " + currentTx);
- txManager.suspend();
- txManager.resume(ltx);
- }
- }
- if (trace) log.trace("Resuming existing tx " + ltx + ", global tx=" + gtx);
-
- // at this point we have a non-null ltx
-
- // Asssociate the local TX with the global TX. Create new
- // transactionContext for TX in txTable, the modifications
- // below will need this transactionContext to add their modifications
- // under the GlobalTx key
- TransactionContext transactionContext = txTable.get(gtx);
- if (transactionContext == null)
- {
- // create a new transaction transactionContext
- if (log.isDebugEnabled()) log.debug("creating new tx transactionContext");
- transactionContext = contextFactory.createTransactionContext(ltx);
- txTable.put(gtx, transactionContext);
- }
-
- setTransactionalContext(ltx, gtx, transactionContext, ctx);
-
- // register a sync handler for this tx.
- registerHandler(ltx, new RemoteSynchronizationHandler(gtx, ltx, transactionContext), ctx);
-
- success = false;
-
- // replay modifications
- replayModifications(ctx, ltx, command);
-
- success = true; // no exceptions were thrown above!!
-
- // now pass the prepare command up the chain as well.
- if (command.isOnePhaseCommit())
- {
- if (trace)
- log.trace("Using one-phase prepare. Not propagating the prepare call up the stack until called to do so by the sync handler.");
- }
- else
- {
- // now pass up the prepare method itself.
- invokeNextInterceptor(ctx, command);
- }
- // JBCACHE-361 Confirm that the transaction is ACTIVE
- assertTxIsStillValid(ltx);
- }
- finally
- {
- // if we are running a one-phase commit, perform a commit or rollback now.
- if (trace) log.trace("Are we running a 1-phase commit? " + command.isOnePhaseCommit());
-
- if (command.isOnePhaseCommit())
- {
- try
- {
- if (success)
- {
- ltx.commit();
- }
- else
- {
- ltx.rollback();
- }
- }
- catch (Throwable t)
- {
- log.error("Commit/rollback failed.", t);
- if (success)
- {
- // try another rollback...
- try
- {
- log.info("Attempting anotehr rollback");
- //invokeOnePhaseCommitMethod(globalTransaction, modifications.size() > 0, false);
- ltx.rollback();
- }
- catch (Throwable t2)
- {
- log.error("Unable to rollback", t2);
- }
- }
- }
- finally
- {
- transactions.remove(ltx);// JBAS-298
- }
- }
-
- txManager.suspend();// suspends ltx - could be null
- // resume whatever else we had going.
- if (currentTx != null) txManager.resume(currentTx);
- if (log.isDebugEnabled()) log.debug("Finished remote prepare " + gtx);
- }
-
- return retval;
- }
-
- private ReplicableCommand attachGlobalTransaction(InvocationContext ctx, Transaction tx, VisitableCommand command) throws Throwable
- {
- if (trace)
- {
- log.trace(" local transaction exists - registering global tx if not present for " + Thread.currentThread());
- }
- if (trace)
- {
- GlobalTransaction tempGtx = txTable.get(tx);
- log.trace("Associated gtx in txTable is " + tempGtx);
- }
-
- // register a sync handler for this tx - only if the globalTransaction is not remotely initiated.
- GlobalTransaction gtx = registerTransaction(tx, ctx);
- if (gtx == null)
- {
- // get the current globalTransaction from the txTable.
- gtx = txTable.get(tx);
- }
-
- // make sure we attach this globalTransaction to the invocation context.
- ctx.setGlobalTransaction(gtx);
-
- return command;
- }
-
- /**
- * Replays modifications
- */
- protected void replayModifications(InvocationContext ctx, Transaction ltx, PrepareCommand command) throws Throwable
- {
- try
- {
- // replay modifications
- for (VisitableCommand modification : command.getModifications())
- {
- invokeNextInterceptor(ctx, modification);
- assertTxIsStillValid(ltx);
- }
- }
- catch (Throwable th)
- {
- log.error("prepare failed!", th);
- throw th;
- }
- }
-
- private void resumeTransactionOnCompletion(InvocationContext ctx, Transaction currentTx)
- throws SystemException, InvalidTransactionException
- {
- if (trace) log.trace("Resuming suspended transaction " + currentTx);
- txManager.suspend();
- if (currentTx != null)
- {
- txManager.resume(currentTx);
- ctx.setTransaction(currentTx);
- }
- }
-
- /**
- * Handles a commit or a rollback. Called by the synch handler. Simply tests that we are in the correct tx and
- * passes the meth call up the interceptor chain.
- *
- * @throws Throwable
- */
- @SuppressWarnings("deprecation")
- private Object handleCommitRollback(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- GlobalTransaction gtx = ctx.getGlobalTransaction();
- Object result;
- VisitableCommand originalCommand = ctx.getCommand();
- ctx.setCommand(command);
- try
- {
- result = invokeNextInterceptor(ctx, command);
- }
- finally
- {
- ctx.setCommand(originalCommand);
- }
- if (log.isDebugEnabled()) log.debug("Finished local commit/rollback method for " + gtx);
- return result;
- }
-
- // --------------------------------------------------------------
- // Transaction phase runners
- // --------------------------------------------------------------
-
- protected PrepareCommand buildPrepareCommand(GlobalTransaction gtx, List modifications, boolean onePhaseCommit)
- {
- return commandsFactory.buildPrepareCommand(gtx, modifications, rpcManager.getLocalAddress(), onePhaseCommit);
- }
-
- /**
- * creates a commit()
- */
- protected void runCommitPhase(InvocationContext ctx, GlobalTransaction gtx, List modifications, boolean onePhaseCommit)
- {
- try
- {
- VisitableCommand commitCommand = onePhaseCommit ? buildPrepareCommand(gtx, modifications, true) : commandsFactory.buildCommitCommand(gtx);
-
- if (trace) log.trace("Running commit for " + gtx);
-
- handleCommitRollback(ctx, commitCommand);
- }
- catch (Throwable e)
- {
- log.warn("Commit failed. Clearing stale locks.");
- try
- {
- cleanupStaleLocks(ctx);
- }
- catch (RuntimeException re)
- {
- log.error("Unable to clear stale locks", re);
- throw re;
- }
- catch (Throwable e2)
- {
- log.error("Unable to clear stale locks", e2);
- throw new RuntimeException(e2);
- }
- if (e instanceof RuntimeException)
- throw (RuntimeException) e;
- else
- throw new RuntimeException("Commit failed.", e);
- }
- }
-
- protected void cleanupStaleLocks(InvocationContext ctx) throws Throwable
- {
- TransactionContext transactionContext = ctx.getTransactionContext();
- if (transactionContext != null) lockManager.unlock(ctx);
- }
-
- /**
- * creates a rollback()
- */
- protected void runRollbackPhase(InvocationContext ctx, GlobalTransaction gtx, Transaction tx)
- {
- try
- {
- // JBCACHE-457
- VisitableCommand rollbackCommand = commandsFactory.buildRollbackCommand(gtx);
- if (trace) log.trace(" running rollback for " + gtx);
-
- //JBCACHE-359 Store a lookup for the globalTransaction so a listener
- // callback can find it
- rollbackTransactions.put(tx, gtx);
-
- handleCommitRollback(ctx, rollbackCommand);
- }
- catch (Throwable e)
- {
- log.warn("Rollback had a problem", e);
- }
- finally
- {
- rollbackTransactions.remove(tx);
- }
- }
-
- private boolean isOnePhaseCommit()
- {
- if (!configuration.getCacheMode().isSynchronous())
- {
- // this is a REPL_ASYNC call - do 1-phase commit. break!
- if (trace) log.trace("This is a REPL_ASYNC call (1 phase commit) - do nothing for beforeCompletion()");
- return true;
- }
- return false;
- }
-
- /**
- * Handles a local prepare - invoked by the sync handler. Tests if the current tx matches the gtx passed in to the
- * method call and passes the prepare() call up the chain.
- */
- @SuppressWarnings("deprecation")
- public Object runPreparePhase(InvocationContext ctx, GlobalTransaction gtx, List<VisitableCommand> modifications) throws Throwable
- {
- // running a 2-phase commit.
- VisitableCommand prepareCommand = buildPrepareCommand(gtx, modifications, false);
-
- Object result;
-
- // Is there a local transaction associated with GTX ?
- Transaction ltx = ctx.getTransaction();
-
- //if ltx is not null and it is already running
- Transaction currentTransaction = txManager.getTransaction();
- if (currentTransaction != null && ltx != null && currentTransaction.equals(ltx))
- {
- VisitableCommand originalCommand = ctx.getCommand();
- ctx.setCommand(prepareCommand);
- try
- {
- result = invokeNextInterceptor(ctx, prepareCommand);
- }
- finally
- {
- ctx.setCommand(originalCommand);
- }
- }
- else
- {
- log.warn("Local transaction does not exist or does not match expected transaction " + gtx);
- throw new CacheException(" local transaction " + ltx + " does not exist or does not match expected transaction " + gtx);
- }
- return result;
- }
-
- // --------------------------------------------------------------
- // Private helper methods
- // --------------------------------------------------------------
-
- protected void assertTxIsStillValid(Transaction tx)
- {
- if (!TransactionTable.isActive(tx))
- {
- try
- {
- throw new ReplicationException("prepare() failed -- local transaction status is not STATUS_ACTIVE; is " + tx.getStatus());
- }
- catch (SystemException e)
- {
- throw new ReplicationException("prepare() failed -- local transaction status is not STATUS_ACTIVE; Unable to retrieve transaction status.");
- }
- }
- }
-
- /**
- * Creates a gtx (if one doesnt exist), a sync handler, and registers the tx.
- */
- private GlobalTransaction registerTransaction(Transaction tx, InvocationContext ctx) throws Exception
- {
- GlobalTransaction gtx;
-
- if (TransactionTable.isValid(tx) && transactions.add(tx))
- {
- gtx = txTable.getCurrentTransaction(tx, true);
- TransactionContext transactionContext;
- if (ctx.getGlobalTransaction() == null)
- {
- ctx.setGlobalTransaction(gtx);
- transactionContext = txTable.get(gtx);
- ctx.setTransactionContext(transactionContext);
- }
- else
- {
- transactionContext = ctx.getTransactionContext();
- }
- if (gtx.isRemote())
- {
- // should be no need to register a handler since this a remotely initiated globalTransaction
- if (trace) log.trace("is a remotely initiated gtx so no need to register a tx for it");
- }
- else
- {
- if (trace) log.trace("Registering sync handler for tx " + tx + ", gtx " + gtx);
-
- // see the comment in the LocalSyncHandler for the last isOriginLocal param.
- LocalSynchronizationHandler myHandler = new LocalSynchronizationHandler(gtx, tx, transactionContext, !ctx.isOriginLocal());
- registerHandler(tx, myHandler, ctx);
- }
- }
- else if ((gtx = rollbackTransactions.get(tx)) != null)
- {
- if (trace) log.trace("Transaction " + tx + " is already registered and is rolling back.");
- }
- else
- {
- if (trace) log.trace("Transaction " + tx + " is already registered.");
- }
- return gtx;
- }
-
- /**
- * Registers a sync hander against a tx.
- */
- private void registerHandler(Transaction tx, Synchronization handler, InvocationContext ctx) throws Exception
- {
- OrderedSynchronizationHandler orderedHandler = ctx.getTransactionContext().getOrderedSynchronizationHandler(); //OrderedSynchronizationHandler.getInstance(tx);
-
- if (trace) log.trace("registering for TX completion: SynchronizationHandler(" + handler + ")");
-
- orderedHandler.registerAtHead(handler);// needs to be invoked first on TX commit
-
- notifier.notifyTransactionRegistered(tx, ctx);
- }
-
- /**
- * Creates and starts a local tx
- *
- * @throws Exception
- */
- protected Transaction createLocalTx() throws Exception
- {
- if (trace)
- {
- log.trace("Creating transaction for thread " + Thread.currentThread());
- }
- Transaction localTx;
- if (txManager == null) throw new Exception("Failed to create local transaction; TransactionManager is null");
- txManager.begin();
- localTx = txManager.getTransaction();
- return localTx;
- }
-
- // ------------------------------------------------------------------------
- // Synchronization classes
- // ------------------------------------------------------------------------
-
- // this controls the whole transaction
-
- private class RemoteSynchronizationHandler implements Synchronization
- {
- Transaction tx = null;
- GlobalTransaction gtx = null;
- List<VisitableCommand> modifications = null;
- TransactionContext transactionContext = null;
- protected InvocationContext ctx; // the context for this call.
-
- RemoteSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext entry)
- {
- this.gtx = gtx;
- this.tx = tx;
- this.transactionContext = entry;
- }
-
- public void beforeCompletion()
- {
- if (trace) log.trace("Running beforeCompletion on gtx " + gtx);
-
- if (transactionContext == null)
- {
- log.error("Transaction has a null transaction entry - beforeCompletion() will fail.");
- throw new IllegalStateException("cannot find transaction entry for " + gtx);
- }
-
- modifications = transactionContext.getModifications();
- ctx = invocationContextContainer.get();
- setTransactionalContext(tx, gtx, transactionContext, ctx);
-
- if (ctx.isOptionsUninitialised() && transactionContext.getOption() != null)
- ctx.setOptionOverrides(transactionContext.getOption());
-
- assertCanContinue();
-
- ctx.setOriginLocal(false);
- }
-
- // this should really not be done here -
- // it is supposed to be post commit not actually run the commit
- public void afterCompletion(int status)
- {
- // could happen if a rollback is called and beforeCompletion() doesn't get called.
- if (ctx == null)
- {
- ctx = invocationContextContainer.get();
- setTransactionalContext(tx, gtx, transactionContext, ctx);
-
- if (ctx.isOptionsUninitialised() && transactionContext != null && transactionContext.getOption() != null)
- {
- // use the options from the transaction entry instead
- ctx.setOptionOverrides(transactionContext.getOption());
- }
- }
-
- try
- {
- assertCanContinue();
-
- try
- {
- if (txManager.getTransaction() != null && !txManager.getTransaction().equals(tx)) txManager.resume(tx);
- }
- catch (Exception e)
- {
- log.error("afterCompletion error: " + status, e);
- }
-
- if (trace) log.trace("calling aftercompletion for " + gtx);
-
- // set any transaction wide options as current for this thread.
- if (transactionContext != null)
- {
- // this should ideally be set in beforeCompletion(), after compacting the list.
- if (modifications == null) modifications = transactionContext.getModifications();
- ctx.setOptionOverrides(transactionContext.getOption());
- }
- if (tx != null) transactions.remove(tx);
-
- switch (status)
- {
- case Status.STATUS_COMMITTED:
- boolean onePhaseCommit = isOnePhaseCommit();
- if (log.isDebugEnabled()) log.debug("Running commit phase. One phase? " + onePhaseCommit);
- runCommitPhase(ctx, gtx, modifications, onePhaseCommit);
- log.debug("Finished commit phase");
- break;
- case Status.STATUS_UNKNOWN:
- log.warn("Received JTA STATUS_UNKNOWN in afterCompletion()! XA resources may not be in sync. The app should manually clean up resources at this point.");
- case Status.STATUS_MARKED_ROLLBACK:
- case Status.STATUS_ROLLEDBACK:
- log.debug("Running rollback phase");
- runRollbackPhase(ctx, gtx, tx);
- log.debug("Finished rollback phase");
- break;
-
- default:
- throw new IllegalStateException("illegal status: " + status);
- }
- }
- catch (Exception th)
- {
- log.trace("Caught exception ", th);
-
- }
- finally
- {
- // clean up the tx table
- txTable.remove(gtx);
- txTable.remove(tx);
- setTransactionalContext(null, null, null, ctx);
- cleanupInternalState();
- }
- }
-
- private void assertCanContinue()
- {
- if (!componentRegistry.invocationsAllowed(true) && (ctx.getOptionOverrides() == null || !ctx.getOptionOverrides().isSkipCacheStatusCheck()))
- throw new IllegalStateException("Cache not in STARTED state!");
- }
-
- /**
- * Cleans out (nullifies) member variables held by the sync object for easier gc. Could be (falsely) seen as a mem
- * leak if the TM implementation hangs on to the synchronizations for an unnecessarily long time even after the tx
- * completes. See JBCACHE-1007.
- */
- private void cleanupInternalState()
- {
- tx = null;
- gtx = null;
- modifications = null;
- if (transactionContext != null) transactionContext.reset();
- transactionContext = null;
- }
-
- @Override
- public String toString()
- {
- return "TxInterceptor.RemoteSynchronizationHandler(gtx=" + gtx + ", tx=" + getTxAsString() + ")";
- }
-
- protected String getTxAsString()
- {
- // JBCACHE-1114 -- don't call toString() on tx or it can lead to stack overflow
- if (tx == null)
- return null;
-
- return tx.getClass().getName() + "@" + System.identityHashCode(tx);
- }
- }
-
- private class LocalSynchronizationHandler extends RemoteSynchronizationHandler
- {
- private boolean localRollbackOnly = true;
- // a VERY strange situation where a tx has remote origins, but since certain buddy group org methods perform local
- // cleanups even when remotely triggered, and optimistic locking is used, you end up with an implicit local tx.
- // This is STILL remotely originating though and this needs to be made explicit here.
- // this can be checked by inspecting the InvocationContext.isOriginLocal() at the time of registering the sync.
- private boolean remoteLocal = false;
- private Option originalOptions, transactionalOptions;
-
- /**
- * A Synchronization for locally originating txs.
- * <p/>
- * a VERY strange situation where a tx has remote origins, but since certain buddy group org methods perform local
- * cleanups even when remotely triggered, and optimistic locking is used, you end up with an implicit local tx.
- * This is STILL remotely originating though and this needs to be made explicit here.
- * this can be checked by inspecting the InvocationContext.isOriginLocal() at the time of registering the sync.
- *
- * @param gtx
- * @param tx
- * @param remoteLocal
- */
- LocalSynchronizationHandler(GlobalTransaction gtx, Transaction tx, TransactionContext transactionContext, boolean remoteLocal)
- {
- super(gtx, tx, transactionContext);
- this.remoteLocal = remoteLocal;
- }
-
- @Override
- public void beforeCompletion()
- {
- super.beforeCompletion();
- ctx.setOriginLocal(!remoteLocal); // this is the LOCAL sync handler after all!
- // fetch the modifications before the transaction is committed
- // (and thus removed from the txTable)
- setTransactionalContext(tx, gtx, transactionContext, ctx);
- if (!transactionContext.hasModifications())
- {
- if (trace) log.trace("No modifications in this tx. Skipping beforeCompletion()");
- modifications = Collections.emptyList();
- return;
- }
- else
- {
- modifications = transactionContext.getModifications();
- }
-
- // set any transaction wide options as current for this thread, caching original options that would then be reset
- originalOptions = ctx.getOptionOverrides();
- transactionalOptions = transactionContext.getOption();
- ctx.setOptionOverrides(transactionalOptions);
-
- try
- {
- switch (tx.getStatus())
- {
- // if we are active or preparing then we can go ahead
- case Status.STATUS_ACTIVE:
- case Status.STATUS_PREPARING:
- // run a prepare call.
-
- Object result = isOnePhaseCommit() ? null : runPreparePhase(ctx, gtx, modifications);
-
- if (result instanceof Throwable)
- {
- if (log.isDebugEnabled())
- log.debug("Transaction needs to be rolled back - the cache returned an instance of Throwable for this prepare call (tx=" + tx + " and gtx=" + gtx + ")", (Throwable) result);
- tx.setRollbackOnly();
- throw (Throwable) result;
- }
- break;
- default:
- throw new CacheException("transaction " + tx + " in status " + tx.getStatus() + " unable to start transaction");
- }
- }
- catch (Throwable t)
- {
- if (log.isWarnEnabled()) log.warn("Caught exception, will now set transaction to roll back", t);
- try
- {
- tx.setRollbackOnly();
- }
- catch (SystemException se)
- {
- throw new RuntimeException("setting tx rollback failed ", se);
- }
- if (t instanceof RuntimeException)
- throw (RuntimeException) t;
- else
- throw new RuntimeException("", t);
- }
- finally
- {
- localRollbackOnly = false;
- setTransactionalContext(null, null, null, ctx);
- ctx.setOptionOverrides(originalOptions);
- }
- }
-
- @Override
- public void afterCompletion(int status)
- {
- // could happen if a rollback is called and beforeCompletion() doesn't get called.
- if (ctx == null) ctx = invocationContextContainer.get();
- ctx.setLocalRollbackOnly(localRollbackOnly);
- setTransactionalContext(tx, gtx, transactionContext, ctx);
- if (transactionalOptions != null) ctx.setOptionOverrides(transactionalOptions);
- try
- {
- super.afterCompletion(status);
- }
- finally
- {
- ctx.setOptionOverrides(originalOptions);
- }
- }
-
- @Override
- public String toString()
- {
- return "TxInterceptor.LocalSynchronizationHandler(gtx=" + gtx + ", tx=" + getTxAsString() + ")";
- }
- }
-
- @ManagedOperation
- public void resetStatistics()
- {
- prepares = 0;
- commits = 0;
- rollbacks = 0;
- }
-
- @ManagedOperation
- public Map<String, Object> dumpStatistics()
- {
- Map<String, Object> retval = new HashMap<String, Object>(3);
- retval.put("Prepares", prepares);
- retval.put("Commits", commits);
- retval.put("Rollbacks", rollbacks);
- return retval;
- }
-
- @ManagedAttribute
- public boolean getStatisticsEnabled()
- {
- return this.statsEnabled;
- }
-
- @ManagedAttribute
- public void setStatisticsEnabled(boolean enabled)
- {
- this.statsEnabled = enabled;
- }
-
- @ManagedAttribute(description = "number of transaction prepares")
- public long getPrepares()
- {
- return prepares;
- }
-
- @ManagedAttribute(description = "number of transaction commits")
- public long getCommits()
- {
- return commits;
- }
-
- @ManagedAttribute(description = "number of transaction rollbacks")
- public long getRollbacks()
- {
- return rollbacks;
- }
-}
\ No newline at end of file
Deleted: core/branches/flat/src/main/java/org/jboss/starobrno/UnsortedDataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/UnsortedDataContainer.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/UnsortedDataContainer.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -1,78 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno;
-
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-/**
- * // TODO: crappy and inefficient - but just a placeholder for now.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @since 3.0
- */
-public class UnsortedDataContainer<K, V> implements DataContainer<K, V>
-{
- private final ConcurrentMap<K, V> data = new ConcurrentHashMap<K, V>();
-
- public Set<Entry<K, V>> getEntries()
- {
- return data.entrySet();
- }
-
- public Entry<K, V> getEntry(K k)
- {
- if (k == null) throw new NullPointerException("I don't like nulls!");
- for (Entry<K, V> e : data.entrySet())
- {
- if (k.equals(e.getKey())) return e;
- }
- return null;
- }
-
- public void putEntry(Entry<K, V> kvEntry)
- {
- data.put(kvEntry.getKey(), kvEntry.getValue());
- }
-
- public boolean exists(Entry<K, V> kvEntry)
- {
- return data.containsKey(kvEntry.getKey());
- }
-
- public int size()
- {
- return data.size();
- }
-
- public void clear()
- {
- data.clear();
- }
-
- public void removeEntry(K key)
- {
- data.remove(key);
- }
-}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -24,8 +24,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.starobrno.commands.Visitor;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.mvcc.MVCCEntry;
import org.jboss.starobrno.notifications.Notifier;
/**
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ClearCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ClearCommand.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ClearCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -23,8 +23,8 @@
import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.commands.Visitor;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.mvcc.MVCCEntry;
/**
* @author Mircea.Markus(a)jboss.com
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -23,8 +23,8 @@
import org.jboss.starobrno.commands.Visitor;
import org.jboss.starobrno.commands.read.AbstractDataCommand;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.mvcc.MVCCEntry;
/**
* @author Mircea.Markus(a)jboss.com
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -23,8 +23,8 @@
import org.jboss.starobrno.commands.Visitor;
import org.jboss.starobrno.commands.read.AbstractDataCommand;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.mvcc.MVCCEntry;
/**
* Implements functionality defined by {@link Cache#put(org.jboss.cache.Fqn, Object, Object)}.
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -23,8 +23,8 @@
import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.commands.Visitor;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.mvcc.MVCCEntry;
import java.util.Map;
import java.util.Map.Entry;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -23,8 +23,8 @@
import org.jboss.starobrno.commands.Visitor;
import org.jboss.starobrno.commands.read.AbstractDataCommand;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.mvcc.MVCCEntry;
/**
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -23,8 +23,8 @@
import org.jboss.starobrno.commands.Visitor;
import org.jboss.starobrno.commands.read.AbstractDataCommand;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
-import org.jboss.starobrno.mvcc.MVCCEntry;
/**
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/container/DataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/DataContainer.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/DataContainer.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -21,7 +21,6 @@
*/
package org.jboss.starobrno.container;
-import java.util.Map.Entry;
import java.util.Set;
/**
@@ -32,17 +31,17 @@
*/
public interface DataContainer<K, V>
{
- Set<Entry<K, V>> getEntries();
+ V get(K k);
- Entry<K, V> getEntry(K k);
+ void put(K k, V v);
- void putEntry(Entry<K, V> entry);
+ boolean containsKey(K k);
- boolean exists(Entry<K, V> entry);
+ V remove(K k);
int size();
void clear();
- void removeEntry(K key);
+ Set<K> keySet();
}
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntry.java (from rev 6894, core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/MVCCEntry.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntry.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntry.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -0,0 +1,57 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.container;
+
+import org.jboss.starobrno.context.InvocationContext;
+
+import java.util.Map.Entry;
+
+/**
+ * // TODO: MANIK: Document this
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public interface MVCCEntry extends Entry
+{
+ boolean isNullEntry();
+
+ void copyForUpdate(DataContainer container, boolean writeSkewCheck);
+
+ void commitUpdate(InvocationContext ctx, DataContainer container);
+
+ void rollbackUpdate();
+
+ boolean isChanged();
+
+ boolean isCreated();
+
+ void setCreated(boolean created);
+
+ boolean isDeleted();
+
+ void setDeleted(boolean deleted);
+
+ boolean isValid();
+
+ void setValid(boolean valid);
+}
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java (from rev 6895, core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/MVCCEntryWrapper.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/MVCCEntryCreator.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -0,0 +1,179 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.container;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.lock.TimeoutException;
+import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.context.InvocationContext;
+import org.jboss.starobrno.factories.EntryFactory;
+import org.jboss.starobrno.factories.annotations.Inject;
+import org.jboss.starobrno.factories.annotations.Start;
+import org.jboss.starobrno.lock.LockManager;
+
+/**
+ * Wraps mvcc entries.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class MVCCEntryCreator
+{
+ DataContainer container;
+ boolean writeSkewCheck;
+ LockManager lockManager;
+ Configuration configuration;
+ long defaultLockAcquisitionTimeout;
+ EntryFactory entryFactory;
+
+ private static final Log log = LogFactory.getLog(MVCCEntryCreator.class);
+ private static final boolean trace = log.isTraceEnabled();
+
+
+ @Inject
+ public void injectDependencies(DataContainer dataContainer, LockManager lockManager, Configuration configuration, EntryFactory entryFactory)
+ {
+ this.container = dataContainer;
+ this.configuration = configuration;
+ this.lockManager = lockManager;
+ this.entryFactory = entryFactory;
+ }
+
+ @Start
+ public void start()
+ {
+ defaultLockAcquisitionTimeout = configuration.getLockAcquisitionTimeout();
+ writeSkewCheck = configuration.isWriteSkewCheck();
+ }
+
+ public MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext) throws InterruptedException
+ {
+ return wrapEntryForReading(ctx, key, putInContext, false);
+ }
+
+ public MVCCEntry wrapEntryForReading(InvocationContext ctx, Object key, boolean putInContext, boolean forceWriteLock) throws InterruptedException
+ {
+ // TODO: Do we need to wrap for reading if we are not in a TX?
+ // TODO: Also, do we need to wrap for reading even IN a TX if we are using read-committed?
+
+ MVCCEntry mvccEntry;
+ if (forceWriteLock)
+ {
+ if (trace) log.trace("Forcing lock on reading key " + key);
+ return wrapEntryForWriting(ctx, key, false, false);
+ }
+ else if ((mvccEntry = ctx.lookupEntry(key)) == null)
+ {
+ if (trace) log.trace("Key " + key + " is not in context, fetching from container.");
+ // simple implementation. Peek the node, wrap it, put wrapped node in the context.
+ Object value = container.get(key);
+ mvccEntry = entryFactory.createWrappedEntry(key, value, false);
+ if (mvccEntry != null && putInContext) ctx.putLookedUpEntry(mvccEntry);
+ return mvccEntry;
+ }
+ else
+ {
+ if (trace) log.trace("Key " + key + " is already in context.");
+ return mvccEntry;
+ }
+ }
+
+ public MVCCEntry wrapEntryForWriting(InvocationContext ctx, Object key, boolean createIfAbsent, boolean forceLockIfAbsent) throws InterruptedException
+ {
+ MVCCEntry mvccEntry = ctx.lookupEntry(key);
+ if (createIfAbsent && mvccEntry != null && mvccEntry.isNullEntry()) mvccEntry = null;
+ if (mvccEntry != null) // exists in context! Just acquire lock if needed, and wrap.
+ {
+ // acquire lock if needed
+ if (acquireLock(ctx, key))
+ {
+ // create a copy of the underlying node
+ mvccEntry.copyForUpdate(container, writeSkewCheck);
+ }
+ if (trace) log.trace("Retrieving wrapped node " + key);
+ if (mvccEntry.isDeleted() && createIfAbsent)
+ {
+ if (trace) log.trace("Node is deleted in current scope. Need to un-delete.");
+ mvccEntry.setDeleted(false);
+ mvccEntry.setValid(true);
+ }
+ }
+ else
+ {
+ // else, fetch from dataContainer.
+ Object value = container.get(key);
+ if (value != null)
+ {
+ // exists in cache! Just acquire lock if needed, and wrap.
+ // do we need a lock?
+ boolean needToCopy = false;
+ if (acquireLock(ctx, key)) needToCopy = true;
+ mvccEntry = entryFactory.createWrappedEntry(key, value, false);
+ ctx.putLookedUpEntry(mvccEntry);
+ if (needToCopy) mvccEntry.copyForUpdate(container, writeSkewCheck);
+ }
+ else if (createIfAbsent) // else, do we need to create one?
+ {
+ // now to lock and create the node. Lock first to prevent concurrent creation!
+ acquireLock(ctx, key);
+ mvccEntry = entryFactory.createWrappedEntry(key, value, true);
+ mvccEntry.setCreated(true);
+ ctx.putLookedUpEntry(mvccEntry);
+ mvccEntry.copyForUpdate(container, writeSkewCheck);
+ }
+ }
+
+ // see if we need to force the lock on nonexistent entries.
+ if (mvccEntry == null && forceLockIfAbsent) acquireLock(ctx, key);
+
+ return mvccEntry;
+ }
+
+ /**
+ * Attempts to lock a node if the lock isn't already held in the current scope, and records the lock in the context.
+ *
+ * @param ctx context
+ * @param fqn Fqn to lock
+ * @return true if a lock was needed and acquired, false if it didn't need to acquire the lock (i.e., lock was already held)
+ * @throws InterruptedException if interrupted
+ * @throws org.jboss.cache.lock.TimeoutException
+ * if we are unable to acquire the lock after a specified timeout.
+ */
+ private boolean acquireLock(InvocationContext ctx, Object key) throws InterruptedException, TimeoutException
+ {
+ // don't EVER use lockManager.isLocked() since with lock striping it may be the case that we hold the relevant
+ // lock which may be shared with another Fqn that we have a lock for already.
+ // nothing wrong, just means that we fail to record the lock. And that is a problem.
+ // Better to check our records and lock again if necessary.
+ if (!ctx.hasLockedKey(key))
+ {
+ if (!lockManager.lockAndRecord(key, ctx))
+ {
+ Object owner = lockManager.getOwner(key);
+ throw new TimeoutException("Unable to acquire lock on key [" + key + "] after [" + ctx.getLockAcquisitionTimeout(defaultLockAcquisitionTimeout) + "] milliseconds for requestor [" + lockManager.getLockOwner(ctx) + "]! Lock held by [" + owner + "]");
+ }
+ return true;
+ }
+ return false;
+ }
+}
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/container/NullMarkerEntry.java (from rev 6895, core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/NullMarkerEntry.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/NullMarkerEntry.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/NullMarkerEntry.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -0,0 +1,68 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.container;
+
+/**
+ * A marker node to represent a null node for repeatable read, so that a read that returns a null can continue to return
+ * null.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class NullMarkerEntry extends ReadCommittedEntry
+{
+ /**
+ * @return always returns true
+ */
+ @Override
+ public boolean isNullEntry()
+ {
+ return true;
+ }
+
+ /**
+ * @return always returns true so that any get commands, upon getting this node, will ignore the node as though it were removed.
+ */
+ @Override
+ public boolean isDeleted()
+ {
+ return true;
+ }
+
+ /**
+ * @return always returns true so that any get commands, upon getting this node, will ignore the node as though it were invalid.
+ */
+ @Override
+ public boolean isValid()
+ {
+ return false;
+ }
+
+ /**
+ * A no-op.
+ */
+ @Override
+ public void copyForUpdate(DataContainer d, boolean b)
+ {
+ // no op
+ }
+}
\ No newline at end of file
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java (from rev 6895, core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/ReadCommittedEntry.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/ReadCommittedEntry.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -0,0 +1,205 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.container;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import static org.jboss.starobrno.container.ReadCommittedEntry.Flags.*;
+import org.jboss.starobrno.context.InvocationContext;
+
+/**
+ * A node delegate that encapsulates read committed semantics when writes are initiated, committed or rolled back.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class ReadCommittedEntry implements MVCCEntry
+{
+ private static final Log log = LogFactory.getLog(ReadCommittedEntry.class);
+ private static final boolean trace = log.isTraceEnabled();
+
+ protected Object key, value, oldValue;
+ protected byte flags = 0;
+
+
+ protected ReadCommittedEntry()
+ {
+ setValid(true);
+ }
+
+ public ReadCommittedEntry(Object key, Object value)
+ {
+ setValid(true);
+ this.key = key;
+ this.value = value;
+ }
+
+ public Object getKey()
+ {
+ return key;
+ }
+
+ public Object getValue()
+ {
+ return value;
+ }
+
+ public Object setValue(Object value)
+ {
+ return this.value = value;
+ }
+
+ protected static enum Flags
+ {
+ CHANGED(0x1), CREATED(0x2), DELETED(0x4), VALID(0x8);
+ final byte mask;
+
+ Flags(int mask)
+ {
+ this.mask = (byte) mask;
+ }
+ }
+
+ /**
+ * Tests whether a flag is set.
+ *
+ * @param flag flag to test
+ * @return true if set, false otherwise.
+ */
+ protected final boolean isFlagSet(Flags flag)
+ {
+ return (flags & flag.mask) != 0;
+ }
+
+ /**
+ * Unility method that sets the value of the given flag to true.
+ *
+ * @param flag flag to set
+ */
+ protected final void setFlag(Flags flag)
+ {
+ flags |= flag.mask;
+ }
+
+ /**
+ * Utility method that sets the value of the flag to false.
+ *
+ * @param flag flag to unset
+ */
+ protected final void unsetFlag(Flags flag)
+ {
+ flags &= ~flag.mask;
+ }
+
+ public boolean isNullEntry()
+ {
+ return false;
+ }
+
+ public void copyForUpdate(DataContainer container, boolean writeSkewCheck)
+ {
+ if (isFlagSet(CHANGED)) return; // already copied
+
+ setFlag(CHANGED); // mark as changed
+
+ // if newly created, then nothing to copy.
+ if (!isFlagSet(CREATED)) oldValue = value;
+ }
+
+ @SuppressWarnings("unchecked")
+ public void commitUpdate(InvocationContext ctx, DataContainer container)
+ {
+ // only do stuff if there are changes.
+ if (isFlagSet(CHANGED))
+ {
+ if (trace)
+ log.trace("Updating entry [" + getKey() + "]. deleted=" + isDeleted() + " valid=" + isValid() + " changed=" + isChanged() + " created=" + isFlagSet(CREATED));
+ if (isFlagSet(DELETED))
+ {
+ container.remove(key);
+
+ }
+ else
+ {
+ container.put(key, value);
+ }
+ reset();
+ }
+ }
+
+ private void reset()
+ {
+ oldValue = null;
+ flags = 0;
+ setValid(true);
+ }
+
+ public void rollbackUpdate()
+ {
+ value = oldValue;
+ reset();
+ }
+
+ public boolean isChanged()
+ {
+ return isFlagSet(CHANGED);
+ }
+
+ public boolean isValid()
+ {
+ return isFlagSet(VALID);
+ }
+
+ public void setValid(boolean valid)
+ {
+ if (valid)
+ setFlag(VALID);
+ else
+ unsetFlag(VALID);
+ }
+
+ public boolean isCreated()
+ {
+ return isFlagSet(CREATED);
+ }
+
+ public void setCreated(boolean created)
+ {
+ if (created)
+ setFlag(CREATED);
+ else
+ unsetFlag(CREATED);
+ }
+
+ public boolean isDeleted()
+ {
+ return isFlagSet(DELETED);
+ }
+
+ public void setDeleted(boolean deleted)
+ {
+ if (deleted)
+ setFlag(DELETED);
+ else
+ unsetFlag(DELETED);
+ }
+}
\ No newline at end of file
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java (from rev 6895, core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/RepeatableReadEntry.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/RepeatableReadEntry.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -0,0 +1,69 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.container;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.jboss.cache.mvcc.RepeatableReadNode;
+import org.jboss.starobrno.CacheException;
+import static org.jboss.starobrno.container.ReadCommittedEntry.Flags.CHANGED;
+
+/**
+ * A node delegate that encapsulates repeatable read semantics when writes are initiated, committed or rolled back.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class RepeatableReadEntry extends ReadCommittedEntry
+{
+ private static final Log log = LogFactory.getLog(RepeatableReadNode.class);
+
+ public RepeatableReadEntry(Object key, Object value)
+ {
+ super(key, value);
+ }
+
+ @Override
+ public void copyForUpdate(DataContainer container, boolean writeSkewCheck)
+ {
+ if (isFlagSet(CHANGED)) return; // already copied
+
+ // mark node as changed.
+ setFlag(CHANGED);
+
+ if (writeSkewCheck)
+ {
+ // check for write skew.
+ Object actualValue = container.get(key);
+
+ if (actualValue != null && actualValue != value)
+ {
+ String errormsg = new StringBuilder().append("Detected write skew on key [").append(getKey()).append("]. Another process has changed the entry since we last read it!").toString();
+ if (log.isWarnEnabled()) log.warn(errormsg + ". Unable to copy entry for update.");
+ throw new CacheException(errormsg);
+ }
+ }
+
+ // make a backup copy
+ oldValue = value;
+ }
+}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/container/UnsortedDataContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/container/UnsortedDataContainer.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/container/UnsortedDataContainer.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -21,7 +21,6 @@
*/
package org.jboss.starobrno.container;
-import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@@ -36,29 +35,24 @@
{
private final ConcurrentMap<K, V> data = new ConcurrentHashMap<K, V>();
- public Set<Entry<K, V>> getEntries()
+ public V get(K k)
{
- return data.entrySet();
+ return data.get(k);
}
- public Entry<K, V> getEntry(K k)
+ public void put(K k, V v)
{
- if (k == null) throw new NullPointerException("I don't like nulls!");
- for (Entry<K, V> e : data.entrySet())
- {
- if (k.equals(e.getKey())) return e;
- }
- return null;
+ data.put(k, v);
}
- public void putEntry(Entry<K, V> kvEntry)
+ public boolean containsKey(K k)
{
- data.put(kvEntry.getKey(), kvEntry.getValue());
+ return data.containsKey(k);
}
- public boolean exists(Entry<K, V> kvEntry)
+ public V remove(K k)
{
- return data.containsKey(kvEntry.getKey());
+ return data.remove(k);
}
public int size()
@@ -71,8 +65,8 @@
data.clear();
}
- public void removeEntry(K key)
+ public Set<K> keySet()
{
- data.remove(key);
+ return data.keySet();
}
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/EntryLookup.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -21,7 +21,7 @@
*/
package org.jboss.starobrno.context;
-import org.jboss.starobrno.mvcc.MVCCEntry;
+import org.jboss.starobrno.container.MVCCEntry;
import java.util.Map;
import java.util.Set;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/InvocationContextImpl.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -26,7 +26,7 @@
import org.jboss.cache.util.Immutables;
import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.config.Option;
-import org.jboss.starobrno.mvcc.MVCCEntry;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jboss.starobrno.transaction.TransactionTable;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/context/TransactionContextImpl.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -24,7 +24,7 @@
import org.jboss.cache.util.Immutables;
import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.config.Option;
-import org.jboss.starobrno.mvcc.MVCCEntry;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.transaction.OrderedSynchronizationHandler;
import javax.transaction.RollbackException;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -23,7 +23,6 @@
import org.jboss.cache.RegionRegistry;
-import org.jboss.starobrno.batch.BatchContainer;
import org.jboss.cache.buddyreplication.BuddyFqnTransformer;
import org.jboss.cache.invocation.CacheInvocationDelegate;
import org.jboss.cache.loader.CacheLoaderManager;
@@ -31,12 +30,13 @@
import org.jboss.cache.marshall.Marshaller;
import org.jboss.cache.marshall.VersionAwareMarshaller;
import org.jboss.cache.remoting.jgroups.ChannelMessageListener;
+import org.jboss.starobrno.batch.BatchContainer;
import org.jboss.starobrno.commands.CommandsFactory;
import org.jboss.starobrno.config.ConfigurationException;
+import org.jboss.starobrno.container.MVCCEntryCreator;
import org.jboss.starobrno.factories.annotations.DefaultFactoryFor;
import org.jboss.starobrno.factories.context.ContextFactory;
import org.jboss.starobrno.invocation.InvocationContextContainer;
-import org.jboss.starobrno.mvcc.MVCCEntryWrapper;
import org.jboss.starobrno.notifications.Notifier;
import org.jboss.starobrno.transaction.TransactionTable;
@@ -48,7 +48,7 @@
*/
@DefaultFactoryFor(classes = {Notifier.class, RegionRegistry.class,
ChannelMessageListener.class, CacheLoaderManager.class, Marshaller.class, InvocationContextContainer.class,
- CacheInvocationDelegate.class, TransactionTable.class, MVCCEntryWrapper.class,
+ CacheInvocationDelegate.class, TransactionTable.class, MVCCEntryCreator.class,
LockStrategyFactory.class, BuddyFqnTransformer.class, BatchContainer.class,
ContextFactory.class, EntryFactory.class, CommandsFactory.class})
public class EmptyConstructorFactory extends ComponentFactory
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactory.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactory.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -21,10 +21,8 @@
*/
package org.jboss.starobrno.factories;
-import org.jboss.starobrno.mvcc.MVCCEntry;
+import org.jboss.starobrno.container.MVCCEntry;
-import java.util.Map.Entry;
-
/**
* // TODO: MANIK: Document this
*
@@ -33,7 +31,5 @@
*/
public interface EntryFactory
{
- Entry createEntry(Object key, Object value, boolean putInContainer);
-
- MVCCEntry createWrappedEntry(Entry entry);
+ MVCCEntry createWrappedEntry(Object key, Object value, boolean isForInsert);
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactoryImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactoryImpl.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/factories/EntryFactoryImpl.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -24,16 +24,13 @@
import org.jboss.cache.lock.IsolationLevel;
import org.jboss.starobrno.config.Configuration;
import org.jboss.starobrno.container.DataContainer;
+import org.jboss.starobrno.container.MVCCEntry;
+import org.jboss.starobrno.container.NullMarkerEntry;
+import org.jboss.starobrno.container.ReadCommittedEntry;
+import org.jboss.starobrno.container.RepeatableReadEntry;
import org.jboss.starobrno.factories.annotations.Inject;
import org.jboss.starobrno.factories.annotations.Start;
-import org.jboss.starobrno.mvcc.EntryImpl;
-import org.jboss.starobrno.mvcc.MVCCEntry;
-import org.jboss.starobrno.mvcc.NullMarkerEntry;
-import org.jboss.starobrno.mvcc.ReadCommittedEntry;
-import org.jboss.starobrno.mvcc.RepeatableReadEntry;
-import java.util.Map.Entry;
-
/**
* // TODO: MANIK: Document this
*
@@ -61,18 +58,11 @@
useRepeatableRead = configuration.getIsolationLevel() == IsolationLevel.REPEATABLE_READ;
}
- public Entry createEntry(Object key, Object value, boolean putInContainer)
+ public MVCCEntry createWrappedEntry(Object key, Object value, boolean isForInsert)
{
- Entry e = new EntryImpl(key, value);
- if (putInContainer) dataContainer.putEntry(e);
- return e;
- }
+ if (value == null && !isForInsert) return useRepeatableRead ? NULL_MARKER : null;
- public MVCCEntry createWrappedEntry(Entry entry)
- {
- if (entry == null) return useRepeatableRead ? NULL_MARKER : null;
-
- MVCCEntry mvccEntry = useRepeatableRead ? new RepeatableReadEntry(entry) : new ReadCommittedEntry(entry);
+ MVCCEntry mvccEntry = useRepeatableRead ? new RepeatableReadEntry(key, value) : new ReadCommittedEntry(key, value);
return mvccEntry;
}
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/InterceptorChain.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -24,13 +24,12 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.starobrno.CacheException;
+import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.annotations.Inject;
import org.jboss.starobrno.factories.annotations.Start;
-import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.interceptors.base.CommandInterceptor;
import org.jboss.starobrno.invocation.InvocationContextContainer;
-import org.jboss.cache.util.CachePrinter;
import java.util.ArrayList;
import java.util.Collections;
@@ -75,6 +74,7 @@
@Start
private void printChainInfo()
{
+ if (log.isDebugEnabled()) log.debug("Interceptor chain size: " + size());
if (log.isDebugEnabled()) log.debug("Interceptor chain is: " + toString());
}
@@ -358,14 +358,11 @@
{
StringBuilder sb = new StringBuilder();
CommandInterceptor i = firstInChain;
- if (i != null)
+ while (i != null)
{
- if (i.getNext() != null)
- {
- sb.append(i.getNext()).append("\n");
- }
- sb.append("\t>> ");
+ sb.append("\n\t>> ");
sb.append(i.getClass().getName());
+ i = i.getNext();
}
return sb.toString();
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/LockingInterceptor.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -21,6 +21,7 @@
*/
package org.jboss.starobrno.interceptors;
+import org.jboss.cache.lock.IsolationLevel;
import org.jboss.starobrno.commands.VisitableCommand;
import org.jboss.starobrno.commands.read.GetKeyValueCommand;
import org.jboss.starobrno.commands.read.GravitateDataCommand;
@@ -35,16 +36,18 @@
import org.jboss.starobrno.commands.write.RemoveCommand;
import org.jboss.starobrno.commands.write.ReplaceCommand;
import org.jboss.starobrno.container.DataContainer;
+import org.jboss.starobrno.container.MVCCEntry;
+import org.jboss.starobrno.container.MVCCEntryCreator;
import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.annotations.Inject;
+import org.jboss.starobrno.factories.annotations.Start;
import org.jboss.starobrno.interceptors.base.PrePostProcessingCommandInterceptor;
import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.mvcc.MVCCEntry;
-import org.jboss.starobrno.mvcc.MVCCEntryWrapper;
+import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
-import java.util.Map.Entry;
+import java.util.Set;
/**
* Interceptor to implement <a href="http://wiki.jboss.org/wiki/JBossCacheMVCC">MVCC</a> functionality.
@@ -57,16 +60,23 @@
{
LockManager lockManager;
DataContainer dataContainer;
- MVCCEntryWrapper entryWrapper;
+ MVCCEntryCreator entryWrapper;
+ boolean useReadCommitted;
@Inject
- public void setDependencies(LockManager lockManager, DataContainer dataContainer, MVCCEntryWrapper entryWrapper)
+ public void setDependencies(LockManager lockManager, DataContainer dataContainer, MVCCEntryCreator entryWrapper)
{
this.lockManager = lockManager;
this.dataContainer = dataContainer;
this.entryWrapper = entryWrapper;
}
+ @Start
+ private void determineIsolationLevel()
+ {
+ useReadCommitted = configuration.getIsolationLevel() == IsolationLevel.READ_COMMITTED;
+ }
+
@Override
protected boolean doBeforeCall(InvocationContext ctx, VisitableCommand command)
{
@@ -138,11 +148,7 @@
public Object handleClearCommand(InvocationContext ctx, ClearCommand command) throws Throwable
{
// get a snapshot of all keys in the data container
- for (Object o : dataContainer.getEntries())
- {
- Object key = ((Entry) o).getKey();
- entryWrapper.wrapEntryForWriting(ctx, key, false, false);
- }
+ for (Object key : dataContainer.keySet()) entryWrapper.wrapEntryForWriting(ctx, key, false, false);
return invokeNextInterceptor(ctx, command);
}
@@ -211,7 +217,22 @@
}
else
{
- if (trace) log.trace("Nothing to do since there is a transaction in scope.");
+ if (useReadCommitted)
+ {
+ // wipe all unchanged entries from context, to force subsequent reads to go to the container,
+ // hence providing R_C semantics.
+ Set<Object> keysToRemove = new HashSet<Object>();
+ for (MVCCEntry e : ctx.getLookedUpEntries().values())
+ {
+ if (e.isChanged()) keysToRemove.add(e.getKey());
+ }
+ for (Object k : keysToRemove) ctx.removeKeyLocked(k);
+ }
+ else
+ {
+ if (trace) log.trace("Nothing to do since there is a transaction in scope.");
+ }
+
}
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/notifications/NotifierImpl.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -36,13 +36,13 @@
import org.jboss.starobrno.CacheException;
import org.jboss.starobrno.CacheSPI;
import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.container.MVCCEntry;
import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.annotations.Destroy;
import org.jboss.starobrno.factories.annotations.Inject;
import org.jboss.starobrno.factories.annotations.NonVolatile;
import org.jboss.starobrno.factories.annotations.Start;
import org.jboss.starobrno.factories.annotations.Stop;
-import org.jboss.starobrno.mvcc.MVCCEntry;
import org.jboss.starobrno.notifications.event.NodeModifiedEvent;
import org.jgroups.View;
Modified: core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java 2008-10-09 12:52:15 UTC (rev 6896)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/BasicTest.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -31,7 +31,7 @@
* @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
* @since 3.0
*/
-@Test
+@Test(groups = "functional")
public class BasicTest
{
public void basicTest()
Added: core/branches/flat/src/test/java/org/jboss/starobrno/profiling/MemConsumptionTest.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/profiling/MemConsumptionTest.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/profiling/MemConsumptionTest.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -0,0 +1,114 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.cache.profiling;
+
+import org.jboss.cache.DefaultCacheFactory;
+import org.jboss.starobrno.Cache;
+import org.jboss.starobrno.util.TestingUtil;
+import org.testng.annotations.Test;
+
+import java.io.IOException;
+import java.text.NumberFormat;
+import java.util.Arrays;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
+
+@Test(groups = "profiling")
+public class MemConsumptionTest
+{
+ // adjust the next 3 numbers
+ int numEntries = 1000000;
+ int payloadSize = 20; // bytes
+ int keySize = 10; // bytes
+ int bytesPerChar = 2;
+
+ Random r = new Random();
+
+ public void testMemConsumption() throws IOException
+ {
+ int kBytesCached = (bytesPerChar * numEntries * (payloadSize + keySize)) / 1024;
+ System.out.println("Bytes to be cached: " + NumberFormat.getIntegerInstance().format(kBytesCached) + " kb");
+
+// Cache<byte[], byte[]> c = new DefaultCacheFactory<byte[], byte[]>().createCache(); // default LOCAL cache
+ Cache<String, String> c = new DefaultCacheFactory<String, String>().createCache(); // default LOCAL cache
+// Map<String, String> c = new ConcurrentHashMap<String, String>();
+ long start = System.nanoTime();
+ for (int i = 0; i < numEntries; i++)
+ {
+// c.put(generateUniqueKey(i, keySize), generateBytePayload(payloadSize));
+ c.put(generateUniqueString(i, keySize), generateRandomString(payloadSize));
+ if (i % 1000 == 0) System.out.println("Added " + i + " entries");
+ }
+ long duration = System.nanoTime() - start;
+ System.out.println("Done, took " + TimeUnit.NANOSECONDS.toSeconds(duration) + " seconds!");
+
+ System.out.println("Calling System.gc()");
+ System.gc(); // clear any unnecessary objects
+
+ TestingUtil.sleepThread(1000); // wait for gc
+
+ // wait for manual test exit
+ System.out.println("Cache populated; check mem usage using jconsole, etc.!");
+ System.in.read();
+ }
+
+ private String generateUniqueString(int runNumber, int keySize)
+ {
+ // string size should be exactly equal to key size but also be unique.
+ // start by creating a string from the run number
+ StringBuilder sb = new StringBuilder();
+ // append the run number
+ sb.append(runNumber);
+ for (int i = sb.length(); i < keySize; i++) sb.append("_");
+ return sb.toString();
+ }
+
+ private byte[] generateUniqueKey(int runNumber, int keySize)
+ {
+ byte[] b = new byte[keySize];
+ b[0] = (byte) (runNumber >>> 0);
+ b[1] = (byte) (runNumber >>> 8);
+ b[2] = (byte) (runNumber >>> 16);
+ b[3] = (byte) (runNumber >>> 24);
+
+ for (int i = 4; i < keySize; i++) b[i] = 0;
+ return b;
+ }
+
+ private byte[] generateBytePayload(int payloadSize)
+ {
+ byte[] b = new byte[payloadSize];
+ Arrays.fill(b, (byte) 0);
+ return b;
+ }
+
+ private String generateRandomString(int stringSize)
+ {
+ StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < stringSize; i++)
+ {
+ sb.append(r.nextInt(9)); // single digit
+ }
+ assert sb.length() == stringSize;
+ return sb.toString();
+ }
+}
Added: core/branches/flat/src/test/java/org/jboss/starobrno/util/TestingUtil.java
===================================================================
--- core/branches/flat/src/test/java/org/jboss/starobrno/util/TestingUtil.java (rev 0)
+++ core/branches/flat/src/test/java/org/jboss/starobrno/util/TestingUtil.java 2008-10-09 13:22:09 UTC (rev 6897)
@@ -0,0 +1,641 @@
+/*
+ * JBoss, the OpenSource J2EE webOS
+ *
+ * Distributable under LGPL license.
+ * See terms of license at gnu.org.
+ */
+
+package org.jboss.starobrno.util;
+
+import org.jboss.cache.CacheStatus;
+import org.jboss.cache.invocation.CacheInvocationDelegate;
+import org.jboss.starobrno.Cache;
+import org.jboss.starobrno.CacheSPI;
+import org.jboss.starobrno.commands.CommandsFactory;
+import org.jboss.starobrno.commands.VisitableCommand;
+import org.jboss.starobrno.factories.ComponentRegistry;
+import org.jboss.starobrno.interceptors.InterceptorChain;
+import org.jboss.starobrno.interceptors.base.CommandInterceptor;
+import org.jboss.starobrno.lock.LockManager;
+import org.jgroups.JChannel;
+
+import java.io.File;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Random;
+
+/**
+ * Utilities for unit testing JBossCache.
+ *
+ * @author <a href="mailto://brian.stansberry@jboss.com">Brian Stansberry</a>
+ * @version $Revision$
+ */
+public class TestingUtil
+{
+ private static Random random = new Random();
+
+ /**
+ * Extracts the value of a field in a given target instance using reflection, able to extract private fields as well.
+ *
+ * @param target object to extract field from
+ * @param fieldName name of field to extract
+ * @return field value
+ */
+ public static Object extractField(Object target, String fieldName)
+ {
+ return extractField(target.getClass(), target, fieldName);
+ }
+
+ public static void replaceField(Object newValue, String fieldName, Object owner, Class baseType)
+ {
+ Field field;
+ try
+ {
+ field = baseType.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ field.set(owner, newValue);
+ }
+ catch (Exception e)
+ {
+ throw new RuntimeException(e);//just to simplify exception handeling
+ }
+ }
+
+
+ public static Object extractField(Class type, Object target, String fieldName)
+ {
+ Field field;
+ try
+ {
+ field = type.getDeclaredField(fieldName);
+ field.setAccessible(true);
+ return field.get(target);
+ }
+ catch (Exception e)
+ {
+ if (type.equals(Object.class))
+ {
+ e.printStackTrace();
+ return null;
+ }
+ else
+ {
+ // try with superclass!!
+ return extractField(type.getSuperclass(), target, fieldName);
+ }
+ }
+ }
+
+ public static <T extends CommandInterceptor> T findInterceptor(CacheSPI<?, ?> cache, Class<T> interceptorToFind)
+ {
+ for (CommandInterceptor i : cache.getInterceptorChain())
+ {
+ if (interceptorToFind.isInstance(i)) return interceptorToFind.cast(i);
+ }
+ return null;
+ }
+
+ /**
+ * Injects an interceptor after a specified interceptor in a running cache. Your new interceptor need not be
+ * initialised with pointers to the next interceptor, etc. as this method does all that for you, including calling
+ * setCache().
+ *
+ * @param cache running cache instance
+ * @param interceptorToInject interceptor instance to inject.
+ * @param interceptorAfterWhichToInject class of interceptor to search for in the chain and after which to add your interceptor
+ */
+ public static void injectInterceptor(CacheSPI<?, ?> cache, CommandInterceptor interceptorToInject, Class<? extends CommandInterceptor> interceptorAfterWhichToInject)
+ {
+ cache.addInterceptor(interceptorToInject, interceptorAfterWhichToInject);
+ }
+
+ /**
+ * Loops, continually calling {@link #areCacheViewsComplete(org.jboss.cache.Cache[])}
+ * until it either returns true or <code>timeout</code> ms have elapsed.
+ *
+ * @param caches caches which must all have consistent views
+ * @param timeout max number of ms to loop
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without
+ * all caches having the same number of members.
+ */
+ public static void blockUntilViewsReceived(Cache[] caches, long timeout)
+ {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime)
+ {
+ sleepThread(100);
+ if (areCacheViewsComplete(caches))
+ {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+ /**
+ * Version of blockUntilViewsReceived that uses varargs
+ */
+ public static void blockUntilViewsReceived(long timeout, Cache... caches)
+ {
+ blockUntilViewsReceived(caches, timeout);
+ }
+
+ /**
+ * Loops, continually calling {@link #areCacheViewsComplete(org.jboss.cache.CacheSPI[])}
+ * until it either returns true or <code>timeout</code> ms have elapsed.
+ *
+ * @param caches caches which must all have consistent views
+ * @param timeout max number of ms to loop
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without
+ * all caches having the same number of members.
+ */
+ public static void blockUntilViewsReceived(CacheSPI[] caches, long timeout)
+ {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime)
+ {
+ sleepThread(100);
+ if (areCacheViewsComplete(caches))
+ {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+
+ /**
+ * An overloaded version of {@link #blockUntilViewsReceived(long,org.jboss.cache.Cache[])} that allows for 'shrinking' clusters.
+ * I.e., the usual method barfs if there are more members than expected. This one takes a param (barfIfTooManyMembers) which,
+ * if false, will NOT barf but will wait until the cluster 'shrinks' to the desired size. Useful if in tests, you kill
+ * a member and want to wait until this fact is known across the cluster.
+ *
+ * @param timeout
+ * @param barfIfTooManyMembers
+ * @param caches
+ */
+ public static void blockUntilViewsReceived(long timeout, boolean barfIfTooManyMembers, Cache... caches)
+ {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime)
+ {
+ sleepThread(100);
+ if (areCacheViewsComplete(caches, barfIfTooManyMembers))
+ {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+ /**
+ * Loops, continually calling {@link #areCacheViewsComplete(org.jboss.cache.CacheSPI[])}
+ * until it either returns true or <code>timeout</code> ms have elapsed.
+ *
+ * @param groupSize number of caches expected in the group
+ * @param timeout max number of ms to loop
+ * @throws RuntimeException if <code>timeout</code> ms have elapse without
+ * all caches having the same number of members.
+ */
+ public static void blockUntilViewReceived(CacheSPI cache, int groupSize, long timeout)
+ {
+ blockUntilViewReceived(cache, groupSize, timeout, true);
+ }
+
+ public static void blockUntilViewReceived(CacheSPI cache, int groupSize, long timeout, boolean barfIfTooManyMembersInView)
+ {
+ long failTime = System.currentTimeMillis() + timeout;
+
+ while (System.currentTimeMillis() < failTime)
+ {
+ sleepThread(100);
+ if (isCacheViewComplete(cache, groupSize, barfIfTooManyMembersInView))
+ {
+ return;
+ }
+ }
+
+ throw new RuntimeException("timed out before caches had complete views");
+ }
+
+ /**
+ * Checks each cache to see if the number of elements in the array
+ * returned by {@link CacheSPI#getMembers()} matches the size of
+ * the <code>caches</code> parameter.
+ *
+ * @param caches caches that should form a View
+ * @return <code>true</code> if all caches have
+ * <code>caches.length</code> members; false otherwise
+ * @throws IllegalStateException if any of the caches have MORE view
+ * members than caches.length
+ */
+ public static boolean areCacheViewsComplete(Cache[] caches)
+ {
+ return areCacheViewsComplete(caches, true);
+ }
+
+ public static boolean areCacheViewsComplete(Cache[] caches, boolean barfIfTooManyMembers)
+ {
+ int memberCount = caches.length;
+
+ for (int i = 0; i < memberCount; i++)
+ {
+ if (!isCacheViewComplete(caches[i], memberCount, barfIfTooManyMembers))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Checks each cache to see if the number of elements in the array
+ * returned by {@link org.jboss.cache.RPCManager#getMembers()} matches the size of
+ * the <code>caches</code> parameter.
+ *
+ * @param caches caches that should form a View
+ * @return <code>true</code> if all caches have
+ * <code>caches.length</code> members; false otherwise
+ * @throws IllegalStateException if any of the caches have MORE view
+ * members than caches.length
+ */
+ public static boolean areCacheViewsComplete(CacheSPI[] caches)
+ {
+ if (caches == null) throw new NullPointerException("Cache impl array is null");
+ Cache[] c = new Cache[caches.length];
+ for (int i = 0; i < caches.length; i++) c[i] = caches[i];
+ return areCacheViewsComplete(c);
+ }
+
+ /**
+ * @param cache
+ * @param memberCount
+ */
+ public static boolean isCacheViewComplete(CacheSPI cache, int memberCount)
+ {
+ List members = cache.getRPCManager().getMembers();
+ if (members == null || memberCount > members.size())
+ {
+ return false;
+ }
+ else if (memberCount < members.size())
+ {
+ // This is an exceptional condition
+ StringBuilder sb = new StringBuilder("Cache at address ");
+ sb.append(cache.getRPCManager().getLocalAddress());
+ sb.append(" had ");
+ sb.append(members.size());
+ sb.append(" members; expecting ");
+ sb.append(memberCount);
+ sb.append(". Members were (");
+ for (int j = 0; j < members.size(); j++)
+ {
+ if (j > 0)
+ {
+ sb.append(", ");
+ }
+ sb.append(members.get(j));
+ }
+ sb.append(')');
+
+ throw new IllegalStateException(sb.toString());
+ }
+
+ return true;
+ }
+
+ /**
+ * @param c
+ * @param memberCount
+ */
+ public static boolean isCacheViewComplete(Cache c, int memberCount)
+ {
+ return isCacheViewComplete(c, memberCount, true);
+ }
+
+ public static boolean isCacheViewComplete(Cache c, int memberCount, boolean barfIfTooManyMembers)
+ {
+ CacheSPI cache = (CacheSPI) c;
+ List members = cache.getRPCManager().getMembers();
+ if (members == null || memberCount > members.size())
+ {
+ return false;
+ }
+ else if (memberCount < members.size())
+ {
+ if (barfIfTooManyMembers)
+ {
+ // This is an exceptional condition
+ StringBuilder sb = new StringBuilder("Cache at address ");
+ sb.append(cache.getRPCManager().getLocalAddress());
+ sb.append(" had ");
+ sb.append(members.size());
+ sb.append(" members; expecting ");
+ sb.append(memberCount);
+ sb.append(". Members were (");
+ for (int j = 0; j < members.size(); j++)
+ {
+ if (j > 0)
+ {
+ sb.append(", ");
+ }
+ sb.append(members.get(j));
+ }
+ sb.append(')');
+
+ throw new IllegalStateException(sb.toString());
+ }
+ else return false;
+ }
+
+ return true;
+ }
+
+
+ /**
+ * Puts the current thread to sleep for the desired number of ms, suppressing
+ * any exceptions.
+ *
+ * @param sleeptime number of ms to sleep
+ */
+ public static void sleepThread(long sleeptime)
+ {
+ try
+ {
+ Thread.sleep(sleeptime);
+ }
+ catch (InterruptedException ie)
+ {
+ }
+ }
+
+ public static void sleepRandom(int maxTime)
+ {
+ sleepThread(random.nextInt(maxTime));
+ }
+
+ public static void recursiveFileRemove(String directoryName)
+ {
+ File file = new File(directoryName);
+ recursiveFileRemove(file);
+ }
+
+ public static void recursiveFileRemove(File file)
+ {
+ if (file.exists())
+ {
+ System.out.println("Deleting file " + file);
+ recursivedelete(file);
+ }
+ }
+
+ private static void recursivedelete(File f)
+ {
+ if (f.isDirectory())
+ {
+ File[] files = f.listFiles();
+ for (File file : files)
+ {
+ recursivedelete(file);
+ }
+ }
+ //System.out.println("File " + f.toURI() + " deleted = " + f.delete());
+ f.delete();
+ }
+
+ /**
+ * Kills a cache - stops it, clears any data in any cache loaders, and rolls back any associated txs
+ */
+ public static void killCaches(Cache... caches)
+ {
+ for (Cache c : caches)
+ {
+ try
+ {
+ if (c != null && c.getCacheStatus() == CacheStatus.STARTED)
+ {
+ CacheSPI spi = (CacheSPI) c;
+ if (spi.getTransactionManager() != null)
+ {
+ try
+ {
+ spi.getTransactionManager().rollback();
+ }
+ catch (Exception e)
+ {
+ // don't care
+ }
+ }
+
+ // TODO fix cache loader stuff
+ /*
+ CacheLoaderManager clm = spi.getCacheLoaderManager();
+ CacheLoader cl = clm == null ? null : clm.getCacheLoader();
+ if (cl != null)
+ {
+ try
+ {
+ cl.remove(Fqn.ROOT);
+ }
+ catch (Exception e)
+ {
+ // don't care
+ }
+ }
+ */
+
+ spi.stop();
+ }
+ }
+ catch (Throwable t)
+ {
+
+ }
+ }
+ }
+
+ /**
+ * Clears any associated transactions with the current thread in the caches' transaction managers.
+ */
+ public static void killTransactions(Cache... caches)
+ {
+ for (Cache c : caches)
+ {
+ if (c != null && c.getCacheStatus() == CacheStatus.STARTED)
+ {
+ CacheSPI ci = (CacheSPI) c;
+ if (ci.getTransactionManager() != null)
+ {
+ try
+ {
+ ci.getTransactionManager().rollback();
+ }
+ catch (Exception e)
+ {
+ // don't care
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * For testing only - introspects a cache and extracts the ComponentRegistry
+ *
+ * @param cache cache to introspect
+ * @return component registry
+ */
+ public static ComponentRegistry extractComponentRegistry(Cache cache)
+ {
+ return (ComponentRegistry) extractField(cache, "componentRegistry");
+ }
+
+ public static LockManager extractLockManager(Cache cache)
+ {
+ return extractComponentRegistry(cache).getComponent(LockManager.class);
+ }
+
+ /**
+ * For testing only - introspects a cache and extracts the ComponentRegistry
+ *
+ * @param ci interceptor chain to introspect
+ * @return component registry
+ */
+ public static ComponentRegistry extractComponentRegistry(InterceptorChain ci)
+ {
+ return (ComponentRegistry) extractField(ci, "componentRegistry");
+ }
+
+
+ /**
+ * Replaces the existing interceptor chain in the cache wih one represented by the interceptor passed in. This
+ * utility updates dependencies on all components that rely on the interceptor chain as well.
+ *
+ * @param cache cache that needs to be altered
+ * @param interceptor the first interceptor in the new chain.
+ */
+ public static void replaceInterceptorChain(CacheSPI<?, ?> cache, CommandInterceptor interceptor)
+ {
+ ComponentRegistry cr = extractComponentRegistry(cache);
+ // make sure all interceptors here are wired.
+ CommandInterceptor i = interceptor;
+ do
+ {
+ cr.wireDependencies(i);
+ }
+ while ((i = i.getNext()) != null);
+
+ InterceptorChain inch = cr.getComponent(InterceptorChain.class);
+ inch.setFirstInChain(interceptor);
+ }
+
+ /**
+ * Retrieves the remote delegate for a given cache. It is on this remote delegate that the JGroups RPCDispatcher
+ * invokes remote methods.
+ *
+ * @param cache cache instance for which a remote delegate is to be retrieved
+ * @return remote delegate, or null if the cacge is not configured for replication.
+ */
+ public static CacheInvocationDelegate getInvocationDelegate(CacheSPI cache)
+ {
+ ComponentRegistry cr = extractComponentRegistry(cache);
+ return cr.getComponent(CacheInvocationDelegate.class);
+ }
+
+ /**
+ * Blocks until the cache has reached a specified state.
+ *
+ * @param cache cache to watch
+ * @param cacheStatus status to wait for
+ * @param timeout timeout to wait for
+ */
+ public static void blockUntilCacheStatusAchieved(Cache cache, CacheStatus cacheStatus, long timeout)
+ {
+ CacheSPI spi = (CacheSPI) cache;
+ long killTime = System.currentTimeMillis() + timeout;
+ while (System.currentTimeMillis() < killTime)
+ {
+ if (spi.getCacheStatus() == cacheStatus) return;
+ sleepThread(50);
+ }
+ throw new RuntimeException("Timed out waiting for condition");
+ }
+
+ public static void replicateCommand(CacheSPI cache, VisitableCommand command) throws Throwable
+ {
+ ComponentRegistry cr = extractComponentRegistry(cache);
+ InterceptorChain ic = cr.getComponent(InterceptorChain.class);
+ ic.invoke(command);
+ }
+
+ public static void blockUntilViewsReceived(int timeout, List caches)
+ {
+ blockUntilViewsReceived((Cache[]) caches.toArray(new Cache[]{}), timeout);
+ }
+
+
+ public static CommandsFactory extractCommandsFactory(CacheSPI<Object, Object> cache)
+ {
+ return (CommandsFactory) extractField(cache, "commandsFactory");
+ }
+
+ public static String getJGroupsAttribute(Cache cache, String protocol, String attribute)
+ {
+ String s = ((JChannel) ((CacheSPI) cache).getRPCManager().getChannel()).getProperties();
+ String[] protocols = s.split(":");
+ String attribs = null;
+ for (String p : protocols)
+ {
+ boolean hasAttribs = p.contains("(");
+ String name = hasAttribs ? p.substring(0, p.indexOf('(')) : p;
+ attribs = hasAttribs ? p.substring(p.indexOf('(') + 1, p.length() - 1) : null;
+
+ if (name.equalsIgnoreCase(protocol)) break;
+ }
+
+ if (attribs != null)
+ {
+ String[] attrArray = attribs.split(";");
+ for (String a : attrArray)
+ {
+ String[] kvPairs = a.split("=");
+ if (kvPairs[0].equalsIgnoreCase(attribute)) return kvPairs[1];
+ }
+ }
+ return null;
+ }
+
+ public static void dumpCacheContents(List caches)
+ {
+ System.out.println("**** START: Cache Contents ****");
+ int count = 1;
+ for (Object o : caches)
+ {
+ CacheSPI c = (CacheSPI) o;
+ if (c == null)
+ {
+ System.out.println(" ** Cache " + count + " is null!");
+ }
+ else
+ {
+ System.out.println(" ** Cache " + count + " is " + c.getRPCManager().getLocalAddress());
+// System.out.println(" " + CachePrinter.printCacheDetails(c));
+ }
+ count++;
+ }
+ System.out.println("**** END: Cache Contents ****");
+ }
+
+ public static void dumpCacheContents(Cache... caches)
+ {
+ dumpCacheContents(Arrays.asList(caches));
+ }
+}
17 years, 2 months
JBoss Cache SVN: r6896 - in core/branches/flat/src/main/java/org/jboss: cache/interceptors and 5 other directories.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2008-10-09 08:52:15 -0400 (Thu, 09 Oct 2008)
New Revision: 6896
Added:
core/branches/flat/src/main/java/org/jboss/starobrno/batch/
core/branches/flat/src/main/java/org/jboss/starobrno/batch/BatchContainer.java
core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java
Removed:
core/branches/flat/src/main/java/org/jboss/cache/batch/BatchContainer.java
core/branches/flat/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/OrderedSynchronizationHandler.java
Modified:
core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
core/branches/flat/src/main/java/org/jboss/starobrno/Cache.java
core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java
core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java
Log:
baching support added
Deleted: core/branches/flat/src/main/java/org/jboss/cache/batch/BatchContainer.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/batch/BatchContainer.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/cache/batch/BatchContainer.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -1,101 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.batch;
-
-import org.jboss.starobrno.CacheException;
-import org.jboss.starobrno.factories.annotations.Inject;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-
-/**
- * A container for holding thread locals for batching, to be used with the {@link org.jboss.cache.Cache_Legacy#startBatch()} and
- * {@link org.jboss.cache.Cache_Legacy#endBatch(boolean)} calls.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @since 3.0
- */
-public class BatchContainer
-{
- TransactionManager transactionManager;
- private ThreadLocal<Transaction> batchTransactionContainer = new ThreadLocal<Transaction>();
-
- @Inject
- void inject(TransactionManager transactionManager)
- {
- this.transactionManager = transactionManager;
- }
-
- public void startBatch() throws CacheException
- {
- try
- {
- if (transactionManager.getTransaction() != null) return;
- if (batchTransactionContainer.get() == null)
- {
- transactionManager.begin();
- batchTransactionContainer.set(transactionManager.suspend());
- }
- }
- catch (Exception e)
- {
- throw new CacheException("Unable to start batch", e);
- }
- }
-
- public void endBatch(boolean success)
- {
- Transaction tx = batchTransactionContainer.get();
- if (tx == null) return;
- Transaction existingTx = null;
- try
- {
- existingTx = transactionManager.getTransaction();
- transactionManager.resume(tx);
- if (success)
- tx.commit();
- else
- tx.rollback();
- }
- catch (Exception e)
- {
- throw new CacheException("Unable to end batch", e);
- }
- finally
- {
- batchTransactionContainer.remove();
- try
- {
- if (existingTx != null) transactionManager.resume(existingTx);
- }
- catch (Exception e)
- {
- throw new CacheException("Failed resuming existing transaction " + existingTx, e);
- }
- }
- }
-
- public Transaction getBatchTransaction()
- {
- return batchTransactionContainer.get();
- }
-}
Deleted: core/branches/flat/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -1,79 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.cache.interceptors;
-
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.batch.BatchContainer;
-import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.interceptors.base.CommandInterceptor;
-import org.jboss.starobrno.factories.annotations.Inject;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-
-/**
- * Interceptor that captures batched calls and attaches contexts.
- *
- * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
- * @since 3.0
- */
-public class BatchingInterceptor extends CommandInterceptor
-{
- BatchContainer batchContainer;
- TransactionManager transactionManager;
-
- @Inject
- private void inject(BatchContainer batchContainer, TransactionManager transactionManager)
- {
- this.batchContainer = batchContainer;
- this.transactionManager = transactionManager;
- }
-
- /**
- * Simply check if there is an ongoing tx.
- * <ul>
- * <li>If there is one, this is a no-op and just passes the call up the chain.</li>
- * <li>If there isn't one and there is a batch in progress, resume the batch's tx, pass up, and finally suspend the batch's tx.</li>
- * <li>If there is no batch in progress, just pass the call up the chain.</li>
- * </ul>
- */
- @Override
- protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
- {
- Transaction tx = null;
- try
- {
- // if in a batch, attach tx
- if (transactionManager.getTransaction() == null &&
- (tx = batchContainer.getBatchTransaction()) != null)
- {
- transactionManager.resume(tx);
- }
- return super.handleDefault(ctx, command);
- }
- finally
- {
- if (tx != null && transactionManager.getTransaction() != null)
- transactionManager.suspend();
- }
- }
-}
Modified: core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/cache/invocation/CacheInvocationDelegate.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -34,7 +34,7 @@
import org.jboss.cache.Region;
import org.jboss.cache.RegionManager;
import org.jboss.cache.Version;
-import org.jboss.cache.batch.BatchContainer;
+import org.jboss.starobrno.batch.BatchContainer;
import org.jboss.cache.buddyreplication.BuddyManager;
import org.jboss.cache.buddyreplication.GravitateResult;
import org.jboss.cache.commands.CommandsFactory;
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/Cache.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/Cache.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/Cache.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -53,4 +53,8 @@
AtomicGroup getAtomicGroup(K key);
CacheStatus getCacheStatus();
+
+ public void startBatch();
+
+ public void endBatch(boolean successful);
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -38,6 +38,7 @@
import org.jboss.starobrno.commands.write.RemoveCommand;
import org.jboss.starobrno.commands.write.ReplaceCommand;
import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.config.ConfigurationException;
import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.ComponentRegistry;
import org.jboss.starobrno.factories.annotations.Inject;
@@ -47,6 +48,7 @@
import org.jboss.starobrno.notifications.Notifier;
import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jboss.starobrno.transaction.TransactionTable;
+import org.jboss.starobrno.batch.BatchContainer;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
@@ -66,6 +68,7 @@
protected InterceptorChain invoker;
protected Configuration config;
protected Notifier notifier;
+ private BatchContainer batchContainer;
protected ComponentRegistry componentRegistry;
@Inject
@@ -336,4 +339,18 @@
{
return componentRegistry.getState();
}
+
+ public void startBatch()
+ {
+ if (!config.isInvocationBatchingEnabled())
+ throw new ConfigurationException("Invocation batching not enabled in current configuration! Please use the <invocationBatching /> element.");
+ batchContainer.startBatch();
+ }
+
+ public void endBatch(boolean successful)
+ {
+ if (!config.isInvocationBatchingEnabled())
+ throw new ConfigurationException("Invocation batching not enabled in current configuration! Please use the <invocationBatching /> element.");
+ batchContainer.endBatch(successful);
+ }
}
Deleted: core/branches/flat/src/main/java/org/jboss/starobrno/OrderedSynchronizationHandler.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/OrderedSynchronizationHandler.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/OrderedSynchronizationHandler.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -1,119 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source.
- * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
- * as indicated by the @author tags. See the copyright.txt file in the
- * distribution for a full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software 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 software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.starobrno;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import javax.transaction.RollbackException;
-import javax.transaction.Synchronization;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import java.util.LinkedList;
-
-/**
- * Maintains a list of Synchronization handlers. Reason is that we have to
- * invoke certain handlers <em>before</em> others. See the description in
- * SyncTxUnitTestCase.testConcurrentPuts(). For example, for synchronous
- * replication, we have to execute the ReplicationInterceptor's
- * afterCompletion() <em>before</em> the TransactionInterceptor's.
- *
- * @author Bela Ban
- * @version $Id$
- */
-public class OrderedSynchronizationHandler implements Synchronization
-{
- static final Log log = LogFactory.getLog(org.jboss.cache.interceptors.OrderedSynchronizationHandler.class);
-
- private Transaction tx = null;
- private final LinkedList<Synchronization> handlers = new LinkedList<Synchronization>();
-
- public OrderedSynchronizationHandler(Transaction tx) throws SystemException, RollbackException
- {
- this.tx = tx;
- tx.registerSynchronization(this);
- }
-
- public void registerAtHead(Synchronization handler)
- {
- register(handler, true);
- }
-
- public void registerAtTail(Synchronization handler)
- {
- register(handler, false);
- }
-
- void register(Synchronization handler, boolean head)
- {
- if (handler != null && !handlers.contains(handler))
- {
- if (head)
- handlers.addFirst(handler);
- else
- handlers.addLast(handler);
- }
- }
-
- public void beforeCompletion()
- {
- for (Synchronization sync : handlers)
- {
- sync.beforeCompletion();
- }
- }
-
- public void afterCompletion(int status)
- {
- RuntimeException exceptionInAfterCompletion = null;
- for (Synchronization sync : handlers)
- {
- try
- {
- sync.afterCompletion(status);
- }
- catch (Throwable t)
- {
- log.error("failed calling afterCompletion() on " + sync, t);
- exceptionInAfterCompletion = (RuntimeException) t;
- }
- }
-
- // throw the exception so the TM can deal with it.
- if (exceptionInAfterCompletion != null) throw exceptionInAfterCompletion;
- }
-
- @Override
- public String toString()
- {
- return "tx=" + getTxAsString() + ", handlers=" + handlers;
- }
-
- private String getTxAsString()
- {
- // JBCACHE-1114 -- don't call toString() on tx or it can lead to stack overflow
- if (tx == null)
- return null;
-
- return tx.getClass().getName() + "@" + System.identityHashCode(tx);
- }
-}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/TxInterceptor.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -39,20 +39,13 @@
import org.jboss.starobrno.jmx.annotations.ManagedAttribute;
import org.jboss.starobrno.jmx.annotations.ManagedOperation;
import org.jboss.starobrno.lock.LockManager;
-import org.jboss.starobrno.notifier.Notifier;
+import org.jboss.starobrno.notifications.Notifier;
import org.jboss.starobrno.transaction.GlobalTransaction;
+import org.jboss.starobrno.transaction.OrderedSynchronizationHandler;
import org.jboss.starobrno.transaction.TransactionTable;
-import javax.transaction.InvalidTransactionException;
-import javax.transaction.Status;
-import javax.transaction.Synchronization;
-import javax.transaction.SystemException;
-import javax.transaction.Transaction;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import javax.transaction.*;
+import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
/**
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/batch/BatchContainer.java (from rev 6895, core/branches/flat/src/main/java/org/jboss/cache/batch/BatchContainer.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/batch/BatchContainer.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/batch/BatchContainer.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -0,0 +1,101 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.batch;
+
+import org.jboss.starobrno.CacheException;
+import org.jboss.starobrno.factories.annotations.Inject;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+/**
+ * A container for holding thread locals for batching, to be used with the {@link org.jboss.cache.Cache_Legacy#startBatch()} and
+ * {@link org.jboss.cache.Cache_Legacy#endBatch(boolean)} calls.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class BatchContainer
+{
+ TransactionManager transactionManager;
+ private ThreadLocal<Transaction> batchTransactionContainer = new ThreadLocal<Transaction>();
+
+ @Inject
+ void inject(TransactionManager transactionManager)
+ {
+ this.transactionManager = transactionManager;
+ }
+
+ public void startBatch() throws CacheException
+ {
+ try
+ {
+ if (transactionManager.getTransaction() != null) return;
+ if (batchTransactionContainer.get() == null)
+ {
+ transactionManager.begin();
+ batchTransactionContainer.set(transactionManager.suspend());
+ }
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to start batch", e);
+ }
+ }
+
+ public void endBatch(boolean success)
+ {
+ Transaction tx = batchTransactionContainer.get();
+ if (tx == null) return;
+ Transaction existingTx = null;
+ try
+ {
+ existingTx = transactionManager.getTransaction();
+ transactionManager.resume(tx);
+ if (success)
+ tx.commit();
+ else
+ tx.rollback();
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Unable to end batch", e);
+ }
+ finally
+ {
+ batchTransactionContainer.remove();
+ try
+ {
+ if (existingTx != null) transactionManager.resume(existingTx);
+ }
+ catch (Exception e)
+ {
+ throw new CacheException("Failed resuming existing transaction " + existingTx, e);
+ }
+ }
+ }
+
+ public Transaction getBatchTransaction()
+ {
+ return batchTransactionContainer.get();
+ }
+}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java 2008-10-09 09:55:17 UTC (rev 6895)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/factories/EmptyConstructorFactory.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -23,7 +23,7 @@
import org.jboss.cache.RegionRegistry;
-import org.jboss.cache.batch.BatchContainer;
+import org.jboss.starobrno.batch.BatchContainer;
import org.jboss.cache.buddyreplication.BuddyFqnTransformer;
import org.jboss.cache.invocation.CacheInvocationDelegate;
import org.jboss.cache.loader.CacheLoaderManager;
Copied: core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java (from rev 6895, core/branches/flat/src/main/java/org/jboss/cache/interceptors/BatchingInterceptor.java)
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java (rev 0)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/interceptors/BatchingInterceptor.java 2008-10-09 12:52:15 UTC (rev 6896)
@@ -0,0 +1,79 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2000 - 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software 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 software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.starobrno.interceptors;
+
+import org.jboss.cache.InvocationContext;
+import org.jboss.starobrno.batch.BatchContainer;
+import org.jboss.cache.commands.VisitableCommand;
+import org.jboss.cache.interceptors.base.CommandInterceptor;
+import org.jboss.starobrno.factories.annotations.Inject;
+
+import javax.transaction.Transaction;
+import javax.transaction.TransactionManager;
+
+/**
+ * Interceptor that captures batched calls and attaches contexts.
+ *
+ * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik(a)jboss.org</a>)
+ * @since 3.0
+ */
+public class BatchingInterceptor extends CommandInterceptor
+{
+ BatchContainer batchContainer;
+ TransactionManager transactionManager;
+
+ @Inject
+ private void inject(BatchContainer batchContainer, TransactionManager transactionManager)
+ {
+ this.batchContainer = batchContainer;
+ this.transactionManager = transactionManager;
+ }
+
+ /**
+ * Simply check if there is an ongoing tx.
+ * <ul>
+ * <li>If there is one, this is a no-op and just passes the call up the chain.</li>
+ * <li>If there isn't one and there is a batch in progress, resume the batch's tx, pass up, and finally suspend the batch's tx.</li>
+ * <li>If there is no batch in progress, just pass the call up the chain.</li>
+ * </ul>
+ */
+ @Override
+ protected Object handleDefault(InvocationContext ctx, VisitableCommand command) throws Throwable
+ {
+ Transaction tx = null;
+ try
+ {
+ // if in a batch, attach tx
+ if (transactionManager.getTransaction() == null &&
+ (tx = batchContainer.getBatchTransaction()) != null)
+ {
+ transactionManager.resume(tx);
+ }
+ return super.handleDefault(ctx, command);
+ }
+ finally
+ {
+ if (tx != null && transactionManager.getTransaction() != null)
+ transactionManager.suspend();
+ }
+ }
+}
17 years, 2 months
JBoss Cache SVN: r6895 - in core/branches/flat/src/main/java/org/jboss: starobrno and 2 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-09 05:55:17 -0400 (Thu, 09 Oct 2008)
New Revision: 6895
Modified:
core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferGenerator.java
core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java
core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/MVCCEntryWrapper.java
core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/NullMarkerEntry.java
core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/ReadCommittedEntry.java
core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/RepeatableReadEntry.java
Log:
Several pints of Starobrno
Modified: core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferGenerator.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferGenerator.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferGenerator.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -31,7 +31,6 @@
import org.jboss.cache.loader.CacheLoader;
import org.jboss.cache.marshall.NodeData;
import org.jboss.cache.marshall.NodeDataExceptionMarker;
-import org.jboss.starobrno.factories.annotations.Start;
import java.io.IOException;
import java.io.ObjectOutputStream;
@@ -58,11 +57,11 @@
// this.cache = cache;
// }
- @Start(priority = 14)
- private void start()
- {
- this.internalFqns = cache.getInternalFqns();
- }
+// @Start(priority = 14)
+// private void start()
+// {
+// this.internalFqns = cache.getInternalFqns();
+// }
public void generateState(ObjectOutputStream out, Object rootNode, boolean generateTransient,
boolean generatePersistent, boolean suppressErrors) throws Exception
Modified: core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/cache/statetransfer/DefaultStateTransferIntegrator.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -70,10 +70,11 @@
this.cfg = cfg;
}
+
@Start(priority = 14)
public void start()
{
- this.internalFqns = cache.getInternalFqns();
+// this.internalFqns = cache.getInternalFqns();
needToPersistState = cfg.getCacheLoaderConfig() != null && !cfg.getCacheLoaderConfig().isFetchPersistentState() &&
!cfg.getCacheLoaderConfig().isShared();
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -149,7 +149,8 @@
public V remove(Object key)
{
RemoveCommand command = commandsFactory.buildRemoveCommand(key, null);
- return (V) invoker.invoke(buildCtx(), command);
+ V oldval = (V) invoker.invoke(buildCtx(), command);
+ return oldval;
}
public void putAll(Map<? extends K, ? extends V> t)
@@ -328,7 +329,7 @@
public ComponentRegistry getComponentRegistry()
{
- return null; //TODO: Autogenerated. Implement me properly
+ return componentRegistry;
}
public CacheStatus getCacheStatus()
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -51,13 +51,13 @@
return visitor.visitRemoveCommand(ctx, this);
}
- public Boolean perform(InvocationContext ctx) throws Throwable
+ public Object perform(InvocationContext ctx) throws Throwable
{
MVCCEntry e = ctx.lookupEntry(key);
- if (e == null || e.isNullEntry()) return false;
+ if (e == null || e.isNullEntry()) return null;
e.setDeleted(true);
e.setValid(false);
- return true;
+ return e.getValue();
}
public int getCommandId()
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/MVCCEntryWrapper.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/MVCCEntryWrapper.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/MVCCEntryWrapper.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -139,7 +139,7 @@
{
// now to lock and create the node. Lock first to prevent concurrent creation!
acquireLock(ctx, key);
- entry = entryFactory.createEntry(key, null, true);
+ entry = entryFactory.createEntry(key, null, false);
mvccEntry = entryFactory.createWrappedEntry(entry);
mvccEntry.setCreated(true);
ctx.putLookedUpEntry(mvccEntry);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/NullMarkerEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/NullMarkerEntry.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/NullMarkerEntry.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -32,11 +32,18 @@
*/
public class NullMarkerEntry extends RepeatableReadEntry
{
+ private static final Object NULL = new Object();
+
public NullMarkerEntry()
{
super(null);
}
+ public Object getKey()
+ {
+ return NULL;
+ }
+
/**
* @return always returns true
*/
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/ReadCommittedEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/ReadCommittedEntry.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/ReadCommittedEntry.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -147,7 +147,14 @@
if (trace)
log.trace("Updating entry [" + getKey() + "]. deleted=" + isDeleted() + " valid=" + isValid() + " changed=" + isChanged() + " created=" + isFlagSet(CREATED));
updateEntry(container);
- container.putEntry(entry);
+ if (isFlagSet(DELETED))
+ {
+ container.removeEntry(getKey());
+ }
+ else
+ {
+ container.putEntry(entry);
+ }
reset();
}
}
@@ -170,7 +177,6 @@
{
// swap refs
if (!isFlagSet(CREATED)) ((EntryReference) backup).setDelegate(entry);
- entry = backup;
}
public void rollbackUpdate()
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/RepeatableReadEntry.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/RepeatableReadEntry.java 2008-10-09 09:31:22 UTC (rev 6894)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/mvcc/RepeatableReadEntry.java 2008-10-09 09:55:17 UTC (rev 6895)
@@ -75,6 +75,6 @@
@SuppressWarnings("unchecked")
protected void updateEntry(DataContainer dataContainer)
{
- entry = backup;
+ // do nothing
}
}
\ No newline at end of file
17 years, 2 months
JBoss Cache SVN: r6894 - in core/branches/flat/src/main/java/org/jboss/starobrno/commands: tx and 1 other directories.
by jbosscache-commits@lists.jboss.org
Author: mircea.markus
Date: 2008-10-09 05:31:22 -0400 (Thu, 09 Oct 2008)
New Revision: 6894
Modified:
core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/AbstractTransactionBoundaryCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/CommitCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/RollbackCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java
Log:
added hash codes etc
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/AbstractDataCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -59,4 +59,21 @@
{
return new Object[]{key};
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ AbstractDataCommand that = (AbstractDataCommand) o;
+
+ if (key != null ? !key.equals(that.key) : that.key != null) return false;
+
+ return true;
+ }
+
+ public int hashCode()
+ {
+ return (key != null ? key.hashCode() : 0);
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/AbstractTransactionBoundaryCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/AbstractTransactionBoundaryCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/AbstractTransactionBoundaryCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -45,13 +45,6 @@
this.gtx = gtx;
}
- /**
- * This is a no-op.
- *
- * @param ctx
- * @return
- * @throws Throwable
- */
public Object perform(InvocationContext ctx) throws Throwable
{
return null;
@@ -66,4 +59,21 @@
{
gtx = (GlobalTransaction) args[0];
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ AbstractTransactionBoundaryCommand that = (AbstractTransactionBoundaryCommand) o;
+
+ if (gtx != null ? !gtx.equals(that.gtx) : that.gtx != null) return false;
+
+ return true;
+ }
+
+ public int hashCode()
+ {
+ return (gtx != null ? gtx.hashCode() : 0);
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/CommitCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/CommitCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/CommitCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -54,4 +54,10 @@
return METHOD_ID;
}
+ public String toString()
+ {
+ return "CommitCommand {" +
+ "gtx=" + gtx +
+ '}';
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/RollbackCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/RollbackCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/tx/RollbackCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -54,4 +54,10 @@
return METHOD_ID;
}
+ public String toString()
+ {
+ return "RollbackCommand{" +
+ "gtx=" + gtx +
+ '}';
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/EvictCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -57,4 +57,12 @@
{
return METHOD_ID;
}
+
+
+ public String toString()
+ {
+ return "AbstractDataCommand{" +
+ "key=" + key +
+ '}';
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -87,4 +87,36 @@
{
this.putIfAbsent = putIfAbsent;
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (!(o instanceof PutKeyValueCommand)) return false;
+ if (!super.equals(o)) return false;
+
+ PutKeyValueCommand that = (PutKeyValueCommand) o;
+
+ if (putIfAbsent != that.putIfAbsent) return false;
+ if (value != null ? !value.equals(that.value) : that.value != null) return false;
+
+ return true;
+ }
+
+ public int hashCode()
+ {
+ int result = super.hashCode();
+ result = 31 * result + (value != null ? value.hashCode() : 0);
+ result = 31 * result + (putIfAbsent ? 1 : 0);
+ return result;
+ }
+
+
+ public String toString()
+ {
+ return "PutKeyValueCommand{" +
+ "key= " + key +
+ ", value=" + value +
+ ", putIfAbsent=" + putIfAbsent +
+ '}';
+ }
}
\ No newline at end of file
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutMapCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -82,4 +82,29 @@
if (commandId != METHOD_ID) throw new IllegalStateException("Invalid method id");
map = (Map) parameters[0];
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (!(o instanceof PutMapCommand)) return false;
+
+ PutMapCommand that = (PutMapCommand) o;
+
+ if (map != null ? !map.equals(that.map) : that.map != null) return false;
+
+ return true;
+ }
+
+ public int hashCode()
+ {
+ return (map != null ? map.hashCode() : 0);
+ }
+
+
+ public String toString()
+ {
+ return "PutMapCommand{" +
+ "map=" + map +
+ '}';
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -64,4 +64,33 @@
{
return METHOD_ID;
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (!(o instanceof RemoveCommand)) return false;
+ if (!super.equals(o)) return false;
+
+ RemoveCommand that = (RemoveCommand) o;
+
+ if (value != null ? !value.equals(that.value) : that.value != null) return false;
+
+ return true;
+ }
+
+ public int hashCode()
+ {
+ int result = super.hashCode();
+ result = 31 * result + (value != null ? value.hashCode() : 0);
+ return result;
+ }
+
+
+ public String toString()
+ {
+ return "RemoveCommand{" +
+ "key=" + key +
+ ", value=" + value +
+ '}';
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/ReplaceCommand.java 2008-10-09 09:31:22 UTC (rev 6894)
@@ -82,4 +82,35 @@
oldValue = parameters[1];
newValue = parameters[2];
}
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ if (!(o instanceof ReplaceCommand)) return false;
+ if (!super.equals(o)) return false;
+
+ ReplaceCommand that = (ReplaceCommand) o;
+
+ if (newValue != null ? !newValue.equals(that.newValue) : that.newValue != null) return false;
+ if (oldValue != null ? !oldValue.equals(that.oldValue) : that.oldValue != null) return false;
+
+ return true;
+ }
+
+ public int hashCode()
+ {
+ int result = super.hashCode();
+ result = 31 * result + (oldValue != null ? oldValue.hashCode() : 0);
+ result = 31 * result + (newValue != null ? newValue.hashCode() : 0);
+ return result;
+ }
+
+ public String toString()
+ {
+ return "ReplaceCommand{" +
+ "key=" + key +
+ ", oldValue=" + oldValue +
+ ", newValue=" + newValue +
+ '}';
+ }
}
17 years, 2 months
JBoss Cache SVN: r6893 - in core/branches/flat/src/main/java/org/jboss: cache/marshall and 5 other directories.
by jbosscache-commits@lists.jboss.org
Author: manik.surtani(a)jboss.com
Date: 2008-10-09 05:27:58 -0400 (Thu, 09 Oct 2008)
New Revision: 6893
Modified:
core/branches/flat/src/main/java/org/jboss/cache/RPCManagerImpl.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java
core/branches/flat/src/main/java/org/jboss/cache/marshall/RegionalizedMethodCall.java
core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactory.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
core/branches/flat/src/main/java/org/jboss/starobrno/factories/ComponentRegistry.java
Log:
Several pints of Starobrno
Modified: core/branches/flat/src/main/java/org/jboss/cache/RPCManagerImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/cache/RPCManagerImpl.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -32,7 +32,6 @@
import org.jboss.cache.lock.LockManager;
import org.jboss.cache.lock.TimeoutException;
import org.jboss.cache.marshall.CommandAwareRpcDispatcher;
-import org.jboss.cache.marshall.InactiveRegionAwareRpcDispatcher;
import org.jboss.cache.marshall.Marshaller;
import org.jboss.cache.remoting.jgroups.ChannelMessageListener;
import org.jboss.cache.statetransfer.DefaultStateTransferManager;
@@ -305,7 +304,7 @@
channel.setOpt(Channel.AUTO_RECONNECT, true);
channel.setOpt(Channel.AUTO_GETSTATE, fetchState);
channel.setOpt(Channel.BLOCK, true);
-
+ /*
if (configuration.isUseRegionBasedMarshalling())
{
rpcDispatcher = new InactiveRegionAwareRpcDispatcher(channel, messageListener, new MembershipListenerAdaptor(),
@@ -316,6 +315,7 @@
rpcDispatcher = new CommandAwareRpcDispatcher(channel, messageListener, new MembershipListenerAdaptor(),
invocationContextContainer, invocationContextContainer, interceptorChain, componentRegistry);
}
+ */
checkAppropriateConfig();
rpcDispatcher.setRequestMarshaller(marshaller);
rpcDispatcher.setResponseMarshaller(marshaller);
@@ -452,7 +452,7 @@
throw new TimeoutException("State retrieval timed out waiting for flush unblock.");
}
useOutOfBandMessage = false;
- RspList rsps = rpcDispatcher.invokeRemoteCommands(recipients, command, modeToUse, timeout, isUsingBuddyReplication, useOutOfBandMessage, responseFilter);
+ RspList rsps = null;//rpcDispatcher.invokeRemoteCommands(recipients, command, modeToUse, timeout, isUsingBuddyReplication, useOutOfBandMessage, responseFilter);
if (mode == GroupRequest.GET_NONE) return Collections.emptyList();// async case
if (trace)
log.trace("(" + getLocalAddress() + "): responses for method " + command.getClass().getSimpleName() + ":\n" + rsps);
Modified: core/branches/flat/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/AbstractMarshaller.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -25,37 +25,16 @@
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.RegionManager;
-import org.jboss.cache.commands.DataCommand;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.commands.WriteCommand;
-import org.jboss.cache.commands.read.ExistsCommand;
-import org.jboss.cache.commands.read.GetChildrenNamesCommand;
-import org.jboss.cache.commands.read.GetDataMapCommand;
-import org.jboss.cache.commands.read.GetKeyValueCommand;
-import org.jboss.cache.commands.read.GetKeysCommand;
-import org.jboss.cache.commands.read.GravitateDataCommand;
-import org.jboss.cache.commands.remote.AnnounceBuddyPoolNameCommand;
-import org.jboss.cache.commands.remote.AssignToBuddyGroupCommand;
-import org.jboss.cache.commands.remote.ClusteredGetCommand;
-import org.jboss.cache.commands.remote.DataGravitationCleanupCommand;
-import org.jboss.cache.commands.remote.RemoveFromBuddyGroupCommand;
-import org.jboss.cache.commands.remote.ReplicateCommand;
-import org.jboss.cache.commands.tx.AbstractTransactionCommand;
-import org.jboss.cache.commands.tx.CommitCommand;
-import org.jboss.cache.commands.tx.PrepareCommand;
-import org.jboss.cache.commands.tx.RollbackCommand;
-import org.jboss.cache.commands.write.EvictCommand;
-import org.jboss.cache.commands.write.InvalidateCommand;
import org.jboss.cache.io.ByteBuffer;
-import org.jboss.cache.transaction.GlobalTransaction;
+import org.jboss.starobrno.commands.ReplicableCommand;
import org.jboss.starobrno.config.Configuration;
import org.jboss.starobrno.factories.annotations.Inject;
import org.jboss.starobrno.factories.annotations.Start;
+import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jgroups.util.Buffer;
import java.io.InputStream;
import java.io.ObjectInputStream;
-import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -143,6 +122,9 @@
protected Fqn extractFqn(ReplicableCommand cmd)
{
+ throw new UnsupportedOperationException("fix me"); // todo fix me!
+ /*
+
if (cmd == null) throw new NullPointerException("Command is null");
Fqn fqn = null;
@@ -214,5 +196,6 @@
if (trace) log.trace("extract(): received " + cmd + "extracted fqn: " + fqn);
return fqn;
+ */
}
}
Modified: core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/CacheMarshaller200.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -25,13 +25,13 @@
import org.jboss.cache.Region;
import org.jboss.cache.Region.Status;
import org.jboss.cache.buddyreplication.GravitateResult;
-import org.jboss.cache.commands.CommandsFactory;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.transaction.GlobalTransaction;
import org.jboss.cache.util.FastCopyHashMap;
import org.jboss.cache.util.Immutables;
import org.jboss.starobrno.CacheException;
+import org.jboss.starobrno.commands.CommandsFactory;
+import org.jboss.starobrno.commands.ReplicableCommand;
import org.jboss.starobrno.factories.annotations.Inject;
+import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jgroups.Address;
import org.jgroups.stack.IpAddress;
@@ -691,7 +691,7 @@
for (int i = 0; i < numArgs; i++) args[i] = unmarshallObject(in, refMap);
}
- return commandsFactory.fromStream(methodId, args);
+ return commandsFactory.fromStream((byte) methodId, args);
}
private GlobalTransaction unmarshallGlobalTransaction(ObjectInputStream in, UnmarshalledReferences refMap) throws Exception
Modified: core/branches/flat/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/CommandAwareRpcDispatcher.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -21,17 +21,17 @@
*/
package org.jboss.cache.marshall;
-import org.jboss.cache.InvocationContext;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.commands.VisitableCommand;
-import org.jboss.cache.commands.remote.AnnounceBuddyPoolNameCommand;
-import org.jboss.cache.commands.remote.AssignToBuddyGroupCommand;
-import org.jboss.cache.commands.remote.RemoveFromBuddyGroupCommand;
-import org.jboss.cache.interceptors.InterceptorChain;
-import org.jboss.cache.invocation.InvocationContextContainer;
import org.jboss.cache.util.concurrent.WithinThreadExecutor;
+import org.jboss.starobrno.commands.ReplicableCommand;
+import org.jboss.starobrno.commands.VisitableCommand;
+import org.jboss.starobrno.commands.remote.AnnounceBuddyPoolNameCommand;
+import org.jboss.starobrno.commands.remote.AssignToBuddyGroupCommand;
+import org.jboss.starobrno.commands.remote.RemoveFromBuddyGroupCommand;
import org.jboss.starobrno.config.Configuration;
+import org.jboss.starobrno.context.InvocationContext;
import org.jboss.starobrno.factories.ComponentRegistry;
+import org.jboss.starobrno.interceptors.InterceptorChain;
+import org.jboss.starobrno.invocation.InvocationContextContainer;
import org.jgroups.Address;
import org.jgroups.Channel;
import org.jgroups.MembershipListener;
Modified: core/branches/flat/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/InactiveRegionAwareRpcDispatcher.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -21,10 +21,10 @@
*/
package org.jboss.cache.marshall;
-import org.jboss.cache.commands.ReplicableCommand;
-import org.jboss.cache.interceptors.InterceptorChain;
-import org.jboss.cache.invocation.InvocationContextContainer;
+import org.jboss.starobrno.commands.ReplicableCommand;
import org.jboss.starobrno.factories.ComponentRegistry;
+import org.jboss.starobrno.interceptors.InterceptorChain;
+import org.jboss.starobrno.invocation.InvocationContextContainer;
import org.jgroups.Channel;
import org.jgroups.MembershipListener;
import org.jgroups.Message;
Modified: core/branches/flat/src/main/java/org/jboss/cache/marshall/RegionalizedMethodCall.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/cache/marshall/RegionalizedMethodCall.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/cache/marshall/RegionalizedMethodCall.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -22,7 +22,7 @@
package org.jboss.cache.marshall;
import org.jboss.cache.Fqn;
-import org.jboss.cache.commands.ReplicableCommand;
+import org.jboss.starobrno.commands.ReplicableCommand;
/**
* A regionalized MethodCall object, created when {@link Marshaller#regionalizedMethodCallFromByteBuffer(byte[])} or
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/CacheDelegate.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -125,7 +125,8 @@
public boolean containsKey(Object key)
{
GetKeyValueCommand command = commandsFactory.buildGetKeyValueCommand(key);
- return (Boolean) invoker.invoke(buildCtx(), command);
+ Object response = invoker.invoke(buildCtx(), command);
+ return response != null;
}
public boolean containsValue(Object value)
@@ -227,12 +228,12 @@
public void start()
{
- //TODO: Autogenerated. Implement me properly
+ componentRegistry.start();
}
public void stop()
{
- //TODO: Autogenerated. Implement me properly
+ componentRegistry.stop();
}
private InvocationContext buildCtx()
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactory.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactory.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactory.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -21,17 +21,22 @@
*/
package org.jboss.starobrno.commands;
-import org.jboss.starobrno.commands.write.*;
+import org.jboss.starobrno.commands.read.GetKeyValueCommand;
import org.jboss.starobrno.commands.read.SizeCommand;
-import org.jboss.starobrno.commands.read.GetKeyValueCommand;
+import org.jboss.starobrno.commands.tx.CommitCommand;
import org.jboss.starobrno.commands.tx.PrepareCommand;
import org.jboss.starobrno.commands.tx.RollbackCommand;
-import org.jboss.starobrno.commands.tx.CommitCommand;
+import org.jboss.starobrno.commands.write.ClearCommand;
+import org.jboss.starobrno.commands.write.EvictCommand;
+import org.jboss.starobrno.commands.write.PutKeyValueCommand;
+import org.jboss.starobrno.commands.write.PutMapCommand;
+import org.jboss.starobrno.commands.write.RemoveCommand;
+import org.jboss.starobrno.commands.write.ReplaceCommand;
import org.jboss.starobrno.transaction.GlobalTransaction;
import org.jgroups.Address;
+import java.util.List;
import java.util.Map;
-import java.util.List;
/**
* @author Mircea.Markus(a)jboss.com
@@ -59,4 +64,6 @@
CommitCommand buildCommitCommand(GlobalTransaction gtx);
RollbackCommand buildRollbackCommand(GlobalTransaction gtx);
+
+ ReplicableCommand fromStream(byte methodId, Object[] args);
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/CommandsFactoryImpl.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -21,6 +21,7 @@
*/
package org.jboss.starobrno.commands;
+import org.jboss.starobrno.CacheException;
import org.jboss.starobrno.commands.read.GetKeyValueCommand;
import org.jboss.starobrno.commands.read.SizeCommand;
import org.jboss.starobrno.commands.tx.CommitCommand;
@@ -110,4 +111,65 @@
{
return new RollbackCommand(gtx);
}
+
+ public ReplicableCommand fromStream(byte id, Object[] parameters)
+ {
+ ReplicableCommand command;
+ switch (id)
+ {
+ case PutKeyValueCommand.METHOD_ID:
+ {
+ PutKeyValueCommand c = new PutKeyValueCommand();
+ command = c;
+ break;
+ }
+ case RemoveCommand.METHOD_ID:
+ {
+ RemoveCommand c = new RemoveCommand();
+ command = c;
+ break;
+ }
+ case ReplaceCommand.METHOD_ID:
+ {
+ ReplaceCommand c = new ReplaceCommand();
+ command = c;
+ break;
+ }
+ case GetKeyValueCommand.METHOD_ID:
+ {
+ GetKeyValueCommand c = new GetKeyValueCommand();
+ command = c;
+ break;
+ }
+ case ClearCommand.METHOD_ID:
+ {
+ ClearCommand c = new ClearCommand();
+ command = c;
+ break;
+ }
+ case PrepareCommand.METHOD_ID:
+ {
+ PrepareCommand c = new PrepareCommand();
+ command = c;
+ break;
+ }
+ case CommitCommand.METHOD_ID:
+ {
+ CommitCommand c = new CommitCommand();
+ command = c;
+ break;
+ }
+ case RollbackCommand.METHOD_ID:
+ {
+ RollbackCommand c = new RollbackCommand();
+ command = c;
+ break;
+ }
+ default:
+ throw new CacheException("Unknown command id " + id + "!");
+ }
+
+ command.setParameters(id, parameters);
+ return command;
+ }
}
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/read/GetKeyValueCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -47,6 +47,10 @@
this.notifier = notifier;
}
+ public GetKeyValueCommand()
+ {
+ }
+
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
{
return visitor.visitGetKeyValueCommand(ctx, this);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/PutKeyValueCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -46,6 +46,10 @@
this.putIfAbsent = putIfAbsent;
}
+ public PutKeyValueCommand()
+ {
+ }
+
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
{
return visitor.visitPutKeyValueCommand(ctx, this);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/commands/write/RemoveCommand.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -30,7 +30,7 @@
/**
* @author Mircea.Markus(a)jboss.com
*/
-public class RemoveCommand extends AbstractDataCommand
+public class RemoveCommand extends AbstractDataCommand
{
public static final int METHOD_ID = 6;
@@ -42,6 +42,10 @@
this.value = value;
}
+ public RemoveCommand()
+ {
+ }
+
public Object acceptVisitor(InvocationContext ctx, Visitor visitor) throws Throwable
{
return visitor.visitRemoveCommand(ctx, this);
Modified: core/branches/flat/src/main/java/org/jboss/starobrno/factories/ComponentRegistry.java
===================================================================
--- core/branches/flat/src/main/java/org/jboss/starobrno/factories/ComponentRegistry.java 2008-10-09 08:56:47 UTC (rev 6892)
+++ core/branches/flat/src/main/java/org/jboss/starobrno/factories/ComponentRegistry.java 2008-10-09 09:27:58 UTC (rev 6893)
@@ -38,6 +38,7 @@
import org.jboss.starobrno.factories.annotations.NonVolatile;
import org.jboss.starobrno.factories.annotations.Start;
import org.jboss.starobrno.factories.annotations.Stop;
+import org.jboss.starobrno.lifecycle.Lifecycle;
import javax.management.MBeanServerFactory;
import java.lang.reflect.Method;
@@ -78,7 +79,7 @@
* @since 2.1.0
*/
@NonVolatile
-public class ComponentRegistry
+public class ComponentRegistry implements Lifecycle
{
/**
* Contains class definitions of component factories that can be used to construct certain components
17 years, 2 months