referenceAnnotation, Pattern matchingAnnotationPattern) {
- T matchingAnnotation = null;
- Annotation[] annotations = element.getAnnotations();
- for (Annotation annotation : annotations) {
- if (validateCustomAnnotationPattern(annotation.annotationType().getName(), matchingAnnotationPattern)) {
- if (matchingAnnotation != null) {
- throw new IllegalStateException("You are not allowed to use more than one @" + referenceAnnotation.getName()
- + " annotations for the same element : "
- + element.toString());
- }
- matchingAnnotation = AnnotationProxyFactory.getAnnotationProxy(annotation, referenceAnnotation);
- }
- }
- return matchingAnnotation;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/filter/annotations/ReferenceAnnotation.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/filter/annotations/ReferenceAnnotation.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/filter/annotations/ReferenceAnnotation.java (revision 0)
@@ -1,35 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.pool.sizeof.filter.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.FIELD, ElementType.TYPE, ElementType.PACKAGE })
-public @interface ReferenceAnnotation {
- String version() default "hello";
- boolean deprecated() default false;
- int differentReturnType() default 5;
- String[] things();
- Class aClass() default String.class;
- ExampleEnum anEnum() default ExampleEnum.ONE;
- Deprecated anAnnotation() default @Deprecated;
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-storage-strategy.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-storage-strategy.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-storage-strategy.xml (revision 0)
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMISynchronousCacheReplicator.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMISynchronousCacheReplicator.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMISynchronousCacheReplicator.java (revision 0)
@@ -1,388 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.distribution;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-
-import java.io.Serializable;
-import java.util.List;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Listens to {@link net.sf.ehcache.CacheManager} and {@link net.sf.ehcache.Cache} events and propagates those to
- * {@link CachePeer} peers of the Cache.
- *
- * @author Greg Luck
- * @version $Id: RMISynchronousCacheReplicator.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class RMISynchronousCacheReplicator implements CacheReplicator {
-
- private static final Logger LOG = LoggerFactory.getLogger(RMISynchronousCacheReplicator.class.getName());
-
-
- /**
- * The status of the replicator. Only replicates when STATUS_ALIVE
- */
- protected Status status;
-
- /**
- * Whether to replicate puts.
- */
- protected final boolean replicatePuts;
-
- /**
- * Whether a put should replicated by copy or by invalidation, (a remove).
- *
- * By copy is best when the entry is expensive to produce. By invalidation is best when
- * we are really trying to force other caches to sync back to a canonical source like a database.
- * An example of a latter usage would be a read/write cache being used in Hibernate.
- *
- * This setting only has effect if #replicateUpdates
is true.
- */
- protected boolean replicatePutsViaCopy;
-
- /**
- * Whether to replicate updates.
- */
- protected final boolean replicateUpdates;
-
- /**
- * Whether an update (a put) should be by copy or by invalidation, (a remove).
- *
- * By copy is best when the entry is expensive to produce. By invalidation is best when
- * we are really trying to force other caches to sync back to a canonical source like a database.
- * An example of a latter usage would be a read/write cache being used in Hibernate.
- *
- * This setting only has effect if #replicateUpdates
is true.
- */
- protected final boolean replicateUpdatesViaCopy;
- /**
- * Whether to replicate removes
- */
- protected final boolean replicateRemovals;
-
- /**
- * Constructor for internal and subclass use
- *
- * @param replicatePuts
- * @param replicateUpdates
- * @param replicateUpdatesViaCopy
- * @param replicateRemovals
- */
- public RMISynchronousCacheReplicator(
- boolean replicatePuts,
- boolean replicatePutsViaCopy,
- boolean replicateUpdates,
- boolean replicateUpdatesViaCopy,
- boolean replicateRemovals) {
- this.replicatePuts = replicatePuts;
- this.replicatePutsViaCopy = replicatePutsViaCopy;
- this.replicateUpdates = replicateUpdates;
- this.replicateUpdatesViaCopy = replicateUpdatesViaCopy;
- this.replicateRemovals = replicateRemovals;
- status = Status.STATUS_ALIVE;
- }
-
- /**
- * Called immediately after an element has been put into the cache. The {@link net.sf.ehcache.Cache#put(net.sf.ehcache.Element)} method
- * will block until this method returns.
- *
- * Implementers may wish to have access to the Element's fields, including value, so the element is provided.
- * Implementers should be careful not to modify the element. The effect of any modifications is undefined.
- *
- * @param cache the cache emitting the notification
- * @param element the element which was just put into the cache.
- */
- public void notifyElementPut(final Ehcache cache, final Element element) throws CacheException {
- if (notAlive()) {
- return;
- }
-
- if (!replicatePuts) {
- return;
- }
-
- if (!element.isSerializable()) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Object with key " + element.getObjectKey() + " is not Serializable and cannot be replicated");
- }
- return;
- }
-
- if (replicatePutsViaCopy) {
- replicatePutNotification(cache, element);
- } else {
- replicateRemovalNotification(cache, (Serializable) element.getObjectKey());
- }
- }
-
- /**
- * Does the actual RMI remote call.
- *
- * If a Throwable occurs a SEVERE log message will be logged, but attempts to replicate to the other
- * peers will continue.
- */
- protected static void replicatePutNotification(Ehcache cache, Element element) throws RemoteCacheException {
- List cachePeers = listRemoteCachePeers(cache);
- for (Object cachePeer1 : cachePeers) {
- CachePeer cachePeer = (CachePeer) cachePeer1;
- try {
- cachePeer.put(element);
- } catch (Throwable t) {
- LOG.error("Exception on replication of putNotification. " + t.getMessage() + ". Continuing...", t);
- }
- }
- }
-
-
- /**
- * Called immediately after an element has been put into the cache and the element already
- * existed in the cache. This is thus an update.
- *
- * The {@link net.sf.ehcache.Cache#put(net.sf.ehcache.Element)} method
- * will block until this method returns.
- *
- * Implementers may wish to have access to the Element's fields, including value, so the element is provided.
- * Implementers should be careful not to modify the element. The effect of any modifications is undefined.
- *
- * @param cache the cache emitting the notification
- * @param element the element which was just put into the cache.
- */
- public void notifyElementUpdated(final Ehcache cache, final Element element) throws CacheException {
- if (notAlive()) {
- return;
- }
- if (!replicateUpdates) {
- return;
- }
-
- if (replicateUpdatesViaCopy) {
- if (!element.isSerializable()) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Object with key " + element.getObjectKey()
- + " is not Serializable and cannot be updated via copy");
- }
- return;
- }
-
- replicatePutNotification(cache, element);
- } else {
- if (!element.isKeySerializable()) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Key " + element.getObjectKey() + " is not Serializable and cannot be replicated.");
- }
- return;
- }
-
- replicateRemovalNotification(cache, (Serializable) element.getObjectKey());
- }
- }
-
- /**
- * Called immediately after an attempt to remove an element. The remove method will block until
- * this method returns.
- *
- * This notification is received regardless of whether the cache had an element matching
- * the removal key or not. If an element was removed, the element is passed to this method,
- * otherwise a synthetic element, with only the key set is passed in.
- *
- *
- * @param cache the cache emitting the notification
- * @param element the element just deleted, or a synthetic element with just the key set if
- * no element was removed.param element just deleted
- */
- public void notifyElementRemoved(final Ehcache cache, final Element element) throws CacheException {
- if (notAlive()) {
- return;
- }
-
- if (!replicateRemovals) {
- return;
- }
-
- if (!element.isKeySerializable()) {
- if (LOG.isWarnEnabled()) {
- LOG.warn("Key " + element.getObjectKey() + " is not Serializable and cannot be replicated.");
- }
- return;
- }
-
- replicateRemovalNotification(cache, (Serializable) element.getObjectKey());
- }
-
- /**
- * Does the actual RMI remote call.
- *
- * If a Throwable occurs a SEVERE log message will be logged, but attempts to replicate to the other
- * peers will continue.
- */
- protected static void replicateRemovalNotification(Ehcache cache, Serializable key) throws RemoteCacheException {
- List cachePeers = listRemoteCachePeers(cache);
- for (Object cachePeer1 : cachePeers) {
- CachePeer cachePeer = (CachePeer) cachePeer1;
- try {
- cachePeer.remove(key);
- } catch (Throwable t) {
- LOG.error("Exception on replication of removeNotification. " + t.getMessage() + ". Continuing...", t);
- }
- }
- }
-
-
- /**
- * {@inheritDoc}
- *
- * This implementation does not propagate expiries. It does not need to do anything because the element will
- * expire in the remote cache at the same time. If the remote peer is not configured the same way they should
- * not be in an cache cluster.
- */
- public final void notifyElementExpired(final Ehcache cache, final Element element) {
- /*do not propagate expiries. The element should expire in the remote cache at the same time, thus
- preseerving coherency.
- */
- }
-
- /**
- * Called immediately after an element is evicted from the cache. Evicted in this sense
- * means evicted from one store and not moved to another, so that it exists nowhere in the
- * local cache.
- *
- * In a sense the Element has been removed from the cache, but it is different,
- * thus the separate notification.
- *
- * This replicator does not propagate these events
- *
- * @param cache the cache emitting the notification
- * @param element the element that has just been evicted
- */
- public void notifyElementEvicted(final Ehcache cache, final Element element) {
- /**
- * do not notify these
- */
- }
-
-
- /**
- * Called during {@link net.sf.ehcache.Ehcache#removeAll()} to indicate that the all
- * elements have been removed from the cache in a bulk operation. The usual
- * {@link #notifyElementRemoved(net.sf.ehcache.Ehcache,net.sf.ehcache.Element)}
- * is not called.
- *
- * This notification exists because clearing a cache is a special case. It is often
- * not practical to serially process notifications where potentially millions of elements
- * have been bulk deleted.
- *
- * @param cache the cache emitting the notification
- */
- public void notifyRemoveAll(final Ehcache cache) {
- if (notAlive()) {
- return;
- }
-
- if (!replicateRemovals) {
- return;
- }
-
- replicateRemoveAllNotification(cache);
- }
-
- /**
- * Does the actual RMI remote call.
- *
- * If a Throwable occurs a SEVERE log message will be logged, but attempts to replicate to the other
- * peers will continue.
- *
- */
- protected void replicateRemoveAllNotification(Ehcache cache) {
- List cachePeers = listRemoteCachePeers(cache);
- for (Object cachePeer1 : cachePeers) {
- CachePeer cachePeer = (CachePeer) cachePeer1;
- try {
- cachePeer.removeAll();
- } catch (Throwable t) {
- LOG.error("Exception on replication of removeAllNotification. " + t.getMessage() + ". Continuing...", t);
- }
- }
- }
-
- /**
- * Package protected List of cache peers
- *
- * @param cache
- * @return a list of {@link CachePeer} peers for the given cache, excluding the local peer.
- */
- static List listRemoteCachePeers(Ehcache cache) {
- CacheManagerPeerProvider provider = cache.getCacheManager().getCacheManagerPeerProvider("RMI");
- return provider.listRemoteCachePeers(cache);
- }
-
-
- /**
- * @return whether update is through copy or invalidate
- */
- public final boolean isReplicateUpdatesViaCopy() {
- return replicateUpdatesViaCopy;
- }
-
- /**
- * Asserts that the replicator is active.
- *
- * @return true if the status is not STATUS_ALIVE
- */
- public final boolean notAlive() {
- return !alive();
- }
-
- /**
- * Checks that the replicator is is STATUS_ALIVE
.
- */
- public final boolean alive() {
- if (status == null) {
- return false;
- } else {
- return (status.equals(Status.STATUS_ALIVE));
- }
- }
-
- /**
- * Give the replicator a chance to cleanup and free resources when no longer needed
- */
- public void dispose() {
- status = Status.STATUS_SHUTDOWN;
- }
-
- /**
- * Creates a clone of this listener. This method will only be called by ehcache before a cache is initialized.
- *
- * This may not be possible for listeners after they have been initialized. Implementations should throw
- * CloneNotSupportedException if they do not support clone.
- *
- * @return a clone
- * @throws CloneNotSupportedException if the listener could not be cloned.
- */
- public Object clone() throws CloneNotSupportedException {
- //shutup checkstyle
- super.clone();
- return new RMISynchronousCacheReplicator(replicatePuts, replicatePutsViaCopy, replicateUpdates,
- replicateUpdatesViaCopy, replicateRemovals);
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/LocalTransactionContext.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/LocalTransactionContext.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/LocalTransactionContext.java (revision 0)
@@ -1,313 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.local;
-
-import net.sf.ehcache.transaction.SoftLock;
-import net.sf.ehcache.transaction.TransactionException;
-import net.sf.ehcache.transaction.TransactionID;
-import net.sf.ehcache.transaction.TransactionIDFactory;
-import net.sf.ehcache.transaction.TransactionTimeoutException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-import static java.util.concurrent.TimeUnit.MILLISECONDS;
-
-/**
- * A local transaction's thread context
- *
- * @author Ludovic Orban
- */
-public class LocalTransactionContext {
-
- private static final Logger LOG = LoggerFactory.getLogger(LocalTransactionContext.class.getName());
-
- private boolean rollbackOnly;
- private final long expirationTimestamp;
- private final TransactionIDFactory transactionIdFactory;
- private final TransactionID transactionId;
- private final Map> softLockMap = new HashMap>();
- private final Map storeMap = new HashMap();
- private final List listeners = new ArrayList();
-
- /**
- * Create a new LocalTransactionContext
- * @param transactionTimeout the timeout before the context expires
- * @param transactionIdFactory the transaction ID factory to retrieve a new transaction id from
- */
- public LocalTransactionContext(int transactionTimeout, TransactionIDFactory transactionIdFactory) {
- this.expirationTimestamp = MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS) +
- MILLISECONDS.convert(transactionTimeout, TimeUnit.SECONDS);
- this.transactionIdFactory = transactionIdFactory;
- this.transactionId = transactionIdFactory.createTransactionID();
- }
-
- /**
- * Check if the context timed out
- * @return true if the context timed out, false otherwise
- */
- public boolean timedOut() {
- return timeBeforeTimeout() <= 0;
- }
-
- /**
- * Get the time until this context will expire
- * @return the time in milliseconds after which this context will expire
- */
- public long timeBeforeTimeout() {
- return Math.max(0, expirationTimestamp - MILLISECONDS.convert(System.nanoTime(), TimeUnit.NANOSECONDS));
- }
-
- /**
- * Mark the context for rollback
- */
- public void setRollbackOnly() {
- this.rollbackOnly = true;
- }
-
- /**
- * Register a soft lock in the context
- * @param cacheName the name of the cache this soft lock is in
- * @param store the LocalTransactionStore this soft lock is in
- * @param softLock the soft lock
- */
- public void registerSoftLock(String cacheName, LocalTransactionStore store, SoftLock softLock) {
- List softLocks = softLockMap.get(cacheName);
- if (softLocks == null) {
- softLocks = new ArrayList();
- softLockMap.put(cacheName, softLocks);
- storeMap.put(cacheName, store);
- }
- softLocks.add(softLock);
- }
-
- //todo this method isn't needed if there is no copy on read/write in the underlying store
- /**
- * Update a soft lock already registered in the context
- * @param cacheName the name of the cache this soft lock is in
- * @param softLock the soft lock
- */
- public void updateSoftLock(String cacheName, SoftLock softLock) {
- List softLocks = softLockMap.get(cacheName);
- softLocks.remove(softLock);
- softLocks.add(softLock);
- }
-
- /**
- * Get all soft locks registered in this context for a specific cache
- * @param cacheName the name of the cache
- * @return a List of registered soft locks for this cache
- */
- public List getSoftLocksForCache(String cacheName) {
- List softLocks = softLockMap.get(cacheName);
- if (softLocks == null) {
- return Collections.emptyList();
- }
-
- return Collections.unmodifiableList(softLocks);
- }
-
- /**
- * Check if anything was locked in this transaction's context
- * @return true if at least one soft lock got registered, false otherwise
- */
- public boolean hasLockedAnything() {
- return !softLockMap.isEmpty();
- }
-
- /**
- * Commit all work done in the context and release all registered soft locks
- * @param ignoreTimeout true if commit should proceed no matter the timeout
- */
- public void commit(boolean ignoreTimeout) {
- if (!ignoreTimeout && timedOut()) {
- rollback();
- throw new TransactionTimeoutException("transaction timed out, rolled back on commit");
- }
- if (rollbackOnly) {
- rollback();
- throw new TransactionException("transaction was marked as rollback only, rolled back on commit");
- }
-
- try {
- fireBeforeCommitEvent();
- if (LOG.isDebugEnabled()) {
- LOG.debug("{} participating cache(s), committing transaction {}", softLockMap.keySet().size(), transactionId);
- }
- freeze();
- transactionIdFactory.markForCommit(transactionId);
-
- for (Map.Entry> stringListEntry : softLockMap.entrySet()) {
- String cacheName = stringListEntry.getKey();
- LocalTransactionStore store = storeMap.get(cacheName);
- List softLocks = stringListEntry.getValue();
-
- LOG.debug("committing soft locked values of cache {}", cacheName);
- store.commit(softLocks, transactionId);
- }
- LOG.debug("committed transaction {}", transactionId);
- } finally {
- try {
- unfreezeAndUnlock();
- } finally {
- softLockMap.clear();
- storeMap.clear();
- fireAfterCommitEvent();
- }
- }
- }
-
- /**
- * Rollback all work done in the context and release all registered soft locks
- */
- public void rollback() {
- try {
- if (LOG.isDebugEnabled()) {
- LOG.debug("{} participating cache(s), rolling back transaction {}", softLockMap.keySet().size(), transactionId);
- }
- freeze();
-
- for (Map.Entry> stringListEntry : softLockMap.entrySet()) {
- String cacheName = stringListEntry.getKey();
- LocalTransactionStore store = storeMap.get(cacheName);
- List softLocks = stringListEntry.getValue();
-
- LOG.debug("rolling back soft locked values of cache {}", cacheName);
- store.rollback(softLocks, transactionId);
- }
- LOG.debug("rolled back transaction {}", transactionId);
- } finally {
- try {
- unfreezeAndUnlock();
- } finally {
- softLockMap.clear();
- storeMap.clear();
- fireAfterRollbackEvent();
- }
- }
- }
-
- /**
- * Get the transaction ID of the context
- * @return the transaction ID
- */
- public TransactionID getTransactionId() {
- return transactionId;
- }
-
- /**
- * Add a TransactionListener to this context
- * @param listener the listener
- */
- public void addListener(TransactionListener listener) {
- this.listeners.add(listener);
- }
-
- private void fireBeforeCommitEvent() {
- for (TransactionListener listener : listeners) {
- try {
- listener.beforeCommit();
- } catch (Exception e) {
- LOG.error("beforeCommit error", e);
- }
- }
- }
-
- private void fireAfterCommitEvent() {
- for (TransactionListener listener : listeners) {
- try {
- listener.afterCommit();
- } catch (Exception e) {
- LOG.error("afterCommit error", e);
- }
- }
- }
-
- private void fireAfterRollbackEvent() {
- for (TransactionListener listener : listeners) {
- try {
- listener.afterRollback();
- } catch (Exception e) {
- LOG.error("afterRollback error", e);
- }
- }
- }
-
- private void unfreezeAndUnlock() {
- LOG.debug("unfreezing and unlocking soft lock(s)");
- boolean success = true;
- for (Map.Entry> stringListEntry : softLockMap.entrySet()) {
- List softLocks = stringListEntry.getValue();
-
- for (SoftLock softLock : softLocks) {
- try {
- softLock.unfreeze();
- LOG.debug("unfroze {}", softLock);
- } catch (Exception e) {
- success = false;
- LOG.error("error unfreezing " + softLock, e);
- }
- try {
- softLock.unlock();
- LOG.debug("unlocked {}", softLock);
- } catch (Exception e) {
- success = false;
- LOG.error("error unlocking " + softLock, e);
- }
- }
- }
- if (!success) {
- throw new TransactionException("Error unfreezing/unlocking transaction with ID " + transactionId);
- }
- }
-
- private void freeze() {
- for (Map.Entry> stringListEntry : softLockMap.entrySet()) {
- List softLocks = stringListEntry.getValue();
-
- for (SoftLock softLock : softLocks) {
- softLock.freeze();
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int hashCode() {
- return transactionId.hashCode();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof LocalTransactionContext) {
- LocalTransactionContext otherCtx = (LocalTransactionContext) obj;
- return transactionId.equals(otherCtx.transactionId);
- }
- return false;
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-nonstop-behavior-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-nonstop-behavior-test.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-nonstop-behavior-test.xml (revision 0)
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/InvalidConfigurationException.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/InvalidConfigurationException.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/InvalidConfigurationException.java (revision 0)
@@ -1,80 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.config;
-
-import net.sf.ehcache.CacheException;
-
-import java.util.Collection;
-
-/**
- * An exception to report invalid configuration settings.
- *
- * @author gbevin
- * @author Greg Luck
- */
-public class InvalidConfigurationException extends CacheException {
-
- /**
- * Constructs a new exception with a detailed message that explains the cause.
- * @param message the exception message
- */
- public InvalidConfigurationException(String message) {
- super(message);
- }
-
- /**
- * Constructs a new exception with a message containing all config errors
- * @param errors the list of error encountered
- */
- public InvalidConfigurationException(final Collection errors) {
- this(null, errors);
- }
-
- /**
- * Constructs a new exception with a message containing all config errors
- * @param errors the list of error encountered
- */
- public InvalidConfigurationException(final String rootCause, final Collection errors) {
- super(createErrorMessage(rootCause, errors));
- }
-
- private static String createErrorMessage(final String rootCause, Collection errors) {
- final StringBuilder sb = new StringBuilder();
- if (rootCause == null) {
- sb.append("There ");
- if (errors.size() == 1) {
- sb.append("is one error ");
- } else {
- sb.append("are ")
- .append(errors.size())
- .append(" errors ");
- }
- sb.append("in your configuration: \n");
- } else {
- sb.append(rootCause).append('\n');
- }
- for (ConfigError error : errors) {
- sb.append("\t* ")
- .append(error.toString())
- .append('\n');
- }
- return sb
- .append("\n")
- .toString();
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache/src/test/resources/serializedforms/ReflectionAttributeExtractorSerializationTest.testMethodsKey.ser
===================================================================
diff -u -N -r11085 -r11127
Binary files differ
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/ElementValueComparatorConfiguration.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/ElementValueComparatorConfiguration.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/ElementValueComparatorConfiguration.java (revision 0)
@@ -1,111 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.config;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.store.DefaultElementValueComparator;
-import net.sf.ehcache.store.ElementValueComparator;
-import net.sf.ehcache.util.ClassLoaderUtil;
-
-/**
- * @author Ludovic Orban
- */
-public class ElementValueComparatorConfiguration {
-
- private static final String DEFAULT_IMPL = DefaultElementValueComparator.class.getName();
-
- private volatile String className = DEFAULT_IMPL;
-
- /**
- * Returns the fully qualified class name for the ElementValueComparator to use
- *
- * @return FQCN to the ElementValueComparator implementation to use
- */
- public String getClassName() {
- return className;
- }
-
- /**
- * Sets the fully qualified class name for the ElementValueComparator to use
- *
- * @param className
- * FQCN
- */
- public void setClass(final String className) {
- this.className = className;
- }
-
- /**
- * Get (and potentially) instantiate the instance
- *
- * @param cacheConfiguration the cache configuration
- * @param loader classloader to use to create the instance
- * @return the instance
- */
- public ElementValueComparator createElementComparatorInstance(CacheConfiguration cacheConfiguration, ClassLoader loader) {
- try {
- if (DEFAULT_IMPL.equals(className)) {
- loader = getClass().getClassLoader();
- }
-
- return (ElementValueComparator) ClassLoaderUtil.createNewInstance(
- loader,
- className,
- new Class[] {CacheConfiguration.class},
- new Object[] {cacheConfiguration}
- );
- } catch (ClassCastException cce) {
- throw new CacheException(className + " must implement " + ElementValueComparator.class.getName(), cce);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((className == null) ? 0 : className.hashCode());
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (getClass() != obj.getClass()) {
- return false;
- }
- ElementValueComparatorConfiguration other = (ElementValueComparatorConfiguration) obj;
- if (className == null) {
- if (other.className != null) {
- return false;
- }
- } else if (!className.equals(other.className)) {
- return false;
- }
- return true;
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/terracotta/TerracottaBootstrapCacheLoader.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/terracotta/TerracottaBootstrapCacheLoader.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/terracotta/TerracottaBootstrapCacheLoader.java (revision 0)
@@ -1,271 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.terracotta;
-
-import java.io.IOException;
-import java.util.Set;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.DiskStorePathManager;
-import net.sf.ehcache.Disposable;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.distribution.RemoteCacheException;
-import net.sf.ehcache.store.MemoryLimitedCacheLoader;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A {@link net.sf.ehcache.bootstrap.BootstrapCacheLoader} that will load Elements into a Terracotta clustered cache, based on a previously
- * snapshotted key set. It is also responsible to create snapshot files to disk
- *
- * @author Alex Snaps
- */
-public class TerracottaBootstrapCacheLoader extends MemoryLimitedCacheLoader implements Disposable {
-
- /**
- * The default interval in seconds, between each snapshot
- */
- public static final long DEFAULT_INTERVAL = 10 * 60;
- /**
- * The default on whether to do the snapshot on a dedicated thread or using the CacheManager's
- * {@link java.util.concurrent.ScheduledExecutorService}
- */
- public static final boolean DEFAULT_DEDICATED_THREAD = false;
-
- private static final Logger LOG = LoggerFactory.getLogger(TerracottaBootstrapCacheLoader.class);
-
- private final boolean aSynchronous;
- private final boolean doKeySnapshot;
- private final boolean doKeySnapshotOnDedicatedThread;
- private final long interval;
- private final DiskStorePathManager diskStorePathManager;
-
- private volatile KeySnapshotter keySnapshotter;
- private volatile boolean immediateShutdown;
- private volatile boolean doKeySnapshotOnDispose;
-
- private TerracottaBootstrapCacheLoader(final boolean doKeySnapshot, final boolean aSynchronous, final String directory,
- final long interval, final boolean doKeySnapshotOnDedicatedThread) {
- this.aSynchronous = aSynchronous;
- this.doKeySnapshot = doKeySnapshot;
- this.doKeySnapshotOnDedicatedThread = doKeySnapshotOnDedicatedThread;
- this.interval = interval;
- this.diskStorePathManager = directory != null ? new DiskStorePathManager(directory) : null;
- }
-
- /**
- * Constructor
- *
- * @param asynchronous do the loading asynchronously, or synchronously
- * @param directory the directory to read snapshot files from, and write them to
- * @param doKeySnapshots Whether to do keysnapshotting
- */
- public TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, boolean doKeySnapshots) {
- this(doKeySnapshots, asynchronous, directory, DEFAULT_INTERVAL, DEFAULT_DEDICATED_THREAD);
- }
-
- /**
- * Constructor
- *
- * @param asynchronous do the loading asynchronously, or synchronously
- * @param directory the directory to read snapshot files from, and write them to
- * @param interval the interval in seconds at which the snapshots of the local key set has to occur
- */
- public TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, long interval) {
- this(asynchronous, directory, interval, false);
- }
-
- /**
- * Constructor
- *
- * @param asynchronous do the loading asynchronously, or synchronously
- * @param directory the directory to read snapshot files from, and write them to
- * @param interval the interval in seconds at which the snapshots of the local key set has to occur
- * @param onDedicatedThread whether to do the snapshot on a dedicated thread or using the CacheManager's
- * {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService}
- */
- public TerracottaBootstrapCacheLoader(final boolean asynchronous, String directory, long interval, boolean onDedicatedThread) {
- this(true, asynchronous, directory, interval, onDedicatedThread);
- }
-
- /**
- * Whether the on going keysnapshot will finish before the instance is disposed
- *
- * @return true if disposable is immediate
- * @see Disposable
- */
- public boolean isImmediateShutdown() {
- return immediateShutdown;
- }
-
- /**
- * Sets whether the disposal of the instance will let the potential current key set being written to disk finish, or whether the
- * shutdown will be immediate
- *
- * @param immediateShutdown true if immediate, false to let the snapshot finish
- */
- public void setImmediateShutdown(final boolean immediateShutdown) {
- this.immediateShutdown = immediateShutdown;
- }
-
- /**
- * {@inheritDoc}
- */
- public void load(final Ehcache cache) throws CacheException {
- if (!cache.getCacheConfiguration().isTerracottaClustered()) {
- LOG.error("You're trying to bootstrap a non Terracotta clustered cache with a TerracottaBootstrapCacheLoader! Cache "
- + "'{}' will not be bootstrapped and no keySet snapshot will be recorded...", cache.getName());
- return;
- }
-
- if (cache.getStatus() != Status.STATUS_ALIVE) {
- throw new CacheException("Cache '" + cache.getName() + "' isn't alive yet: " + cache.getStatus());
- }
-
- if (isAsynchronous()) {
- BootstrapThread thread = new BootstrapThread(cache);
- thread.start();
- } else {
- doLoad(cache);
- }
- }
-
- private void doLoad(final Ehcache cache) {
- CacheManager manager = cache.getCacheManager();
- if (manager == null) {
- throw new CacheException("Cache must belong to a cache manager to bootstrap");
- }
-
- DiskStorePathManager pathManager = diskStorePathManager != null ? diskStorePathManager : cache.getCacheManager()
- .getDiskStorePathManager();
-
- final RotatingSnapshotFile snapshotFile = new RotatingSnapshotFile(pathManager, cache.getName(), manager.getConfiguration().getClassLoader());
- try {
- final Set keys = snapshotFile.readAll();
- int loaded = 0;
- for (Object key : keys) {
- if (isInMemoryLimitReached(cache, loaded)) {
- break;
- }
- cache.get(key);
- loaded++;
- }
- LOG.info("Finished loading {} keys (of {} on disk) from previous snapshot for Cache '{}'",
- new Object[] {Integer.valueOf(loaded), keys.size(), cache.getName()});
- } catch (IOException e) {
- LOG.error("Couldn't load keySet for Cache '{}'", cache.getName(), e);
- }
-
- if (doKeySnapshot) {
- keySnapshotter = new KeySnapshotter(cache, interval, doKeySnapshotOnDedicatedThread, snapshotFile);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isAsynchronous() {
- return aSynchronous;
- }
-
- /**
- * Will shut the keysnapshot thread and other resources down.
- * If a snapshot is currently in progress, the method will either shutdown immediately or let the snapshot finish
- * based on the configured {@link #setImmediateShutdown(boolean)} value
- */
- public void dispose() {
- if (keySnapshotter != null) {
- if (doKeySnapshotOnDispose) {
- try {
- keySnapshotter.doSnapshot();
- } catch (IOException e) {
- LOG.error("Error writing local key set for Cache '{}'", keySnapshotter.getCacheName(), e);
- }
- } else {
- keySnapshotter.dispose(immediateShutdown);
- }
- }
- if (diskStorePathManager != null) {
- diskStorePathManager.releaseLock();
- }
- }
-
- /**
- * Calling this method will result in a snapshot being taken or wait for the one in progress to finish
- *
- * @throws IOException On exception being thrown while doing the snapshot
- */
- public void doLocalKeySnapshot() throws IOException {
- keySnapshotter.doSnapshot();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
-
- /**
- * Accessor to the associated {@link KeySnapshotter}
- *
- * @return the {@link KeySnapshotter} used by this loader instance
- */
- KeySnapshotter getKeySnapshotter() {
- return keySnapshotter;
- }
-
- /**
- * Configures the Loader to take a snapshot when it is being disposed
- *
- * @param doKeySnapshotOnDispose whether to snapshot on loader disposal
- */
- public void setSnapshotOnDispose(final boolean doKeySnapshotOnDispose) {
- this.doKeySnapshotOnDispose = doKeySnapshotOnDispose;
- }
-
- /**
- * A background daemon thread that asynchronously calls doLoad
- */
- private final class BootstrapThread extends Thread {
- private Ehcache cache;
-
- public BootstrapThread(Ehcache cache) {
- super("Bootstrap Thread for cache " + cache.getName());
- this.cache = cache;
- setDaemon(true);
- setPriority(Thread.NORM_PRIORITY);
- }
-
- /**
- * RemoteDebugger thread method.
- */
- @Override
- public final void run() {
- try {
- doLoad(cache);
- } catch (RemoteCacheException e) {
- LOG.warn("Error asynchronously performing bootstrap. The cause was: " + e.getMessage(), e);
- }
- cache = null;
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/nonstop/package.html
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/nonstop/package.html (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/nonstop/package.html (revision 0)
@@ -1,10 +0,0 @@
-
-
-
-
-Ehcache-nonstopcache package
-
-This package contains core classes for NonStopCache features
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-scheduled-refresh/src/test/resources/ehcache-scheduled-refresh.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-scheduled-refresh/src/test/resources/ehcache-scheduled-refresh.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-scheduled-refresh/src/test/resources/ehcache-scheduled-refresh.xml (revision 0)
@@ -1,20 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/WatchableTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/WatchableTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/WatchableTest.java (revision 0)
@@ -1,76 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-
-package org.terracotta.modules.ehcache;
-
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.util.concurrent.ConcurrentHashMap;
-import org.junit.Before;
-import org.junit.Test;
-import org.terracotta.toolkit.concurrent.locks.ToolkitLock;
-import org.terracotta.toolkit.internal.cache.BufferingToolkitCache;
-
-import java.io.Serializable;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.locks.Condition;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-/**
- * @author Eugene Shelestovich
- */
-public class WatchableTest {
-
- private ToolkitLock configLock;
- private ToolkitLock activeLock;
- private WanAwareToolkitCache watchable;
-
- @Before
- public void setUp() throws Exception {
- final ConcurrentMap configMap = new ConcurrentHashMap();
- final BufferingToolkitCache delegate = mock(BufferingToolkitCache.class);
- Condition condition = mock(Condition.class);
- configLock = when(mock(ToolkitLock.class).getCondition()).thenReturn(condition).getMock();
- activeLock = when(mock(ToolkitLock.class).isHeldByCurrentThread()).thenReturn(false, true).getMock();
- watchable = new WanAwareToolkitCache(
- delegate, configMap, null, configLock, activeLock, new CacheConfiguration(), true, true);
- }
-
- @Test
- public void testMustAcquireLockOnGoLive() {
- when(activeLock.isHeldByCurrentThread()).thenReturn(false, true);
- watchable.goLive();
- verify(activeLock).lock();
- }
-
- @Test
- public void testMustNotAcquireLockIfAlreadyHeld() {
- when(activeLock.isHeldByCurrentThread()).thenReturn(true);
- watchable.goLive();
- verify(activeLock, never()).lock();
- }
-
- @Test
- public void testMustDeactivateCacheIfLockReleased() {
- watchable.goLive();
- when(activeLock.tryLock()).thenReturn(true);
- assertFalse(watchable.probeLiveness());
- assertFalse(watchable.isOrchestratorAlive());
- verify(activeLock).unlock();
- }
-
- @Test
- public void testMustNotDeactivateCacheIfLockHeld() {
- watchable.goLive();
- when(activeLock.tryLock()).thenReturn(false);
- assertTrue(watchable.probeLiveness());
- assertTrue(watchable.isOrchestratorAlive());
- verify(activeLock, never()).unlock();
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/loader/ComponentC.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/loader/ComponentC.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/loader/ComponentC.java (revision 0)
@@ -1,49 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.loader;
-
-/**
- * Written for Dead-lock poc
- *
- * @author Greg Luck
- * @version $Id: ComponentC.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class ComponentC {
-
- private Object obj;
-
- /**
- * @param obj
- */
- public ComponentC(Object obj) {
- this.obj = obj;
- }
-
- /**
- * @return
- */
- public Object getObj() {
- return obj;
- }
-
- /**
- * @return
- */
- public String toString() {
- return "C(" + obj + ")";
- }
-}
Index: rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/bin/relative-paths.sh
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/bin/relative-paths.sh (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/bin/relative-paths.sh (revision 0)
@@ -1,13 +0,0 @@
-#!/bin/bash
-
-case "$1" in
- tc_install_dir)
- echo ../../../..
- ;;
- ehcache_jars_dir)
- echo ../../..
- ;;
- *)
- echo "unknown param"
- exit 1
-esac
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusteredCacheRemovalTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusteredCacheRemovalTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusteredCacheRemovalTest.java (revision 0)
@@ -1,12 +0,0 @@
-package org.terracotta.ehcache.tests;
-
-import com.tc.test.config.model.TestConfig;
-
-/**
- * @author Alex Snaps
- */
-public class ClusteredCacheRemovalTest extends AbstractCacheTestBase {
- public ClusteredCacheRemovalTest(TestConfig testConfig) {
- super("one-cache-test.xml", testConfig, CacheRemovalClient.class);
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/CacheStoreHelper.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/CacheStoreHelper.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/CacheStoreHelper.java (revision 0)
@@ -1,49 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache;
-
-import net.sf.ehcache.store.Store;
-
-/**
- * A helper class to get the internal Store from a Cache
- *
- * @author Abhishek Sanoujam
- *
- */
-public class CacheStoreHelper {
-
- private final Cache cache;
-
- /**
- * Constructor accepting the cache
- *
- * @param cache
- */
- public CacheStoreHelper(final Cache cache) {
- this.cache = cache;
- }
-
- /**
- * Returns the internal {@link Store} of the cache
- *
- * @return the internal {@link Store} of the cache
- */
- public Store getStore() {
- return cache.getStore();
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/SynchronousDeadBucketWriteBehindTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/SynchronousDeadBucketWriteBehindTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/SynchronousDeadBucketWriteBehindTest.java (revision 0)
@@ -1,92 +0,0 @@
-/*
- * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright
- * notice. All rights reserved.
- */
-package org.terracotta.modules.ehcache.writebehind;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.modules.ehcache.async.AsyncCoordinatorImpl;
-
-import com.tc.l2.L2DebugLogging.LogLevel;
-import com.tc.test.config.model.TestConfig;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class SynchronousDeadBucketWriteBehindTest extends AbstractCacheTestBase {
- private int totalWriteCount = 0;
- private int totalDeleteCount = 0;
-
- public SynchronousDeadBucketWriteBehindTest(TestConfig testConfig) {
- super("synchronous-writebehind-test.xml", testConfig, WriteBehindClient1.class, WriteBehindClient2.class);
- testConfig.getClientConfig().setParallelClients(false);
- configureTCLogging(AsyncCoordinatorImpl.class.getName(), LogLevel.DEBUG);
- }
-
- @Override
- protected void postClientVerification() {
- System.out.println("[Clients processed a total of " + totalWriteCount + " writes]");
- if (totalWriteCount != 1001 && totalWriteCount != 1002) { // there can be one double write due to JVM exit during
- // async item processing
- throw new AssertionError(totalWriteCount);
- }
-
- System.out.println("[Clients processed a total of " + totalDeleteCount + " deletes]");
- if (totalDeleteCount != 101 && totalDeleteCount != 102) { // there can be one double delete due to JVM exit during
- // async item processing
- throw new AssertionError(totalDeleteCount);
- }
- }
-
- @Override
- protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable {
- super.evaluateClientOutput(clientName, exitCode, output);
-
- FileReader fr = null;
- StringBuilder strBuilder = new StringBuilder();
- try {
- fr = new FileReader(output);
- BufferedReader reader = new BufferedReader(fr);
- String st = "";
- while ((st = reader.readLine()) != null) {
- strBuilder.append(st);
- }
- } catch (Exception e) {
- throw new AssertionError(e);
- } finally {
- try {
- fr.close();
- } catch (Exception e) {
- //
- }
- }
- // Detect the number of writes that have happened
- int writeCount = detectLargestCount(strBuilder.toString(),
- Pattern.compile("\\[WriteBehindCacheWriter written (\\d+) for " + clientName
- + "\\]"));
- totalWriteCount += writeCount;
- System.out.println("[" + clientName + " processed " + writeCount + " writes]");
-
- // Detect the number of deletes that have happened
- int deleteCount = detectLargestCount(strBuilder.toString(),
- Pattern.compile("\\[WriteBehindCacheWriter deleted (\\d+) for " + clientName
- + "\\]"));
- totalDeleteCount += deleteCount;
- System.out.println("[" + clientName + " processed " + deleteCount + " deletes]");
- }
-
- private int detectLargestCount(String clientOutput, Pattern pattern) {
- Matcher matcher = pattern.matcher(clientOutput);
- int count = 0;
- while (matcher.find()) {
- int parsedCount = Integer.parseInt(matcher.group(1));
- if (parsedCount > count) {
- count = parsedCount;
- }
- }
- return count;
- }
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BasicCacheTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BasicCacheTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BasicCacheTest.java (revision 0)
@@ -1,196 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.store;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-import org.terracotta.toolkit.Toolkit;
-import org.terracotta.toolkit.concurrent.ToolkitBarrier;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.util.Collections;
-import java.util.Iterator;
-
-import junit.framework.Assert;
-
-public class BasicCacheTest extends AbstractCacheTestBase {
- private static final int NODE_COUNT = 3;
-
- public BasicCacheTest(TestConfig testConfig) {
- super(testConfig, App.class, App.class, App.class);
- }
-
- public static class App extends ClientBase {
- private final ToolkitBarrier barrier;
-
- public App(String[] args) {
- super(args);
- this.barrier = getClusteringToolkit().getBarrier("test-barrier", NODE_COUNT);
- }
-
- public static void main(String[] args) {
- new App(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- final int index = barrier.await();
-
- // XXX: assert that the cache is clustered via methods on cache config (when methods exist)
-
- Assert.assertEquals(0, cache.getSize());
-
- barrier.await();
-
- if (index == 0) {
- cache.put(new Element("key", "value"));
- }
-
- barrier.await();
-
- Assert.assertEquals(1, cache.getSize());
- Assert.assertEquals("value", cache.get("key").getObjectValue());
- Assert.assertEquals(1, cache.getKeys().size());
- Assert.assertEquals("key", cache.getKeys().iterator().next());
-
- barrier.await();
-
- testKeysetMutations(cache);
-
- barrier.await();
-
- // make sure the cache is still valid after the key set mutations above
- Assert.assertEquals(1, cache.getSize());
- Assert.assertEquals("value", cache.get("key").getObjectValue());
- Assert.assertEquals(1, cache.getKeys().size());
- Assert.assertEquals("key", cache.getKeys().iterator().next());
-
- barrier.await();
-
- if (index == 0) {
- boolean removed = cache.remove("key");
- Assert.assertTrue(removed);
- }
-
- barrier.await();
-
- Assert.assertEquals(0, cache.getSize());
- }
-
- private void testKeysetMutations(Cache cache) {
- try {
- cache.getKeys().clear();
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- try {
- cache.getKeys().add("sdf");
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- try {
- cache.getKeys().add(0, "sdf");
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- try {
- cache.getKeys().addAll(Collections.singletonList("sdfsfd"));
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- try {
- cache.getKeys().addAll(0, Collections.singletonList("SDfsdf"));
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- {
- Iterator iter = cache.getKeys().iterator();
- iter.next();
- try {
- iter.remove();
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
- }
-
- try {
- cache.getKeys().listIterator();
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected for now, but if listIterator() gets implemented this test should make sure you can't mutate the
- // cache through it)
- }
-
- try {
- cache.getKeys().listIterator(0);
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected for now, but if listIterator() gets implemented this test should make sure you can't mutate the
- // cache through it)
- }
-
- try {
- cache.getKeys().remove(0);
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- Assert.assertTrue(cache.getKeys().contains("key"));
- try {
- cache.getKeys().remove("key");
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- try {
- cache.getKeys().removeAll(Collections.singletonList("key"));
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- Assert.assertFalse(cache.getKeys().contains("not in the cache!"));
- try {
- cache.getKeys().retainAll(Collections.singletonList("not in the cache!"));
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- try {
- cache.getKeys().set(0, this);
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected
- }
-
- try {
- cache.getKeys().subList(0, 0);
- Assert.fail();
- } catch (UnsupportedOperationException uoe) {
- // expected for now, but if subList() gets implemented this test should make sure you can't mutate the
- // cache through it (or its further iterators!)
- }
- }
-
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/management-ehcache-impl/management-ehcache-impl-v2/src/test/java/net/sf/ehcache/management/service/impl/DfltSamplerRepositoryServiceV2Test.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/management-ehcache-impl/management-ehcache-impl-v2/src/test/java/net/sf/ehcache/management/service/impl/DfltSamplerRepositoryServiceV2Test.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/management-ehcache-impl/management-ehcache-impl-v2/src/test/java/net/sf/ehcache/management/service/impl/DfltSamplerRepositoryServiceV2Test.java (revision 0)
@@ -1,109 +0,0 @@
-/*
- * All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright
- * notice. All rights reserved.
- */
-package net.sf.ehcache.management.service.impl;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.ClusteredInstanceFactoryAccessor;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ManagementRESTServiceConfiguration;
-import net.sf.ehcache.constructs.blocking.BlockingCache;
-import net.sf.ehcache.terracotta.ClusteredInstanceFactory;
-import net.sf.ehcache.terracotta.TerracottaClient;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Collections;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.anyBoolean;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-import static org.mockito.Mockito.spy;
-
-/**
- * @author Ludovic Orban
- */
-public class DfltSamplerRepositoryServiceV2Test {
-
- private DfltSamplerRepositoryServiceV2 repositoryService;
- private ClusteredInstanceFactory clusteredInstanceFactory;
- private CacheManager cacheManager;
-
- @Before
- public void setUp() throws Exception {
- ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration();
- managementRESTServiceConfiguration.setEnabled(true);
- RemoteAgentEndpointImpl remoteAgentEndpoint = mock(RemoteAgentEndpointImpl.class);
- repositoryService = new DfltSamplerRepositoryServiceV2(managementRESTServiceConfiguration, remoteAgentEndpoint);
-
- Configuration configuration = new Configuration();
- configuration.setName("testCacheManager");
- CacheConfiguration cacheConfiguration = new CacheConfiguration("testCache1", 12);
- configuration.addCache(cacheConfiguration);
- cacheManager = new CacheManager(configuration);
- // Cache ehcache = new Cache(cacheConfiguration);
- TerracottaClient terracottaClient = mock(TerracottaClient.class);
- clusteredInstanceFactory = mock(ClusteredInstanceFactory.class);
-
- ClusteredInstanceFactoryAccessor.setTerracottaClient(cacheManager, terracottaClient);
- when(terracottaClient.getClusteredInstanceFactory()).thenReturn(clusteredInstanceFactory);
-
- repositoryService.register(cacheManager);
- }
-
- @Test
- public void testCreateCacheEntitiesDisablesNonStop() throws Exception {
- repositoryService.createCacheEntities(Collections.singleton("testCacheManager"),
- Collections.singleton("testCache1"),
- Collections.singleton("Size"));
-
- verify(clusteredInstanceFactory, times(4)).enableNonStopForCurrentThread(anyBoolean());
- }
-
- @Test
- public void testCreateCacheStatisticSampleEntityDisablesNonStop() throws Exception {
- repositoryService.createCacheStatisticSampleEntity(Collections.singleton("testCacheManager"),
- Collections.singleton("testCache1"),
- Collections.singleton("Size"));
-
- verify(clusteredInstanceFactory, times(4)).enableNonStopForCurrentThread(anyBoolean());
- }
-
- @Test
- public void testClearCacheDisablesNonStop() throws Exception {
- repositoryService.clearCache("testCacheManager", "testCache1");
-
- verify(clusteredInstanceFactory, times(4)).enableNonStopForCurrentThread(anyBoolean());
- }
-
- @Test
- public void testCanAddDecoratedCache() {
- Cache underlyingCache = new Cache(new CacheConfiguration("decoratedTestCache", 10));
- cacheManager.addCache(new BlockingCache(underlyingCache));
- // not using cacheEventListeners for management anymore : TAB-5077
- assertThat(underlyingCache.getCacheEventNotificationService().hasCacheEventListeners(), is(false));
- }
-
- @Test
- public void testPropertyListenerRemoval() throws Exception {
- CacheManager cacheManagerSpy = spy(cacheManager);
- repositoryService.unregister(cacheManagerSpy);
- verify(cacheManagerSpy).getConfiguration();
- repositoryService.register(cacheManager);
- }
-
- @After
- public void tearDown() {
- CacheManager.getCacheManager("testCacheManager").shutdown();
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/service/ManagementServerLifecycle.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/service/ManagementServerLifecycle.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/service/ManagementServerLifecycle.java (revision 0)
@@ -1,41 +0,0 @@
-/*
- * All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright
- * notice. All rights reserved.
- */
-package net.sf.ehcache.management.service;
-
-import net.sf.ehcache.CacheManager;
-
-/**
- * A interface for services registering {@link CacheManager} objects for sampling.
- *
- * @author brandony
- */
-public interface ManagementServerLifecycle {
-
- /**
- * Register a {@link CacheManager} for sampling.
- *
- * @param cacheManager to register
- */
- void register(CacheManager cacheManager);
-
- /**
- * Unregister a {@link CacheManager} for sampling.
- *
- * @param cacheManager to register
- */
- void unregister(CacheManager cacheManager);
-
- /**
- * An indicator as to whether or not any {@link CacheManager} objects have been registered.
- *
- * @return {@code true} if an object has been registered, {@code false} otherwise
- */
- boolean hasRegistered();
-
- /**
- * Dispose of the repository service mbean
- */
- void dispose();
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-perf-distributed.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-perf-distributed.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-perf-distributed.xml (revision 0)
@@ -1,34 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/CacheDecoratorFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/CacheDecoratorFactory.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/CacheDecoratorFactory.java (revision 0)
@@ -1,85 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.constructs;
-
-import java.util.Properties;
-
-import net.sf.ehcache.Ehcache;
-
-/**
- * An abstract factory for creating decorated Ehcache instances. Implementing classes should provide their own
- * concrete factory extending this factory.
- *
- * @author Abhishek Sanoujam
- */
-public abstract class CacheDecoratorFactory {
-
- /**
- * Dash string : "-"
- */
- public static final String DASH = "-";
-
- /**
- * Creates a decorated {@link Ehcache} using the properties specified for configuring the decorator.
- *
- * If the returned decorated cache has the same name as the underlying cache, then the original cache will be replaced by this new
- * decorated cache in the CacheManager.
- *
- * @param cache
- * a reference to the owning cache
- * @param properties
- * implementation specific properties configured as delimiter
- * separated name value pairs in ehcache.xml
- * @return a decorated Ehcache
- */
- public abstract Ehcache createDecoratedEhcache(Ehcache cache, Properties properties);
-
- /**
- * This method is called when the factory is specified for the defaultCache in the config.
- * Create the decorated {@link Ehcache} using the properties specified.
- *
- * If the returned decorated cache has the same name as the underlying cache, then the original cache will be replaced by this new
- * decorated cache in the CacheManager.
- *
- * @param cache
- * a reference to the owning cache
- * @param properties
- * implementation specific properties configured as delimiter
- * separated name value pairs in ehcache.xml
- * @return a decorated Ehcache
- */
- public abstract Ehcache createDefaultDecoratedEhcache(Ehcache cache, Properties properties);
-
- /**
- * Utility method to generate name of decorated cache to be created using factory specified in defaultCache.
- *
- * @param cache
- * the underlying cache
- * @param cacheNameSuffix
- * Name to be used as suffix. This is normally provided as a property in the decorator config properties. If this parameter
- * is null or empty string, cache.getName() is returned
- * @return Name to be used for the new decorated cache in the form of cache.getName() + "-" + cacheNameSuffix or cache.getName() if
- * cacheNameSuffix is null
- */
- public static String generateDefaultDecoratedCacheName(Ehcache cache, String cacheNameSuffix) {
- if (cacheNameSuffix == null || cacheNameSuffix.trim().length() == 0) {
- return cache.getName();
- }
- return cache.getName() + DASH + cacheNameSuffix;
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/Client6.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/Client6.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/Client6.java (revision 0)
@@ -1,32 +0,0 @@
-package org.terracotta.ehcache.tests.servermap;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-
-import org.terracotta.toolkit.Toolkit;
-
-public class Client6 extends ServerMapClientBase {
-
- public Client6(String[] args) {
- super("test", args);
- }
-
- public static void main(String[] args) {
- new Client6(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- assertClient1Exited(cache);
- BasicServerMapExpressTestHelper.assertValuesInCache(cache);
- }
-
- private void assertClient1Exited(Cache cache) {
- Element element = cache.get("client1-exited");
- if (element == null) { throw new AssertionError("Element should not be null"); }
- if (!"true".equals(element.getObjectValue())) {
- //
- throw new AssertionError("Client1 should have already exited before this");
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicWriteBehindTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicWriteBehindTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicWriteBehindTest.java (revision 0)
@@ -1,88 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.writebehind;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.modules.ehcache.async.AsyncCoordinatorImpl;
-
-import com.tc.l2.L2DebugLogging.LogLevel;
-import com.tc.test.config.model.TestConfig;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class BasicWriteBehindTest extends AbstractCacheTestBase {
- private int totalWriteCount = 0;
- private int totalDeleteCount = 0;
- public static final int ELEMENT_COUNT = 1000;
-
- public BasicWriteBehindTest(TestConfig testConfig) {
- super("basic-writebehind-test.xml", testConfig, BasicWriteBehindTestClient.class);
- configureTCLogging(AsyncCoordinatorImpl.class.getName(), LogLevel.DEBUG);
- }
-
- @Override
- protected void postClientVerification() {
- System.out.println("[Clients processed a total of " + totalWriteCount + " writes]");
- if (totalWriteCount < ELEMENT_COUNT) { throw new AssertionError(totalWriteCount); }
-
- System.out.println("[Clients processed a total of " + totalDeleteCount + " deletes]");
- if (totalDeleteCount < ELEMENT_COUNT / 10) { throw new AssertionError(totalDeleteCount); }
- }
-
- @Override
- protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable {
- super.evaluateClientOutput(clientName, exitCode, output);
-
- FileReader fr = null;
- BufferedReader reader = null;
- StringBuilder strBuilder = new StringBuilder();
- try {
- fr = new FileReader(output);
- reader = new BufferedReader(fr);
- String st = "";
- while ((st = reader.readLine()) != null) {
- strBuilder.append(st);
- }
- } catch (Exception e) {
- throw new AssertionError(e);
- } finally {
- try {
- fr.close();
- reader.close();
- } catch (Exception e) {
- //
- }
- }
-
- // Detect the number of writes that have happened
- int writeCount = detectLargestCount(strBuilder.toString(),
- Pattern.compile("\\[WriteBehindCacheWriter written (\\d+) for " + clientName
- + "\\]"));
- totalWriteCount += writeCount;
- System.out.println("[" + clientName + " processed " + writeCount + " writes]");
-
- // Detect the number of deletes that have happened
- int deleteCount = detectLargestCount(strBuilder.toString(),
- Pattern.compile("\\[WriteBehindCacheWriter deleted (\\d+) for " + clientName
- + "\\]"));
- totalDeleteCount += deleteCount;
- System.out.println("[" + clientName + " processed " + deleteCount + " deletes]");
- }
-
- private int detectLargestCount(String clientOutput, Pattern pattern) {
- Matcher matcher = pattern.matcher(clientOutput);
- int count = 0;
- while (matcher.find()) {
- int parsedCount = Integer.parseInt(matcher.group(1));
- if (parsedCount > count) {
- count = parsedCount;
- }
- }
- return count;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/LockedPoolAccessor.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/LockedPoolAccessor.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/LockedPoolAccessor.java (revision 0)
@@ -1,162 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.pool.impl;
-
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import net.sf.ehcache.pool.Pool;
-import net.sf.ehcache.pool.PoolParticipant;
-import net.sf.ehcache.pool.SizeOfEngine;
-
-/**
- * The PoolAccessor class of the StrictlyBoundedPool
- *
- * @author Ludovic Orban
- * @author Alex Snaps
- */
-final class LockedPoolAccessor extends AbstractPoolAccessor {
-
- private long size;
- private final Lock lock = new ReentrantLock();
-
- /**
- * Creates a locked pool accessor with the specified properties.
- *
- * @param pool pool to be accessed
- * @param poolParticipant accessing poolParticipant
- * @param sizeOfEngine engine used to size objects
- * @param currentSize initial size of the poolParticipant
- */
- LockedPoolAccessor(Pool pool, PoolParticipant poolParticipant, SizeOfEngine sizeOfEngine, long currentSize) {
- super(pool, poolParticipant, sizeOfEngine);
- this.size = currentSize;
- }
-
- /**
- * {@inheritDoc}
- */
- protected long add(long sizeOf, boolean force) throws IllegalArgumentException {
- if (sizeOf < 0L) {
- throw new IllegalArgumentException("cannot add negative size");
- }
-
- lock.lock();
- try {
- while (true) {
- long newSize = getPool().getSize() + sizeOf;
-
- if (newSize <= getPool().getMaxSize()) {
- // there is enough room => add & approve
- size += sizeOf;
- return sizeOf;
- } else {
- // check that the element isn't too big
- if (!force && sizeOf > getPool().getMaxSize()) {
- // this is too big to fit in the pool
- return -1;
- }
-
- // if there is not enough room => evict
- long missingSize = newSize - getPool().getMaxSize();
-
- // eviction must be done outside the lock to avoid deadlocks as it may evict from other pools
- lock.unlock();
- try {
- boolean successful = getPool().getEvictor().freeSpace(getPool().getPoolAccessors(), missingSize);
- if (!force && !successful) {
- // cannot free enough bytes
- return -1;
- }
- } finally {
- lock.lock();
- }
-
- // check that the freed space was not 'stolen' by another thread while
- // eviction was running out of the lock
- if (!force && getPool().getSize() + sizeOf > getPool().getMaxSize()) {
- continue;
- }
-
- size += sizeOf;
- return sizeOf;
- }
- }
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- protected boolean canAddWithoutEvicting(long sizeOf) {
- lock.lock();
- try {
- long newSize = getPool().getSize() + sizeOf;
- return newSize <= getPool().getMaxSize();
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public long delete(long sizeOf) throws IllegalArgumentException {
- checkLinked();
-// if (sizeOf < 0L) {
-// throw new IllegalArgumentException("cannot delete negative size");
-// }
-
- // synchronized makes the size update MT-safe but slow
- lock.lock();
- try {
- size -= sizeOf;
- } finally {
- lock.unlock();
- }
-
- return sizeOf;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getSize() {
- // locking makes the size update MT-safe but slow
- lock.lock();
- try {
- return size;
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- protected void doClear() {
- // locking makes the size update MT-safe but slow
- lock.lock();
- try {
- size = 0L;
- } finally {
- lock.unlock();
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/ClusteredID.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/ClusteredID.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/ClusteredID.java (revision 0)
@@ -1,10 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.transaction;
-
-public interface ClusteredID {
-
- String getOwnerID();
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/SerializableXid.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/SerializableXid.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/SerializableXid.java (revision 0)
@@ -1,106 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.xa;
-
-import java.io.Serializable;
-import java.util.Arrays;
-
-import javax.transaction.xa.Xid;
-
-/**
- * A serializable XID
- *
- * @author Ludovic Orban
- */
-public class SerializableXid implements Xid, Serializable {
-
- private final int formatId;
- private final byte[] globalTransactionId;
- private final byte[] branchQualifier;
-
- /**
- * Create a SerializableXid, copying the GTRID and BQUAL of an existing XID
- *
- * @param xid a SerializableXid
- */
- public SerializableXid(Xid xid) {
- this.formatId = xid.getFormatId();
- this.globalTransactionId = xid.getGlobalTransactionId();
- this.branchQualifier = xid.getBranchQualifier();
- }
-
- /**
- * {@inheritDoc}
- */
- public int getFormatId() {
- return formatId;
- }
-
- /**
- * {@inheritDoc}
- */
- public byte[] getBranchQualifier() {
- return branchQualifier;
- }
-
- /**
- * {@inheritDoc}
- */
- public byte[] getGlobalTransactionId() {
- return globalTransactionId;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean equals(Object obj) {
- if (!(obj instanceof SerializableXid)) {
- return false;
- }
-
- SerializableXid otherXid = (SerializableXid) obj;
- return formatId == otherXid.getFormatId() &&
- Arrays.equals(globalTransactionId, otherXid.getGlobalTransactionId()) &&
- Arrays.equals(branchQualifier, otherXid.branchQualifier);
- }
-
- /**
- * {@inheritDoc}
- */
- public int hashCode() {
- int hashCode = formatId;
- if (globalTransactionId != null) {
- hashCode += Arrays.hashCode(globalTransactionId);
- }
- if (branchQualifier != null) {
- hashCode += Arrays.hashCode(branchQualifier);
- }
- return hashCode;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- return "SerializableXid{" +
- "formatId=" + formatId +
- ", globalTxId=" + Arrays.toString(globalTransactionId) +
- ", branchQualifier=" + Arrays.toString(branchQualifier) +
- '}';
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/bin/relative-paths.bat
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/bin/relative-paths.bat (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/bin/relative-paths.bat (revision 0)
@@ -1,15 +0,0 @@
-@echo off
-
-if "%1" == "tc_install_dir" (
- echo ../../../..
- goto end
-)
-
-if "%1" == "ehcache_jars_dir" (
- echo ../../..
- goto end
-)
-
-echo unknown param
-
-:end
Index: rctags/ehcache-2.10.8.0.7/ehcache/src/test/resources/serializedforms/TransactionalModeSerializationTest.testXa.ser
===================================================================
diff -u -N -r11085 -r11127
Binary files differ
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/BaseClusteredRegionFactoryTestServlet.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/BaseClusteredRegionFactoryTestServlet.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/BaseClusteredRegionFactoryTestServlet.java (revision 0)
@@ -1,46 +0,0 @@
-/*
- * All content copyright (c) Terracotta, Inc., except as may otherwise be noted in a separate copyright
- * notice. All rights reserved.
- */
-package org.terracotta.ehcache.tests.container.hibernate;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.util.Map;
-
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
-
-public abstract class BaseClusteredRegionFactoryTestServlet extends HttpServlet {
-
- @Override
- public final void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
- HttpSession session = request.getSession(true);
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
-
- String server = request.getParameter("server");
- if ("server0".equals(server)) {
- try {
- doServer0(session, request.getParameterMap());
- out.println("OK");
- } catch (Exception e) {
- e.printStackTrace(out);
- }
- } else if ("server1".equals(server)) {
- try {
- doServer1(session, request.getParameterMap());
- out.println("OK");
- } catch (Exception e) {
- e.printStackTrace(out);
- }
- }
- out.flush();
- }
-
- protected abstract void doServer0(HttpSession session, Map parameters) throws Exception;
-
- protected abstract void doServer1(HttpSession session, Map parameters) throws Exception;
-}
Index: rctags/ehcache-2.10.8.0.7/distribution/src/main/assembly/relative-paths.sh
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/src/main/assembly/relative-paths.sh (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/src/main/assembly/relative-paths.sh (revision 0)
@@ -1,13 +0,0 @@
-#!/bin/bash
-
-case "$1" in
- tc_install_dir)
- echo ../../../terracotta
- ;;
- ehcache_jars_dir)
- echo ../../..
- ;;
- *)
- echo "unknown param"
- exit 1
-esac
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/NullStore.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/NullStore.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/NullStore.java (revision 0)
@@ -1,278 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.store;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.writer.CacheWriterManager;
-
-import java.io.IOException;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A store implementation which does not store anything.
- *
- * @author Ludovic Orban
- */
-public final class NullStore extends AbstractStore implements Store {
-
- private NullStore() {
- }
-
- /**
- * Create a new NullStore instance.
- * @return a NullStore instance
- */
- public static NullStore create() {
- return new NullStore();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean put(Element element) throws CacheException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws CacheException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public Element get(Object key) {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Element getQuiet(Object key) {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public List getKeys() {
- return Collections.emptyList();
- }
-
- /**
- * {@inheritDoc}
- */
- public Element remove(Object key) {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Element removeWithWriter(Object key, CacheWriterManager writerManager) throws CacheException {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void removeAll() throws CacheException {
- }
-
- /**
- * {@inheritDoc}
- */
- public Element putIfAbsent(Element element) throws NullPointerException {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException, IllegalArgumentException {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public Element replace(Element element) throws NullPointerException {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- }
-
- /**
- * {@inheritDoc}
- */
- public int getSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getInMemorySize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getOffHeapSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getOnDiskSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getTerracottaClusteredSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getInMemorySizeInBytes() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getOffHeapSizeInBytes() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getOnDiskSizeInBytes() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public Status getStatus() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKey(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyOnDisk(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyOffHeap(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyInMemory(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public void expireElements() {
- }
-
- /**
- * {@inheritDoc}
- */
- public void flush() throws IOException {
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean bufferFull() {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public Policy getInMemoryEvictionPolicy() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setInMemoryEvictionPolicy(Policy policy) {
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getInternalContext() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getMBean() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void recalculateSize(Object key) {
- // no-op
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/concurrent/LongAdder.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/concurrent/LongAdder.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/concurrent/LongAdder.java (revision 0)
@@ -1,201 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-package net.sf.ehcache.util.concurrent;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.Serializable;
-
-/**
- * One or more variables that together maintain an initially zero
- * {@code long} sum. When updates (method {@link #add}) are contended
- * across threads, the set of variables may grow dynamically to reduce
- * contention. Method {@link #sum} (or, equivalently, {@link
- * #longValue}) returns the current total combined across the
- * variables maintaining the sum.
- *
- * This class is usually preferable to {@link java.util.concurrent.atomic.AtomicLong} when
- * multiple threads update a common sum that is used for purposes such
- * as collecting statistics, not for fine-grained synchronization
- * control. Under low update contention, the two classes have similar
- * characteristics. But under high contention, expected throughput of
- * this class is significantly higher, at the expense of higher space
- * consumption.
- *
- *
This class extends {@link Number}, but does not define
- * methods such as {@code hashCode} and {@code compareTo} because
- * instances are expected to be mutated, and so are not useful as
- * collection keys.
- *
- *
jsr166e note: This class is targeted to be placed in
- * java.util.concurrent.atomic.
- *
- * @since 1.8
- * @author Doug Lea
- */
-public class LongAdder extends Striped64 implements Serializable {
- private static final long serialVersionUID = 7249069246863182397L;
-
- /**
- * Version of plus for use in retryUpdate
- */
- final long fn(long v, long x) { return v + x; }
-
- /**
- * Creates a new adder with initial sum of zero.
- */
- public LongAdder() {
- }
-
- /**
- * Adds the given value.
- *
- * @param x the value to add
- */
- public void add(long x) {
- Cell[] as; long b, v; HashCode hc; Cell a; int n;
- if ((as = cells) != null || !casBase(b = base, b + x)) {
- boolean uncontended = true;
- int h = (hc = threadHashCode.get()).code;
- if (as == null || (n = as.length) < 1 ||
- (a = as[(n - 1) & h]) == null ||
- !(uncontended = a.cas(v = a.value, v + x)))
- retryUpdate(x, hc, uncontended);
- }
- }
-
- /**
- * Equivalent to {@code add(1)}.
- */
- public void increment() {
- add(1L);
- }
-
- /**
- * Equivalent to {@code add(-1)}.
- */
- public void decrement() {
- add(-1L);
- }
-
- /**
- * Returns the current sum. The returned value is NOT an
- * atomic snapshot: Invocation in the absence of concurrent
- * updates returns an accurate result, but concurrent updates that
- * occur while the sum is being calculated might not be
- * incorporated.
- *
- * @return the sum
- */
- public long sum() {
- long sum = base;
- Cell[] as = cells;
- if (as != null) {
- int n = as.length;
- for (int i = 0; i < n; ++i) {
- Cell a = as[i];
- if (a != null)
- sum += a.value;
- }
- }
- return sum;
- }
-
- /**
- * Resets variables maintaining the sum to zero. This method may
- * be a useful alternative to creating a new adder, but is only
- * effective if there are no concurrent updates. Because this
- * method is intrinsically racy, it should only be used when it is
- * known that no threads are concurrently updating.
- */
- public void reset() {
- internalReset(0L);
- }
-
- /**
- * Equivalent in effect to {@link #sum} followed by {@link
- * #reset}. This method may apply for example during quiescent
- * points between multithreaded computations. If there are
- * updates concurrent with this method, the returned value is
- * not guaranteed to be the final value occurring before
- * the reset.
- *
- * @return the sum
- */
- public long sumThenReset() {
- long sum = base;
- Cell[] as = cells;
- BASE_UPDATER.set(this, 0);
- if (as != null) {
- int n = as.length;
- for (int i = 0; i < n; ++i) {
- Cell a = as[i];
- if (a != null) {
- sum += a.value;
- a.value = 0L;
- }
- }
- }
- return sum;
- }
-
- /**
- * Returns the String representation of the {@link #sum}.
- * @return the String representation of the {@link #sum}
- */
- public String toString() {
- return Long.toString(sum());
- }
-
- /**
- * Equivalent to {@link #sum}.
- *
- * @return the sum
- */
- public long longValue() {
- return sum();
- }
-
- /**
- * Returns the {@link #sum} as an {@code int} after a narrowing
- * primitive conversion.
- */
- public int intValue() {
- return (int)sum();
- }
-
- /**
- * Returns the {@link #sum} as a {@code float}
- * after a widening primitive conversion.
- */
- public float floatValue() {
- return (float)sum();
- }
-
- /**
- * Returns the {@link #sum} as a {@code double} after a widening
- * primitive conversion.
- */
- public double doubleValue() {
- return (double)sum();
- }
-
- private void writeObject(java.io.ObjectOutputStream s)
- throws java.io.IOException {
- s.defaultWriteObject();
- s.writeLong(sum());
- }
-
- private void readObject(ObjectInputStream s)
- throws IOException, ClassNotFoundException {
- s.defaultReadObject();
- BUSY_UPDATER.set(this, 0);
- cells = null;
- BASE_UPDATER.set(this, s.readLong());
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/distribution/events/src/assemble/bin/start-db.bat
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/events/src/assemble/bin/start-db.bat (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/events/src/assemble/bin/start-db.bat (revision 0)
@@ -1,19 +0,0 @@
-@echo off
-
-if not defined JAVA_HOME (
- echo JAVA_HOME is not defined
- exit /b 1
-)
-
-setlocal
-
-set JAVA_HOME="%JAVA_HOME:"=%"
-set root=%~d0%~p0..
-set root="%root:"=%"
-
-cd %root%
-set h2_jar=%root%\src\main\webapp\WEB-INF\lib\h2-1.1.116.jar
-
-start /b "H2" %JAVA_HOME%\bin\java -cp %h2_jar% org.h2.tools.Server -tcp -tcpAllowOthers
-
-endlocal
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/StatisticsTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/StatisticsTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/StatisticsTest.java (revision 0)
@@ -1,165 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache;
-
-import java.util.concurrent.ExecutionException;
-import net.sf.ehcache.statistics.FlatStatistics;
-import net.sf.ehcache.statistics.StatisticsGateway;
-import net.sf.ehcache.statistics.extended.ExtendedStatistics.Statistic;
-import net.sf.ehcache.store.disk.DiskStoreHelper;
-
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import static org.junit.Assert.fail;
-import static org.hamcrest.core.Is.*;
-import static org.hamcrest.core.IsNot.*;
-import static org.hamcrest.core.IsNull.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-/**
- * Tests for the statistics class
- *
- * @author Greg Luck
- * @version $Id: StatisticsTest.java 7422 2013-04-26 13:01:29Z cdennis $
- */
-public class StatisticsTest extends AbstractCacheTest {
-
- private static final Logger LOG = LoggerFactory.getLogger(StatisticsTest.class.getName());
-
- /**
- * Test statistics directly from Statistics Object
- */
- @Test
- public void testStatisticsFromStatisticsObject() throws InterruptedException, ExecutionException {
- // Set size so the second element overflows to disk.
- Cache cache = new Cache("test", 1, true, false, 5, 2);
- cache.getCacheConfiguration().setMaxEntriesLocalDisk(2);
- manager.addCache(cache);
-
- cache.put(new Element("key1", "value1"));
- cache.put(new Element("key2", "value1"));
-
- // allow disk write thread to complete
- DiskStoreHelper.flushAllEntriesToDisk(cache).get();
-
- cache.get("key1");
- cache.get("key2");
-
- FlatStatistics statistics = cache.getStatistics();
- assertEquals(2, statistics.cacheHitCount());
- assertEquals(1, statistics.localDiskHitCount());
- assertEquals(1, statistics.localHeapHitCount());
- assertEquals(0, statistics.cacheMissCount());
- assertEquals(2, statistics.getSize());
- assertEquals(1, statistics.getLocalHeapSize());
- assertEquals(2, statistics.getLocalDiskSize());
-
- // key 2 should now be in the MemoryStore
- cache.get("key2");
-
- assertEquals(3, statistics.cacheHitCount());
- assertEquals(1, statistics.localDiskHitCount());
- assertEquals(2, statistics.localHeapHitCount());
- assertEquals(0, statistics.cacheMissCount());
-
- // Let the idle expire
- Thread.sleep(6000);
-
- // key 1 should now be expired
- assertThat(cache.get("key1"), nullValue());
- assertEquals(3, statistics.cacheHitCount());
- assertEquals(2, statistics.localDiskHitCount());
- assertEquals(2, statistics.localHeapHitCount());
- assertEquals(1, statistics.cacheMissCount());
-
- // key 2 should also be expired
- assertThat(cache.get("key2"), nullValue());
- assertEquals(3, statistics.cacheHitCount());
- assertEquals(2, statistics.localDiskHitCount());
- assertEquals(2, statistics.localHeapHitCount());
- assertEquals(2, statistics.cacheMissCount());
-
- assertNotNull(statistics.toString());
- }
-
- /**
- * CacheStatistics should always be sensible when the cache has not started.
- */
- @Test
- public void testCacheStatisticsDegradesElegantlyWhenCacheDisposed() {
- Cache cache = new Cache("test", 1, true, false, 5, 2);
- try {
- cache.getStatistics();
- fail();
- } catch (IllegalStateException e) {
- assertEquals("The test Cache is not alive (STATUS_UNINITIALISED)", e.getMessage());
- }
-
- }
-
- /**
- * Tests average get time
- */
- @Test
- public void testAverageGetTime() {
- Ehcache cache = new Cache("test", 0, true, false, 5, 2);
- manager.addCache(cache);
-
- StatisticsGateway statistics = cache.getStatistics();
- Statistic averageGetTime = statistics.cacheGetOperation().latency().average();
- assertThat(averageGetTime.value(), is(Double.NaN));
-
- for (int i = 0; i < 10000; i++) {
- cache.put(new Element(Integer.valueOf(i), "value1"));
- }
- cache.put(new Element("key1", "value1"));
- cache.put(new Element("key2", "value1"));
- for (int i = 0; i < 110000; i++) {
- cache.get(Integer.valueOf(i));
- }
-
- assertThat(averageGetTime.value(), not(Double.NaN));
- }
-
- /**
- * Tests eviction statistics
- */
- @Test
- public void testEvictionStatistics() throws InterruptedException {
- // set to 0 to make it run slow
- Ehcache ehcache = new net.sf.ehcache.Cache("test", 10, false, false, 2, 2);
- manager.addCache(ehcache);
-
- StatisticsGateway statistics = ehcache.getStatistics();
- assertEquals(0, statistics.cacheEvictedCount());
-
- for (int i = 0; i < 10000; i++) {
- ehcache.put(new Element("" + i, "value1"));
- }
- assertEquals(9990, statistics.cacheEvictedCount());
-
- Thread.sleep(2010);
-
- // expiries do not count
- assertEquals(9990, statistics.cacheEvictedCount());
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/com/otherclassloader/Client.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/com/otherclassloader/Client.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/com/otherclassloader/Client.java (revision 0)
@@ -1,94 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package com.otherclassloader;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.event.CacheEventListener;
-import net.sf.ehcache.event.NotificationScope;
-
-import java.io.ByteArrayInputStream;
-import java.util.concurrent.CyclicBarrier;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class Client implements Runnable, CacheEventListener {
-
- private final AtomicInteger putEvents = new AtomicInteger();
- private final String config;
- private final CyclicBarrier barrier;
-
- public Client(String config, CyclicBarrier barrier) {
- this.config = config;
- this.barrier = barrier;
- }
-
- public void run() {
- try {
- run0();
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private void run0() throws Exception {
- CacheManager cm = CacheManager.create(new ByteArrayInputStream(config.getBytes()));
-
- cm.getCache("test").getCacheEventNotificationService().registerListener(this, NotificationScope.ALL);
-
- barrier.await();
-
- long end = System.currentTimeMillis() + 60000L;
- while (System.currentTimeMillis() < end) {
- int puts = putEvents.get();
- System.err.println("puts: " + puts);
- if (puts == 1) { return; }
- if (puts > 1) { throw new AssertionError(puts); }
- Thread.sleep(500);
- }
-
- throw new AssertionError("never saw event");
- }
-
- public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
- //
- }
-
- public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
- System.err.println("TCCL: " + Thread.currentThread().getContextClassLoader());
- System.err.println("put(" + element.getValue() + ") with loader " + element.getValue().getClass().getClassLoader());
-
- if (element.getValue().getClass().getClassLoader() != getClass().getClassLoader()) { throw new AssertionError(); }
-
- // do this after the assertions (so test will fail)
- putEvents.incrementAndGet();
- }
-
- public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
- //
- }
-
- public void notifyElementExpired(Ehcache cache, Element element) {
- //
- }
-
- public void notifyElementEvicted(Ehcache cache, Element element) {
- //
- }
-
- public void notifyRemoveAll(Ehcache cache) {
- //
- }
-
- public void dispose() {
- //
- }
-
- @Override
- public Object clone() throws CloneNotSupportedException {
- throw new CloneNotSupportedException();
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ThreadLocalTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ThreadLocalTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ThreadLocalTest.java (revision 0)
@@ -1,186 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests;
-
-import static org.objectweb.asm.Opcodes.ACC_PRIVATE;
-import static org.objectweb.asm.Opcodes.ACC_PUBLIC;
-import static org.objectweb.asm.Opcodes.ACC_SUPER;
-import static org.objectweb.asm.Opcodes.ALOAD;
-import static org.objectweb.asm.Opcodes.GETFIELD;
-import static org.objectweb.asm.Opcodes.ILOAD;
-import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
-import static org.objectweb.asm.Opcodes.IRETURN;
-import static org.objectweb.asm.Opcodes.PUTFIELD;
-import static org.objectweb.asm.Opcodes.RETURN;
-import static org.objectweb.asm.Opcodes.V1_5;
-import net.sf.ehcache.util.lang.VicariousThreadLocal;
-
-import org.objectweb.asm.ClassWriter;
-import org.objectweb.asm.FieldVisitor;
-import org.objectweb.asm.Label;
-import org.objectweb.asm.MethodVisitor;
-
-import java.lang.ref.WeakReference;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicReference;
-
-import junit.framework.Assert;
-import junit.framework.TestCase;
-
-public class ThreadLocalTest extends TestCase {
-
- public void test() throws Throwable {
- // Construct Value instances from a foreign classloader
- ClassLoader otherClassLoader = createClassLoader();
-
- final AtomicReference> ref = new AtomicReference>();
- ref.set((Class extends Valueable>) otherClassLoader.loadClass("org.terracotta.ehcache.tests.Value"));
-
- VicariousThreadLocal threadLocal = new VicariousThreadLocal() {
-
- @Override
- protected Valueable initialValue() {
- try {
- Valueable v = ref.get().newInstance();
- v.setValue(5);
- return v;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- };
- int value = threadLocal.get().value();
- Assert.assertEquals(5, value);
-
- System.out.println("classloader: " + threadLocal.get().getClass().getClassLoader());
- Assert.assertTrue(otherClassLoader == threadLocal.get().getClass().getClassLoader());
-
- WeakReference weakLoader = new WeakReference(threadLocal.get().getClass()
- .getClassLoader());
-
- System.out.println("Weak loader: " + weakLoader.get());
-
- // release all references to the classloader for gc
- otherClassLoader = null;
- ref.set(null);
- threadLocal = null;
- int count = 0;
- while (true) {
- new PermStress().stress(10000);
- for (int i = 0; i < 10; i++) {
- System.gc();
- }
- // System.out.println("threadLocal.get(): " + threadLocal);
- System.out.println("Weak loader: " + weakLoader.get());
- if (weakLoader.get() == null) {
- break;
- }
- Thread.sleep(1000);
- if (++count >= 60) { throw new AssertionError("Class loader leak"); }
- }
- }
-
- protected ClassLoader createClassLoader() {
- try {
- byte[] valueBytes = createValueClass();
-
- Map classes = new HashMap();
- classes.put("org.terracotta.ehcache.tests.Value", valueBytes);
-
- return new ByteClassLoader(new URL[] {}, getClass().getClassLoader(), classes);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- protected byte[] createValueClass() throws Exception {
- ClassWriter cw = new ClassWriter(0);
- FieldVisitor fv;
- MethodVisitor mv;
-
- cw.visit(V1_5, ACC_PUBLIC + ACC_SUPER, "org/terracotta/ehcache/tests/Value", null, "java/lang/Object",
- new String[] { "org/terracotta/ehcache/tests/Valueable" });
-
- cw.visitSource("Value.java", null);
-
- fv = cw.visitField(ACC_PRIVATE, "v", "I", null, null);
- fv.visitEnd();
- {
- mv = cw.visitMethod(ACC_PUBLIC, "", "()V", null, null);
- mv.visitCode();
- Label l0 = new Label();
- mv.visitLabel(l0);
- mv.visitLineNumber(9, l0);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V");
- Label l1 = new Label();
- mv.visitLabel(l1);
- mv.visitLineNumber(11, l1);
- mv.visitInsn(RETURN);
- Label l2 = new Label();
- mv.visitLabel(l2);
- mv.visitLocalVariable("this", "Lorg/terracotta/ehcache/tests/Value;", null, l0, l2, 0);
- mv.visitMaxs(1, 1);
- mv.visitEnd();
- }
- {
- mv = cw.visitMethod(ACC_PUBLIC, "value", "()I", null, null);
- mv.visitCode();
- Label l0 = new Label();
- mv.visitLabel(l0);
- mv.visitLineNumber(18, l0);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitFieldInsn(GETFIELD, "org/terracotta/ehcache/tests/Value", "v", "I");
- mv.visitInsn(IRETURN);
- Label l1 = new Label();
- mv.visitLabel(l1);
- mv.visitLocalVariable("this", "Lorg/terracotta/ehcache/tests/Value;", null, l0, l1, 0);
- mv.visitMaxs(1, 1);
- mv.visitEnd();
- }
- {
- mv = cw.visitMethod(ACC_PUBLIC, "setValue", "(I)V", null, null);
- mv.visitCode();
- Label l0 = new Label();
- mv.visitLabel(l0);
- mv.visitLineNumber(22, l0);
- mv.visitVarInsn(ALOAD, 0);
- mv.visitVarInsn(ILOAD, 1);
- mv.visitFieldInsn(PUTFIELD, "org/terracotta/ehcache/tests/Value", "v", "I");
- Label l1 = new Label();
- mv.visitLabel(l1);
- mv.visitLineNumber(23, l1);
- mv.visitInsn(RETURN);
- Label l2 = new Label();
- mv.visitLabel(l2);
- mv.visitLocalVariable("this", "Lorg/terracotta/ehcache/tests/Value;", null, l0, l2, 0);
- mv.visitLocalVariable("v", "I", null, l0, l2, 1);
- mv.visitMaxs(2, 2);
- mv.visitEnd();
- }
- cw.visitEnd();
-
- return cw.toByteArray();
- }
-
- public static class ByteClassLoader extends URLClassLoader {
- private final Map extraClassDefs;
-
- public ByteClassLoader(URL[] urls, ClassLoader parent, Map extraClassDefs) {
- super(urls, parent);
- this.extraClassDefs = new HashMap(extraClassDefs);
- }
-
- @Override
- protected Class> findClass(final String name) throws ClassNotFoundException {
- byte[] classBytes = this.extraClassDefs.remove(name);
- if (classBytes != null) { return defineClass(name, classBytes, 0, classBytes.length); }
- return super.findClass(name);
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/net/sf/ehcache/osgi/TestScheduledRefreshFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/net/sf/ehcache/osgi/TestScheduledRefreshFactory.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/net/sf/ehcache/osgi/TestScheduledRefreshFactory.java (revision 0)
@@ -1,21 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package net.sf.ehcache.osgi;
-
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.constructs.scheduledrefresh.ScheduledRefreshCacheExtension;
-import net.sf.ehcache.constructs.scheduledrefresh.ScheduledRefreshConfiguration;
-import net.sf.ehcache.extension.CacheExtension;
-import net.sf.ehcache.extension.CacheExtensionFactory;
-
-import java.util.Properties;
-
-public class TestScheduledRefreshFactory extends CacheExtensionFactory {
-
- @Override
- public CacheExtension createCacheExtension(Ehcache cache, Properties properties) {
- ScheduledRefreshConfiguration conf = new ScheduledRefreshConfiguration().fromProperties(properties).build();
- return new ScheduledRefreshCacheExtension(conf, cache);
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusterCacheEventsRejoinEnabledTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusterCacheEventsRejoinEnabledTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusterCacheEventsRejoinEnabledTest.java (revision 0)
@@ -1,15 +0,0 @@
-package org.terracotta.ehcache.tests;
-
-import com.tc.test.config.model.TestConfig;
-
-/**
- * @author Alex Snaps
- */
-public class ClusterCacheEventsRejoinEnabledTest extends AbstractCacheTestBase {
-
- public ClusterCacheEventsRejoinEnabledTest(TestConfig testConfig) {
- super("basic-rejoin-cache-test.xml", testConfig, ClusterCacheEventsRejoinEnabledClient.class,
- ClusterCacheEventsRejoinEnabledClient.class);
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriter.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriter.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriter.java (revision 0)
@@ -1,152 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.writer;
-
-import net.sf.ehcache.CacheEntry;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.writer.writebehind.operations.SingleOperationType;
-
-import java.util.Collection;
-
-/**
- * A CacheWriter is an interface used for write-through and write-behind caching to a underlying resource.
- *
- * If configured for a cache, CacheWriter's methods will be called on a cache operation. A cache put will cause a CacheWriter write
- * and a cache remove will cause a writer delete.
- *
- * Implementers should create an implementation which handles storing and deleting to an underlying resource.
- *
- *
Write-Through
- * In write-through mode, the cache operation will occur and the writer operation will occur before CacheEventListeners are notified. If
- * the write operation fails an exception will be thrown. This can result in a cache which is inconsistent with the underlying resource.
- * To avoid this, the cache and the underlying resource should be configured to participate in a transaction. In the event of a failure
- * a rollback can return all components to a consistent state.
- *
- *
Write-Behind
- * In write-behind mode, writes are written to a write-behind queue. They are written by a separate execution thread in a configurable
- * way. When used with Terracotta Server Array, the queue is highly available. In addition any node in the cluster may perform the
- * write-behind operations.
- *
- * It's important to note that the operations that are handled by the {@code CacheWriter} don't have any guaranteed ordering in write-behind mode.
- * The processing ordering can be different than the scheduling ordering, so your application needs to be written with this
- * in mind. More information in the CacheWriter chapter of the documentation.
- *
- *
Creation and Configuration
- * CacheWriters can be created using the CacheWriterFactory or explicitly by instantiating them through Java code, giving
- * you access to local resources.
- *
- * The manner upon which a CacheWriter is actually called is determined by the {@link net.sf.ehcache.config.CacheWriterConfiguration} that is set up for cache
- * that is using the CacheWriter.
- *
- * See the CacheWriter chapter in the documentation for more information on how to use writers.
- *
- * @author Greg Luck
- * @author Geert Bevin
- * @version $Id: CacheWriter.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public interface CacheWriter {
-
- /**
- * Creates a clone of this writer. This method will only be called by ehcache before a
- * cache is initialized.
- *
- * Implementations should throw CloneNotSupportedException if they do not support clone
- * but that will stop them from being used with defaultCache.
- *
- * @return a clone
- * @throws CloneNotSupportedException if the extension could not be cloned.
- */
- public CacheWriter clone(Ehcache cache) throws CloneNotSupportedException;
-
-
- /**
- * Notifies writer to initialise themselves.
- *
- * This method is called during the Cache's initialise method after it has changed it's
- * status to alive. Cache operations are legal in this method. If you register a cache writer
- * manually after a cache has been initialised already, this method will be called on the
- * cache writer as soon as it has been registered.
- *
- * Note that if you reuse cache writer instances or create a factory that returns the
- * same cache writer instance as a singleton, your init
method should be able
- * to handle that situation. Unless you perform this multiple usage of a cache writer yourself,
- * Ehcache will not do this though. So in the majority of the use cases, you don't need to do
- * anything special.
- *
- * @throws net.sf.ehcache.CacheException
- */
- void init();
-
- /**
- * Providers may be doing all sorts of exotic things and need to be able to clean up on
- * dispose.
- *
- * Cache operations are illegal when this method is called. The cache itself is partly
- * disposed when this method is called.
- */
- void dispose() throws CacheException;
-
- /**
- * Write the specified value under the specified key to the underlying store.
- * This method is intended to support both key/value creation and value update for a specific key.
- *
- * @param element the element to be written
- */
- void write(Element element) throws CacheException;
-
- /**
- * Write the specified Elements to the underlying store. This method is intended to support both insert and update.
- * If this operation fails (by throwing an exception) after a partial success,
- * the convention is that entries which have been written successfully are to be removed from the specified mapEntries,
- * indicating that the write operation for the entries left in the map has failed or has not been attempted.
- *
- * @param elements the Elements to be written
- */
- void writeAll(Collection elements) throws CacheException;
-
-
- /**
- * Delete the cache entry from the store
- *
- * @param entry the cache entry that is used for the delete operation
- */
- void delete(CacheEntry entry) throws CacheException;
-
-
- /**
- * Remove data and keys from the underlying store for the given collection of keys, if present. If this operation fails
- * (by throwing an exception) after a partial success, the convention is that keys which have been erased successfully
- * are to be removed from the specified keys, indicating that the erase operation for the keys left in the collection
- * has failed or has not been attempted.
- *
- * @param entries the entries that have been removed from the cache
- */
- void deleteAll(Collection entries) throws CacheException;
-
- /**
- * This method will be called, whenever an Element couldn't be handled by the writer and all
- * the {@link net.sf.ehcache.config.CacheWriterConfiguration#getRetryAttempts() retryAttempts} have been tried.
- * When batching is enabled all the elements in the failing batch will be passed to this methods
- *
Try to not throw RuntimeExceptions from this method. Should an Exception occur, it will be logged, but
- * the element will be lost anyways.
- * @param element the Element that triggered the failure, or one of the elements part of the batch that failed
- * @param operationType the operation we tried to execute
- * @param e the RuntimeException thrown by the Writer when the last retry attempt was being executed
- */
- void throwAway(Element element, SingleOperationType operationType, RuntimeException e);
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/QueryCacheInvalidationServlet.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/QueryCacheInvalidationServlet.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/QueryCacheInvalidationServlet.java (revision 0)
@@ -1,69 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.container.hibernate.nontransactional;
-
-import org.hibernate.Session;
-import org.hibernate.Transaction;
-import org.hibernate.stat.SecondLevelCacheStatistics;
-import org.hibernate.stat.Statistics;
-import org.junit.Assert;
-import org.terracotta.ehcache.tests.container.hibernate.BaseClusteredRegionFactoryTestServlet;
-import org.terracotta.ehcache.tests.container.hibernate.domain.Item;
-
-import java.util.Map;
-
-import javax.servlet.http.HttpSession;
-
-public class QueryCacheInvalidationServlet extends BaseClusteredRegionFactoryTestServlet {
-
- @Override
- protected void doServer0(HttpSession session, Map parameters) throws Exception {
- HibernateUtil.dropAndCreateDatabaseSchema();
-
- Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
- stats.setStatisticsEnabled(true);
-
- Session s = HibernateUtil.getSessionFactory().openSession();
- Transaction t = s.beginTransaction();
- Item i = new Item();
- i.setName("widget");
- i.setDescription("A really top-quality, full-featured widget.");
- s.persist(i);
- t.commit();
- s.close();
-
- final SecondLevelCacheStatistics statistics = stats.getSecondLevelCacheStatistics(Item.class.getName());
- Assert.assertEquals(1, statistics.getPutCount());
- Assert.assertEquals(1, statistics.getElementCountInMemory());
- }
-
- @Override
- protected void doServer1(HttpSession session, Map parameters) throws Exception {
- Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
- stats.setStatisticsEnabled(true);
-
- Session s = HibernateUtil.getSessionFactory().openSession();
- Transaction t = s.beginTransaction();
- Item i = (Item) s.get(Item.class, Long.valueOf(1L));
-
- SecondLevelCacheStatistics slcs = stats.getSecondLevelCacheStatistics(Item.class.getName());
-
- Assert.assertEquals(1, slcs.getHitCount());
- Assert.assertEquals(0, slcs.getMissCount());
-
- i.setDescription("A bog standard item");
-
- t.commit();
- s.close();
-
- Assert.assertEquals(1, slcs.getPutCount());
-
- // cleanup
- s = HibernateUtil.getSessionFactory().openSession();
- t = s.beginTransaction();
- s.delete(i);
- t.commit();
- s.close();
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/CacheManagerPeerProvider.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/CacheManagerPeerProvider.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/CacheManagerPeerProvider.java (revision 0)
@@ -1,80 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.distribution;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-
-import java.util.List;
-
-/**
- * Provides a discovery service to locate {@link CachePeer} listener peers for a Cache.
- * @author Greg Luck
- * @version $Id: CacheManagerPeerProvider.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public interface CacheManagerPeerProvider {
-
- /**
- * Register a new peer.
- * @param nodeId Identifies a node in this replication scheme (ex: RMI URL)
- */
- void registerPeer(String nodeId);
-
- /**
- * Unregisters a peer.
- *
- * @param nodeId Identifies a node in this replication scheme (ex: RMI URL)
- */
- void unregisterPeer(String nodeId);
-
- /**
- * @return a list of {@link CachePeer} peers for the given cache, excluding the local peer.
- */
- List listRemoteCachePeers(Ehcache cache) throws CacheException;
-
- /**
- * Notifies providers to initialise themselves.
- * @throws CacheException
- */
- void init();
-
-
- /**
- * Providers may be doing all sorts of exotic things and need to be able to clean up on dispose.
- * @throws CacheException
- */
- void dispose() throws CacheException;
-
- /**
- * Time for a cluster to form. This varies considerably, depending on the implementation.
- * @return the time in ms, for a cluster to form
- */
- long getTimeForClusterToForm();
-
-
- /**
- * The replication scheme. Each peer provider has a scheme name, which can be used to specify
- * the scheme for replication and bootstrap purposes. Each CacheReplicator
should lookup
- * the provider for its scheme type during replication. Similarly a BootstrapCacheLoader
- * should also look up the provider for its scheme.
- *
- * @since 1.6 introduced to permit multiple distribution schemes to be used in the same CacheManager
- * @return the well-known scheme name, which is determined by the replication provider author.
- */
- String getScheme();
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/config/ehcache-terracotta.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/config/ehcache-terracotta.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/config/ehcache-terracotta.xml (revision 0)
@@ -1,823 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/nonstop/util/package.html
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/nonstop/util/package.html (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/nonstop/util/package.html (revision 0)
@@ -1,10 +0,0 @@
-
-
-
-
-Ehcache-nonstopcache utility package
-
-This package contains utility classes for NonStopCache features
-
-
-
Index: rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/jetty6.1/9082/logs/.placeholder
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/jetty6.1/9082/logs/.placeholder (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/jetty6.1/9082/logs/.placeholder (revision 0)
@@ -1 +0,0 @@
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/jetty6.1/9081/logs/.placeholder
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/jetty6.1/9081/logs/.placeholder (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/jetty6.1/9081/logs/.placeholder (revision 0)
@@ -1 +0,0 @@
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/management/Store.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/management/Store.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/management/Store.java (revision 0)
@@ -1,131 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.management;
-
-import java.io.Serializable;
-import javax.management.Attribute;
-import javax.management.AttributeList;
-import javax.management.AttributeNotFoundException;
-import javax.management.DynamicMBean;
-import javax.management.InvalidAttributeValueException;
-import javax.management.MBeanException;
-import javax.management.MBeanInfo;
-import javax.management.MalformedObjectNameException;
-import javax.management.NotCompliantMBeanException;
-import javax.management.ObjectName;
-import javax.management.ReflectionException;
-import javax.management.StandardMBean;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.hibernate.management.impl.EhcacheHibernateMbeanNames;
-
-/**
- * Wrapper class for store specific dynamic mbeans.
- *
- * @author Chris Dennis
- */
-public final class Store implements Serializable, DynamicMBean {
-
- private static final long serialVersionUID = 3477287016924524437L;
-
- private final ObjectName objectName;
- private final DynamicMBean storeBean;
-
- private Store(Ehcache ehcache, Object storeBean) throws NotCompliantMBeanException {
- this.objectName = createObjectName(ehcache.getCacheManager().getName(), ehcache.getName());
- if (storeBean instanceof DynamicMBean) {
- this.storeBean = (DynamicMBean) storeBean;
- } else {
- this.storeBean = new StandardMBean(storeBean, null);
- }
- }
-
- /**
- * Get the optional store management bean for the given cache.
- */
- static Store getBean(Ehcache cache) throws NotCompliantMBeanException {
- if (cache instanceof net.sf.ehcache.Cache) {
- Object bean = ((net.sf.ehcache.Cache) cache).getStoreMBean();
- if (bean != null) {
- return new Store(cache, bean);
- }
- }
- return null;
- }
-
- /**
- * Creates an object name using the scheme "net.sf.ehcache:type=Store,CacheManager=,name="
- */
- static ObjectName createObjectName(String cacheManagerName, String cacheName) {
- try {
- return new ObjectName("net.sf.ehcache:type=Store,CacheManager=" + cacheManagerName + ",name="
- + EhcacheHibernateMbeanNames.mbeanSafe(cacheName));
- } catch (MalformedObjectNameException e) {
- throw new CacheException(e);
- }
- }
-
- /**
- * @return the object name for this MBean
- */
- public ObjectName getObjectName() {
- return objectName;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException, ReflectionException {
- return storeBean.getAttribute(attribute);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setAttribute(Attribute attribute) throws AttributeNotFoundException, InvalidAttributeValueException,
- MBeanException, ReflectionException {
- storeBean.setAttribute(attribute);
- }
-
- /**
- * {@inheritDoc}
- */
- public AttributeList getAttributes(String[] attributes) {
- return storeBean.getAttributes(attributes);
- }
-
- /**
- * {@inheritDoc}
- */
- public AttributeList setAttributes(AttributeList attributes) {
- return storeBean.setAttributes(attributes);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException {
- return storeBean.invoke(actionName, params, signature);
- }
-
- /**
- * {@inheritDoc}
- */
- public MBeanInfo getMBeanInfo() {
- return storeBean.getMBeanInfo();
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/checkstyle/checkstyle.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/checkstyle/checkstyle.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/checkstyle/checkstyle.xml (revision 0)
@@ -1,209 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/CopyOnWriteClient.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/CopyOnWriteClient.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/CopyOnWriteClient.java (revision 0)
@@ -1,30 +0,0 @@
-package org.terracotta.ehcache.tests;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-
-import org.terracotta.toolkit.Toolkit;
-
-import java.io.Serializable;
-
-public class CopyOnWriteClient extends ClientBase {
-
- public CopyOnWriteClient(String[] args) {
- super("test", args);
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit toolkit) throws Throwable {
- final Foo foo = new Foo();
- Element e = new Element("foo", foo);
- cache.put(e);
- Object o = cache.get("foo").getObjectValue();
-
- if (o == foo) { throw new AssertionError(); }
- }
-
- private static class Foo implements Serializable {
- //
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/ClassSelector.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/ClassSelector.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/ClassSelector.java (revision 0)
@@ -1,63 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.manager.selector;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.transaction.TransactionManager;
-
-/**
- * Abstract selector for instanciating a class
- *
- * @author Ludovic Orban
- */
-public abstract class ClassSelector extends Selector {
- private static final Logger LOG = LoggerFactory.getLogger(ClassSelector.class);
-
- private final String classname;
-
- /**
- * Constructor
- *
- * @param vendor the transaction manager vendor name
- * @param classname the name of the class to instanciate
- */
- public ClassSelector(String vendor, String classname) {
- super(vendor);
- this.classname = classname;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected TransactionManager doLookup() {
- TransactionManager transactionManager = null;
-
- try {
- Class txManagerClass = Class.forName(classname);
- transactionManager = (TransactionManager) txManagerClass.newInstance();
- } catch (ClassNotFoundException e) {
- LOG.debug("FactorySelector failed lookup", e);
- } catch (InstantiationException e) {
- LOG.debug("FactorySelector failed lookup", e);
- } catch (IllegalAccessException e) {
- LOG.debug("FactorySelector failed lookup", e);
- }
- return transactionManager;
- }
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SimpleTx1.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SimpleTx1.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SimpleTx1.java (revision 0)
@@ -1,161 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.txns;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup;
-import net.sf.ehcache.transaction.manager.TransactionManagerLookup;
-
-import org.junit.Assert;
-import org.terracotta.toolkit.Toolkit;
-
-import java.io.Serializable;
-
-import javax.transaction.TransactionManager;
-
-public class SimpleTx1 extends AbstractTxClient {
-
- public SimpleTx1(String[] args) {
- super(args);
-
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit toolkit) throws Throwable {
- final TransactionManagerLookup lookup = new DefaultTransactionManagerLookup();
- final TransactionManager txnManager = lookup.getTransactionManager();
- int commitCount = 0;
- int rollbackCount = 0;
- System.out.println(txnManager);
-
- SomeClass instance = new SomeClass(1);
- instance.someOtherInstance = new SomeClass(2);
-
- Assert.assertTrue(cache.getCacheConfiguration().isCopyOnRead());
- Assert.assertTrue(cache.getCacheConfiguration().isCopyOnWrite());
-
- try {
- txnManager.begin();
- cache.put(new Element("key1", "value1"));
-
- cache.put(new Element("someInstance", instance));
-
- Element element = cache.get("key1");
- System.out.println("key1:" + element.getValue());
- System.out.println("size1: " + cache.getSize());
- Assert.assertTrue("Should NOT be the same instance", instance != cache.get("someInstance").getValue());
- txnManager.commit();
- commitCount++;
- } catch (Exception e) {
- e.printStackTrace();
- txnManager.rollback();
- rollbackCount++;
- }
-
- instance.someValue = 3;
-
- try {
- txnManager.begin();
- cache.put(new Element("key1", "value2"));
-
- Assert.assertTrue("Should NOT be the same instance", instance != cache.get("someInstance").getValue());
- Assert.assertTrue("Should NOT reflect the post commit change!", instance.someValue != ((SomeClass)cache.get("someInstance").getValue()).someValue);
-
- Element element = cache.get("key1");
- System.out.println("key1:" + element.getValue());
- if (!element.getValue().equals("value2")) { throw new AssertionError("put should be visible in same thread"); }
- System.out.println("size1: " + cache.getSize());
- throw new Exception();
- } catch (AssertionError e) {
- throw new AssertionError(e);
- } catch (Exception e) {
- txnManager.rollback();
- rollbackCount++;
- }
-
- try {
- txnManager.begin();
-
- Element element = cache.get("key1");
- System.out.println("key1:" + element.getValue());
- if (!element.getValue().equals("value1")) { throw new AssertionError("should be old value"); }
- System.out.println("size1: " + cache.getSize());
-
- txnManager.commit();
- commitCount++;
- } catch (AssertionError e) {
- throw new AssertionError(e);
- } catch (Exception e) {
- e.printStackTrace();
- txnManager.rollback();
- rollbackCount++;
- }
-
- if (commitCount != 2) { throw new AssertionError("expected 2 commits got: " + commitCount); }
-
- if (rollbackCount != 1) { throw new AssertionError("expected 1 rollback got: " + rollbackCount); }
-
- try {
- txnManager.begin();
-
- cache.put(new Element("remove1", "removeValue"));
- System.out.println("size1: " + cache.getSize());
-
- txnManager.commit();
- commitCount++;
- } catch (AssertionError e) {
- throw new AssertionError(e);
- } catch (Exception e) {
- txnManager.rollback();
- rollbackCount++;
- }
-
- if (commitCount != 3) { throw new AssertionError("expected 3 commits got: " + commitCount); }
-
- if (rollbackCount != 1) { throw new AssertionError("expected 1 rollback got: " + rollbackCount); }
-
- try {
- txnManager.begin();
-
- int sizeBefore = cache.getSize();
- cache.remove("remove1");
- System.out.println("size1: " + cache.getSize());
-
- int sizeAfter = cache.getSize();
- if (sizeAfter >= sizeBefore) { throw new AssertionError("remove should reduce the size, expected: "
- + (sizeBefore - 1) + " got: " + sizeAfter); }
-
- Element removedElement = cache.get("remove1");
- if (removedElement != null) { throw new AssertionError("remove1 key should not exist!"); }
-
- txnManager.commit();
- commitCount++;
- } catch (AssertionError e) {
- throw new AssertionError(e);
- } catch (Exception e) {
- txnManager.rollback();
- rollbackCount++;
- }
-
- if (commitCount != 4) { throw new AssertionError("expected 4 commits got: " + commitCount); }
-
- if (rollbackCount != 1) { throw new AssertionError("expected 1 rollback got: " + rollbackCount); }
- getBarrierForAllClients().await();
- }
-
- public static void main(String[] args) {
- new SimpleTx1(args).run();
- }
-
- public static final class SomeClass implements Serializable {
-
- public int someValue;
- public SomeClass someOtherInstance;
-
- public SomeClass(final int someValue) {
- this.someValue = someValue;
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/ExceptionOnTimeoutStore.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/ExceptionOnTimeoutStore.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/ExceptionOnTimeoutStore.java (revision 0)
@@ -1,621 +0,0 @@
-/**
- * Copyright Terracotta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
- * either express or implied. See the License for the specific language governing permissions and limitations under the
- * License.
- */
-
-package org.terracotta.modules.ehcache.store.nonstop;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.constructs.nonstop.NonStopCacheException;
-import net.sf.ehcache.search.Attribute;
-import net.sf.ehcache.search.Results;
-import net.sf.ehcache.search.attribute.AttributeExtractor;
-import net.sf.ehcache.store.ElementValueComparator;
-import net.sf.ehcache.store.Policy;
-import net.sf.ehcache.store.StoreListener;
-import net.sf.ehcache.store.StoreQuery;
-import net.sf.ehcache.store.TerracottaStore;
-import net.sf.ehcache.writer.CacheWriterManager;
-import net.sf.ehcache.writer.writebehind.WriteBehind;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Implementation of {@link TerracottaStore} that throws {@link NonStopCacheException} for all operations.
- *
- * @author Abhishek Sanoujam
- */
-public final class ExceptionOnTimeoutStore implements TerracottaStore {
-
- /**
- * the singleton instance
- */
- private static final ExceptionOnTimeoutStore INSTANCE = new ExceptionOnTimeoutStore();
-
- /**
- * private constructor
- */
- private ExceptionOnTimeoutStore() {
- //
- }
-
- /**
- * returns the singleton instance
- */
- public static ExceptionOnTimeoutStore getInstance() {
- return INSTANCE;
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Element get(final Object key) throws IllegalStateException, CacheException {
- throw new NonStopCacheException("get timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Element getQuiet(final Object key) throws IllegalStateException, CacheException {
- throw new NonStopCacheException("getQuiet timed out");
- }
-
- /**
- * {@inheritDoc}
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Map getAllQuiet(Collection> keys) {
- throw new NonStopCacheException("getAllQuiet for '" + keys.size() + "' keys timed out");
- }
-
- /**
- * {@inheritDoc}
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Map getAll(Collection> keys) {
- throw new NonStopCacheException("getAll for '" + keys.size() + "' keys timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public List getKeys() throws IllegalStateException, CacheException {
- throw new NonStopCacheException("getKeys timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean put(final Element element) throws IllegalArgumentException, IllegalStateException, CacheException {
- throw new NonStopCacheException("put timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void putAll(final Collection elements) throws CacheException {
- throw new NonStopCacheException("putAll for " + elements.size() + " elements timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Element remove(final Object key) throws IllegalStateException {
- throw new NonStopCacheException("remove timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void removeAll(final Collection> keys) throws IllegalStateException {
- throw new NonStopCacheException("removeAll for " + keys.size() + " keys timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void removeAll() throws IllegalStateException, CacheException {
- throw new NonStopCacheException("removeAll timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void flush() throws IllegalStateException, CacheException {
- throw new NonStopCacheException("flush timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Object getInternalContext() {
- throw new NonStopCacheException("getInternalContext timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public int getSize() throws IllegalStateException, CacheException {
- throw new NonStopCacheException("getSize timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Element putIfAbsent(Element element) throws NullPointerException {
- throw new NonStopCacheException("putIfAbsent timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Element replace(Element element) throws NullPointerException {
- throw new NonStopCacheException("replace timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void addStoreListener(StoreListener listener) {
- throw new NonStopCacheException("addStoreListener timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean bufferFull() {
- throw new NonStopCacheException("bufferFull timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean containsKey(Object key) {
- throw new NonStopCacheException("containsKey timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean containsKeyInMemory(Object key) {
- throw new NonStopCacheException("containsKeyInMemory timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean containsKeyOffHeap(Object key) {
- throw new NonStopCacheException("containsKeyOffHeap timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean containsKeyOnDisk(Object key) {
- throw new NonStopCacheException("containsKeyOnDisk timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void dispose() {
- throw new NonStopCacheException("dispose timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Results executeQuery(StoreQuery query) {
- throw new NonStopCacheException("executeQuery timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void expireElements() {
- throw new NonStopCacheException("expireElements timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Policy getInMemoryEvictionPolicy() {
- throw new NonStopCacheException("getInMemoryEvictionPolicy timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public int getInMemorySize() {
- throw new NonStopCacheException("getInMemorySize timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public long getInMemorySizeInBytes() {
- throw new NonStopCacheException("getInMemorySizeInBytes timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Object getMBean() {
- throw new NonStopCacheException("getMBean timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public int getOffHeapSize() {
- throw new NonStopCacheException("getOffHeapSize timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public long getOffHeapSizeInBytes() {
- throw new NonStopCacheException("getOffHeapSizeInBytes timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public int getOnDiskSize() {
- throw new NonStopCacheException("getOnDiskSize timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public long getOnDiskSizeInBytes() {
- throw new NonStopCacheException("getOnDiskSizeInBytes timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean hasAbortedSizeOf() {
- throw new NonStopCacheException("hasAbortedSizeOf timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Status getStatus() {
- throw new NonStopCacheException("getStatus timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public int getTerracottaClusteredSize() {
- throw new NonStopCacheException("getTerracottaClusteredSize timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean isCacheCoherent() {
- throw new NonStopCacheException("isCacheCoherent timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean isClusterCoherent() {
- throw new NonStopCacheException("isClusterCoherent timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean isNodeCoherent() {
- throw new NonStopCacheException("isNodeCoherent timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws CacheException {
- throw new NonStopCacheException("putWithWriter timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException {
- throw new NonStopCacheException("removeElement timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void removeStoreListener(StoreListener listener) {
- throw new NonStopCacheException("removeStoreListener timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Element removeWithWriter(Object key, CacheWriterManager writerManager) throws CacheException {
- throw new NonStopCacheException("removeWithWriter timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException,
- IllegalArgumentException {
- throw new NonStopCacheException("replace timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void setAttributeExtractors(Map extractors) {
- throw new NonStopCacheException("setAttributeExtractors timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void setInMemoryEvictionPolicy(Policy policy) {
- throw new NonStopCacheException("setInMemoryEvictionPolicy timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void setNodeCoherent(boolean coherent) throws UnsupportedOperationException {
- throw new NonStopCacheException("setNodeCoherent timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public void waitUntilClusterCoherent() throws UnsupportedOperationException {
- throw new NonStopCacheException("waitUntilClusterCoherent timed out");
- }
-
- @Override
- public Set getSearchAttributes() {
- throw new NonStopCacheException("getSearchAttributes timed out");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link NonStopCacheException}
- */
- @Override
- public Attribute getSearchAttribute(String attributeName) {
- throw new NonStopCacheException("getSearchAttribute timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set getLocalKeys() {
- throw new NonStopCacheException("getLocalKeys() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public CacheConfiguration.TransactionalMode getTransactionalMode() {
- throw new NonStopCacheException("getTransactionalMode() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- public Element unlockedGet(Object key) {
- throw new NonStopCacheException("unlockedGet() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- public Element unlockedGetQuiet(Object key) {
- throw new NonStopCacheException("unlockedGetQuiet() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Element unsafeGet(Object key) {
- throw new NonStopCacheException("unsafeGet() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void quickClear() {
- throw new NonStopCacheException("quickClear() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int quickSize() {
- throw new NonStopCacheException("quickSize() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- public Element unsafeGetQuiet(Object key) {
- throw new NonStopCacheException("unsafeGetQuiet() timed out");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void recalculateSize(Object key) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public WriteBehind createWriteBehind() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void notifyCacheEventListenersChanged() {
- throw new NonStopCacheException("notifyCacheEventListenersChanged() timed out");
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/store/CachingTier.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/store/CachingTier.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/store/CachingTier.java (revision 0)
@@ -1,166 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.store;
-
-import java.util.concurrent.Callable;
-
-/**
- * This interface is to be implemented by CachingTier that sit above the {@link AuthoritativeTier}.
- * An important contract here is that a value being faulted in get is to be entirely faulted in before it
- * can become an eviction candidate, i.e. this cache can never evict mappings being faulted in
- *
- * @param
- * @param
- * @author Alex Snaps
- */
-public interface CachingTier {
-
- /**
- * Returns {@code true} if values should be loaded to this cache on put.
- *
- * This may be a dynamic decision, based for example on the occupancy of the cache.
- *
- * @return {@code true} if values should be loaded on put
- */
- boolean loadOnPut();
-
- /**
- * Returns the value associated with the key, or populates the mapping using the Callable instance
- *
- * @param key the key to look up
- * @param source the source to use, in the case of no mapping present
- * @param updateStats true to update the stats, false otherwise
- * @return the value mapped to the key
- */
- V get(K key, Callable source, boolean updateStats);
-
- /**
- * Removes the mapping associated to the key passed in
- *
- * @param key the key to the mapping to remove
- * @return the value removed, null if none
- */
- V remove(K key);
-
- /**
- * Clears the cache...
- * Doesn't notify any listeners
- */
- void clear();
-
- /**
- * Clears the cache notifying listeners
- */
- void clearAndNotify();
-
- /**
- * Adds a {@link Listener} to the cache
- *
- * @param listener the listener to add
- */
- void addListener(Listener listener);
-
- /**
- * Can we avoid having this somehow ?
- *
- * @return the count of entries held in heap
- */
- @Deprecated
- int getInMemorySize();
-
- /**
- * Can we avoid having this somehow ?
- *
- * @return the count of entries held off heap
- */
- @Deprecated
- int getOffHeapSize();
-
- /**
- * This should go away once the stats are in
- * As the method is only there to know what tier the key is going to be fetched from
- *
- * @param key
- * @return
- */
- @Deprecated
- boolean contains(K key);
-
- /**
- * CacheTier could keep hold of the PoolAccessors for each tier...
- * But what about non pooled resources ?
- *
- * @return
- */
- @Deprecated
- long getInMemorySizeInBytes();
-
- /**
- * CacheTier could keep hold of the PoolAccessors for each tier...
- * But what about non pooled resources ?
- *
- * @return
- */
- @Deprecated
- long getOffHeapSizeInBytes();
-
- /**
- * CacheTier could keep hold of the PoolAccessors for each tier...
- * But what about non pooled resources ?
- *
- * @return
- */
- @Deprecated
- long getOnDiskSizeInBytes();
-
- /**
- * This is evil! Don't call this!
- * @param key the key to perform the recalculation for
- */
- @Deprecated
- void recalculateSize(K key);
-
- /**
- * queries the potential eviction policy for the heap caching tier
- * @return the policy
- */
- @Deprecated
- Policy getEvictionPolicy();
-
- /**
- * sets the eviction policy on the heap caching tier
- * @param policy the policy to use
- */
- @Deprecated
- void setEvictionPolicy(Policy policy);
-
- /**
- * A listener that will be notified when eviction of a mapping happens
- *
- * @param
- * @param
- */
- public interface Listener {
-
- /**
- * Invoked when a mapping is evicted.
- *
- * @param key the key evicted
- * @param value the value evicted
- */
- void evicted(K key, V value);
- }
-}
Index: rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/ClusteredCacheInternalContext.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/ClusteredCacheInternalContext.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/ClusteredCacheInternalContext.java (revision 0)
@@ -1,33 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache;
-
-import net.sf.ehcache.concurrent.CacheLockProvider;
-import net.sf.ehcache.concurrent.Sync;
-
-import org.terracotta.toolkit.Toolkit;
-
-public class ClusteredCacheInternalContext implements ToolkitLookup, CacheLockProvider {
- private final Toolkit toolkit;
- private final CacheLockProvider cacheLockProvider;
-
- public ClusteredCacheInternalContext(Toolkit toolkit, CacheLockProvider cacheLockProvider) {
- this.toolkit = toolkit;
- this.cacheLockProvider = cacheLockProvider;
- }
-
- @Override
- public Sync getSyncForKey(Object key) {
- return cacheLockProvider.getSyncForKey(key);
- }
-
- @Override
- public Toolkit getToolkit() {
- return toolkit;
- }
-
- public CacheLockProvider getCacheLockProvider() {
- return cacheLockProvider;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/store/EvictionListenerTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/store/EvictionListenerTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/store/EvictionListenerTest.java (revision 0)
@@ -1,137 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.store;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.event.CacheEventListener;
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-import org.terracotta.toolkit.Toolkit;
-import org.terracotta.toolkit.concurrent.ToolkitBarrier;
-import org.terracotta.toolkit.concurrent.atomic.ToolkitAtomicLong;
-
-import com.tc.properties.TCPropertiesConsts;
-import com.tc.test.config.model.TestConfig;
-
-import java.util.concurrent.Callable;
-
-import static org.terracotta.test.util.WaitUtil.waitUntilCallableReturnsTrue;
-
-public class EvictionListenerTest extends AbstractCacheTestBase {
-
- private static final int NODE_COUNT = 2;
-
- public EvictionListenerTest(TestConfig testConfig) {
- super("evict-cache-test.xml", testConfig, App.class, App.class);
-// testConfig.setDgcEnabled(true);
-// testConfig.setDgcIntervalInSec(10);
-// testConfig.getL2Config().setMaxHeap(1024);
- testConfig.addTcProperty(TCPropertiesConsts.EHCACHE_EVICTOR_LOGGING_ENABLED, "true");
- }
-
- public static class App extends ClientBase implements CacheEventListener {
-
- private final ToolkitBarrier barrier;
- private final ToolkitAtomicLong actualEvictionsCount;
-
- public App(String[] args) {
- super("test2", args);
- this.actualEvictionsCount = getClusteringToolkit().getAtomicLong("testLong");
- this.barrier = getClusteringToolkit().getBarrier("testBarrier", NODE_COUNT);
- }
-
- public static void main(String[] args) {
- new App(args).run();
- }
-
- @Override
- protected void runTest(final Cache cache, final Toolkit clusteringToolkit) throws Throwable {
- final int numOfElements = 1000;
- final long maxEntriesInCache = cache.getCacheConfiguration().getMaxEntriesInCache();
- final long expectedEvictionsCount = numOfElements - maxEntriesInCache;
- final int index = barrier.await();
-
- cache.getCacheEventNotificationService().registerListener(this);
- // XXX: assert that the cache is clustered via methods on cache config (when methods exist)
- System.err.println(cache);
- assertEquals(0, cache.getSize());
- assertEquals(1, cache.getCacheConfiguration().getTerracottaConfiguration().getConcurrency());
- barrier.await();
-
- if (index == 0) {
- for (int i = 0; i < numOfElements; i++) {
- cache.put(new Element(i, "value"));
- }
- }
- barrier.await();
-
- waitUntilCallableReturnsTrue(new Callable() {
- @Override
- public Boolean call() throws Exception {
- System.out.println("Client " + index + ", cache size so far: " + cache.getSize());
- return cache.getSize() == maxEntriesInCache; // it must evict exactly 600 elements, because concurrency = 1
- }
- });
- System.out.println("Client " + index + ", final cache size: " + cache.getSize());
- barrier.await();
-
- waitUntilCallableReturnsTrue(new Callable() {
- @Override
- public Boolean call() throws Exception {
- System.out.println("Client " + index + ", evicted count so far: " + actualEvictionsCount.get());
- // NOTE! Only one client should ever receive eviction events, and we actually don't know which one
- return actualEvictionsCount.get() == expectedEvictionsCount;
- }
- });
- barrier.await();
-
- assertEquals(expectedEvictionsCount, this.actualEvictionsCount.get());
- }
-
- @Override
- public void dispose() {
- // don't care
- }
-
- @Override
- public void notifyElementEvicted(Ehcache cache, Element element) {
- System.out.println("Element [" + element + "] evicted");
- actualEvictionsCount.incrementAndGet();
- }
-
- @Override
- public void notifyElementExpired(Ehcache cache, Element element) {
- // don't care
- }
-
- @Override
- public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
- // don't care
- }
-
- @Override
- public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
- // don't care
- }
-
- @Override
- public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
- // don't care
- }
-
- @Override
- public void notifyRemoveAll(Ehcache cache) {
- // don't care
- }
-
- @Override
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/event/EvictionListenerTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/event/EvictionListenerTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/event/EvictionListenerTest.java (revision 0)
@@ -1,382 +0,0 @@
-package net.sf.ehcache.event;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
-import java.io.NotSerializableException;
-import java.util.Map;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Filter;
-import java.util.logging.LogRecord;
-import java.util.logging.Logger;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.DiskStoreConfiguration;
-import net.sf.ehcache.config.MemoryUnit;
-import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
-import net.sf.ehcache.store.disk.DiskStorageFactory;
-import net.sf.ehcache.store.disk.DiskStoreHelper;
-
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.terracotta.test.categories.CheckShorts;
-
-/**
- * @author Alex Snaps
- */
-@Category(CheckShorts.class)
-public class EvictionListenerTest {
-
- private static CacheManager cacheManager;
- private static final String CACHE_NAME = "listening";
- private Cache cache;
- private static final int THREADS = 6;
- private static final int PER_THREAD = 15000;
-
- @BeforeClass
- public static void createCacheManager() {
- Configuration configuration = new Configuration();
- configuration.diskStore(new DiskStoreConfiguration().path("./target/tmp/")).name(EvictionListenerTest.class.getSimpleName());
- cacheManager = new CacheManager(configuration);
- Logger.getLogger(DiskStorageFactory.class.getName()).setFilter(new Filter() {
- public boolean isLoggable(LogRecord lr) {
- return !(lr.getThrown() instanceof NotSerializableException);
- }
- });
- }
-
- @Before
- public void setup() {
- CacheConfiguration configuration = new CacheConfiguration(CACHE_NAME, 100).overflowToDisk(true)
- .maxBytesLocalDisk(1, MemoryUnit.MEGABYTES);
- cache = new Cache(configuration);
- cacheManager.addCache(cache);
- }
-
- @Test
- public void testEvictedOnlyOnce() throws InterruptedException, ExecutionException {
- CountingCacheEventListener countingCacheEventListener = new CountingCacheEventListener();
- cache.getCacheEventNotificationService().registerListener(countingCacheEventListener);
- int amountOfEntries = 10000;
- for (int i = 0; i < amountOfEntries; i++) {
- cache.get("key" + (1000 + (i % 10)));
- cache.put(new Element("key" + i, UUID.randomUUID().toString()));
- }
- DiskStoreHelper.flushAllEntriesToDisk(cache).get();
- final long diskStoreSize = cache.getStatistics().getLocalDiskSize();
- Map cacheElementsEvicted = countingCacheEventListener.getCacheElementsEvicted(cache);
- System.out.println("\n\n ****");
- System.out.println("DiskStore store size : " + diskStoreSize);
- System.out.println(" ****\n\n");
- assertThat(cacheElementsEvicted.isEmpty(), is(false));
- for (Map.Entry entry : cacheElementsEvicted.entrySet()) {
- assertThat("Evicted multiple times: " + entry.getKey(), entry.getValue().get(), equalTo(1));
- }
- for (int i = 0; i < amountOfEntries; i++) {
- String key = "key" + i;
- if (!cache.isKeyInCache(key) && !cacheElementsEvicted.containsKey(key)) {
- final String message = "Key '" + key + "' isn't in cache & we didn't get notified about its eviction!";
- System.out.println(message);
- assertThat(cacheElementsEvicted.size(), is((int) (amountOfEntries - diskStoreSize)));
- fail(message);
- }
- }
- }
-
- @Test
- public void testGetsAllEvictedKeys() throws InterruptedException, ExecutionException {
- CountingCacheEventListener countingCacheEventListener = accessCache(cache);
- DiskStoreHelper.flushAllEntriesToDisk(cache).get();
- Map cacheElementsEvicted = countingCacheEventListener.getCacheElementsEvicted(cache);
- for (Map.Entry entry : cacheElementsEvicted.entrySet()) {
- assertThat("Evicted multiple times: " + entry.getKey(), entry.getValue().get(), equalTo(1));
- }
- assertThat(cache.getSize(), not(is(0)));
- assertThat(cacheElementsEvicted.size() + cache.getSize(), is(THREADS * PER_THREAD));
- }
-
- @Test
- public void testGetsAllEvictedKeysClockEviction() throws InterruptedException, ExecutionException {
- cacheManager.removeCache(CACHE_NAME);
- CacheConfiguration configuration = new CacheConfiguration(CACHE_NAME, 100)
- .memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.CLOCK);
- cache = new Cache(configuration);
- cacheManager.addCache(cache);
- CountingCacheEventListener countingCacheEventListener = accessCache(cache);
- Map cacheElementsEvicted = countingCacheEventListener.getCacheElementsEvicted(cache);
- for (Map.Entry entry : cacheElementsEvicted.entrySet()) {
- assertThat("Evicted multiple times: " + entry.getKey(), entry.getValue().get(), equalTo(1));
- }
- assertThat(cache.getSize(), not(is(0)));
- assertThat(cacheElementsEvicted.size() + cache.getSize(), is(THREADS * PER_THREAD));
- }
-
- @Test
- public void testGetsAllEvictedKeysWithoutDiskSizeBased() throws InterruptedException {
- CacheConfiguration configuration = new CacheConfiguration().name("noDisk").maxBytesLocalHeap(100, MemoryUnit.KILOBYTES);
- final Cache noDiskCache = new Cache(configuration);
- cacheManager.addCache(noDiskCache);
- CountingCacheEventListener countingCacheEventListener = accessCache(noDiskCache);
- assertThat(noDiskCache.getStatistics().getLocalHeapSize() <= noDiskCache.getCacheConfiguration().getMaxBytesLocalHeap(), is(true));
- Map cacheElementsEvicted = countingCacheEventListener.getCacheElementsEvicted(noDiskCache);
- for (Map.Entry entry : cacheElementsEvicted.entrySet()) {
- assertThat("Evicted multiple times: " + entry.getKey(), entry.getValue().get(), equalTo(1));
- }
- assertThat(noDiskCache.getSize(), not(is(0)));
- assertThat(cacheElementsEvicted.size(), not(is(0)));
- System.out.println(noDiskCache.getSize());
- assertThat(cacheElementsEvicted.size() + noDiskCache.getSize(), is(THREADS * PER_THREAD));
- }
-
- @Test
- public void testGetsAllEvictedKeysWithoutDiskEntryBased() throws InterruptedException {
- CacheConfiguration configuration = new CacheConfiguration().name("noDiskEntry").maxEntriesLocalHeap(100);
- final Cache noDiskCache = new Cache(configuration);
- cacheManager.addCache(noDiskCache);
- CountingCacheEventListener countingCacheEventListener = accessCache(noDiskCache);
- Map cacheElementsEvicted = countingCacheEventListener.getCacheElementsEvicted(noDiskCache);
- for (Map.Entry entry : cacheElementsEvicted.entrySet()) {
- assertThat("Evicted multiple times: " + entry.getKey(), entry.getValue().get(), equalTo(1));
- }
- assertThat(noDiskCache.getSize(), not(is(0)));
- assertThat(cacheElementsEvicted.size(), not(is(0)));
- System.out.println(noDiskCache.getSize());
- assertThat(cacheElementsEvicted.size() + noDiskCache.getSize(), is(THREADS * PER_THREAD));
- }
-
- @Test
- public void testGetsAllEvictedKeysWithDiskEntryBased() throws InterruptedException, ExecutionException {
- CacheConfiguration configuration = new CacheConfiguration().name("diskEntry").maxEntriesLocalHeap(100)
- .overflowToDisk(true).maxEntriesLocalDisk(2000);
- final Cache diskCache = new Cache(configuration);
- cacheManager.addCache(diskCache);
- CountingCacheEventListener countingCacheEventListener = accessCache(diskCache);
- Map cacheElementsEvicted = countingCacheEventListener.getCacheElementsEvicted(diskCache);
- for (Map.Entry entry : cacheElementsEvicted.entrySet()) {
- assertThat("Evicted multiple times: " + entry.getKey(), entry.getValue().get(), equalTo(1));
- }
- assertThat(diskCache.getSize(), not(is(0)));
- assertThat(cacheElementsEvicted.size(), not(is(0)));
- DiskStoreHelper.flushAllEntriesToDisk(diskCache).get();
- System.out.println(diskCache.getSize());
- assertThat(cacheElementsEvicted.size() + diskCache.getSize(), is(THREADS * PER_THREAD));
- }
-
- @Test
- public void testGetsAllEvictedKeysWithDiskPersistentEntryBased() throws InterruptedException, ExecutionException {
- cache = new Cache(new CacheConfiguration("testGetsAllEvictedKeysWithDiskPersistentEntryBased", 100)
- .maxEntriesLocalDisk(2000)
- .eternal(true)
- .diskPersistent(true));
- cacheManager.addCache(cache);
- CountingCacheEventListener countingCacheEventListener = accessCache(cache);
- DiskStoreHelper.flushAllEntriesToDisk(cache).get();
- Map cacheElementsEvicted = countingCacheEventListener.getCacheElementsEvicted(cache);
-// for (Map.Entry entry : cacheElementsEvicted.entrySet()) {
-// assertThat("Evicted multiple times: " + entry.getKey(), entry.getValue().get(), equalTo(1));
-// }
-
- DiskStoreHelper.flushAllEntriesToDisk(cache).get(); // Make sure all is flushed...
- final int cacheSize = cache.getSize();
- final int evictedElementCount = cacheElementsEvicted.size();
-
- assertThat(cacheSize, greaterThan(0));
- assertThat(evictedElementCount, greaterThan(0));
- System.out.println(cacheSize);
- assertThat(evictedElementCount + cacheSize, is(THREADS * PER_THREAD));
- }
-
- private CountingCacheEventListener accessCache(final Cache cacheUT) throws InterruptedException {
- CountingCacheEventListener countingCacheEventListener = new CountingCacheEventListener();
- cacheUT.getCacheEventNotificationService().registerListener(countingCacheEventListener);
- Thread[] threads = new Thread[THREADS];
- final AtomicInteger counter = new AtomicInteger();
- for (int i = 0; i < threads.length; i++) {
- threads[i] = new Thread() {
-
- private final int index = counter.getAndIncrement();
-
- @Override
- public void run() {
- for (int j = index * PER_THREAD; j < (index + 1) * PER_THREAD; j++) {
- cacheUT.get("key" + (1000 + (j % 10)));
- if (j % 125 == 0) {
- cacheUT.put(new Element("key" + j, new Object()));
- } else {
- cacheUT.put(new Element("key" + j, UUID.randomUUID().toString()));
- }
- }
- }
- };
- threads[i].run();
- }
- for (Thread thread : threads) {
- thread.join();
- }
- return countingCacheEventListener;
- }
-
- @Test
- public void testEvictionDuplicates() throws Exception {
- CacheConfiguration configuration = new CacheConfiguration().name("heapOnly").maxBytesLocalHeap(4, MemoryUnit.KILOBYTES).eternal(true).overflowToOffHeap(false);
- final Cache heapOnlyCache = new Cache(configuration);
- cacheManager.addCache(heapOnlyCache);
-
- final ConcurrentHashMap evicted = new ConcurrentHashMap();
- heapOnlyCache.getCacheEventNotificationService().registerListener(new CacheEventListenerAdapter(){
- @Override
- public void notifyElementEvicted(Ehcache cache, Element element) {
- AtomicInteger old = evicted.put(element.getObjectKey(), new AtomicInteger(1));
- if (old != null) {
- fail("Got multiple evictions for " + element.getObjectKey() + "! Evicted " + old.incrementAndGet() + " times");
- }
- }
- });
-
- Putter[] putters = new Putter[2];
- for (int i = 0; i < 2; i++) {
- putters[i] = new Putter(i, heapOnlyCache);
- }
- for (Putter putter : putters) {
- putter.start();
- }
- for (Putter putter : putters) {
- putter.join();
- assertFalse(putter.failed);
- }
- }
-
- private static final class Putter extends Thread {
- private final int id;
- private final Cache c;
- private volatile boolean failed;
-
-
- private Putter(int id, Cache c) {
- this.id = id;
- this.c = c;
- }
-
- @Override
- public void run() {
- try {
- for (int i = 0; i < 10000; i++) {
- c.put(new Element(id + "-" + i, "" + i));
- }
- } catch (Throwable t) {
- t.printStackTrace();
- failed = true;
- }
- }
- }
-
- @After
- public void tearDown() throws ExecutionException, InterruptedException {
- if(cache != null) {
- cache.removeAll();
- final Future future = DiskStoreHelper.flushAllEntriesToDisk(cache);
- if(future != null) {
- future.get();
- }
- }
- cacheManager.removeAllCaches();
- }
-
- @AfterClass
- public static void cleanUp() {
- cacheManager.shutdown();
- }
-
- private static class CountingCacheEventListener implements CacheEventListener {
-
- private final ConcurrentMap> evictions = createMap();
-
- public void notifyElementRemoved(final Ehcache cache, final Element element) throws CacheException {
- // To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void notifyElementPut(final Ehcache cache, final Element element) throws CacheException {
- // To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void notifyElementUpdated(final Ehcache cache, final Element element) throws CacheException {
- // To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void notifyElementExpired(final Ehcache cache, final Element element) {
- // To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void notifyElementEvicted(final Ehcache cache, final Element element) {
- getCounterFor(element, getEntriesFor(cache, evictions)).incrementAndGet();
- }
-
- public void notifyRemoveAll(final Ehcache cache) {
- // To change body of implemented methods use File | Settings | File Templates.
- }
-
- public void dispose() {
- // To change body of implemented methods use File | Settings | File Templates.
- }
-
- @Override
- public Object clone() throws CloneNotSupportedException {
- super.clone();
- throw new UnsupportedOperationException("Don't clone me!");
- }
-
- private AtomicInteger getCounterFor(final Element element, final ConcurrentMap entries) {
- AtomicInteger counter = entries.get(element.getKey());
- if (counter == null) {
- counter = new AtomicInteger(0);
- AtomicInteger previous = entries.putIfAbsent(element.getKey(), counter);
- if (previous != null) {
- counter = previous;
- }
- }
- return counter;
- }
-
- private ConcurrentMap getEntriesFor(final Ehcache cache,
- final ConcurrentMap> map) {
- ConcurrentMap entries;
- entries = map.get(cache.getName());
- if (entries == null) {
- entries = new ConcurrentHashMap();
- ConcurrentMap previous = map.putIfAbsent(cache.getName(), entries);
- if (previous != null) {
- entries = previous;
- }
- }
- return entries;
- }
-
- private ConcurrentHashMap createMap() {
- return new ConcurrentHashMap();
- }
-
- public Map getCacheElementsEvicted(final Cache cache) {
- return getEntriesFor(cache, evictions);
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/DiskStoreBootstrapCacheLoaderFactoryTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/DiskStoreBootstrapCacheLoaderFactoryTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/DiskStoreBootstrapCacheLoaderFactoryTest.java (revision 0)
@@ -1,168 +0,0 @@
-package net.sf.ehcache.store;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.DiskStoreConfiguration;
-import net.sf.ehcache.store.disk.DiskStoreHelper;
-
-import org.junit.After;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.terracotta.test.categories.CheckShorts;
-
-import java.util.concurrent.BrokenBarrierException;
-import java.util.concurrent.CyclicBarrier;
-
-import static net.sf.ehcache.config.MemoryUnit.KILOBYTES;
-import static net.sf.ehcache.config.MemoryUnit.MEGABYTES;
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo;
-import static org.junit.Assert.assertThat;
-
-/**
- * @author Alex Snaps
- */
-@Category(CheckShorts.class)
-public class DiskStoreBootstrapCacheLoaderFactoryTest {
-
- private static final int ELEMENTS_ON_DISK = 500;
- private CacheManager manager;
- private Cache cacheElementCountBound;
- private Cache cacheSizeBound;
- private TestDiskStoreBootstrapCacheLoader cacheElementCountBoundBootstrapCacheLoader;
- private TestDiskStoreBootstrapCacheLoader cacheSizeBoundBootstrapCacheLoader;
-
- public void setUp(CacheUT cut) {
- initCacheManager(cut);
- switch (cut) {
- case elementBased:
- cacheElementCountBound.removeAll();
- populateCache(cacheElementCountBound);
- break;
- case sizeBased:
- cacheSizeBound.removeAll();
- populateCache(cacheSizeBound);
- break;
- }
- }
-
- private void populateCache(final Cache cache) {
- for (int i = 0; i < ELEMENTS_ON_DISK; i++) {
- cache.put(new Element(i, "Some value for key " + i));
- }
- }
-
- @Test
- public void testLoadsFromDiskWithMaxElementsInMemorySet() throws Exception {
- setUp(CacheUT.elementBased);
- DiskStoreHelper.flushAllEntriesToDisk(cacheElementCountBound).get();
- long onDiskElements = cacheElementCountBound.getStatistics().getLocalDiskSize();
- cacheElementCountBoundBootstrapCacheLoader.triggerLoad();
- assertThat(cacheElementCountBound.getStatistics().getLocalHeapSize(), is(100L));
- manager.shutdown();
- initCacheManager(CacheUT.elementBased);
- assertThat(cacheElementCountBound.getStatistics().getLocalDiskSize(), is(onDiskElements));
- assertThat(cacheElementCountBound.getStatistics().getLocalHeapSize(), is(0L));
- cacheElementCountBoundBootstrapCacheLoader.triggerLoad();
- assertThat(cacheElementCountBound.getStatistics().getLocalDiskSize(), is(onDiskElements));
- assertThat(cacheElementCountBound.getStatistics().getLocalHeapSize(), is(100L));
- }
-
- @Test
- public void testLoadsFromDiskWithMaxBytesOnHeapSet() throws Exception {
- setUp(CacheUT.sizeBased);
- DiskStoreHelper.flushAllEntriesToDisk(cacheSizeBound).get();
- cacheSizeBoundBootstrapCacheLoader.triggerLoad();
- long onDiskSize = cacheSizeBound.getStatistics().getLocalDiskSize();
- assertThat(cacheSizeBound.getStatistics().getLocalHeapSize(), greaterThan(0L));
- assertThat(cacheSizeBound.getStatistics().getLocalHeapSizeInBytes(), lessThanOrEqualTo(KILOBYTES.toBytes(220L)));
- assertThat(cacheSizeBound.getStatistics().getLocalDiskSize(), is(onDiskSize));
- manager.shutdown();
- initCacheManager(CacheUT.sizeBased);
- assertThat(cacheSizeBound.getStatistics().getLocalDiskSize(), is(onDiskSize));
- assertThat(cacheSizeBound.getStatistics().getLocalHeapSize(), is(0L));
- cacheSizeBoundBootstrapCacheLoader.triggerLoad();
- assertThat(cacheSizeBound.getStatistics().getLocalHeapSize(), greaterThan(0L));
- assertThat(cacheSizeBound.getStatistics().getLocalHeapSizeInBytes(), lessThanOrEqualTo(KILOBYTES.toBytes(220L)));
- }
-
- private void initCacheManager(CacheUT cut) {
- switch (cut) {
- case elementBased:
- manager = new CacheManager(new Configuration().diskStore(new DiskStoreConfiguration().path("java.io.tmpdir/DiskPersistent")));
- cacheElementCountBoundBootstrapCacheLoader = new TestDiskStoreBootstrapCacheLoader();
- cacheElementCountBound = new Cache(new CacheConfiguration("maxElementsInMemory", 100)
- .eternal(true)
- .diskPersistent(true)
- .overflowToDisk(true)
- .maxEntriesLocalDisk(ELEMENTS_ON_DISK), null, cacheElementCountBoundBootstrapCacheLoader);
- manager.addCache(cacheElementCountBound);
- break;
- case sizeBased:
- manager = new CacheManager(new Configuration().diskStore(new DiskStoreConfiguration().path("java.io.tmpdir/DiskPersistentSize")));
- cacheSizeBoundBootstrapCacheLoader = new TestDiskStoreBootstrapCacheLoader();
- cacheSizeBound = new Cache(new CacheConfiguration("maxOnHeap", 0)
- .eternal(true)
- .diskPersistent(true)
- .overflowToDisk(true)
- .maxBytesLocalHeap(220, KILOBYTES)
- .maxBytesLocalDisk(300, MEGABYTES), null, cacheSizeBoundBootstrapCacheLoader);
- manager.addCache(cacheSizeBound);
- break;
- }
- }
-
- @After
- public void shutdown() {
- if (manager != null && manager.getStatus() == Status.STATUS_ALIVE) {
- manager.shutdown();
- }
- }
-
- private static enum CacheUT {
- elementBased, sizeBased
- }
-
- static class TestDiskStoreBootstrapCacheLoader extends DiskStoreBootstrapCacheLoader {
-
- private final CyclicBarrier before = new CyclicBarrier(2);
- private final CyclicBarrier after = new CyclicBarrier(2);
-
- public TestDiskStoreBootstrapCacheLoader() {
- super(true);
- }
-
- @Override
- protected void doLoad(Ehcache cache) {
- try {
- before.await();
- try {
- super.doLoad(cache);
- } finally {
- after.await();
- }
- } catch (InterruptedException e) {
- throw new AssertionError(e);
- } catch (BrokenBarrierException e) {
- throw new AssertionError(e);
- }
- }
-
- public void triggerLoad() {
- try {
- before.await();
- after.await();
- } catch (InterruptedException e) {
- throw new AssertionError(e);
- } catch (BrokenBarrierException e) {
- throw new AssertionError(e);
- }
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshCacheExtension.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshCacheExtension.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshCacheExtension.java (revision 0)
@@ -1,455 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.constructs.scheduledrefresh;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.extension.CacheExtension;
-import net.sf.ehcache.statistics.extended.ExtendedStatistics;
-import org.quartz.CronScheduleBuilder;
-import org.quartz.CronTrigger;
-import org.quartz.JobBuilder;
-import org.quartz.JobDataMap;
-import org.quartz.JobDetail;
-import org.quartz.Scheduler;
-import org.quartz.SchedulerException;
-import org.quartz.TriggerBuilder;
-import org.quartz.impl.StdSchedulerFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.terracotta.statistics.StatisticsManager;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * This class provides a cache extension which allows for the scheduled refresh
- * of all keys currently in the cache, using whichever CacheLoader's are
- * defined. It uses Quartz to do the job scheduling. One extension should be
- * active for a single clustered cache, as multiple extensions will run
- * independently of each other.
- *
- * @author cschanck
- */
-public class ScheduledRefreshCacheExtension implements CacheExtension {
-
- /**
- * Logger this package uses.
- */
- static final Logger LOG = LoggerFactory.getLogger(ScheduledRefreshCacheExtension.class);
-
- /**
- * Job Property key for Terracotta Job Store to use.
- */
- static final String PROP_QUARTZ_JOB_STORE_TC_CONFIG_URL = "org.quartz.jobStore.tcConfigUrl";
-
- /**
- * Job Property key for cache name this extension's jobs will run against
- */
- static final String PROP_CACHE_NAME = ScheduledRefreshCacheExtension.class.getName() + ".cacheName";
-
- /**
- * Job Property key for cache manager name this extension's jobs will run
- * against
- */
- static final String PROP_CACHE_MGR_NAME = ScheduledRefreshCacheExtension.class.getName() + "cacheManagerName";
-
- /**
- * Job Property key for sending config object to scheduled job
- */
- static final String PROP_CONFIG_OBJECT = ScheduledRefreshCacheExtension.class.getName() + "scheduledRefreshConfig";
-
- /**
- * Job Property key for sending keys to process to scheduled job
- */
- static final String PROP_KEYS_TO_PROCESS = "keyObjects";
-
- private static final String OVERSEER_JOB_NAME = "Overseer";
- private Ehcache underlyingCache;
- private ScheduledRefreshConfiguration config;
- private String name;
- private Scheduler scheduler;
- private String groupName;
- private Status status;
- private AtomicLong refreshCount = new AtomicLong();
- private AtomicLong jobCount = new AtomicLong();
- private AtomicLong keysProcessedCount = new AtomicLong();
-
- /**
- * Constructor. Create an extension with the specified config object against
- * the specified cache.
- *
- * @param config Configuration to use.
- * @param cache Cache to process against.
- */
- public ScheduledRefreshCacheExtension(ScheduledRefreshConfiguration config, Ehcache cache) {
- if(cache == null) {
- throw new IllegalArgumentException("ScheduledRefresh Cache cannot be null");
- }
- this.underlyingCache = cache;
- if(config == null) {
- throw new IllegalArgumentException("ScheduledRefresh extension config cannot be null");
- }
- this.config = config;
- config.validate();
- this.status = Status.STATUS_UNINITIALISED;
- StatisticsManager.associate(this).withParent(cache);
- }
-
- @Override
- public void init() {
- try {
- if (config.getScheduledRefreshName() != null) {
- this.name = "scheduledRefresh_" + underlyingCache.getCacheManager().getName() + "_"
- + underlyingCache.getName() + "_" + config.getScheduledRefreshName();
- } else {
- this.name = "scheduledRefresh_" + underlyingCache.getCacheManager().getName() + "_"
- + underlyingCache.getName();
- }
- this.groupName = name + "_grp";
- try {
- makeAndStartQuartzScheduler();
- try {
- scheduleOverseerJob();
- status = Status.STATUS_ALIVE;
- } catch (SchedulerException e) {
- LOG.error("Unable to schedule control job for Scheduled Refresh", e);
- }
-
- } catch (SchedulerException e) {
- LOG.error("Unable to instantiate Quartz Job Scheduler for Scheduled Refresh", e);
- }
- } catch(RuntimeException e) {
- LOG.error("Unable to initialise ScheduledRefesh extension", e);
- }
- }
-
- /*
- * This is more complicated at first blush than you might expect, but it
- * attempts to prove that one and only one trigger is scheduled for this job,
- * and that it is the right one. Even if multiple cache extensions for the
- * same cache are sharing the Quartz store, it should end up with only one
- * trigger winning. If there are multiple *different* cron expressions,
- * someone will win, but it is not deterministic as to which one.
- */
- private void scheduleOverseerJob() throws SchedulerException {
-
- JobDetail seed = makeOverseerJob();
-
- // build our trigger
- CronScheduleBuilder cronSchedule = CronScheduleBuilder.cronSchedule(config.getCronExpression());
-
- CronTrigger trigger = TriggerBuilder.newTrigger()
- .withIdentity(OVERSEER_JOB_NAME, groupName)
- .forJob(seed).withSchedule(cronSchedule)
- .build();
-
- try {
- scheduler.addJob(seed, false);
- } catch (SchedulerException e) {
- // job already present
- }
- try {
- scheduler.scheduleJob(trigger);
- } catch (SchedulerException e) {
- // trigger already present
- try {
- scheduler.rescheduleJob(trigger.getKey(), trigger);
- } catch (SchedulerException ee) {
- LOG.error("Unable to modify trigger for: " + trigger.getKey());
- }
- }
-
- }
-
- /*
- * Add the control job, an instance of the OverseerJob class.
- */
- private JobDetail makeOverseerJob() throws SchedulerException {
- JobDataMap jdm = new JobDataMap();
- jdm.put(PROP_CACHE_MGR_NAME, underlyingCache.getCacheManager().getName());
- jdm.put(PROP_CACHE_NAME, underlyingCache.getName());
- jdm.put(PROP_CONFIG_OBJECT, config);
- JobDetail seed = JobBuilder.newJob(OverseerJob.class).storeDurably()
- .withIdentity(OVERSEER_JOB_NAME, groupName)
- .usingJobData(jdm).build();
- return seed;
- }
-
- /*
- * Create and start the quartz job scheduler for this cache extension
- */
- private void makeAndStartQuartzScheduler() throws SchedulerException {
- Properties props = new Properties();
- props.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_NAME, name);
- props.put(StdSchedulerFactory.PROP_SCHED_NAME, name);
- props.put(StdSchedulerFactory.PROP_SCHED_MAKE_SCHEDULER_THREAD_DAEMON, Boolean.TRUE.toString());
- props.put("org.quartz.threadPool.threadCount", Integer.toString(config.getQuartzThreadCount() + 1));
- Properties jsProps = getJobStoreProperties();
- for (Object key : props.keySet()) {
- if (!jsProps.containsKey(key)) {
- jsProps.put(key, props.get(key));
- }
- }
-
- StdSchedulerFactory factory = new StdSchedulerFactory(jsProps);
- scheduler = factory.getScheduler();
-
- scheduler.start();
- }
-
- private Properties getJobStoreProperties() throws SchedulerException {
- try {
- String clzName = config.getJobStoreFactoryClass();
- Class> clz = Class.forName(clzName);
- ScheduledRefreshJobStorePropertiesFactory fact = (ScheduledRefreshJobStorePropertiesFactory) clz.newInstance();
- Properties jsProps = fact.jobStoreProperties(underlyingCache, config);
- return jsProps;
- } catch (Throwable t) {
- throw new SchedulerException(t);
- }
- }
-
- /**
- * Note that this will not stop other instances of this refresh extension on
- * other nodes (in a clustered environment) from running. Until and unless
- * the last scheduled refresh cache extension for a particular cache/cache
- * manager/unique name is shutdown, they will continue to run. This is only
- * an issue for clustered, TerracottaJobStore-backed scheduled refresh cache
- * extensions.
- *
- * @throws CacheException
- */
- @Override
- public void dispose() throws CacheException {
- try {
- scheduler.shutdown();
- } catch (SchedulerException e) {
- throw new CacheException(e);
- } catch(Throwable t) {
- LOG.info("ScheduledRefresh cache extension exception during shutdown.",t);
- }
- status = Status.STATUS_SHUTDOWN;
- }
-
- @Override
- public CacheExtension clone(Ehcache cache) throws CloneNotSupportedException {
- return null;
- }
-
- @Override
- public Status getStatus() {
- return status;
- }
-
- /**
- * Gets extension group name.
- *
- * @return the extension group name
- */
- String getExtensionGroupName() {
- return groupName;
- }
-
- /**
- * Gets underlying cache.
- *
- * @return the underlying cache
- */
- Ehcache getUnderlyingCache() {
- return underlyingCache;
- }
-
- /**
- * Find extension from cache.
- *
- * @param cache the cache
- * @param groupName the group name
- * @return the scheduled refresh cache extension
- */
- static ScheduledRefreshCacheExtension findExtensionFromCache(Ehcache cache, String groupName) {
- for (CacheExtension ce : cache.getRegisteredCacheExtensions()) {
- if (ce instanceof ScheduledRefreshCacheExtension) {
- ScheduledRefreshCacheExtension probe = (ScheduledRefreshCacheExtension) ce;
- if (probe.getUnderlyingCache().getName().equals(cache.getName()) &&
- probe.getExtensionGroupName().equals(groupName)) {
- return probe;
- }
- }
- }
- return null;
- }
-
- /**
- * Find all the scheduled refresh cache extensions from a cache.
- *
- * @param cache the cache
- * @return the scheduled refresh cache extension
- */
- static Collection findExtensionsFromCache(Ehcache cache) {
- LinkedList exts=new LinkedList();
- for (CacheExtension ce : cache.getRegisteredCacheExtensions()) {
- if (ce instanceof ScheduledRefreshCacheExtension) {
- exts.add((ScheduledRefreshCacheExtension)ce);
- }
- }
- return exts;
- }
-
- /**
- * Increment refresh count.
- */
- void incrementRefreshCount() {
- refreshCount.incrementAndGet();
- }
-
- /**
- * Increment job count.
- */
- void incrementJobCount() {
- jobCount.incrementAndGet();
- }
-
- /**
- * Increment processed count.
- *
- * @param many the many
- */
- void incrementProcessedCount(int many) {
- keysProcessedCount.addAndGet(many);
- }
-
- /**
- * Gets refresh count.
- *
- * @return the refresh count
- */
- @org.terracotta.statistics.Statistic(name = "refresh", tags = "scheduledrefresh")
- public long getRefreshCount() {
- return refreshCount.get();
- }
-
- /**
- * Gets job count.
- *
- * @return the job count
- */
- @org.terracotta.statistics.Statistic(name = "job", tags = "scheduledrefresh")
- public long getJobCount() {
- return jobCount.get();
- }
-
- /**
- * Gets keys processed count.
- *
- * @return the keys processed count
- */
- @org.terracotta.statistics.Statistic(name = "keysprocessed", tags = "scheduledrefresh")
- public long getKeysProcessedCount() {
- return keysProcessedCount.get();
- }
-
- /**
- * Find refreshed counter statistic. Number of times schedule refresh has been
- * started on this node.
- *
- * @param cache the cache this statistic is attached to.
- * @return the set
- */
- public static Set> findRefreshStatistics(Ehcache cache) {
- return cache.getStatistics().getExtended().passthru("refresh",
- Collections.singletonMap("scheduledrefresh", null).keySet());
- }
-
- /**
- * Find job counter statistic. Number of batch jobs executed on this node.
- *
- * @param cache the cache this statistic is attached to.
- * @return the set
- */
- public static Set> findJobStatistics(Ehcache cache) {
- return cache.getStatistics().getExtended().passthru("job",
- Collections.singletonMap("scheduledrefresh", null).keySet());
- }
-
- /**
- * Find queued counter statistic. Number of batch jobs executed on this node.
- *
- * @param cache the cache this statistic is attached to.
- * @return the set
- */
- public static Set> findKeysProcessedStatistics(Ehcache cache) {
- return cache.getStatistics().getExtended().passthru("keysprocessed",
- Collections.singletonMap("scheduledrefresh", null).keySet());
- }
-
- /**
- * Finds a single refresh statistic for this cache. This is the count of scheduled
- * refresh invocations for this node. Throws {@link IllegalStateException} if
- * there are none or more than one.
- *
- * @param cache the cache
- * @return the extended statistics . statistic
- */
- public static ExtendedStatistics.Statistic findRefreshStatistic(Ehcache cache) {
- Set> set = findRefreshStatistics(cache);
- if (set.size() == 1) {
- return set.iterator().next();
- } else {
- throw new IllegalStateException("Multiple scheduled refresh stats found for this cache");
- }
- }
-
- /**
- * Finds a single job statistic for this cache. This is the count of refresh batch jobs
- * executed on this node. Throws {@link IllegalStateException} if there are none or
- * more than one.
- *
- * @param cache the cache
- * @return the extended statistics . statistic
- */
- public static ExtendedStatistics.Statistic findJobStatistic(Ehcache cache) {
- Set> set = findJobStatistics(cache);
- if (set.size() == 1) {
- return set.iterator().next();
- } else {
- throw new IllegalStateException("Multiple scheduled refresh stats found for this cache");
- }
- }
-
- /**
- * Finds a single keys processed statistic for this cache. This is the count of keys
- * refreshed on this node. Throws {@link IllegalStateException} if
- * there are none or more than one.
- *
- * @param cache the cache
- * @return the extended statistics . statistic
- */
- public static ExtendedStatistics.Statistic findKeysProcessedStatistic(Ehcache cache) {
- Set> set = findKeysProcessedStatistics(cache);
- if (set.size() == 1) {
- return set.iterator().next();
- } else {
- throw new IllegalStateException("Multiple scheduled refresh stats found for this cache");
- }
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/management/provider/MBeanRegistrationProviderException.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/management/provider/MBeanRegistrationProviderException.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/management/provider/MBeanRegistrationProviderException.java (revision 0)
@@ -1,47 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.management.provider;
-
-/**
- * Exception thrown from {@link MBeanRegistrationProvider}
- *
- *
- *
- * @author Abhishek Sanoujam
- * @since 1.7
- */
-public class MBeanRegistrationProviderException extends Exception {
-
- /**
- * Constructor accepting a string message and a Throwable
- *
- * @param message
- * @param cause
- */
- public MBeanRegistrationProviderException(String message, Throwable cause) {
- super(message, cause);
- }
-
- /**
- * Constructor accepting a message
- *
- * @param message
- */
- public MBeanRegistrationProviderException(String message) {
- super(message);
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusteredEventsRemoteClient1.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusteredEventsRemoteClient1.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/ClusteredEventsRemoteClient1.java (revision 0)
@@ -1,24 +0,0 @@
-package org.terracotta.ehcache.tests;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-
-import org.terracotta.toolkit.Toolkit;
-
-public class ClusteredEventsRemoteClient1 extends ClientBase {
-
- public ClusteredEventsRemoteClient1(String[] args) {
- super("testRemote", args);
- }
-
- public static void main(String[] args) {
- new ClusteredEventsRemoteClient1(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit toolkit) throws Throwable {
- getBarrierForAllClients().await();
- cache.put(new Element("key1", "value1"));
- Thread.sleep(5000);
- }
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/AbstractSizeOfTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/AbstractSizeOfTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/AbstractSizeOfTest.java (revision 0)
@@ -1,51 +0,0 @@
-package net.sf.ehcache.pool.sizeof;
-
-import java.lang.management.ManagementFactory;
-
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.openmbean.CompositeData;
-
-import static net.sf.ehcache.pool.sizeof.JvmInformation.CURRENT_JVM_INFORMATION;
-
-abstract class AbstractSizeOfTest {
-
- protected static final boolean COMPRESSED_OOPS;
- protected static final boolean HOTSPOT_CMS;
- protected static final boolean IS_HOTSPOT;
- protected static final boolean IS_JROCKIT;
- protected static final boolean IS_IBM;
- protected static final boolean IS_64_BIT;
-
- static {
- String value = getVmOptionValue("UseCompressedOops");
- if (value == null) {
- System.err.println("Could not detect compressed-oops status assuming: false");
- COMPRESSED_OOPS = false;
- } else {
- COMPRESSED_OOPS = Boolean.valueOf(value);
- }
-
- HOTSPOT_CMS = CURRENT_JVM_INFORMATION.getMinimumObjectSize() > CURRENT_JVM_INFORMATION.getObjectAlignment();
-
- IS_64_BIT = System.getProperty("sun.arch.data.model").equals("64");
-
- IS_HOTSPOT = System.getProperty("java.vm.name", "").toLowerCase().contains("hotspot");
-
- IS_JROCKIT = System.getProperty("jrockit.version") != null ||
- System.getProperty("java.vm.name", "").toLowerCase().indexOf("jrockit") >= 0;
-
- IS_IBM = System.getProperty("java.vm.name", "").contains("IBM") &&
- System.getProperty("java.vm.vendor").contains("IBM");
- }
-
- private static String getVmOptionValue(String name) {
- try {
- MBeanServer server = ManagementFactory.getPlatformMBeanServer();
- Object vmOption = server.invoke(ObjectName.getInstance("com.sun.management:type=HotSpotDiagnostic"), "getVMOption", new Object[] {name}, new String[] {"java.lang.String"});
- return (String) ((CompositeData) vmOption).get("value");
- } catch (Throwable t) {
- return null;
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/distribution/events/src/main/java/org/hibernate/tutorial/util/HibernateUtil.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/events/src/main/java/org/hibernate/tutorial/util/HibernateUtil.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/events/src/main/java/org/hibernate/tutorial/util/HibernateUtil.java (revision 0)
@@ -1,23 +0,0 @@
-package org.hibernate.tutorial.util;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.Configuration;
-
-public class HibernateUtil {
- private static final SessionFactory sessionFactory = buildSessionFactory();
-
- private static SessionFactory buildSessionFactory() {
- try {
- // Create the SessionFactory from hibernate.cfg.xml
- return new Configuration().configure().buildSessionFactory();
- } catch (Throwable ex) {
- // Make sure you log the exception, as it might be swallowed
- System.err.println("Initial SessionFactory creation failed." + ex);
- throw new ExceptionInInitializerError(ex);
- }
- }
-
- public static SessionFactory getSessionFactory() {
- return sessionFactory;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/total-capacity-cache-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/total-capacity-cache-test.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/total-capacity-cache-test.xml (revision 0)
@@ -1,17 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/Selector.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/Selector.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/Selector.java (revision 0)
@@ -1,88 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.manager.selector;
-
-import net.sf.ehcache.transaction.xa.EhcacheXAResource;
-
-import javax.transaction.TransactionManager;
-
-/**
- * Abstract class which is used to do various things related to JTA transaction managers,
- * like looking them up, registering XAResources for recovery...
- *
- * @author Ludovic Orban
- */
-public abstract class Selector {
-
- private final String vendor;
- private volatile TransactionManager transactionManager;
-
- /**
- * Constructor
- *
- * @param vendor an indicative transaction manager vendor name
- * this selector is working with.
- */
- protected Selector(String vendor) {
- this.vendor = vendor;
- }
-
- /**
- * Get the vendor name
- * @return the vendor name
- */
- public String getVendor() {
- return vendor;
- }
-
- /**
- * Get the transaction manager, looking it up if necessary.
- * Once the transaction manager has been looked up, its reference is cached.
- * @return the transaction manager
- */
- public TransactionManager getTransactionManager() {
- if (transactionManager == null) {
- transactionManager = doLookup();
- }
- return transactionManager;
- }
-
- /**
- * Register an XAResource with the transaction manager.
- *
- * @param ehcacheXAResource the XAResource
- * @param forRecovery true if this XAResource is being registered purely for recovery purpose
- */
- public void registerResource(EhcacheXAResource ehcacheXAResource, boolean forRecovery) {
- }
-
- /**
- * Unregister an XAResource from the transaction manager.
- *
- * @param ehcacheXAResource the XAResource
- * @param forRecovery true if this XAResource was registered purely for recovery purpose
- */
- public void unregisterResource(EhcacheXAResource ehcacheXAResource, boolean forRecovery) {
- }
-
- /**
- * Lookup the transaction manager.
- *
- * @return the transaction manager, or null if it could not be looked up.
- */
- protected abstract TransactionManager doLookup();
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/distribution/ehcache-distributed-big-payload-1.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/distribution/ehcache-distributed-big-payload-1.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/distribution/ehcache-distributed-big-payload-1.xml (revision 0)
@@ -1,426 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/concurrent/Striped64.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/concurrent/Striped64.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/concurrent/Striped64.java (revision 0)
@@ -1,290 +0,0 @@
-/*
- * Written by Doug Lea with assistance from members of JCP JSR-166
- * Expert Group and released to the public domain, as explained at
- * http://creativecommons.org/publicdomain/zero/1.0/
- */
-
-package net.sf.ehcache.util.concurrent;
-
-import java.util.Random;
-import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
-import java.util.concurrent.atomic.AtomicLongFieldUpdater;
-
-/**
- * A package-local class holding common representation and mechanics
- * for classes supporting dynamic striping on 64bit values. The class
- * extends Number so that concrete subclasses must publicly do so.
- */
-@SuppressWarnings("restriction")
-abstract class Striped64 extends Number {
- /*
- * This class maintains a lazily-initialized table of atomically
- * updated variables, plus an extra "base" field. The table size
- * is a power of two. Indexing uses masked per-thread hash codes.
- * Nearly all declarations in this class are package-private,
- * accessed directly by subclasses.
- *
- * Table entries are of class Cell; a variant of AtomicLong padded
- * to reduce cache contention on most processors. Padding is
- * overkill for most Atomics because they are usually irregularly
- * scattered in memory and thus don't interfere much with each
- * other. But Atomic objects residing in arrays will tend to be
- * placed adjacent to each other, and so will most often share
- * cache lines (with a huge negative performance impact) without
- * this precaution.
- *
- * In part because Cells are relatively large, we avoid creating
- * them until they are needed. When there is no contention, all
- * updates are made to the base field. Upon first contention (a
- * failed CAS on base update), the table is initialized to size 2.
- * The table size is doubled upon further contention until
- * reaching the nearest power of two greater than or equal to the
- * number of CPUS. Table slots remain empty (null) until they are
- * needed.
- *
- * A single spinlock ("busy") is used for initializing and
- * resizing the table, as well as populating slots with new Cells.
- * There is no need for a blocking lock: When the lock is not
- * available, threads try other slots (or the base). During these
- * retries, there is increased contention and reduced locality,
- * which is still better than alternatives.
- *
- * Per-thread hash codes are initialized to random values.
- * Contention and/or table collisions are indicated by failed
- * CASes when performing an update operation (see method
- * retryUpdate). Upon a collision, if the table size is less than
- * the capacity, it is doubled in size unless some other thread
- * holds the lock. If a hashed slot is empty, and lock is
- * available, a new Cell is created. Otherwise, if the slot
- * exists, a CAS is tried. Retries proceed by "double hashing",
- * using a secondary hash (Marsaglia XorShift) to try to find a
- * free slot.
- *
- * The table size is capped because, when there are more threads
- * than CPUs, supposing that each thread were bound to a CPU,
- * there would exist a perfect hash function mapping threads to
- * slots that eliminates collisions. When we reach capacity, we
- * search for this mapping by randomly varying the hash codes of
- * colliding threads. Because search is random, and collisions
- * only become known via CAS failures, convergence can be slow,
- * and because threads are typically not bound to CPUS forever,
- * may not occur at all. However, despite these limitations,
- * observed contention rates are typically low in these cases.
- *
- * It is possible for a Cell to become unused when threads that
- * once hashed to it terminate, as well as in the case where
- * doubling the table causes no thread to hash to it under
- * expanded mask. We do not try to detect or remove such cells,
- * under the assumption that for long-running instances, observed
- * contention levels will recur, so the cells will eventually be
- * needed again; and for short-lived ones, it does not matter.
- */
-
- /**
- * Padded variant of AtomicLong supporting only raw accesses plus CAS.
- * The value field is placed between pads, hoping that the JVM doesn't
- * reorder them.
- *
- * JVM intrinsics note: It would be possible to use a release-only
- * form of CAS here, if it were provided.
- */
- static final class Cell {
- volatile long p0, p1, p2, p3, p4, p5, p6;
- volatile long value;
- volatile long q0, q1, q2, q3, q4, q5, q6;
- Cell(long x) { VALUE_UPDATER.set(this, x); }
-
- final boolean cas(long cmp, long val) {
- return VALUE_UPDATER.compareAndSet(this, cmp, val);
- }
-
- private static final AtomicLongFieldUpdater VALUE_UPDATER = AtomicLongFieldUpdater.newUpdater(Cell.class, "value");
-
- }
-
- /**
- * Holder for the thread-local hash code. The code is initially
- * random, but may be set to a different value upon collisions.
- */
- static final class HashCode {
- static final Random rng = new Random();
- int code;
- HashCode() {
- int h = rng.nextInt(); // Avoid zero to allow xorShift rehash
- code = (h == 0) ? 1 : h;
- }
- }
-
- /**
- * The corresponding ThreadLocal class
- */
- static final class ThreadHashCode extends ThreadLocal {
- public HashCode initialValue() { return new HashCode(); }
- }
-
- /**
- * Static per-thread hash codes. Shared across all instances to
- * reduce ThreadLocal pollution and because adjustments due to
- * collisions in one table are likely to be appropriate for
- * others.
- */
- static final ThreadHashCode threadHashCode = new ThreadHashCode();
-
- /** Number of CPUS, to place bound on table size */
- static final int NCPU = Runtime.getRuntime().availableProcessors();
-
- /**
- * Table of cells. When non-null, size is a power of 2.
- */
- transient volatile Cell[] cells;
-
- /**
- * Base value, used mainly when there is no contention, but also as
- * a fallback during table initialization races. Updated via CAS.
- */
- transient volatile long base;
-
- /**
- * Spinlock (locked via CAS) used when resizing and/or creating Cells.
- */
- transient volatile int busy;
-
- /**
- * Package-private default constructor
- */
- Striped64() {
- }
-
- /**
- * CASes the base field.
- */
- final boolean casBase(long cmp, long val) {
- return BASE_UPDATER.compareAndSet(this, cmp, val);
- }
-
- /**
- * CASes the busy field from 0 to 1 to acquire lock.
- */
- final boolean casBusy() {
- return BUSY_UPDATER.compareAndSet(this, 0, 1);
- }
-
- /**
- * Computes the function of current and new value. Subclasses
- * should open-code this update function for most uses, but the
- * virtualized form is needed within retryUpdate.
- *
- * @param currentValue the current value (of either base or a cell)
- * @param newValue the argument from a user update call
- * @return result of the update function
- */
- abstract long fn(long currentValue, long newValue);
-
- /**
- * Handles cases of updates involving initialization, resizing,
- * creating new Cells, and/or contention. See above for
- * explanation. This method suffers the usual non-modularity
- * problems of optimistic retry code, relying on rechecked sets of
- * reads.
- *
- * @param x the value
- * @param hc the hash code holder
- * @param wasUncontended false if CAS failed before call
- */
- final void retryUpdate(long x, HashCode hc, boolean wasUncontended) {
- int h = hc.code;
- boolean collide = false; // True if last slot nonempty
- for (;;) {
- Cell[] as; Cell a; int n; long v;
- if ((as = cells) != null && (n = as.length) > 0) {
- if ((a = as[(n - 1) & h]) == null) {
- if (busy == 0) { // Try to attach new Cell
- Cell r = new Cell(x); // Optimistically create
- if (busy == 0 && casBusy()) {
- boolean created = false;
- try { // Recheck under lock
- Cell[] rs; int m, j;
- if ((rs = cells) != null &&
- (m = rs.length) > 0 &&
- rs[j = (m - 1) & h] == null) {
- rs[j] = r;
- created = true;
- }
- } finally {
- BUSY_UPDATER.set(this, 0);
- }
- if (created)
- break;
- continue; // Slot is now non-empty
- }
- }
- collide = false;
- }
- else if (!wasUncontended) // CAS already known to fail
- wasUncontended = true; // Continue after rehash
- else if (a.cas(v = a.value, fn(v, x)))
- break;
- else if (n >= NCPU || cells != as)
- collide = false; // At max size or stale
- else if (!collide)
- collide = true;
- else if (busy == 0 && casBusy()) {
- try {
- if (cells == as) { // Expand table unless stale
- Cell[] rs = new Cell[n << 1];
- for (int i = 0; i < n; ++i)
- rs[i] = as[i];
- cells = rs;
- }
- } finally {
- BUSY_UPDATER.set(this, 0);
- }
- collide = false;
- continue; // Retry with expanded table
- }
- h ^= h << 13; // Rehash
- h ^= h >>> 17;
- h ^= h << 5;
- }
- else if (busy == 0 && cells == as && casBusy()) {
- boolean init = false;
- try { // Initialize table
- if (cells == as) {
- Cell[] rs = new Cell[2];
- rs[h & 1] = new Cell(x);
- cells = rs;
- init = true;
- }
- } finally {
- BUSY_UPDATER.set(this, 0);
- }
- if (init)
- break;
- }
- else if (casBase(v = base, fn(v, x)))
- break; // Fall back on using base
- }
- hc.code = h; // Record index for next time
- }
-
-
- /**
- * Sets base and all cells to the given value.
- */
- final void internalReset(long initialValue) {
- Cell[] as = cells;
- BASE_UPDATER.set(this, initialValue);
- if (as != null) {
- int n = as.length;
- for (int i = 0; i < n; ++i) {
- Cell a = as[i];
- if (a != null)
- a.value = initialValue;
- }
- }
- }
-
- static final AtomicLongFieldUpdater BASE_UPDATER = AtomicLongFieldUpdater.newUpdater(Striped64.class, "base");
- static final AtomicIntegerFieldUpdater BUSY_UPDATER = AtomicIntegerFieldUpdater.newUpdater(Striped64.class, "busy");
-
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/SerializationWriteBehindTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/SerializationWriteBehindTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/SerializationWriteBehindTest.java (revision 0)
@@ -1,92 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.writebehind;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-import org.terracotta.modules.ehcache.async.AsyncCoordinatorImpl;
-import org.terracotta.toolkit.Toolkit;
-import org.terracotta.toolkit.concurrent.ToolkitBarrier;
-import org.terracotta.toolkit.concurrent.atomic.ToolkitAtomicLong;
-
-import com.tc.l2.L2DebugLogging.LogLevel;
-import com.tc.test.config.model.TestConfig;
-
-import junit.framework.Assert;
-
-public class SerializationWriteBehindTest extends AbstractCacheTestBase {
-
- private static final int NODE_COUNT = 2;
-
- public SerializationWriteBehindTest(TestConfig testConfig) {
- super("basic-writebehind-test.xml", testConfig, App.class, App.class);
- configureTCLogging(AsyncCoordinatorImpl.class.getName(), LogLevel.DEBUG);
- }
-
- public static class App extends ClientBase {
-
- private final ToolkitBarrier barrier;
- final ToolkitAtomicLong totalWriteCount;
- final ToolkitAtomicLong totalDeleteCount;
-
- public App(String[] args) {
- super(args);
- this.barrier = getClusteringToolkit().getBarrier("barrier", NODE_COUNT);
- this.totalWriteCount = getClusteringToolkit().getAtomicLong("long1");
- this.totalDeleteCount = getClusteringToolkit().getAtomicLong("long2");
- }
-
- public static void main(String[] args) {
- new App(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- final int index = barrier.await();
-
- WriteBehindCacheWriter writer;
-
- if (0 == index) {
- writer = new WriteBehindCacheWriter("WriteBehindCacheWriter", index, 20L);
- cache.registerCacheWriter(writer);
-
- for (int i = 0; i < 1000; i++) {
- cache.putWithWriter(new Element(new SerializationWriteBehindType("key" + i % 200),
- new SerializationWriteBehindType("value" + i)));
- if (0 == i % 10) {
- cache.removeWithWriter(new SerializationWriteBehindType("key" + i % 200 / 10));
- }
- }
- } else {
- writer = new WriteBehindCacheWriter("WriteBehindCacheWriter", index, 10L);
- cache.registerCacheWriter(writer);
- }
-
- Thread.sleep(60000);
- barrier.await();
-
- System.out.println("[Client " + index + " processed " + writer.getWriteCount() + " writes for writer 1]");
- System.out.println("[Client " + index + " processed " + writer.getDeleteCount() + " deletes for writer 1]");
-
- totalWriteCount.addAndGet(writer.getWriteCount());
- totalDeleteCount.addAndGet(writer.getDeleteCount());
-
- barrier.await();
-
- if (0 == index) {
- System.out.println("[Clients processed a total of " + totalWriteCount.get() + " writes]");
- System.out.println("[Clients processed a total of " + totalDeleteCount.get() + " deletes]");
-
- Assert.assertEquals(1000, totalWriteCount.get());
- Assert.assertEquals(100, totalDeleteCount.get());
- }
-
- barrier.await();
- }
-
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/statistics/ExtendedStatisticsMBeanTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/statistics/ExtendedStatisticsMBeanTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/statistics/ExtendedStatisticsMBeanTest.java (revision 0)
@@ -1,89 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.statistics;
-
-import java.util.EnumSet;
-import java.util.Random;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.Assert;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.store.StoreOperationOutcomes;
-import net.sf.ehcache.store.StoreOperationOutcomes.PutOutcome;
-
-import org.junit.Ignore;
-import org.junit.Test;
-
-/*
- * Not a real test, just a harness for splunking around mbean test
- */
-@Ignore
-public class ExtendedStatisticsMBeanTest {
-
- public void testStupidEnums() {
- EnumSet test = EnumSet.allOf(StoreOperationOutcomes.PutOutcome.class);
- Assert.assertEquals(test.size(), StoreOperationOutcomes.PutOutcome.values().length);
-
- // System.out.println(ExtendedStatisticsImpl.ALL_STORE_PUT_OUTCOMES.size());
- }
-
- @Test
- public void testLongTime() throws InterruptedException {
- CacheManager cm = CacheManager.getInstance();
- final Cache cache = new Cache("test", 400, null, false, null, true, 120, 120, false, 1000, null);
- cm.addCache(cache);
- Thread t1 = new Thread() {
- @Override
- public void run() {
- for (int i = 0; i < 100000; i++) {
- cache.put(new Element(i, i + 1));
- try {
- TimeUnit.MICROSECONDS.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.err.println("puts done");
- }
- };
- Thread t2 = new Thread() {
- @Override
- public void run() {
- Random rand = new Random(0);
- for (int i = 0; i < 10000000; i++) {
- cache.get(rand.nextInt(i + 1));
- try {
- TimeUnit.MICROSECONDS.sleep(10);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- System.err.println("Gets done");
- }
- };
- t1.start();
- t2.start();
- t1.join();
- t2.join();
- Thread.sleep(1000000);
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/writer/TestCacheWriterException.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/writer/TestCacheWriterException.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/writer/TestCacheWriterException.java (revision 0)
@@ -1,19 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.writer;
-
-public class TestCacheWriterException extends AbstractTestCacheWriter {
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/LargeSet.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/LargeSet.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/util/LargeSet.java (revision 0)
@@ -1,31 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.util;
-
-import java.util.Set;
-
-/**
- * Set for holding large entries of set. The purpose is not to iterate through
- * all entries for add and remove operations.
- *
- * @author Nabib El-Rahman
- *
- * @param
- */
-public abstract class LargeSet extends LargeCollection implements Set {
-//
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/CacheKeySetTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/CacheKeySetTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/CacheKeySetTest.java (revision 0)
@@ -1,76 +0,0 @@
-package net.sf.ehcache.store;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
-/**
- * @author Alex Snaps
- */
-public class CacheKeySetTest {
-
- Collection[] keySets = new Collection[] { new HashSet() {{ add(1); add(2); add(3); }},
- new HashSet() {{ add(1); add(4); add(5); }},
- new HashSet() {{ add(1); add(4); add(6); }} };
- CacheKeySet keySet;
-
- @Before
- public void setup() {
- keySet = new CacheKeySet( keySets );
- }
-
- @Test
- public void testIteratesOverAllElementsOnce() {
- Set keys = new HashSet();
- for (Collection set : keySets) {
- keys.addAll(set);
- }
- assertThat(keys.size(), is(6));
- for (Integer integer : keySet) {
- keys.remove(integer);
- }
- assertThat(keys.isEmpty(), is(true));
- }
-
- @Test
- public void testSizeSumsAllCollections() {
- assertThat(keySet.size(), is(9));
- }
-
- @Test
- public void testIsEmptyAccountsForAllKeySets() {
- assertThat(keySet.isEmpty(), is(false));
- assertThat(new CacheKeySet(new HashSet()).isEmpty(), is(true));
- assertThat(new CacheKeySet(new HashSet(), new HashSet()).isEmpty(), is(true));
- assertThat(new CacheKeySet(new HashSet(), new HashSet(), new HashSet()).isEmpty(), is(true));
- assertThat(new CacheKeySet(new HashSet(), new HashSet(), new HashSet() {{ add(1); }}).isEmpty(), is(false));
- assertThat(new CacheKeySet(new HashSet(), new HashSet() {{ add(1); }}, new HashSet() {{ add(1); }}).isEmpty(), is(false));
- assertThat(new CacheKeySet(new HashSet(), new HashSet() {{ add(1); }}, new HashSet()).isEmpty(), is(false));
- assertThat(new CacheKeySet(new HashSet() {{ add(1); }}, new HashSet() {{ add(1); }}, new HashSet()).isEmpty(), is(false));
- assertThat(new CacheKeySet(new HashSet() {{ add(1); }}, new HashSet(), new HashSet()).isEmpty(), is(false));
- }
-
- @Test
- public void testContainsIsSupported() {
- Set keys = new HashSet(keySet);
- for (Integer key : keys) {
- assertThat(keySet.contains(key), is(true));
- }
- }
-
- @Test
- public void testSupportsEmptyKeySets() {
- final CacheKeySet cacheKeySet = new CacheKeySet();
- assertThat(cacheKeySet.isEmpty(), is(true));
- for (Object o : cacheKeySet) {
- fail("Shouldn't get anything!");
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/LfuMemoryStorePerfTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/LfuMemoryStorePerfTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/store/LfuMemoryStorePerfTest.java (revision 0)
@@ -1,193 +0,0 @@
-package net.sf.ehcache.store;
-
-import net.sf.ehcache.Element;
-import net.sf.ehcache.MemoryStorePerfTester;
-import net.sf.ehcache.StopWatch;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.lang.reflect.Method;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.config.Configuration;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Alex Snaps
- */
-public class LfuMemoryStorePerfTest extends MemoryStorePerfTester {
-
- private static final Logger LOG = LoggerFactory.getLogger(LfuMemoryStorePerfTest.class.getName());
-
- private static final Method FIND_EVICTION_CANDIDATE;
- static {
- try {
- FIND_EVICTION_CANDIDATE = MemoryStore.class.getDeclaredMethod("findEvictionCandidate", Element.class);
- FIND_EVICTION_CANDIDATE.setAccessible(true);
- } catch (SecurityException e) {
- throw new RuntimeException(e);
- } catch (NoSuchMethodException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- protected Cache createCache() throws CacheException {
- return new Cache("LfuMemoryStorePerfTest", 12000, MemoryStoreEvictionPolicy.LFU, false, System.getProperty("java.io.tmpdir"),
- true, 60, 30, false, 60, null);
- }
-
- /**
- * Benchmark to test speed.
- * This takes a little longer for LFU than the others.
- * Used to take about 7400ms. Now takes 827.
- */
- @Test
- public void testBenchmarkPutGetSurya() throws Exception {
- benchmarkPutGetSuryaTest(9000);
- }
-
- /**
- * HashMap
- * INFO: done putting: 128ms
- * INFO: 15ms
- *
- * ConcurrentHashMap
- * INFO: done putting: 200ms
- * INFO: 117ms
- *
- * ConcurrentHashMap
- */
-// @Test
- public void testSpeedOfIteration() {
- StopWatch stopWatch = new StopWatch();
- Map map = new ConcurrentHashMap(100000);
- for (int i = 1; i <= 100000; i++) {
- map.put(i, i);
- }
- LOG.info("done putting: " + stopWatch.getElapsedTimeString());
-
- Collection collection = map.values();
- for (Object o : collection) {
- o.toString();
- }
- LOG.info(stopWatch.getElapsedTimeString());
-
- }
-
- /**
- * Check we get reasonable results for 2000 entries where entry 0 is accessed once increasing to entry 1999 accessed
- * 2000 times.
- *
- * 1 to 5000 population, with hit counts ranging from 1 to 500, not selecting lowest half. 5000 tests
- *
- * Samples Cost No
- * 7 38 99.24% confidence
- * 8 27 99.46% confidence
- * 9 10
- * 10 11300 4 99.92% confidence
- * 12 2
- * 20 11428 0 99.99% confidence
- *
- * 1 to 5000 population, with hit counts ranging from 1 to 500, not selecting lowest quarter. 5000 tests
- * S No
- * 10 291 94.18% confidence
- * 20 15
- * 30 11536 1 99.99% confidence
- *
- * For those with a statistical background the branch of stats which deals with this is hypothesis testing and
- * the Student's T distribution. The higher your sample the greater confidence you can have in a hypothesis, in
- * this case whether or not the "lowest" value lies in the bottom half or quarter of the distribution. Adding
- * samples rapidly increases confidence but the return from extra sampling rapidly diminishes.
- *
- * Cost is not affected much by sample size. Profiling shows that it is the iteration that is causing most of the
- * time. If we had access to the array backing Map, all would work very fast. Still, it is fast enough.
- *
- * A 99.99% confidence interval can be achieved that the "lowest" element is actually in the bottom quarter of the
- * hit count distribution.
- *
- * @throws java.io.IOException Performance:
- * With a sample size of 10: 523ms for 5000 runs = 104 ?s per run
- * With a sample size of 30: 628ms for 5000 runs = 125 ?s per run
- */
- @Test
- public void testLowest() throws Exception {
- CacheManager manager = new CacheManager(new Configuration().name("testLowest"));
- try {
- Cache cache = new Cache("test", 5000, MemoryStoreEvictionPolicy.LFU, false, null, true, 60, 30, false, 60, null);
- manager.addCache(cache);
- Store store = getStore(cache);
-
- // Populate the cache with 5000 unaccessed Elements
- for (int i = 0; i < 5000; i++) {
- store.put(new Element(Integer.valueOf(i), new Date()));
- }
-
- for (int i = 0; i < 10; i++) {
- // Add a new Element at the i'th position
- Element newElement = new Element(Integer.valueOf(i), new Date());
- store.put(newElement);
-
- // Hit that Element (i+1) times - this makes it the most hit Element
- // in the cache
- for (int h = 0; h < (i + 1); h++) {
- store.get(Integer.valueOf(i)).updateAccessStatistics();
- }
-
- // Select an Element for "eviction".
- Element element = (Element)FIND_EVICTION_CANDIDATE.invoke(store, new Object[] { null });
- // This shouldn't be the newly added Element as it is the "most hit"
- assertTrue(!element.equals(newElement));
- // In fact since the sample size is > 10, the hit count should be 0
- // as we must have selected some of the non hit Elements in our sample.
- assertTrue(element.getHitCount() == 0);
- }
-
- // Repeat the hitting procedure above, but for the remaining elements
- // This gives a flat distribution of hit counts from 1 to 5000 all with
- // equal probability (1 element of each count).
- for (int i = 10; i < 5000; i++) {
- store.put(new Element(Integer.valueOf(i), new Date()));
- for (int h = 0; h < (i + 1); h++) {
- store.get(Integer.valueOf(i)).updateAccessStatistics();
- }
- }
-
- long lowestQuartile = 5000 / 4;
-
- long findTime = 0;
- StopWatch stopWatch = new StopWatch();
- int lowestQuartileNotIdentified = 0;
- for (int i = 0; i < 5000; i++) {
- stopWatch.getElapsedTime();
- // Select an Element for "eviction"
- Element e = (Element)FIND_EVICTION_CANDIDATE.invoke(store, new Object[] { null });
- findTime += stopWatch.getElapsedTime();
- long lowest = e.getHitCount();
- // See if it is outside the lowest quartile (i.e. it has an abnormaly
- // high hit count).
- if (lowest > lowestQuartile) {
- LOG.info(e.getKey() + " hit count: " + e.getHitCount() + " lowestQuartile: " + lowestQuartile);
- lowestQuartileNotIdentified++;
- }
- }
-
- LOG.info("Find time: " + findTime);
- // Assert that we can do all this in a reasonable length of time
- assertTrue(findTime < 200);
- LOG.info("Selections not in lowest quartile: " + lowestQuartileNotIdentified);
- // Assert that we didn't see too many eviction candidates from outside
- // the lowest quartile.
- assertTrue(lowestQuartileNotIdentified + " > 10!!!", lowestQuartileNotIdentified <= 10);
- } finally {
- manager.shutdown();
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/WriteBehindAtomicitySyncStrongTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/WriteBehindAtomicitySyncStrongTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/WriteBehindAtomicitySyncStrongTest.java (revision 0)
@@ -1,14 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests;
-
-import com.tc.test.config.model.TestConfig;
-
-public class WriteBehindAtomicitySyncStrongTest extends AbstractWriteBehindAtomicityTestBase {
-
- public WriteBehindAtomicitySyncStrongTest(TestConfig testConfig) {
- super("strong-writebehind-test.xml", testConfig, WriteBehindAtomicityTestClient.class);
- }
-
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/AgentLoaderSystemPropTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/AgentLoaderSystemPropTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/AgentLoaderSystemPropTest.java (revision 0)
@@ -1,21 +0,0 @@
-package net.sf.ehcache.pool.sizeof;
-
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-/**
- * @author Alex Snaps
- */
-public class AgentLoaderSystemPropTest {
-
- @Test
- public void testLoadsAgentIntoSystemPropsWhenRequired() {
- System.setProperty("net.sf.ehcache.sizeof.agent.instrumentationSystemProperty", "true");
- AgentLoader.loadAgent();
- if(AgentLoader.agentIsAvailable()) {
- assertThat(System.getProperties().get("net.sf.ehcache.sizeof.agent.instrumentation"), notNullValue());
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/xaresource-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/xaresource-test.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/xaresource-test.xml (revision 0)
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/TransactionListener.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/TransactionListener.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/TransactionListener.java (revision 0)
@@ -1,40 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.local;
-
-/**
- * A listener interface to get called back when a transaction is being terminated
- *
- * @author Ludovic Orban
- */
-public interface TransactionListener {
-
- /**
- * This method gets called right before the transaction is committed
- */
- void beforeCommit();
-
- /**
- * This method gets called right after the transaction is committed
- */
- void afterCommit();
-
- /**
- * This method gets called right after the transaction is rolled back
- */
- void afterRollback();
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/ConfigurationFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/ConfigurationFactory.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/config/ConfigurationFactory.java (revision 0)
@@ -1,240 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.config;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.util.ClassLoaderUtil;
-
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.StringReader;
-import java.net.URL;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.xml.sax.InputSource;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import net.sf.ehcache.config.generator.ConfigurationSource;
-
-/**
- * A utility class which configures beans from XML, using reflection.
- *
- * @author Greg Luck
- * @version $Id: ConfigurationFactory.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public final class ConfigurationFactory {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigurationFactory.class.getName());
-
- private static final String DEFAULT_CLASSPATH_CONFIGURATION_FILE = "/ehcache.xml";
- private static final String FAILSAFE_CLASSPATH_CONFIGURATION_FILE = "/ehcache-failsafe.xml";
-
- /**
- * Constructor.
- */
- private ConfigurationFactory() {
-
- }
-
- /**
- * Configures a bean from an XML file.
- */
- public static Configuration parseConfiguration(final File file) throws CacheException {
- if (file == null) {
- throw new CacheException("Attempt to configure ehcache from null file.");
- }
-
- LOG.debug("Configuring ehcache from file: {}", file);
- Configuration configuration = null;
- InputStream input = null;
- try {
- input = new BufferedInputStream(new FileInputStream(file));
- configuration = parseConfiguration(input);
- } catch (Exception e) {
- throw new CacheException("Error configuring from " + file + ". Initial cause was " + e.getMessage(), e);
- } finally {
- try {
- if (input != null) {
- input.close();
- }
- } catch (IOException e) {
- LOG.error("IOException while closing configuration input stream. Error was " + e.getMessage());
- }
- }
- configuration.setSource(ConfigurationSource.getConfigurationSource(file));
- return configuration;
- }
-
- /**
- * Configures a bean from an XML file available as an URL.
- */
- public static Configuration parseConfiguration(final URL url) throws CacheException {
- LOG.debug("Configuring ehcache from URL: {}", url);
- Configuration configuration;
- InputStream input = null;
- try {
- input = url.openStream();
- configuration = parseConfiguration(input);
- } catch (Exception e) {
- throw new CacheException("Error configuring from " + url + ". Initial cause was " + e.getMessage(), e);
- } finally {
- try {
- if (input != null) {
- input.close();
- }
- } catch (IOException e) {
- LOG.error("IOException while closing configuration input stream. Error was " + e.getMessage());
- }
- }
- configuration.setSource(ConfigurationSource.getConfigurationSource(url));
- return configuration;
- }
-
- /**
- * Configures a bean from an XML file in the classpath.
- */
- public static Configuration parseConfiguration() throws CacheException {
- ClassLoader standardClassloader = Thread.currentThread().getContextClassLoader();
- URL url = null;
- if (standardClassloader != null) {
- url = standardClassloader.getResource(DEFAULT_CLASSPATH_CONFIGURATION_FILE);
- }
- if (url == null) {
- url = ConfigurationFactory.class.getResource(DEFAULT_CLASSPATH_CONFIGURATION_FILE);
- }
- if (url != null) {
- LOG.debug("Configuring ehcache from ehcache.xml found in the classpath: " + url);
- } else {
- url = ConfigurationFactory.class.getResource(FAILSAFE_CLASSPATH_CONFIGURATION_FILE);
-
- LOG.warn("No configuration found. Configuring ehcache from ehcache-failsafe.xml "
- + " found in the classpath: {}", url);
-
- }
- Configuration configuration = parseConfiguration(url);
- configuration.setSource(ConfigurationSource.getConfigurationSource());
- return configuration;
- }
-
- /**
- * Configures a bean from an XML input stream.
- */
- public static Configuration parseConfiguration(final InputStream inputStream) throws CacheException {
-
- LOG.debug("Configuring ehcache from InputStream");
-
- Configuration configuration = new Configuration();
- try {
- InputStream translatedInputStream = translateSystemProperties(inputStream);
- final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
- final BeanHandler handler = new BeanHandler(configuration);
- parser.parse(translatedInputStream, handler);
- } catch (Exception e) {
- throw new CacheException("Error configuring from input stream. Initial cause was " + e.getMessage(), e);
- }
- configuration.setSource(ConfigurationSource.getConfigurationSource(inputStream));
- return configuration;
- }
-
- /**
- * Configures a cache bean from a string of XML.
- */
- public static CacheConfiguration parseCacheConfiguration(String xmlString) throws CacheException {
- CacheConfiguration cacheConfiguration = new CacheConfiguration();
- try {
- InputSource source = new InputSource(new StringReader(xmlString));
- final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
- final BeanHandler handler = new BeanHandler(cacheConfiguration);
- parser.parse(source, handler);
- } catch (Exception e) {
- throw new CacheException("Error configuring from input stream. Initial cause was " + e.getMessage(), e);
- }
- return cacheConfiguration;
- }
-
- /**
- * Translates system properties which can be added as tokens to the config file using ${token} syntax.
- *
- * So, if the config file contains a character sequence "multicastGroupAddress=${multicastAddress}", and there is a system property
- * multicastAddress=230.0.0.12 then the translated sequence becomes "multicastGroupAddress=230.0.0.12"
- *
- * @param inputStream
- * @return a translated stream
- */
- private static InputStream translateSystemProperties(InputStream inputStream) throws IOException {
-
- StringBuilder sb = new StringBuilder();
- int c;
- Reader reader = new InputStreamReader(inputStream, "UTF-8");
- while ((c = reader.read()) != -1) {
- sb.append((char) c);
- }
- String configuration = sb.toString();
-
- Set tokens = extractPropertyTokens(configuration);
- for (Object tokenObject : tokens) {
- String token = (String) tokenObject;
- String leftTrimmed = token.replaceAll("\\$\\{", "");
- String trimmedToken = leftTrimmed.replaceAll("\\}", "");
-
- String property = System.getProperty(trimmedToken);
- if (property == null) {
- LOG.debug("Did not find a system property for the " + token +
- " token specified in the configuration.Replacing with \"\"");
- } else {
- //replaceAll by default clobbers \ and $
- String propertyWithQuotesProtected = Matcher.quoteReplacement(property);
- configuration = configuration.replaceAll("\\$\\{" + trimmedToken + "\\}", propertyWithQuotesProtected);
-
- LOG.debug("Found system property value of " + property + " for the " + token +
- " token specified in the configuration.");
- }
- }
- return new ByteArrayInputStream(configuration.getBytes("UTF-8"));
- }
-
- /**
- * Extracts properties of the form ${...}
- *
- * @param sourceDocument the source document
- * @return a Set of properties. So, duplicates are only counted once.
- */
- static Set extractPropertyTokens(String sourceDocument) {
- Set propertyTokens = new HashSet();
- Pattern pattern = Pattern.compile("\\$\\{.+?\\}");
- Matcher matcher = pattern.matcher(sourceDocument);
- while (matcher.find()) {
- String token = matcher.group();
- propertyTokens.add(token);
- }
- return propertyTokens;
- }
-
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/ModelElement.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/ModelElement.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/ModelElement.java (revision 0)
@@ -1,23 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.search.parser;
-
-public interface ModelElement {
-
- public T asEhcacheObject(ClassLoader loader);
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/DefaultAsyncConfigSerializationTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/DefaultAsyncConfigSerializationTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/DefaultAsyncConfigSerializationTest.java (revision 0)
@@ -1,43 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.terracotta.upgradability.serialization;
-
-import java.io.IOException;
-import java.util.Comparator;
-import org.junit.Test;
-import org.terracotta.modules.ehcache.async.DefaultAsyncConfig;
-
-import static org.terracotta.upgradability.serialization.SerializationUpgradabilityTesting.validateSerializedForm;
-
-/**
- *
- * @author cdennis
- */
-public class DefaultAsyncConfigSerializationTest {
-
- private static final Comparator COMPARATOR = new Comparator() {
- @Override
- public int compare(DefaultAsyncConfig o1, DefaultAsyncConfig o2) {
- return 0;
- }
- };
-
- @Test
- public void testBasic() throws IOException, ClassNotFoundException {
- validateSerializedForm((DefaultAsyncConfig) DefaultAsyncConfig.getInstance(), COMPARATOR, "serializedforms/DefaultAsyncConfigSerializationTest.testBasic.ser");
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/net/sf/ehcache/management/resource/services/CacheResourceServiceImplTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/net/sf/ehcache/management/resource/services/CacheResourceServiceImplTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/net/sf/ehcache/management/resource/services/CacheResourceServiceImplTest.java (revision 0)
@@ -1,683 +0,0 @@
-package net.sf.ehcache.management.resource.services;
-
-import static com.jayway.restassured.RestAssured.expect;
-import static org.hamcrest.CoreMatchers.allOf;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.nullValue;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ManagementRESTServiceConfiguration;
-import net.sf.ehcache.config.TerracottaClientConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration;
-import net.sf.ehcache.management.resource.CacheEntity;
-
-import org.hamcrest.Matchers;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import com.jayway.restassured.http.ContentType;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author: Anthony Dahanne
- * The aim of this test is to check via HTTP that the ehcache standalone agent /tc-management-api/agents/cacheManagers/caches endpoint
- * works fine
- */
-public class CacheResourceServiceImplTest extends ResourceServiceImplITHelper {
-
- protected static final String EXPECTED_RESOURCE_LOCATION = "{baseUrl}/tc-management-api/agents{agentIds}/cacheManagers{cmIds}/caches{cacheIds}";
-
- @BeforeClass
- public static void setUpCluster() throws Exception {
- setUpCluster(CacheResourceServiceImplTest.class);
- }
-
- @Test
- /**
- * - GET the list of caches
- *
- * @throws Exception
- */
- public void getCachesTest() throws Exception {
- /*
- [
- {
- "version": null,
- "agentId": "embedded",
- "name": "testCache2",
- "cacheManagerName": "testCacheManagerProgrammatic",
- "attributes": {
- "OnDiskSize": 1000,
- "CacheOnDiskHitRate": 0,
- "MostRecentRejoinTimestampMillisSample": 0,
- "LocalOffHeapSizeInBytesSample": 0,
- "LocalHeapSizeInBytes": 247920,
- "Searchable": false,
- "CacheHitMostRecentSample": 0,
- "MostRecentRejoinTimeStampMillis": 0,
- "CacheInMemoryHitRate": 0,
- "NonStopFailureSample": 0,
- "CacheHitOffHeapMostRecentSample": 0,
- "NonstopTimeoutRatio": 0,
- "CacheClusterOnlineSample": 0,
- "NonStopTimeoutSample": 0,
- "NonStopFailureRate": 0,
- "LocalHeapCountBased": false,
- "CacheElementPutSample": 0,
- "LoggingEnabled": false,
- "CacheHitRatioMostRecentSample": 0,
- "MaxBytesLocalHeap": 0,
- "XaRecoveredCount": 0,
- "NonStopSuccessRate": 0,
- "EvictedCount": 0,
- "MinGetTimeNanos": null,
- "NodeBulkLoadEnabled": false,
- "MaxBytesLocalOffHeapAsString": "0",
- "CacheSearchRate": 0,
- "CacheElementRemovedMostRecentSample": 0,
- "InMemorySize": 1000,
- "WriterMaxQueueSize": 0,
- "TerracottaConsistency": "na",
- "NonStopRejoinTimeoutSample": 0,
- "CacheHitInMemoryMostRecentSample": 0,
- "CacheElementEvictedSample": 0,
- "WriterConcurrency": 1,
- "CacheMissInMemoryMostRecentSample": 0,
- "CacheHitRatioSample": 0,
- "LocalDiskSize": 1000,
- "OverflowToDisk": true,
- "CacheMissMostRecentSample": 0,
- "LocalOffHeapSize": 0,
- "UpdateCount": 0,
- "InMemoryMissCount": 0,
- "CacheMissExpiredMostRecentSample": 0,
- "CachePutRate": 0,
- "OffHeapMissCount": 0,
- "CacheHitOnDiskMostRecentSample": 0,
- "CacheMissOffHeapMostRecentSample": 0,
- "CacheOnDiskMissRate": 0,
- "DiskPersistent": false,
- "MemoryStoreEvictionPolicy": "LRU",
- "LocalHeapSize": 1000,
- "TimeToIdleSeconds": 0,
- "AverageGetTime": 0,
- "WriterQueueLength": 0,
- "NonStopFailureMostRecentSample": 0,
- "CacheMissOnDiskSample": 0,
- "TransactionCommitRate": 0,
- "NonStopSuccessCount": 0,
- "CacheElementExpiredSample": 0,
- "CacheClusterOfflineMostRecentSample": 0,
- "InMemoryHitCount": 0,
- "XaRollbackCount": 0,
- "SizeSample": 1000,
- "CacheInMemoryMissRate": 0,
- "CacheClusterRejoinMostRecentSample": 0,
- "DiskExpiryThreadIntervalSeconds": 120,
- "NonStopFailureCount": 0,
- "AverageSearchTimeNanos": 0,
- "CacheMissCount": 0,
- "CacheMissOffHeapSample": 0,
- "NonStopRejoinTimeoutRate": 0,
- "MaxBytesLocalOffHeap": 0,
- "CacheClusterOfflineSample": 0,
- "CacheClusterOnlineCount": 0,
- "CacheXaCommitsSample": 0,
- "MaxBytesLocalHeapAsString": "0",
- "CacheClusterOnlineMostRecentSample": 0,
- "CacheMissRate": 0,
- "SearchesPerSecondSample": 0,
- "CacheElementPutMostRecentSample": 0,
- "CacheClusterOfflineCount": 0,
- "WriterQueueLengthSample": 0,
- "CacheElementEvictedMostRecentSample": 0,
- "HasWriteBehindWriter": false,
- "LocalHeapSizeInBytesSample": 247920,
- "MaxBytesLocalDiskAsString": "0",
- "OverflowToOffHeap": false,
- "CacheMissOnDiskMostRecentSample": 0,
- "CacheElementExpiredMostRecentSample": 0,
- "LocalDiskSizeSample": 1000,
- "CacheRemoveRate": 0,
- "CacheElementUpdatedMostRecentSample": 0,
- "CacheMissNotFoundMostRecentSample": 0,
- "LocalDiskSizeInBytes": 246780,
- "AverageGetTimeNanosMostRecentSample": 0,
- "MaxEntriesLocalHeap": 0,
- "CacheOffHeapMissRate": 0,
- "RemoteSizeSample": 0,
- "ClusterBulkLoadEnabled": null,
- "XaCommitCount": 0,
- "Transactional": false,
- "CacheMissCountExpired": 0,
- "CacheUpdateRate": 0,
- "CacheElementUpdatedSample": 0,
- "PinnedToStore": "na",
- "Size": 1000,
- "TerracottaClustered": false,
- "TransactionRollbackRate": 0,
- "CacheHitInMemorySample": 0,
- "LocalHeapSizeSample": 1000,
- "NonStopSuccessSample": 0,
- "CacheMissInMemorySample": 0,
- "NonStopTimeoutRate": 0,
- "CacheMissNotFoundSample": 0,
- "TimeToLiveSeconds": 0,
- "AverageGetTimeSample": 0,
- "CacheHitCount": 0,
- "MaxBytesLocalDisk": 0,
- "CacheHitSample": 0,
- "ExpiredCount": 0,
- "NonStopRejoinTimeoutCount": 0,
- "CacheXaRollbacksSample": 0,
- "CacheMissSample": 0,
- "PutCount": 1000,
- "AverageSearchTimeSample": 0,
- "CacheClusterRejoinSample": 0,
- "Enabled": true,
- "CacheXaCommitsMostRecentSample": 0,
- "CacheXaRollbacksMostRecentSample": 0,
- "CacheHitOffHeapSample": 0,
- "CacheOffHeapHitRate": 0,
- "RemovedCount": 0,
- "CacheHitOnDiskSample": 0,
- "CacheClusterRejoinCount": 0,
- "AverageSearchTime": 0,
- "LocalOffHeapSizeInBytes": 0,
- "MaxEntriesLocalDisk": 0,
- "MaxGetTimeNanos": null,
- "MaxElementsOnDisk": 0,
- "CacheHitRate": 0,
- "LocalOffHeapSizeSample": 0,
- "OffHeapHitCount": 0,
- "CacheExpirationRate": 0,
- "Pinned": false,
- "Eternal": false,
- "NonStopTimeoutMostRecentSample": 0,
- "CacheHitRatio": 0,
- "OffHeapSize": 0,
- "CacheEvictionRate": 0,
- "NonStopTimeoutCount": 0,
- "SearchesPerSecond": 0,
- "MaxEntriesInCache": 0,
- "CacheMissExpiredSample": 0,
- "LocalDiskSizeInBytesSample": 246780,
- "Status": "STATUS_ALIVE",
- "OnDiskMissCount": 0,
- "NonStopRejoinTimeoutMostRecentSample": 0,
- "OnDiskHitCount": 0,
- "NonStopSuccessMostRecentSample": 0,
- "PersistenceStrategy": "",
- "AverageGetTimeNanos": 0,
- "CacheElementRemovedSample": 0
- }
- },
-]
- */
-
-
- // I need a cacheManager not clustered
- CacheManager standaloneCacheManager = createStandaloneCacheManagerARC();
- Cache cacheStandalone = standaloneCacheManager.getCache("testCacheStandaloneARC");
-
-
- for (int i=0; i<1000 ; i++) {
- cacheStandalone.put(new Element("key" + i, "value" + i));
- }
-
- String agentsFilter = "";
- String cmsFilter = "";
- String cachesFilter = "";
-
-
- expect().contentType(ContentType.JSON)
- .body("size()", is(2))
- .body("find { it.name == 'testCache' }.agentId", equalTo("embedded"))
- .rootPath("find { it.name == 'testCacheStandaloneARC' }")
- .body("agentId", equalTo("embedded"))
- .body("cacheManagerName", equalTo("testCacheManagerStandaloneARC"))
- .body("attributes.LocalHeapSizeInBytes", greaterThan(0))
- .body("attributes.InMemorySize", equalTo(1000))
- .body("attributes.LocalDiskSize", greaterThan(0))
- .body("attributes.LocalHeapSize", equalTo(1000))
- .body("attributes.SizeSample", equalTo(1000))
- .body("attributes.DiskExpiryThreadIntervalSeconds", equalTo(120))
- .body("attributes.LocalHeapSizeInBytesSample", greaterThan(0))
- .body("attributes.LocalDiskSizeSample", greaterThan(0))
- .body("attributes.LocalDiskSizeInBytes", greaterThan(0))
- .body("attributes.Size", equalTo(1000))
- .body("attributes.LocalHeapSizeSample", equalTo(1000))
- .body("attributes.PutCount", equalTo(1000))
- .body("attributes.LocalDiskSizeInBytesSample", greaterThan(0))
- .body("attributes.Status", equalTo("STATUS_ALIVE"))
- .statusCode(200)
- .when().get(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
-
- cachesFilter = ";names=testCacheStandaloneARC";
- // we filter to return only the attribute CacheNames, and working only on the testCache2 Cache
- expect().contentType(ContentType.JSON)
- .body("get(0).agentId", equalTo("embedded"))
- .body("get(0).name", equalTo("testCacheStandaloneARC"))
- .body("get(0).cacheManagerName", equalTo("testCacheManagerStandaloneARC"))
- .body("get(0).attributes.PutCount", equalTo(1000))
- .body("get(0).attributes.Size", equalTo(1000))
- .body("get(0).attributes.LocalHeapSizeSample", nullValue())
- .body("size()",is(1))
- .statusCode(200)
- .given()
- .queryParam("show", "Size")
- .queryParam("show", "PutCount")
- .when().get(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
- standaloneCacheManager.removeAllCaches();
- standaloneCacheManager.shutdown();
-
- }
-
- @Test
- /**
- * - PUT an updated CacheEntity
- *
- * @throws Exception
- */
- public void updateCachesTest__FailWhenNotSpecifyingACache() throws Exception {
- // you have to specify a cache when doing mutation
- CacheEntity cacheManagerEntity = new CacheEntity();
- Map attributes = new HashMap();
- attributes.put("MaxEntriesLocalHeap",20000);
- attributes.put("Enabled", Boolean.FALSE);
- cacheManagerEntity.getAttributes().putAll(attributes);
- String agentsFilter = "";
- String cmsFilter = "";
- String cachesFilter = "";
-
- expect().statusCode(400)
- .body("details", equalTo(""))
- .body("error", equalTo("No cache specified. Unsafe requests must specify a single cache name."))
- .given()
- .contentType(ContentType.JSON)
- .body(cacheManagerEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
-
- cachesFilter = ";names=testCache";
- expect().statusCode(400)
- .body("details", equalTo(""))
- .body("error", equalTo("No cache manager specified. Unsafe requests must specify a single cache manager name."))
- .given()
- .contentType(ContentType.JSON)
- .body(cacheManagerEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
- cmsFilter = ";names=testCacheManager";
- cachesFilter = ";names=boups";
- expect().statusCode(400)
- .body("details", equalTo("Cache not found !"))
- .body("error", equalTo("Failed to create or update cache"))
- .given()
- .contentType(ContentType.JSON)
- .body(cacheManagerEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
- cmsFilter = ";names=pif";
- cachesFilter = ";names=testCache";
- expect().statusCode(400)
- .body("details", equalTo("CacheManager not found !"))
- .body("error", equalTo("Failed to create or update cache"))
- .given()
- .contentType(ContentType.JSON)
- .body(cacheManagerEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
- cmsFilter = "";
- cachesFilter = "";
- // we check nothing has changed
- expect().contentType(ContentType.JSON)
- .body("get(0).agentId", equalTo("embedded"))
- .body("get(0).name", equalTo("testCache"))
- .body("get(0).attributes.MaxEntriesLocalHeap",equalTo(10000) )
- .body("get(0).attributes.Enabled", equalTo(Boolean.TRUE))
- .statusCode(200)
- .when().get(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
- }
-
- @Test
- /**
- * - PUT an updated CacheEntity
- *
- * Those are the mutable attributes from the rest agent, followed by Gary's comments
- * ENABLED_ATTR: the user can change directly from the management panel
- * LOGGING_ENABLED: just never had this in the DevConsole and nobody's ever asked for it
- * BULK_LOAD_ENABLED: will probably be adding this with the management panel overhaul
- * MAX_ENTRIES_LOCAL_HEAP: we do support this, but not when you've already specified MAX_BYTES_LOCAL_HEAP
- * MAX_ELEMENTS_ON_DISK: same as above, except you've already specified MAX_BYTES_LOCAL_HEAP
- * MAX_ENTRIES_IN_CACHE: if it's a Terracotta-clustered cache, we support this
- * MAX_BYTES_LOCAL_DISK_STRING
- * MAX_BYTES_LOCAL_HEAP_STRING
- * TIME_TO_IDLE_SEC
- * TIME_TO_LIVE_SEC
- *
- * @throws Exception
- */
- public void updateCachesTest() throws Exception {
-
- // I need a cacheManager not clustered
- CacheManager standaloneCacheManager = createStandaloneCacheManager();
-
- // you have to specify a cache when doing mutation
- CacheEntity cacheEntity = new CacheEntity();
- Map attributes = new HashMap();
- attributes.put("MaxEntriesInCache", 30000);
- attributes.put("MaxEntriesLocalHeap",20000);
- attributes.put("LoggingEnabled", Boolean.TRUE);
- attributes.put("MaxElementsOnDisk",40000);
- attributes.put("TimeToIdleSeconds", 20);
- attributes.put("TimeToLiveSeconds", 43);
- attributes.put("Enabled", Boolean.FALSE);
-
-
- String agentsFilter = "";
- String cmsFilter = ";names=testCacheManagerStandalone";
- String cachesFilter = ";names=testCacheStandalone";
- cacheEntity.getAttributes().putAll(attributes);
- expect().statusCode(204).log().ifStatusCodeIsEqualTo(400)
- .given()
- .contentType(ContentType.JSON)
- .body(cacheEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
-
- cmsFilter = "";
- // we check the properties were changed
- expect().contentType(ContentType.JSON)
- .body("get(0).agentId", equalTo("embedded"))
- .body("get(0).name", equalTo("testCacheStandalone"))
- .body("get(0).attributes.MaxEntriesInCache", equalTo(30000))
- .body("get(0).attributes.MaxEntriesLocalHeap", equalTo(20000))
- .body("get(0).attributes.LoggingEnabled", equalTo(Boolean.TRUE))
- .body("get(0).attributes.MaxElementsOnDisk", equalTo(40000))
- .body("get(0).attributes.TimeToIdleSeconds", equalTo(20))
- .body("get(0).attributes.TimeToLiveSeconds", equalTo(43))
- .body("get(0).attributes.Enabled", equalTo(Boolean.FALSE))
- .statusCode(200)
- .when().get(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
-
- standaloneCacheManager.removeAllCaches();
- standaloneCacheManager.shutdown();
- // I need another cache that does not have set MaxBytesLocalHeap nor MaxBytesLocalDisk
- CacheManager cacheManagerNew = getCacheManagerNew();
-
- cacheEntity = new CacheEntity();
- attributes = new HashMap();
- attributes.put("MaxBytesLocalDiskAsString", "30M");
- attributes.put("MaxBytesLocalHeapAsString","20M");
- cacheEntity.getAttributes().putAll(attributes);
-
- cmsFilter = ";names=cacheManagerNew";
- cachesFilter = ";names=CacheNew";
-
- expect().log().ifStatusCodeIsEqualTo(400)
- .statusCode(204)
- .given()
- .contentType(ContentType.JSON)
- .body(cacheEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
-
- cmsFilter = "";
- cachesFilter = ";names=CacheNew";
- // we check the properties were changed
- expect().contentType(ContentType.JSON)
- .body("get(0).agentId", equalTo("embedded"))
- .body("get(0).name", equalTo("CacheNew"))
- .body("get(0).attributes.MaxBytesLocalDiskAsString", equalTo("30M"))
- .body("get(0).attributes.MaxBytesLocalHeapAsString", equalTo("20M"))
- .statusCode(200)
- .when().get(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
- cacheManagerNew.removeAllCaches();
- cacheManagerNew.shutdown();
-
-
- }
-
- @Test
- /**
- * - PUT an updated CacheEntity
- *
- * Those are the mutable attributes from the rest agent, followed by Gary's comments
- * ENABLED_ATTR: the user can change directly from the management panel
- * LOGGING_ENABLED: just never had this in the DevConsole and nobody's ever asked for it
- * BULK_LOAD_ENABLED: will probably be adding this with the management panel overhaul
- * MAX_ENTRIES_LOCAL_HEAP: we do support this, but not when you've already specified MAX_BYTES_LOCAL_HEAP
- * MAX_ELEMENTS_ON_DISK: same as above, except you've already specified MAX_BYTES_LOCAL_HEAP
- * MAX_ENTRIES_IN_CACHE: if it's a Terracotta-clustered cache, we support this
- * MAX_BYTES_LOCAL_DISK_STRING
- * MAX_BYTES_LOCAL_HEAP_STRING
- * TIME_TO_IDLE_SEC
- * TIME_TO_LIVE_SEC
- *
- * @throws Exception
- */
- public void updateCachesTest__clustered() throws Exception {
-
-
- CacheManager clusteredCacheManager = createClusteredCacheManager();
-
- try {
- // you have to specify a cache when doing mutation
- CacheEntity cacheEntity = new CacheEntity();
- Map attributes = new HashMap();
- attributes.put("MaxEntriesInCache", 30000);
- attributes.put("MaxEntriesLocalHeap", 20000);
- attributes.put("LoggingEnabled", Boolean.TRUE);
- attributes.put("TimeToIdleSeconds", 20);
- attributes.put("TimeToLiveSeconds", 43);
- attributes.put("NodeBulkLoadEnabled", Boolean.TRUE); //ONLY FOR CLUSTERED !!!
- attributes.put("Enabled", Boolean.FALSE);
-
- final String agentsFilter = ";ids=" + clusteredCacheManagerAgentId;
- String cmsFilter = ";names=testCacheManagerClustered";
- String cachesFilter = ";names=testCacheClustered";
- cacheEntity.getAttributes().putAll(attributes);
- expect().statusCode(204).log().ifStatusCodeIsEqualTo(400)
- .given()
- .contentType(ContentType.JSON)
- .body(cacheEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, CLUSTERED_BASE_URL, agentsFilter, cmsFilter, cachesFilter);
-
-
- cmsFilter = "";
- // we check the properties were changed
- expect().contentType(ContentType.JSON)
- .body("get(0).agentId", equalTo(clusteredCacheManagerAgentId))
- .body("get(0).name", equalTo("testCacheClustered"))
- .body("get(0).attributes.MaxEntriesInCache", equalTo(30000))
- .body("get(0).attributes.MaxEntriesLocalHeap", equalTo(20000))
- .body("get(0).attributes.LoggingEnabled", equalTo(Boolean.TRUE))
- .body("get(0).attributes.NodeBulkLoadEnabled", equalTo(Boolean.TRUE)) //ONLY FOR CLUSTERED !!!
- .body("get(0).attributes.ClusterBulkLoadEnabled", equalTo(Boolean.TRUE)) //ONLY FOR CLUSTERED !!!
- .body("get(0).attributes.TimeToIdleSeconds", equalTo(20))
- .body("get(0).attributes.TimeToLiveSeconds", equalTo(43))
- .body("get(0).attributes.Enabled", equalTo(Boolean.FALSE))
- .statusCode(200)
- .when().get(EXPECTED_RESOURCE_LOCATION, CLUSTERED_BASE_URL, agentsFilter, cmsFilter, cachesFilter);
- } finally {
- clusteredCacheManager.shutdown();
- }
-
- }
-
-
- @Test
- /**
- * - PUT an updated CacheEntity, with attributes not allowed
- * only 6 attributes are supported (cf previosu test), the others are forbidden because we do not allow them to be updated
- * @throws Exception
- */
- public void updateCachesTest__FailWhenMutatingForbiddenAttributes() throws Exception {
-
- CacheEntity cacheManagerEntity = new CacheEntity();
- cacheManagerEntity.setName("superName");
- Map attributes = new HashMap();
- attributes.put("LocalOffHeapSizeInBytes","20000");
- attributes.put("Pinned", Boolean.TRUE);
- cacheManagerEntity.getAttributes().putAll(attributes);
-
- String agentsFilter = "";
- String cmsFilter = ";names=testCacheManager";
- String cachesFilter = ";names=testCache";
-
- expect().statusCode(400)
- .body("details", allOf(containsString("You are not allowed to update those attributes : name LocalOffHeapSizeInBytes Pinned . Only"),
- containsString("TimeToIdleSeconds"), containsString("Enabled"), containsString("MaxBytesLocalDiskAsString"),
- containsString("MaxBytesLocalHeapAsString"), containsString("MaxElementsOnDisk"), containsString("TimeToLiveSeconds"),
- containsString("MaxEntriesLocalHeap"), containsString("LoggingEnabled"), containsString("NodeBulkLoadEnabled"),
- containsString("MaxEntriesInCache"), Matchers.containsString(" can be updated for a Cache.")))
- .body("error", equalTo("Failed to create or update cache"))
- .given()
- .contentType(ContentType.JSON)
- .body(cacheManagerEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter, cmsFilter, cachesFilter);
-
- cmsFilter ="";
- // we check nothing has changed
- expect().contentType(ContentType.JSON)
- .body("get(0).agentId", equalTo("embedded"))
- .body("get(0).name", equalTo("testCache"))
- .body("get(0).attributes.LocalOffHeapSizeInBytes", equalTo(0))
- .body("get(0).attributes.Pinned", equalTo(Boolean.FALSE))
- .body("size()",is(1))
- .statusCode(200)
- .when().get(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
- }
-
-
-
- @Test
- /**
- * - PUT an updated CacheEntity
- * @throws Exception
- */
- public void updateCachesTest__CacheManagerDoesNotExist() throws Exception {
-
-
- String agentsFilter = "";
- String cmsFilter = ";names=cachemanagerDoesNotExist";
- String cachesFilter = ";names=testCache";
-
- CacheEntity cacheEntity = new CacheEntity();
- expect().statusCode(400)
- .body("details", equalTo("CacheManager not found !"))
- .body("error", equalTo("Failed to create or update cache"))
- .given()
- .contentType(ContentType.JSON)
- .body(cacheEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
- }
-
-
- @Test
- /**
- * - PUT a CacheEntity, not matching any known caches : creating is not allowed
- *
- * @throws Exception
- */
- public void updateCachesTest__CantCreateCache() throws Exception {
-
-
- String agentsFilter = "";
- String cmsFilter = ";names=testCacheManager";
- String cachesFilter = ";names=cacheThatDoesNotExist";
- CacheEntity cacheEntity = new CacheEntity();
- expect().statusCode(400)
- .body("details", equalTo("Cache not found !"))
- .body("error", equalTo("Failed to create or update cache"))
- .given()
- .contentType(ContentType.JSON)
- .body(cacheEntity)
- .when().put(EXPECTED_RESOURCE_LOCATION, STANDALONE_BASE_URL, agentsFilter,cmsFilter, cachesFilter);
- }
-
- private CacheManager getCacheManagerNew() {
- Configuration configuration = new Configuration();
- configuration.setName("cacheManagerNew");
-
- CacheConfiguration myCache = new CacheConfiguration()
- .eternal(false).name("CacheNew");
- myCache.setMaxBytesLocalHeap("5M");
- myCache.setMaxBytesLocalDisk("3M");
- configuration.addCache(myCache);
- ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration();
- managementRESTServiceConfiguration.setBind("0.0.0.0:"+STANDALONE_REST_AGENT_PORT);
- managementRESTServiceConfiguration.setEnabled(true);
- configuration.addManagementRESTService(managementRESTServiceConfiguration);
- CacheManager cacheManager = new CacheManager(configuration);
- Cache exampleCache = cacheManager.getCache("CacheNew");
- assert (exampleCache != null);
- return cacheManager;
- }
-
- private CacheManager createStandaloneCacheManagerARC() {
- Configuration configuration = new Configuration();
- configuration.setName("testCacheManagerStandaloneARC");
- configuration.setMaxBytesLocalDisk("10M");
- configuration.setMaxBytesLocalHeap("5M");
- CacheConfiguration myCache = new CacheConfiguration().eternal(false).name("testCacheStandaloneARC");
- configuration.addCache(myCache);
- ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration();
- managementRESTServiceConfiguration.setBind("0.0.0.0:"+STANDALONE_REST_AGENT_PORT);
- managementRESTServiceConfiguration.setEnabled(true);
- configuration.addManagementRESTService(managementRESTServiceConfiguration);
-
- CacheManager mgr = new CacheManager(configuration);
- Cache exampleCache = mgr.getCache("testCacheStandaloneARC");
- assert (exampleCache != null);
- return mgr;
- }
-
- private CacheManager createStandaloneCacheManager() {
- CacheConfiguration myCache = new CacheConfiguration().eternal(false).name("testCacheStandalone").maxEntriesLocalHeap(10000);
- Configuration configuration = new Configuration().name("testCacheManagerStandalone").cache(myCache);
-
- ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration();
- managementRESTServiceConfiguration.setBind("0.0.0.0:"+STANDALONE_REST_AGENT_PORT);
- managementRESTServiceConfiguration.setEnabled(true);
- configuration.addManagementRESTService(managementRESTServiceConfiguration);
-
- CacheManager mgr = new CacheManager(configuration);
- Cache exampleCache = mgr.getCache("testCacheStandalone");
- assert (exampleCache != null);
- return mgr;
- }
-
- private String clusteredCacheManagerAgentId;
-
- private CacheManager createClusteredCacheManager() {
- Configuration configuration = new Configuration();
- configuration.setName("testCacheManagerClustered");
- TerracottaClientConfiguration terracottaConfiguration = new TerracottaClientConfiguration().url(CLUSTER_URL);
- configuration.addTerracottaConfig(terracottaConfiguration);
- CacheConfiguration myCache = new CacheConfiguration().eternal(false).name("testCacheClustered").terracotta(new TerracottaConfiguration()).maxEntriesLocalHeap(10000).timeToIdleSeconds(1);
- configuration.addCache(myCache);
- ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration();
- managementRESTServiceConfiguration.setBind("0.0.0.0:"+STANDALONE_REST_AGENT_PORT);
- managementRESTServiceConfiguration.setEnabled(true);
- configuration.addManagementRESTService(managementRESTServiceConfiguration);
-
- CacheManager mgr = new CacheManager(configuration);
- Cache exampleCache = mgr.getCache("testCacheClustered");
- assert (exampleCache != null);
- clusteredCacheManagerAgentId = ResourceServiceImplITHelper.waitUntilEhcacheAgentUp(mgr.getClusterUUID());
- return mgr;
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/transaction/xa/XATransactionSizeOfTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/transaction/xa/XATransactionSizeOfTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/transaction/xa/XATransactionSizeOfTest.java (revision 0)
@@ -1,118 +0,0 @@
-package net.sf.ehcache.transaction.xa;
-
-import bitronix.tm.BitronixTransactionManager;
-import bitronix.tm.TransactionManagerServices;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.CopyStrategyConfiguration;
-import net.sf.ehcache.config.MemoryUnit;
-import net.sf.ehcache.config.SizeOfPolicyConfiguration;
-import net.sf.ehcache.store.compound.SerializationCopyStrategy;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.ConsoleHandler;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.transaction.Status;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author lorban
- */
-public class XATransactionSizeOfTest {
-
- private BitronixTransactionManager transactionManager;
- private CacheManager cacheManager;
- private Ehcache cache1;
-
- @Before
- public void setUp() throws Exception {
- CacheConfiguration txCache1Cfg = new CacheConfiguration().name("txCache1")
- .transactionalMode(CacheConfiguration.TransactionalMode.XA_STRICT)
- .sizeOfPolicy(new SizeOfPolicyConfiguration().maxDepth(13)
- .maxDepthExceededBehavior(SizeOfPolicyConfiguration.MaxDepthExceededBehavior.ABORT));
- CopyStrategyConfiguration copyStrategyConfiguration = new CopyStrategyConfiguration();
- copyStrategyConfiguration.setClass(SerializationCopyStrategy.class.getName());
- txCache1Cfg.addCopyStrategy(copyStrategyConfiguration);
- Configuration configuration = new Configuration().maxBytesLocalHeap(10, MemoryUnit.MEGABYTES)
- .cache(txCache1Cfg);
-
- TransactionManagerServices.getConfiguration().setJournal("null").setServerId(XATransactionSizeOfTest.class.getSimpleName());
- transactionManager = TransactionManagerServices.getTransactionManager();
-
- cacheManager = new CacheManager(configuration);
- transactionManager.begin();
- cache1 = cacheManager.getEhcache("txCache1");
- cache1.removeAll();
- transactionManager.commit();
- }
-
- @After
- public void tearDown() throws Exception {
- if (transactionManager.getStatus() != Status.STATUS_NO_TRANSACTION) {
- transactionManager.rollback();
- }
- transactionManager.shutdown();
- cacheManager.shutdown();
- }
-
- /**
- * Make sure the sizeof engine detects that there are too many objects to be walked.
- */
- @Test
- public void testHasAbortedSizeOf() throws Exception {
- transactionManager.begin();
-
- List strings = new ArrayList();
- for (int i = 0; i < 100; i++) {
- strings.add("" + i);
- }
- cache1.put(new Element(0, strings));
-
- transactionManager.commit();
- assertTrue(cache1.hasAbortedSizeOf());
- }
-
- /**
- * Make sure XA doesn't store stuff that makes the sizeof engine mistakenly walk the whole heap.
- *
- * Here's what is walked when storing elements with integers both as key and value:
- *
- * 40b net.sf.ehcache.store.chm.SelectableConcurrentHashMap$HashEntry@1205901244
- * 80b net.sf.ehcache.Element@1942996580
- * 32b net.sf.ehcache.transaction.SoftLockID@1216216770
- * 80b net.sf.ehcache.Element@350784291
- * 24b java.lang.Integer@1618147776
- * ignored java.lang.Integer@1897411861
- * 24b net.sf.ehcache.transaction.xa.XidTransactionIDImpl@738355611
- * 32b java.lang.String@739090040
- * 32b [C@840888032
- * 24b net.sf.ehcache.transaction.xa.SerializableXid@215272917
- * 56b [B@750131952
- * 56b [B@1738709374
- *
- * That's 12 objects, so make sure SizeOfPolicyConfiguration's maxDepth is >= 13.
- */
- @Test
- public void testSizeOf() throws Exception {
- transactionManager.begin();
-
- for (int i = 0; i < 100; i++) {
- cache1.put(new Element(i, i));
- }
-
- transactionManager.commit();
- assertFalse(cache1.hasAbortedSizeOf());
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/README.txt
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/README.txt (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/colorcache/src/assemble/README.txt (revision 0)
@@ -1,25 +0,0 @@
-How to run this sample
-------------------------------
-
-NOTE: Windows users please use the equivalent Batch scripts
-
-NOTE: JAVA_HOME environment variable must be set to valid path of JDK 1.6+ installation prior to running the scripts below.
-
-1. Start Terracotta server first
- bin/start-sample-server.sh
-
-2. Start sample: bin/start-sample.sh
-
-3. Access colorcache sample at
- -- http://localhost:9081/colorcache
- -- http://localhost:9082/colorcache
-
-4. Shut down sample: bin/stop-sample.sh
-
-How to monitor cache usage with the Terracotta Management Console
-------------------------------
-
-With the sample running, you can monitor the runtime statistics
-of the cache using the Terracotta Management console.
-
-See http://terracotta.org/documentation/tms/tms for more information.
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/ManagementServiceTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/ManagementServiceTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/ManagementServiceTest.java (revision 0)
@@ -1,462 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.management;
-
-import net.sf.ehcache.AbstractCacheTest;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import net.sf.ehcache.constructs.blocking.BlockingCache;
-import net.sf.ehcache.store.disk.DiskStoreHelper;
-
-import org.hamcrest.collection.IsEmptyCollection;
-import org.hamcrest.core.Is;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.BindException;
-import java.rmi.RemoteException;
-import java.rmi.registry.LocateRegistry;
-import java.rmi.server.ExportException;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Random;
-import java.util.Set;
-
-import javax.management.JMException;
-import javax.management.MBeanAttributeInfo;
-import javax.management.MBeanInfo;
-import javax.management.MBeanRegistrationException;
-import javax.management.MBeanServer;
-import javax.management.MBeanServerConnection;
-import javax.management.MBeanServerFactory;
-import javax.management.ObjectName;
-import javax.management.remote.JMXConnector;
-import javax.management.remote.JMXConnectorServer;
-import javax.management.remote.JMXConnectorServerFactory;
-import javax.management.remote.JMXServiceURL;
-
-import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
-import static org.hamcrest.core.IsNull.notNullValue;
-import static org.hamcrest.core.IsNull.nullValue;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
-
-/**
- * These tests use the JDK1.5 platform mbean server
- * To interactively examine behaviour, add a Thread.sleep(...) and add -Dcom.sun.management.jmxremote to the java
- * invocation.
- *
- * To see ehcache specific types in the JMX client add the ehcache.jar to the classpath.
- * e.g. to avoid the "Unavailable" message in jconsole caused by ClassNotFound add:
- * jconsole -J-Djava.class.path=core/target/classes
- *
- * @author Greg Luck
- * @version $Id: ManagementServiceTest.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class ManagementServiceTest extends AbstractCacheTest {
-
- private static final Logger LOG = LoggerFactory.getLogger(ManagementServiceTest.class.getName());
- private static final int OBJECTS_IN_TEST_EHCACHE = 46;
- private MBeanServer mBeanServer;
-
-
- /**
- * setup test
- */
- @Override
- @Before
- public void setUp() throws Exception {
- super.setUp();
- mBeanServer = createMBeanServer();
- }
-
- private MBeanServer create14MBeanServer() {
- return MBeanServerFactory.createMBeanServer("SimpleAgent");
- }
-
- /**
- * teardown
- */
- @Override
- @After
- public void tearDown() throws Exception {
- super.tearDown();
- //Ensure the CacheManager shutdown clears all ObjectNames from the MBeanServer
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), IsEmptyCollection.empty());
- }
-
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testRegistrationServiceFourTrue() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true, true);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
- }
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testRegistrationServiceFourTrueUsing14MBeanServer() throws Exception {
- mBeanServer = create14MBeanServer();
- ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true, true);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
- }
-
-
- /**
- * Integration test for the registration service using a contructed ManagementService as would be done
- * by an IoC container.
- */
- @Test
- public void testRegistrationServiceFourTrueUsing14MBeanServerWithConstructorInjection() throws Exception {
- mBeanServer = create14MBeanServer();
- ManagementService managementService = new ManagementService(manager, mBeanServer, true, true, true, true, true);
- managementService.init();
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
- }
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testRegistrationServiceListensForCacheChanges() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true, true);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
- manager.addCache("new cache");
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE + 3));
- manager.removeCache("sampleCache1");
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
- }
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testMultipleCacheManagers() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true, true);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
- File file = new File(AbstractCacheTest.SRC_CONFIG_DIR + "ehcache.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file).name("cm-2");
- net.sf.ehcache.CacheManager secondCacheManager = new net.sf.ehcache.CacheManager(configuration);
- ManagementService.registerMBeans(secondCacheManager, mBeanServer, true, true, true, true, true);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE + 19));
- secondCacheManager.shutdown();
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
- }
-
- /**
- * Checks that Statistics updates
- */
- @Test
- public void testStatisticsMBeanUpdatesAsStatsChange() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, false, false, false, true, false);
- Ehcache cache = manager.getCache("sampleCache1");
- ObjectName name = CacheStatistics.createObjectName(manager.getName(), cache.getName());
- assertThat(mBeanServer.getAttribute(name, "ObjectCount"), Is.is(Long.valueOf(0L)));
- cache.put(new Element("1", "value"));
- cache.get("1");
- DiskStoreHelper.flushAllEntriesToDisk((net.sf.ehcache.Cache)cache).get();
- assertThat(mBeanServer.getAttribute(name, "ObjectCount"), Is.is(Long.valueOf(1L)));
- assertThat(mBeanServer.getAttribute(name, "MemoryStoreObjectCount"), Is.is(Long.valueOf(1L)));
- assertThat(mBeanServer.getAttribute(name, "DiskStoreObjectCount"), Is.is(Long.valueOf(1L)));
- }
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testRegistrationServiceThreeTrue() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, true, true, true, false, false);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(31));
-
- }
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testRegistrationServiceTwoTrue() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, true, true, false, false, false);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(16));
- }
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testRegistrationServiceOneTrue() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, true, false, false, false, false);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(1));
- }
-
- /**
- * Integration test for the registration service
- */
- @Test
- public void testRegistrationServiceNoneTrue() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, false, false, false, false, false);
- assertThat(mBeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null), IsEmptyCollection.empty());
- }
-
- /**
- * Can we register the CacheManager MBean?
- */
- @Test
- public void testRegisterCacheManager() throws Exception {
- //Set size so the second element overflows to disk.
- Ehcache ehcache = new net.sf.ehcache.Cache("testNoOverflowToDisk", 1, false, false, 500, 200);
- manager.addCache(ehcache);
-
- ehcache.put(new Element("key1", "value1"));
- ehcache.put(new Element("key2", "value1"));
- assertThat(ehcache.get("key1"), nullValue());
- assertThat(ehcache.get("key2"), notNullValue());
-
-
- ObjectName name = new ObjectName("net.sf.ehcache:type=CacheManager,name=1");
- CacheManager cacheManager = new CacheManager(manager);
- mBeanServer.registerMBean(cacheManager, name);
- mBeanServer.unregisterMBean(name);
-
- name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=testOverflowToDisk");
- mBeanServer.registerMBean(new Cache(ehcache), name);
- mBeanServer.unregisterMBean(name);
-
- name = new ObjectName("net.sf.ehcache:type=CacheManager.Cache,CacheManager=1,name=sampleCache1");
- mBeanServer.registerMBean(new Cache(manager.getCache("sampleCache1")), name);
- mBeanServer.unregisterMBean(name);
-
- }
-
-
- /**
- * Can we register the CacheManager MBean?
- */
- @Test
- public void testListCachesFromManager() throws Exception {
- ManagementService.registerMBeans(manager, mBeanServer, true, false, false, false, false);
-
- Ehcache ehcache = manager.getCache("sampleCache1");
-
- ehcache.put(new Element("key1", "value1"));
- ehcache.put(new Element("key2", "value1"));
- assertThat(ehcache.get("key1"), notNullValue());
- assertThat(ehcache.get("key2"), notNullValue());
-
- ObjectName name = CacheManager.createObjectName(manager);
-
- Object object = mBeanServer.getAttribute(name, "Status");
- LOG.info(object.toString());
-
- List> caches = (List>) mBeanServer.getAttribute(name, "Caches");
- assertThat(caches, hasSize(15));
-
- for (int i = 0; i < caches.size(); i++) {
- Cache cache = (Cache) caches.get(i);
- String cacheName = cache.getName();
- CacheStatistics cacheStatistics = cache.getStatistics();
- CacheConfiguration cacheConfiguration = cache.getCacheConfiguration();
- LOG.info(cacheName + " " + cacheStatistics + " " + cacheConfiguration);
- }
- }
-
- /**
- * Shows that all MBeans are fully traversable locally
- *
- * @throws JMException
- */
- @Test
- public void testTraversalUsingMBeanServer() throws JMException {
- //Test CacheManager
- //not all attributes are accessible due to serializability constraints
- traverseMBeanAttributesUsingMBeanServer("CacheManager");
-
- //Test Cache
- //not all attributes are accessible due to serializability constraints
- traverseMBeanAttributesUsingMBeanServer("Cache");
-
- //Test CacheStatistics
- traverseMBeanAttributesUsingMBeanServer("CacheStatistics");
-
- //Test CacheConfiguration
- traverseMBeanAttributesUsingMBeanServer("CacheConfiguration");
-
- }
-
-
- /**
- * Creates an RMI JMXConnectorServer, connects to it and demonstrates what attributes are traversable.
- * The answer is not all.
- *
- * Note that this test creates a Registry which will keep running until the JVM Exists. There
- * is no way to stop it but it should do no harm.
- */
- @Test
- public void testJMXConnectorServer() throws Exception {
-
- ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true, true);
-
- int registryPort = startRegistry(50000, 60000, 100);
- JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:" + registryPort + "/ManagementServiceTest/testJMXConnectorServer");
- JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mBeanServer);
- cs.start();
- JMXConnector connector = cs.toJMXConnector(null);
- connector.connect(null);
- MBeanServerConnection connection = connector.getMBeanServerConnection();
- assertThat(connection.queryNames(new ObjectName("net.sf.ehcache:*"), null), hasSize(OBJECTS_IN_TEST_EHCACHE));
-
-
- Ehcache ehcache = manager.getCache("sampleCache1");
-
- ehcache.put(new Element("key1", "value1"));
- ehcache.put(new Element("key2", "value1"));
- assertThat(ehcache.get("key1"), notNullValue());
- assertThat(ehcache.get("key2"), notNullValue());
-
- //Test CacheManager
- //not all attributes are accessible due to serializability constraints
- //traverseMBeanAttributes(connection, "CacheManager");
-
- //Test Cache
- //not all attributes are accessible due to serializability constraints
- //traverseMBeanAttributes(connection, "Cache");
-
- //Test CacheStatistics
- traverseMBeanAttributes(connection, "CacheStatistics");
-
- //Test CacheConfiguration
- traverseMBeanAttributes(connection, "CacheConfiguration");
-
- cs.stop();
- }
-
- private int startRegistry(int portRangeStart, int portRangeEnd, int attempts) throws RemoteException {
- Random rndm = new Random();
- for (int i = 0; ; i++) {
- int candidatePort = rndm.nextInt(portRangeEnd - portRangeStart) + portRangeStart;
- LOG.info("Attempting to start RMI registry on port " + candidatePort);
- try {
- LocateRegistry.createRegistry(candidatePort);
- return candidatePort;
- } catch (ExportException e) {
- if (e.getCause() instanceof BindException) {
- LOG.warn("Failed to bind to port " + candidatePort);
- }
- if (i >= attempts) {
- throw e;
- }
- }
- }
- }
-
- @Test
- public void testSupportsDecoratedCaches() {
- ManagementService.registerMBeans(manager, mBeanServer, true, true, true, true, true);
-
- net.sf.ehcache.Cache cache = new net.sf.ehcache.Cache(new net.sf.ehcache.config.CacheConfiguration("decoratedCache", 1000));
- BlockingCache blockingCache = new BlockingCache(cache);
-
- manager.addCacheIfAbsent(blockingCache);
- }
-
- @Test
- public void testNotifyCacheRemovedCallsUnregisterForAll() throws Exception {
- MBeanServer server = mock(MBeanServer.class);
- when(server.isRegistered(any(ObjectName.class))).thenReturn(true);
-
- net.sf.ehcache.CacheManager cm = mock(net.sf.ehcache.CacheManager.class);
- when(cm.toString()).thenReturn("cmName");
-
- ManagementService managementService = new ManagementService(cm, server, false, true, true, true, true);
-
- managementService.notifyCacheRemoved("testName");
- verify(server, times(4)).isRegistered(any(ObjectName.class));
- verify(server, times(4)).unregisterMBean(any(ObjectName.class));
- }
-
- @Test
- public void testNotifyCacheRemovedDoesNotCallWhenNotRegistered() {
- MBeanServer server = mock(MBeanServer.class);
- when(server.isRegistered(any(ObjectName.class))).thenReturn(true);
-
- net.sf.ehcache.CacheManager cm = mock(net.sf.ehcache.CacheManager.class);
- when(cm.toString()).thenReturn("cmName");
-
- ManagementService managementService = new ManagementService(cm, server, false, false, false, false, false);
-
- managementService.notifyCacheRemoved("testName");
- verifyZeroInteractions(server);
- }
-
- @Test
- public void testNotifyCacheRemovedCallsUnregisterForAllEvenWithException() throws Exception {
- MBeanServer server = mock(MBeanServer.class);
- when(server.isRegistered(any(ObjectName.class))).thenReturn(true);
- doThrow(new MBeanRegistrationException(new IllegalStateException())).when(server).unregisterMBean(any(ObjectName.class));
-
- net.sf.ehcache.CacheManager cm = mock(net.sf.ehcache.CacheManager.class);
- when(cm.toString()).thenReturn("cmName");
-
- ManagementService managementService = new ManagementService(cm, server, false, true, true, true, true);
-
- managementService.notifyCacheRemoved("testName");
- verify(server, times(4)).isRegistered(any(ObjectName.class));
- verify(server, times(4)).unregisterMBean(any(ObjectName.class));
- }
-
- private void traverseMBeanAttributes(MBeanServerConnection connection, String type) throws JMException, IOException {
- Set objectNames = connection.queryNames(new ObjectName("net.sf.ehcache:type=" + type + ",*"), null);
- for (Iterator iterator = objectNames.iterator(); iterator.hasNext();) {
- ObjectName objectName = (ObjectName) iterator.next();
- MBeanInfo mBeanInfo = connection.getMBeanInfo(objectName);
- MBeanAttributeInfo[] attributes = mBeanInfo.getAttributes();
- for (MBeanAttributeInfo attribute : attributes) {
- LOG.info(attribute.getName() + " " + connection.getAttribute(objectName, attribute.getName()));
- }
- }
- }
-
- private void traverseMBeanAttributesUsingMBeanServer(String type) throws JMException {
- Set objectNames = mBeanServer.queryNames(new ObjectName("net.sf.ehcache:type=" + type + ",*"), null);
- for (Iterator iterator = objectNames.iterator(); iterator.hasNext();) {
- ObjectName objectName = (ObjectName) iterator.next();
- MBeanInfo mBeanInfo = mBeanServer.getMBeanInfo(objectName);
- MBeanAttributeInfo[] attributes = mBeanInfo.getAttributes();
- for (MBeanAttributeInfo attribute : attributes) {
- LOG.info(attribute.getName() + " " + mBeanServer.getAttribute(objectName, attribute.getName()));
- }
- }
- }
-
-
-}
Index: rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/ToolkitNonStopConfigurationTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/ToolkitNonStopConfigurationTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/ToolkitNonStopConfigurationTest.java (revision 0)
@@ -1,51 +0,0 @@
-/**
- * Copyright Terracotta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
- * either express or implied. See the License for the specific language governing permissions and limitations under the
- * License.
- */
-
-package org.terracotta.modules.ehcache.store;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import net.sf.ehcache.config.NonstopConfiguration;
-import net.sf.ehcache.config.TimeoutBehaviorConfiguration;
-
-import org.junit.Test;
-import org.terracotta.toolkit.nonstop.NonStopConfigurationFields;
-
-/**
- * ToolkitNonStopConfigurationTest
- */
-public class ToolkitNonStopConfigurationTest {
-
- @Test
- public void testTimeoutBehaviorTypeConversion() {
- TimeoutBehaviorConfiguration timeoutBehaviorException = new TimeoutBehaviorConfiguration();
- timeoutBehaviorException.setType("exception");
- assertConfig(timeoutBehaviorException, NonStopConfigurationFields.NonStopReadTimeoutBehavior.EXCEPTION,
- NonStopConfigurationFields.NonStopWriteTimeoutBehavior.EXCEPTION);
-
- timeoutBehaviorException.setType("noop");
- assertConfig(timeoutBehaviorException, NonStopConfigurationFields.NonStopReadTimeoutBehavior.NO_OP, NonStopConfigurationFields.NonStopWriteTimeoutBehavior.NO_OP);
-
- timeoutBehaviorException.setType("localReads");
- assertConfig(timeoutBehaviorException, NonStopConfigurationFields.NonStopReadTimeoutBehavior.LOCAL_READS, NonStopConfigurationFields.NonStopWriteTimeoutBehavior.NO_OP);
-
- timeoutBehaviorException.setType("localReadsAndExceptionOnWrite");
- assertConfig(timeoutBehaviorException, NonStopConfigurationFields.NonStopReadTimeoutBehavior.LOCAL_READS, NonStopConfigurationFields.NonStopWriteTimeoutBehavior.EXCEPTION);
- }
-
- private void assertConfig(TimeoutBehaviorConfiguration timeoutBehaviorConfiguration,
- NonStopConfigurationFields.NonStopReadTimeoutBehavior readTimeoutBehavior,
- NonStopConfigurationFields.NonStopWriteTimeoutBehavior writeTimeoutBehavior) {
- NonstopConfiguration nonstopConfiguration = new NonstopConfiguration();
- ToolkitNonStopConfiguration nonStopConfiguration = new ToolkitNonStopConfiguration(nonstopConfiguration.timeoutBehavior(timeoutBehaviorConfiguration));
- assertThat(nonStopConfiguration.getReadOpNonStopTimeoutBehavior(), is(readTimeoutBehavior));
- assertThat(nonStopConfiguration.getWriteOpNonStopTimeoutBehavior(), is(writeTimeoutBehavior));
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMICacheManagerPeerListener.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMICacheManagerPeerListener.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMICacheManagerPeerListener.java (revision 0)
@@ -1,603 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.distribution;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.event.CacheEventListener;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.UnknownHostException;
-import java.rmi.Naming;
-import java.rmi.NotBoundException;
-import java.rmi.Remote;
-import java.rmi.RemoteException;
-import java.rmi.registry.LocateRegistry;
-import java.rmi.registry.Registry;
-import java.rmi.server.ExportException;
-import java.rmi.server.UnicastRemoteObject;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A cache server which exposes available cache operations remotely through RMI.
- *
- * It acts as a Decorator to a Cache. It holds an instance of cache, which is a local cache it talks to.
- *
- * This class could specify a security manager with code like:
- *
- * if (System.getSecurityManager() == null) {
- * System.setSecurityManager(new RMISecurityManager());
- * }
- *
- * Doing so would require the addition of grant statements in the java.policy file.
- *
- * If no security manager is specified no class loading, by RMI clients or servers, is allowed,
- * aside from what can be found in the local CLASSPATH. The classpath of each instance of this class should have
- * all required classes to enable distribution, so no remote classloading is required or desirable. Accordingly,
- * no security manager is set and there are no special JVM configuration requirements.
- *
- * This class opens a ServerSocket. The dispose method should be called for orderly closure of that socket. This class
- * has a shutdown hook which calls dispose() as a convenience feature for developers.
- *
- * @author Greg Luck
- * @version $Id: RMICacheManagerPeerListener.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class RMICacheManagerPeerListener implements CacheManagerPeerListener {
-
- private static final Logger LOG = LoggerFactory.getLogger(RMICacheManagerPeerListener.class.getName());
- private static final int MINIMUM_SENSIBLE_TIMEOUT = 200;
- private static final int NAMING_UNBIND_RETRY_INTERVAL = 400;
- private static final int NAMING_UNBIND_MAX_RETRIES = 10;
-
- /**
- * The cache peers. The value is an RMICachePeer.
- */
- protected final Map cachePeers = new HashMap();
-
- /**
- * status.
- */
- protected Status status;
-
- /**
- * The RMI listener port
- */
- protected Integer port;
-
- private Registry registry;
- private boolean registryCreated;
- private final String hostName;
-
- private CacheManager cacheManager;
- private Integer socketTimeoutMillis;
- private Integer remoteObjectPort;
-
- /**
- * Constructor with full arguments.
- *
- * @param hostName may be null, in which case the hostName will be looked up. Machines with multiple
- * interfaces should specify this if they do not want it to be the default NIC.
- * @param port a port in the range 1025 - 65536
- * @param remoteObjectPort the port number on which the remote objects bound in the registry receive calls.
- This defaults to a free port if not specified.
- * @param cacheManager the CacheManager this listener belongs to
- * @param socketTimeoutMillis TCP/IP Socket timeout when waiting on response
- */
- public RMICacheManagerPeerListener(String hostName, Integer port, Integer remoteObjectPort, CacheManager cacheManager,
- Integer socketTimeoutMillis) throws UnknownHostException {
-
- status = Status.STATUS_UNINITIALISED;
-
- if (hostName != null && hostName.length() != 0) {
- this.hostName = hostName;
- if (hostName.equals("localhost")) {
- LOG.warn("Explicitly setting the listener hostname to 'localhost' is not recommended. "
- + "It will only work if all CacheManager peers are on the same machine.");
- }
- } else {
- this.hostName = calculateHostAddress();
- }
- if (port == null || port.intValue() == 0) {
- assignFreePort(false);
- } else {
- this.port = port;
- }
-
- //by default is 0, which is ok.
- this.remoteObjectPort = remoteObjectPort;
-
- this.cacheManager = cacheManager;
- if (socketTimeoutMillis == null || socketTimeoutMillis.intValue() < MINIMUM_SENSIBLE_TIMEOUT) {
- throw new IllegalArgumentException("socketTimoutMillis must be a reasonable value greater than 200ms");
- }
- this.socketTimeoutMillis = socketTimeoutMillis;
-
- }
-
- /**
- * Assigns a free port to be the listener port.
- *
- * @throws IllegalStateException if the statis of the listener is not {@link net.sf.ehcache.Status#STATUS_UNINITIALISED}
- */
- protected void assignFreePort(boolean forced) throws IllegalStateException {
- if (status != Status.STATUS_UNINITIALISED) {
- throw new IllegalStateException("Cannot change the port of an already started listener.");
- }
- this.port = Integer.valueOf(this.getFreePort());
- if (forced) {
- LOG.warn("Resolving RMI port conflict by automatically using a free TCP/IP port to listen on: " + this.port);
- } else {
- LOG.debug("Automatically finding a free TCP/IP port to listen on: " + this.port);
- }
- }
-
-
- /**
- * Calculates the host address as the default NICs IP address
- *
- * @throws UnknownHostException
- */
- protected String calculateHostAddress() throws UnknownHostException {
- return InetAddress.getLocalHost().getHostAddress();
- }
-
-
- /**
- * Gets a free server socket port.
- *
- * @return a number in the range 1025 - 65536 that was free at the time this method was executed
- * @throws IllegalArgumentException
- */
- protected int getFreePort() throws IllegalArgumentException {
- ServerSocket serverSocket = null;
- try {
- serverSocket = new ServerSocket(0);
- return serverSocket.getLocalPort();
- } catch (IOException e) {
- throw new IllegalArgumentException("Could not acquire a free port number.");
- } finally {
- if (serverSocket != null && !serverSocket.isClosed()) {
- try {
- serverSocket.close();
- } catch (Exception e) {
- LOG.debug("Error closing ServerSocket: " + e.getMessage());
- }
- }
- }
- }
-
-
- /**
- * {@inheritDoc}
- */
- public void init() throws CacheException {
- if (!status.equals(Status.STATUS_UNINITIALISED)) {
- return;
- }
- RMICachePeer rmiCachePeer = null;
- try {
- startRegistry();
- int counter = 0;
- populateListOfRemoteCachePeers();
- synchronized (cachePeers) {
- for (Iterator iterator = cachePeers.values().iterator(); iterator.hasNext();) {
- rmiCachePeer = (RMICachePeer) iterator.next();
- bind(rmiCachePeer.getUrl(), rmiCachePeer);
- counter++;
- }
- }
- LOG.debug(counter + " RMICachePeers bound in registry for RMI listener");
- status = Status.STATUS_ALIVE;
- } catch (Exception e) {
- String url = null;
- if (rmiCachePeer != null) {
- url = rmiCachePeer.getUrl();
- }
-
- throw new CacheException("Problem starting listener for RMICachePeer "
- + url + ". Initial cause was " + e.getMessage(), e);
- }
- }
-
- /**
- * Bind a cache peer
- *
- * @param rmiCachePeer
- */
- protected void bind(String peerName, RMICachePeer rmiCachePeer) throws Exception {
- Naming.rebind(peerName, rmiCachePeer);
- }
-
- /**
- * Returns a list of bound objects.
- *
- * This should match the list of cachePeers i.e. they should always be bound
- *
- * @return a list of String representations of RMICachePeer objects
- */
- protected String[] listBoundRMICachePeers() throws CacheException {
- try {
- return registry.list();
- } catch (RemoteException e) {
- throw new CacheException("Unable to list cache peers " + e.getMessage());
- }
- }
-
- /**
- * Returns a reference to the remote object.
- *
- * @param name the name of the cache e.g. sampleCache1
- */
- protected Remote lookupPeer(String name) throws CacheException {
- try {
- return registry.lookup(name);
- } catch (Exception e) {
- throw new CacheException("Unable to lookup peer for replicated cache " + name + " "
- + e.getMessage());
- }
- }
-
- /**
- * Should be called on init because this is one of the last things that should happen on CacheManager startup.
- */
- protected void populateListOfRemoteCachePeers() throws RemoteException {
- String[] names = cacheManager.getCacheNames();
- for (int i = 0; i < names.length; i++) {
- String name = names[i];
- Ehcache cache = cacheManager.getEhcache(name);
- synchronized (cachePeers) {
- if (cachePeers.get(name) == null) {
- if (isDistributed(cache)) {
- RMICachePeer peer;
- if (cache.getCacheConfiguration().getTransactionalMode().isTransactional()) {
- peer = new TransactionalRMICachePeer(cache, hostName, port, remoteObjectPort, socketTimeoutMillis);
- } else {
- peer = new RMICachePeer(cache, hostName, port, remoteObjectPort, socketTimeoutMillis);
- }
- cachePeers.put(name, peer);
- }
- }
- }
- }
-
- }
-
- /**
- * Determine if the given cache is distributed.
- *
- * @param cache the cache to check
- * @return true if a CacheReplicator is found in the listeners
- */
- protected boolean isDistributed(Ehcache cache) {
- Set listeners = cache.getCacheEventNotificationService().getCacheEventListeners();
- for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
- CacheEventListener cacheEventListener = (CacheEventListener) iterator.next();
- if (cacheEventListener instanceof CacheReplicator) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Start the rmiregistry.
- *
- * The alternative is to use the rmiregistry binary, in which case:
- *
- * rmiregistry running
- * -Djava.rmi.server.codebase="file:///Users/gluck/work/ehcache/build/classes/ file:///Users/gluck/work/ehcache/lib/commons-logging-1.0.4.jar"
- *
- *
- * @throws RemoteException
- */
- protected void startRegistry() throws RemoteException {
- try {
- registry = LocateRegistry.getRegistry(port.intValue());
- try {
- registry.list();
- } catch (RemoteException e) {
- //may not be created. Let's create it.
- registry = LocateRegistry.createRegistry(port.intValue());
- registryCreated = true;
- }
- } catch (ExportException exception) {
- LOG.error("Exception starting RMI registry. Error was " + exception.getMessage(), exception);
- }
- }
-
- /**
- * Stop the rmiregistry if it was started by this class.
- *
- * @throws RemoteException
- */
- protected void stopRegistry() throws RemoteException {
- if (registryCreated) {
- // the unexportObject call must be done on the Registry object returned
- // by createRegistry not by getRegistry, a NoSuchObjectException is
- // thrown otherwise
- boolean success = UnicastRemoteObject.unexportObject(registry, true);
- if (success) {
- LOG.debug("rmiregistry unexported.");
- } else {
- LOG.warn("Could not unexport rmiregistry.");
- }
- }
- }
-
- /**
- * Stop the listener. It
- *
- * unbinds the objects from the registry
- * unexports Remote objects
- *
- */
- public void dispose() throws CacheException {
- if (!status.equals(Status.STATUS_ALIVE)) {
- return;
- }
- try {
- int counter = 0;
- synchronized (cachePeers) {
- for (Iterator iterator = cachePeers.values().iterator(); iterator.hasNext();) {
- RMICachePeer rmiCachePeer = (RMICachePeer) iterator.next();
- disposeRMICachePeer(rmiCachePeer);
- counter++;
- }
- stopRegistry();
- }
- LOG.debug(counter + " RMICachePeers unbound from registry in RMI listener");
- status = Status.STATUS_SHUTDOWN;
- } catch (Exception e) {
- throw new CacheException("Problem unbinding remote cache peers. Initial cause was " + e.getMessage(), e);
- }
- }
-
- /**
- * A template method to dispose an individual RMICachePeer. This consists of:
- *
- * Unbinding the peer from the naming service
- * Unexporting the peer
- *
- * Override to specialise behaviour
- *
- * @param rmiCachePeer the cache peer to dispose of
- * @throws Exception thrown if something goes wrong
- */
- protected void disposeRMICachePeer(RMICachePeer rmiCachePeer) throws Exception {
- unbind(rmiCachePeer);
- }
-
- /**
- * Unbinds an RMICachePeer and unexports it.
- *
- * We unbind from the registry first before unexporting.
- * Unbinding first removes the very small possibility of a client
- * getting the object from the registry while we are trying to unexport it.
- *
- * This method may take up to 4 seconds to complete, if we are having trouble
- * unexporting the peer.
- *
- * @param rmiCachePeer the bound and exported cache peer
- * @throws Exception
- */
- protected void unbind(RMICachePeer rmiCachePeer) throws Exception {
- String url = rmiCachePeer.getUrl();
- try {
- Naming.unbind(url);
- } catch (NotBoundException e) {
- LOG.warn(url + " not bound therefore not unbinding.");
- }
- // Try to gracefully unexport before forcing it.
- boolean unexported = UnicastRemoteObject.unexportObject(rmiCachePeer, false);
- for (int count = 1; (count < NAMING_UNBIND_MAX_RETRIES) && !unexported; count++) {
- try {
- Thread.sleep(NAMING_UNBIND_RETRY_INTERVAL);
- } catch (InterruptedException ie) {
- // break out of the unexportObject loop
- break;
- }
- unexported = UnicastRemoteObject.unexportObject(rmiCachePeer, false);
- }
-
- // If we still haven't been able to unexport, force the unexport
- // as a last resort.
- if (!unexported) {
- if (!UnicastRemoteObject.unexportObject(rmiCachePeer, true)) {
- LOG.warn("Unable to unexport rmiCachePeer: " + rmiCachePeer.getUrl() + ". Skipping.");
- }
- }
- }
-
- /**
- * All of the caches which are listening for remote changes.
- *
- * @return a list of RMICachePeer objects. The list if not live
- */
- public List getBoundCachePeers() {
- List cachePeerList = new ArrayList();
- synchronized (cachePeers) {
- for (Iterator iterator = cachePeers.values().iterator(); iterator.hasNext();) {
- RMICachePeer rmiCachePeer = (RMICachePeer) iterator.next();
- cachePeerList.add(rmiCachePeer);
- }
- }
- return cachePeerList;
- }
-
- /**
- * Returns the listener status.
- */
- public Status getStatus() {
- return status;
- }
-
- /**
- * A listener will normally have a resource that only one instance can use at the same time,
- * such as a port. This identifier is used to tell if it is unique and will not conflict with an
- * existing instance using the resource.
- *
- * @return a String identifier for the resource
- */
- public String getUniqueResourceIdentifier() {
- return "RMI listener port: " + port;
- }
-
- /**
- * If a conflict is detected in unique resource use, this method signals the listener to attempt
- * automatic resolution of the resource conflict.
- *
- * @throws IllegalStateException if the statis of the listener is not {@link net.sf.ehcache.Status#STATUS_UNINITIALISED}
- */
- public void attemptResolutionOfUniqueResourceConflict() throws IllegalStateException, CacheException {
- assignFreePort(true);
- }
-
- /**
- * The replication scheme this listener interacts with.
- * Each peer provider has a scheme name, which can be used by caches to specify for replication and bootstrap purposes.
- *
- * @return the well-known scheme name, which is determined by the replication provider author.
- */
- public String getScheme() {
- return "RMI";
- }
-
- /**
- * Called immediately after a cache has been added and activated.
- *
- * Note that the CacheManager calls this method from a synchronized method. Any attempt to call a synchronized
- * method on CacheManager from this method will cause a deadlock.
- *
- * Note that activation will also cause a CacheEventListener status change notification from
- * {@link net.sf.ehcache.Status#STATUS_UNINITIALISED} to {@link net.sf.ehcache.Status#STATUS_ALIVE}. Care should be
- * taken on processing that notification because:
- *
- * the cache will not yet be accessible from the CacheManager.
- * the addCaches methods whih cause this notification are synchronized on the CacheManager. An attempt to call
- * {@link net.sf.ehcache.CacheManager#getCache(String)} will cause a deadlock.
- *
- * The calling method will block until this method returns.
- *
- * Repopulates the list of cache peers and rebinds the list.
- * This method should be called if a cache is dynamically added
- *
- * @param cacheName the name of the Cache the operation relates to
- * @see net.sf.ehcache.event.CacheEventListener
- */
- public void notifyCacheAdded(String cacheName) throws CacheException {
-
-
- LOG.debug("Adding to RMI listener", cacheName);
-
- //Don't add if exists.
- synchronized (cachePeers) {
- if (cachePeers.get(cacheName) != null) {
- return;
- }
- }
-
- Ehcache cache = cacheManager.getEhcache(cacheName);
- if (isDistributed(cache)) {
- RMICachePeer rmiCachePeer = null;
- String url = null;
- try {
- if (cache.getCacheConfiguration().getTransactionalMode().isTransactional()) {
- rmiCachePeer = new TransactionalRMICachePeer(cache, hostName, port, remoteObjectPort, socketTimeoutMillis);
- } else {
- rmiCachePeer = new RMICachePeer(cache, hostName, port, remoteObjectPort, socketTimeoutMillis);
- }
- url = rmiCachePeer.getUrl();
- bind(url, rmiCachePeer);
- } catch (Exception e) {
- throw new CacheException("Problem starting listener for RMICachePeer "
- + url + ". Initial cause was " + e.getMessage(), e);
- }
-
- synchronized (cachePeers) {
- cachePeers.put(cacheName, rmiCachePeer);
- }
-
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug(cachePeers.size() + " RMICachePeers bound in registry for RMI listener");
- }
- }
-
- /**
- * Called immediately after a cache has been disposed and removed. The calling method will block until
- * this method returns.
- *
- * Note that the CacheManager calls this method from a synchronized method. Any attempt to call a synchronized
- * method on CacheManager from this method will cause a deadlock.
- *
- * Note that a {@link net.sf.ehcache.event.CacheEventListener} status changed will also be triggered. Any attempt from that notification
- * to access CacheManager will also result in a deadlock.
- *
- * @param cacheName the name of the Cache the operation relates to
- */
- public void notifyCacheRemoved(String cacheName) {
-
-
- LOG.debug("Removing from RMI listener", cacheName);
-
- //don't remove if already removed.
- synchronized (cachePeers) {
- if (cachePeers.get(cacheName) == null) {
- return;
- }
- }
-
- RMICachePeer rmiCachePeer;
- synchronized (cachePeers) {
- rmiCachePeer = (RMICachePeer) cachePeers.remove(cacheName);
- }
- String url = null;
- try {
- unbind(rmiCachePeer);
- } catch (Exception e) {
- throw new CacheException("Error removing Cache Peer "
- + url + " from listener. Message was: " + e.getMessage(), e);
- }
-
- if (LOG.isDebugEnabled()) {
- LOG.debug(cachePeers.size() + " RMICachePeers bound in registry for RMI listener");
- }
- }
-
-
- /**
- * Package local method for testing
- */
- void addCachePeer(String name, RMICachePeer peer) {
- synchronized (cachePeers) {
- cachePeers.put(name, peer);
-
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/terracotta/EventReplicationTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/terracotta/EventReplicationTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/terracotta/EventReplicationTest.java (revision 0)
@@ -1,44 +0,0 @@
-package net.sf.ehcache.terracotta;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration;
-import net.sf.ehcache.event.TerracottaCacheEventReplicationFactory;
-import org.junit.Test;
-
-import java.util.List;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.junit.Assert.assertThat;
-
-/**
- * @author Alex Snaps
- */
-public class EventReplicationTest {
-
- @Test
- public void testConfigFileHonorsClusteringOff() {
- final CacheManager cacheManager = new CacheManager(CacheManager.class.getResourceAsStream("/terracotta/ehcache-event-replication.xml"));
- try{
- final Cache cache = cacheManager.getCache("replication");
- assertThat(cache, notNullValue());
- final TerracottaConfiguration terracottaConfiguration = cache.getCacheConfiguration().getTerracottaConfiguration();
- assertThat(terracottaConfiguration, notNullValue());
- assertThat(terracottaConfiguration.isClustered(), is(false));
- final List eventListenerConfigurations = cache.getCacheConfiguration().getCacheEventListenerConfigurations();
- assertThat(eventListenerConfigurations, notNullValue());
- assertThat(eventListenerConfigurations.size(), is(1));
- assertThat(((CacheConfiguration.CacheEventListenerFactoryConfiguration)eventListenerConfigurations.get(0)).getFullyQualifiedClassPath(),
- equalTo(TerracottaCacheEventReplicationFactory.class.getName()));
- cache.put(new Element("key", "value"));
- assertThat((String) cache.get("key").getValue(), equalTo("value"));
-
- } finally {
- cacheManager.shutdown();
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/DummyManagementServerImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/DummyManagementServerImpl.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/DummyManagementServerImpl.java (revision 0)
@@ -1,60 +0,0 @@
-package net.sf.ehcache.management;
-
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.config.ManagementRESTServiceConfiguration;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * @author Ludovic Orban
- */
-public class DummyManagementServerImpl implements ManagementServer {
-
- public static enum Status {
- STARTED, STOPPED
- }
-
- public Status status = Status.STOPPED;
- public final static Map registeredCacheManagers = new HashMap();
-
- public DummyManagementServerImpl() {
- }
-
- @Override
- public void start() {
- status = Status.STARTED;
- }
-
- @Override
- public void stop() {
- status = Status.STOPPED;
- }
-
- @Override
- public void register(CacheManager managedResource) {
- registeredCacheManagers.put(managedResource.getName(), managedResource);
- }
-
- @Override
- public void unregister(CacheManager managedResource) {
- registeredCacheManagers.remove(managedResource.getName());
- }
-
- @Override
- public boolean hasRegistered() {
- return !registeredCacheManagers.isEmpty();
- }
-
- @Override
- public void initialize(ManagementRESTServiceConfiguration configuration) {
- }
-
- @Override
- public void registerClusterRemoteEndpoint(String clientUUID) {
- }
-
- @Override
- public void unregisterClusterRemoteEndpoint(String clientUUID) {
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/distribution/RMICacheManagerPeerIT.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/distribution/RMICacheManagerPeerIT.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/distribution/RMICacheManagerPeerIT.java (revision 0)
@@ -1,228 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.distribution;
-
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.util.RetryAssert;
-
-import org.hamcrest.collection.IsEmptyCollection;
-import org.junit.After;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import org.junit.Test;
-
-import java.net.SocketTimeoutException;
-import java.rmi.RemoteException;
-import java.rmi.UnmarshalException;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.distribution.RmiEventMessage.RmiEventType;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Unit tests for RMICachePeer
- *
- * Note these tests need a live network interface running in multicast mode to work
- *
- * @author Greg Luck
- * @version $Id: RMICacheManagerPeerIT.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class RMICacheManagerPeerIT extends AbstractRMITest {
-
- private static final Logger LOG = LoggerFactory.getLogger(RMICacheManagerPeerIT.class.getName());
-
- @After
- public void tearDown() throws InterruptedException {
- RetryAssert.assertBy(30, TimeUnit.SECONDS, new Callable>() {
- public Set call() throws Exception {
- return getActiveReplicationThreads();
- }
- }, IsEmptyCollection.empty());
- }
-
-
- /**
- * Can we create the peer using remote port of 0?
- */
- @Test
- public void testCreatePeerWithAutomaticRemotePort() throws RemoteException {
- Cache cache = new Cache(new CacheConfiguration().name("test").maxEntriesLocalHeap(10));
- for (int i = 0; i < 10; i++) {
- new RMICachePeer(cache, "localhost", 5010, Integer.valueOf(0), Integer.valueOf(2000));
- }
- }
-
-
- /**
- * Can we create the peer using a specified free remote port of 45000
- */
- @Test
- public void testCreatePeerWithSpecificRemotePort() throws RemoteException {
- Cache cache = new Cache(new CacheConfiguration().name("test").maxEntriesLocalHeap(10));
- for (int i = 0; i < 10; i++) {
- new RMICachePeer(cache, "localhost", 5010, Integer.valueOf(45000), Integer.valueOf(2000));
- }
- }
-
-
- /**
- * See if socket.setSoTimeout(socketTimeoutMillis) works. Should throw a SocketTimeoutException
- *
- * @throws RemoteException
- */
- @Test
- public void testFailsIfTimeoutExceeded() throws Exception {
- CacheManager manager = new CacheManager(new Configuration().name("testFailsIfTimeoutExceeded"));
- try {
- Cache cache = new Cache(new CacheConfiguration().name("test").maxEntriesLocalHeap(10));
- RMICacheManagerPeerListener peerListener = new RMICacheManagerPeerListener("localhost", 5010, Integer.valueOf(0), manager, Integer.valueOf(2000));
- try {
- RMICachePeer rmiCachePeer = new SlowRMICachePeer(cache, "localhost", 5010, Integer.valueOf(1000), 2000);
- peerListener.addCachePeer(cache.getName(), rmiCachePeer);
- peerListener.init();
-
-
- try {
- CachePeer cachePeer = new ManualRMICacheManagerPeerProvider().lookupRemoteCachePeer(rmiCachePeer.getUrl());
- cachePeer.put(new Element("1", new Date()));
- fail();
- } catch (UnmarshalException e) {
- assertEquals(SocketTimeoutException.class, e.getCause().getClass());
- }
- } finally {
- peerListener.dispose();
- }
- } finally {
- manager.shutdown();
- }
- }
-
- /**
- * See if socket.setSoTimeout(socketTimeoutMillis) works.
- * Should not fail because the put takes less than the timeout.
- *
- * @throws RemoteException
- */
- @Test
- public void testWorksIfTimeoutNotExceeded() throws Exception {
- CacheManager manager = new CacheManager(new Configuration().name("testWorksIfTimeoutNotExceeded"));
- try {
- Cache cache = new Cache(new CacheConfiguration().name("test").maxEntriesLocalHeap(10));
- RMICacheManagerPeerListener peerListener = new RMICacheManagerPeerListener("localhost", 5010, Integer.valueOf(0), manager, Integer.valueOf(2000));
- try {
- RMICachePeer rmiCachePeer = new SlowRMICachePeer(cache, "localhost", 5010, Integer.valueOf(2000), 0);
-
- peerListener.addCachePeer(cache.getName(), rmiCachePeer);
- peerListener.init();
-
- CachePeer cachePeer = new ManualRMICacheManagerPeerProvider().lookupRemoteCachePeer(rmiCachePeer.getUrl());
- cachePeer.put(new Element("1", new Date()));
- } finally {
- peerListener.dispose();
- }
- } finally {
- manager.shutdown();
- }
- }
-
- /**
- * Test send.
- *
- * This is a unit test because it was throwing AbstractMethodError if a method has changed signature,
- * or NoSuchMethodError is a new one is added. The problem is that rmic needs
- * to recompile the stub after any changes are made to the CachePeer source, something done by ant
- * compile but not by the IDE.
- */
- @Test
- public void testSend() throws Exception {
- CacheManager manager = new CacheManager(new Configuration().name("testWorksIfTimeoutNotExceeded"));
- try {
- Cache cache = new Cache(new CacheConfiguration().name("test").maxEntriesLocalHeap(10));
- RMICachePeer rmiCachePeer = new RMICachePeer(cache, "localhost", 5010, Integer.valueOf(0), Integer.valueOf(2100));
- RMICacheManagerPeerListener peerListener = new RMICacheManagerPeerListener("localhost", 5010, Integer.valueOf(0), manager, Integer.valueOf(2000));
- manager.addCache(cache);
-
- peerListener.addCachePeer(cache.getName(), rmiCachePeer);
- peerListener.init();
-
- CachePeer cachePeer = new ManualRMICacheManagerPeerProvider().lookupRemoteCachePeer(rmiCachePeer.getUrl());
- Element element = new Element("1", new Date());
- RmiEventMessage eventMessage = new RmiEventMessage(null, RmiEventType.PUT, null, element);
- List eventMessages = new ArrayList();
- eventMessages.add(eventMessage);
- cachePeer.send(eventMessages);
- } finally {
- manager.shutdown();
- }
- }
-
-
- /**
- * RMICachePeer that breaks in lots of interesting ways.
- */
- class SlowRMICachePeer extends RMICachePeer {
-
- private final long sleepTime;
-
- /**
- * Constructor
- *
- * @param cache
- * @param hostName
- * @param port
- * @param socketTimeoutMillis
- * @throws RemoteException
- */
- public SlowRMICachePeer(Ehcache cache, String hostName, Integer port, Integer socketTimeoutMillis, int sleepTime)
- throws RemoteException {
- super(cache, hostName, port, Integer.valueOf(0), socketTimeoutMillis);
- this.sleepTime = sleepTime;
- }
-
- /**
- * Puts an Element into the underlying cache without notifying listeners or updating statistics.
- *
- * @param element
- * @throws java.rmi.RemoteException
- * @throws IllegalArgumentException
- * @throws IllegalStateException
- */
- @Override
- public void put(Element element) throws RemoteException, IllegalArgumentException, IllegalStateException {
- try {
- Thread.sleep(sleepTime);
- } catch (InterruptedException exception) {
- LOG.error(exception.getMessage(), exception);
- }
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/blocking/UpdatingCacheEntryFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/blocking/UpdatingCacheEntryFactory.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/constructs/blocking/UpdatingCacheEntryFactory.java (revision 0)
@@ -1,50 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.constructs.blocking;
-
-/**
- * A CacheEntryFactory with one additional method, updateEntryValue((Serializable key, Serializable value)
- * which allows the cache entry to updated rather than replaced. This has the following
- * potential benefits:
- *
- * Where only part of the value needs to be updated, it is quicker
- * Memory use can be smoothed, which is useful for particularly large objects which are being
- * refreshed contrinuously
- *
- *
- * @author Greg Luck
- * @version $Id: UpdatingCacheEntryFactory.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public interface UpdatingCacheEntryFactory extends CacheEntryFactory {
- /**
- * Perform an incremental update of data within a CacheEntry.
- * Based on identification of dirty values within a CacheEntry
- * Insert Update or Delete those entries based on the existing value.
- *
- * This method does not return a modified value, because it modifies the value passed into it, relying
- * on the pass by reference feature of Java.
- *
- * Implementations of this method must be thread safe.
- *
- * @param key the cache Key
- * @param value a value copied from the value that belonged to the Element in the cache. Value must be mutable
- * @throws Exception
- */
- void updateEntryValue(Object key, Object value) throws Exception;
-
-}
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/store/PressuredStore.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/store/PressuredStore.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/store/PressuredStore.java (revision 0)
@@ -1,32 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.store;
-
-import java.util.concurrent.Callable;
-
-/**
- * A store that can be under pressure... you wouldn't want your store to be under pressure, now would you ?
- *
- * @author Alex Snaps
- */
-public interface PressuredStore {
-
- /**
- * Registers an emergency valve
- * @param valve
- */
- void registerEmergencyValve(Callable valve);
-}
Index: rctags/ehcache-2.10.8.0.7/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/services/CacheStatisticSamplesResourceServiceImplV2.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/services/CacheStatisticSamplesResourceServiceImplV2.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/services/CacheStatisticSamplesResourceServiceImplV2.java (revision 0)
@@ -1,74 +0,0 @@
-/*
- * All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright
- * notice. All rights reserved.
- */
-package net.sf.ehcache.management.resource.services;
-
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import net.sf.ehcache.management.service.EntityResourceFactoryV2;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.terracotta.management.ServiceExecutionException;
-import org.terracotta.management.ServiceLocator;
-import org.terracotta.management.resource.ResponseEntityV2;
-import org.terracotta.management.resource.exceptions.ResourceRuntimeException;
-import org.terracotta.management.resource.services.validator.RequestValidator;
-
-/**
- * @author brandony
- */
-@Path("/v2/agents/cacheManagers/caches/statistics/samples")
-public final class CacheStatisticSamplesResourceServiceImplV2 {
- private static final Logger LOG = LoggerFactory.getLogger(CacheStatisticSamplesResourceServiceImplV2.class);
- private final EntityResourceFactoryV2 entityResourceFactory;
-
- private final RequestValidator validator;
-
- public CacheStatisticSamplesResourceServiceImplV2() {
- this.entityResourceFactory = ServiceLocator.locate(EntityResourceFactoryV2.class);
- this.validator = ServiceLocator.locate(RequestValidator.class);
- }
-
- /**
- *
- * @param info
- * @return
- */
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public ResponseEntityV2 getCacheStatisticSamples(@Context UriInfo info) {
- LOG.debug(String.format("Invoking CacheStatisticSamplesResourceServiceImpl.getCacheStatisticSamples: %s",
- info.getRequestUri()));
-
- validator.validateSafe(info);
-
- String cacheManagerNames = info.getPathSegments().get(2).getMatrixParameters().getFirst("names");
- Set cmNames = cacheManagerNames == null ? null : new HashSet(
- Arrays.asList(cacheManagerNames.split(",")));
-
- String cacheNames = info.getPathSegments().get(3).getMatrixParameters().getFirst("names");
- Set cNames = cacheNames == null ? null : new HashSet(Arrays.asList(cacheNames.split(",")));
-
- String sampleNames = info.getPathSegments().get(5).getMatrixParameters().getFirst("names");
- Set sNames = sampleNames == null ? null : new HashSet(Arrays.asList(sampleNames.split(",")));
-
- try {
- return entityResourceFactory.createCacheStatisticSampleEntity(cmNames, cNames, sNames);
- } catch (ServiceExecutionException e) {
- throw new ResourceRuntimeException("Failed to get cache statistics sample", e,
- Response.Status.BAD_REQUEST.getStatusCode());
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/hibernate/EhcacheJtaTransactionManagerLookup.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/hibernate/EhcacheJtaTransactionManagerLookup.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/hibernate/EhcacheJtaTransactionManagerLookup.java (revision 0)
@@ -1,60 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.hibernate;
-
-import net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup;
-import org.hibernate.HibernateException;
-import org.hibernate.transaction.TransactionManagerLookup;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-import java.util.Properties;
-
-/**
- * Hibernate TransactionManagerLookup which also is a Ehcache transaction manager lookup.
- *
- * @author Ludovic Orban
- */
-public class EhcacheJtaTransactionManagerLookup extends DefaultTransactionManagerLookup implements TransactionManagerLookup {
-
- /**
- * Construct a new transaction manager lookup.
- */
- public EhcacheJtaTransactionManagerLookup() {
- super();
- }
-
- /**
- * {@inheritDoc}
- */
- public TransactionManager getTransactionManager(Properties properties) throws HibernateException {
- return getTransactionManager();
- }
-
- /**
- * {@inheritDoc}
- */
- public String getUserTransactionName() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getTransactionIdentifier(Transaction transaction) {
- return transaction;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/writer/writebehind/WriteBehindQueueTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/writer/writebehind/WriteBehindQueueTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/writer/writebehind/WriteBehindQueueTest.java (revision 0)
@@ -1,111 +0,0 @@
-package net.sf.ehcache.writer.writebehind;
-
-import net.sf.ehcache.CacheEntry;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.CacheWriterConfiguration;
-import net.sf.ehcache.writer.CacheWriter;
-import net.sf.ehcache.writer.writebehind.operations.SingleOperationType;
-
-import org.junit.Test;
-
-import java.util.Collection;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-import static org.junit.Assert.*;
-
-/**
- * WriteBehindQueueTest
- */
-public class WriteBehindQueueTest {
- @Test
- public void testLastWriteBlockedOnFullQueue() throws InterruptedException {
- CacheConfiguration cacheConfiguration = new CacheConfiguration();
- CacheWriterConfiguration writerConfiguration = cacheConfiguration.getCacheWriterConfiguration();
- writerConfiguration.setWriteBehindMaxQueueSize(1);
- writerConfiguration.setMinWriteDelay(0);
- final WriteBehindQueue writeBehindQueue = new WriteBehindQueue(cacheConfiguration);
-
- writeBehindQueue.start(new BlockingWriter());
-
- writeBehindQueue.write(new Element("a", "a"));
-
- new Thread(new Runnable() {
- @Override
- public void run() {
- writeBehindQueue.write(new Element("b", "b"));
- }
- }).start();
-
- new Thread(new Runnable() {
- @Override
- public void run() {
- writeBehindQueue.write(new Element("c", "c"));
- }
- }).start();
-
- BlockingWriter.firstLatch.countDown();
-
- boolean await = BlockingWriter.secondLatch.await(10, TimeUnit.SECONDS);
- if (!await) {
- fail("write still stuck after 10 seconds");
- }
- }
-
- private static class BlockingWriter implements CacheWriter {
-
- static CountDownLatch firstLatch = new CountDownLatch(1);
- static CountDownLatch secondLatch = new CountDownLatch(2);
-
- @Override
- public CacheWriter clone(Ehcache cache) throws CloneNotSupportedException {
- throw new UnsupportedOperationException("TODO Implement me!");
- }
-
- @Override
- public void init() {
- throw new UnsupportedOperationException("TODO Implement me!");
- }
-
- @Override
- public void dispose() throws CacheException {
- throw new UnsupportedOperationException("TODO Implement me!");
- }
-
- @Override
- public void write(Element element) throws CacheException {
- if (element.getObjectKey().equals("a")) {
- try {
- firstLatch.await();
- } catch (InterruptedException e) {
- throw new CacheException(e);
- }
- } else {
- secondLatch.countDown();
- }
- }
-
- @Override
- public void writeAll(Collection elements) throws CacheException {
- throw new UnsupportedOperationException("TODO Implement me!");
- }
-
- @Override
- public void delete(CacheEntry entry) throws CacheException {
- throw new UnsupportedOperationException("TODO Implement me!");
- }
-
- @Override
- public void deleteAll(Collection entries) throws CacheException {
- throw new UnsupportedOperationException("TODO Implement me!");
- }
-
- @Override
- public void throwAway(Element element, SingleOperationType operationType, RuntimeException e) {
- throw new UnsupportedOperationException("TODO Implement me!");
- }
- }
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/sampled/MBeanRegistrationProviderTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/sampled/MBeanRegistrationProviderTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/management/sampled/MBeanRegistrationProviderTest.java (revision 0)
@@ -1,221 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.management.sampled;
-
-import static org.junit.Assert.assertEquals;
-
-import java.io.File;
-import java.util.Set;
-
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-
-import net.sf.ehcache.AbstractCacheTest;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Tests for testing the mbean registration provider
- *
- * @author Abhishek Sanoujam
- * @version $Id: MBeanRegistrationProviderTest.java 1178 2009-09-23 23:50:15Z
- * asingh
- * $
- */
-public class MBeanRegistrationProviderTest extends AbstractCacheTest {
-
- private static final Logger LOG = LoggerFactory.getLogger(MBeanRegistrationProviderTest.class.getName());
-
- private MBeanServer mbeanServer;
-
- private CacheManager cacheManager;
-
- @Override
- @Before
- public void setUp() throws Exception {
- super.setUp();
- mbeanServer = createMBeanServer();
- cleanUpExistingMbeans();
- }
-
- @Override
- @After
- public void tearDown() throws Exception {
- if (cacheManager != null) {
- cacheManager.shutdown();
- }
- super.tearDown();
- assertEquals(0, mbeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null).size());
- cacheManager = null;
- cleanUpExistingMbeans();
- }
-
- private void cleanUpExistingMbeans() throws Exception {
- Set queryNames = mbeanServer.queryNames(new ObjectName("net.sf.ehcache:*"), null);
- for (ObjectName name : queryNames) {
- mbeanServer.unregisterMBean(name);
- }
- }
-
- @Test
- public void testMonitoringOn() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-on.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- cacheManager = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(3);
- assertCacheManagerMBeansRegistered("cacheManagerOn", 1);
- }
-
- private void assertSampledMBeansGroupRegistered(final int size) throws Exception {
- Set queryNames = mbeanServer.queryNames(new ObjectName(SampledEhcacheMBeans.GROUP_ID + ":*"), null);
- assertEquals(size, queryNames.size());
- }
-
- private void assertCacheManagerMBeansRegistered(String cacheManagerName, int size) throws Exception {
- Set queryNames = mbeanServer.queryNames(SampledEhcacheMBeans.getCacheManagerObjectName(null, cacheManagerName), null);
- assertEquals(size, queryNames.size());
- }
-
- private void assertCacheManagerMBeansRegistered(int size) throws Exception {
- Set queryNames = mbeanServer.queryNames(SampledEhcacheMBeans.getQueryCacheManagersObjectName(null), null);
- assertEquals(size, queryNames.size());
- }
-
- @Test
- public void testMonitoringOff() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-off.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- cacheManager = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(0);
- assertCacheManagerMBeansRegistered("cacheManagerOff", 0);
- }
-
- @Test
- public void testMonitoringAutodetect() throws Exception {
- System.setProperty("tc.active", "false");
- doTestMonitoringAutodetect(false, "tc-not-active");
-
- System.setProperty("tc.active", "true");
- doTestMonitoringAutodetect(true, "tc-active");
-
- // reset property
- System.setProperty("tc.active", "false");
- }
-
- public void doTestMonitoringAutodetect(boolean dsoActive, String name) throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-autodetect.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file).name(name);
- CacheManager localCacheManager = new CacheManager(configuration);
- try {
- if (dsoActive) {
- assertSampledMBeansGroupRegistered(3);
- assertCacheManagerMBeansRegistered("cacheManagerAutoDetect", 0);
- } else {
- assertSampledMBeansGroupRegistered(0);
- assertCacheManagerMBeansRegistered("cacheManagerAutoDetect", 0);
- }
- } finally {
- localCacheManager.shutdown();
- }
- }
-
- @Test
- public void testMultipleCacheManagerDifferentNames() throws Exception {
- System.setProperty("tc.active", "true");
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-autodetect.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- cacheManager = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(3);
- assertCacheManagerMBeansRegistered("cacheManagerAutoDetect", 1);
-
- file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-on.xml");
- configuration = ConfigurationFactory.parseConfiguration(file);
- CacheManager otherCacheManager = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(3 + 3);
- assertCacheManagerMBeansRegistered(2);
-
- cacheManager.shutdown();
- otherCacheManager.shutdown();
- // reset property
- System.setProperty("tc.active", "false");
- }
-
- @Test
- public void testMultipleCacheManagerSameNames() throws Exception {
- int count = 8;
- CacheManager[] managers = new CacheManager[count];
- for (int i = 0; i < count; i++) {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-on.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file).name("cm-" + i);
- managers[i] = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(3 * (i + 1));
- assertCacheManagerMBeansRegistered(i + 1);
- }
-
- CacheManager[] duplicates = new CacheManager[count];
- for (int i = 0; i < count; i++) {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-on.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file).name("cm-dup-" + i);
-
- duplicates[i] = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(3 * (i + 1) + count * 3);
- assertCacheManagerMBeansRegistered((i + 1) + count);
- }
- // shutting down the cacheManager should clean up the mbeans
- for (CacheManager mgr : managers) {
- mgr.shutdown();
- }
- for (CacheManager mgr : duplicates) {
- mgr.shutdown();
- }
- assertSampledMBeansGroupRegistered(0);
- assertCacheManagerMBeansRegistered(0);
- }
-
- @Test
- public void testInvalidCacheNames() throws Exception {
- System.setProperty("tc.active", "true");
-
- File file = new File(TEST_CONFIG_DIR + "ehcache-invalid-cache-names.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- cacheManager = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(4);
- assertCacheManagerMBeansRegistered("invalidCacheNames", 1);
-
- System.setProperty("tc.active", "false");
- }
-
- @Test
- public void testInvalidCacheManagerName() throws Exception {
- System.setProperty("tc.active", "true");
-
- File file = new File(TEST_CONFIG_DIR + "ehcache-invalid-cache-manager-name.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- cacheManager = new CacheManager(configuration);
- assertSampledMBeansGroupRegistered(1);
- assertCacheManagerMBeansRegistered("invalid:CacheManagerName", 1);
-
- System.setProperty("tc.active", "false");
- }
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/Valueable.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/Valueable.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/Valueable.java (revision 0)
@@ -1,11 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests;
-
-import java.io.Serializable;
-
-public interface Valueable extends Serializable {
- int value();
- void setValue(int value);
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapClearExpressTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapClearExpressTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapClearExpressTest.java (revision 0)
@@ -1,14 +0,0 @@
-package org.terracotta.ehcache.tests.servermap;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-
-import com.tc.test.config.model.TestConfig;
-
-public class ServerMapClearExpressTest extends AbstractCacheTestBase {
-
- public ServerMapClearExpressTest(TestConfig testConfig) {
- super("/servermap/servermap-clear-test.xml", testConfig, ServerMapClearExpressTestClient1.class,
- ServerMapClearExpressTestClient2.class);
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-nolisteners.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-nolisteners.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-nolisteners.xml (revision 0)
@@ -1,182 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/NullSelector.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/NullSelector.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/NullSelector.java (revision 0)
@@ -1,41 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.manager.selector;
-
-import javax.transaction.TransactionManager;
-
-/**
- * A selector that always returns a null transaction manager
- *
- * @author Ludovic Orban
- */
-public class NullSelector extends Selector {
-
- /**
- * Constructor
- */
- public NullSelector() {
- super("null");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- protected TransactionManager doLookup() {
- return null;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/loader/ExceptionThrowingLoader.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/loader/ExceptionThrowingLoader.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/loader/ExceptionThrowingLoader.java (revision 0)
@@ -1,117 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.loader;
-
-
-import net.sf.ehcache.CacheException;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Random;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- * A cache loader that throws exceptions when used
- *
- * Each load has a random delay to introduce some nice threading entropy.
- *
- * @author Greg Luck
- * @version $Id: ExceptionThrowingLoader.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class ExceptionThrowingLoader extends CountingCacheLoader {
-
- private static final Logger LOG = LoggerFactory.getLogger(ExceptionThrowingLoader.class.getName());
-
- private int loadCounter;
- private int loadAllCounter;
- private Random random = new Random();
- private String name = "ExceptionThrowingLoader";
-
- /**
- * loads an object. Application writers should implement this
- * method to customize the loading of cache object. This method is called
- * by the caching service when the requested object is not in the cache.
- *
- *
- * @param key the key identifying the object being loaded
- * @return The object that is to be stored in the cache.
- */
- public Object load(Object key) throws CacheException {
- try {
- Thread.sleep(random.nextInt(3) + 1);
- } catch (InterruptedException e) {
- LOG.error("Interrupted");
- }
- throw new CacheException("Some exception with key " + key);
- }
-
- /**
- * loads multiple object. Application writers should implement this
- * method to customize the loading of cache object. This method is called
- * by the caching service when the requested object is not in the cache.
- *
- *
- * @param keys a Collection of keys identifying the objects to be loaded
- * @return A Map of objects that are to be stored in the cache.
- */
-
- public Map loadAll(Collection keys) throws CacheException {
- Map map = new HashMap(keys.size());
- for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
- Object key = iterator.next();
- try {
- Thread.sleep(random.nextInt(4));
- } catch (InterruptedException e) {
- LOG.error("Interrupted");
- }
- map.put(key, Integer.valueOf(loadAllCounter++));
- throw new CacheException("Some exception with key " + key);
- }
-
- return map;
- }
-
-
- /**
- * Load using both a key and an argument.
- *
- * JCache will use the load(key) method where the argument is null.
- */
- public Object load(Object key, Object argument) throws CacheException {
- try {
- Thread.sleep(random.nextInt(3) + 1);
- } catch (InterruptedException e) {
- LOG.error("Interrupted");
- }
- throw new CacheException("Some exception with key " + key);
- }
-
- /**
- * Load using both a key and an argument.
- *
- * JCache will use the loadAll(key) method where the argument is null.
- */
- public Map loadAll(Collection keys, Object argument) throws CacheException {
- throw new CacheException("Some exception with key " + keys.toArray()[0]);
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/DistributionDeadBucketWriteBehindTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/DistributionDeadBucketWriteBehindTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/DistributionDeadBucketWriteBehindTest.java (revision 0)
@@ -1,98 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.writebehind;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.modules.ehcache.async.AsyncCoordinatorImpl;
-
-import com.tc.l2.L2DebugLogging.LogLevel;
-import com.tc.test.config.model.TestConfig;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class DistributionDeadBucketWriteBehindTest extends AbstractCacheTestBase {
- public static final String DISTRIBUTION_BARRIER_NAME = "DistributionDeadBucketWriteBehindTestBarrier";
- public static final int NODE_COUNT = 4;
- private int totalWriteCount = 0;
- private int totalDeleteCount = 0;
-
- public DistributionDeadBucketWriteBehindTest(TestConfig testConfig) {
- super("basic-writebehind-test.xml", testConfig);
- disableTest();
- testConfig.getClientConfig().setClientClasses(DeadBucketWriteBehindClient.class, NODE_COUNT);
- testConfig.getClientConfig().setParallelClients(true);
- configureTCLogging(AsyncCoordinatorImpl.class.getName(), LogLevel.DEBUG);
- }
-
- @Override
- protected void postClientVerification() {
- System.out.println("[Clients processed a total of " + totalWriteCount + " writes]");
- if (totalWriteCount < 2000 || totalWriteCount > 2003) { throw new AssertionError(totalWriteCount); }
-
- System.out.println("[Clients processed a total of " + totalDeleteCount + " deletes]");
- if (totalDeleteCount < 200 || totalDeleteCount > 203) { throw new AssertionError(totalDeleteCount); }
- }
-
- @Override
- protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable {
- super.evaluateClientOutput(clientName, exitCode, output);
-
- FileReader fr = null;
- BufferedReader reader = null;
- StringBuilder strBuilder = new StringBuilder();
- try {
- fr = new FileReader(output);
- reader = new BufferedReader(fr);
- String st = "";
- while ((st = reader.readLine()) != null) {
- strBuilder.append(st);
- }
- } catch (Exception e) {
- throw new AssertionError(e);
- } finally {
- try {
- fr.close();
- reader.close();
- } catch (Exception e) {
- //
- }
- }
-
- // Detect the number of writes that have happened
- int writeCount = detectLargestCount(strBuilder.toString(),
- Pattern.compile("\\[WriteBehindCacheWriter written (\\d+) for " + clientName
- + "\\]"));
- totalWriteCount += writeCount;
- System.out.println("[" + clientName + " processed " + writeCount + " writes]");
- if (writeCount < 1 || writeCount > 1001) { throw new AssertionError(
- "dead nodes distribution is not uniform writeCount "
- + writeCount); }
-
- // Detect the number of deletes that have happened
- int deleteCount = detectLargestCount(strBuilder.toString(),
- Pattern.compile("\\[WriteBehindCacheWriter deleted (\\d+) for " + clientName
- + "\\]"));
- totalDeleteCount += deleteCount;
- System.out.println("[" + clientName + " processed " + deleteCount + " deletes]");
- if (deleteCount < 1 || deleteCount > 101) { throw new AssertionError(
- "dead nodes distribution is not uniform deleteCount "
- + deleteCount); }
- }
-
- private int detectLargestCount(String clientOutput, Pattern pattern) {
- Matcher matcher = pattern.matcher(clientOutput);
- int count = 0;
- while (matcher.find()) {
- int parsedCount = Integer.parseInt(matcher.group(1));
- if (parsedCount > count) {
- count = parsedCount;
- }
- }
- return count;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/event/CacheManagerEventListenerFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/event/CacheManagerEventListenerFactory.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/event/CacheManagerEventListenerFactory.java (revision 0)
@@ -1,45 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.event;
-
-import net.sf.ehcache.CacheManager;
-
-import java.util.Properties;
-
-/**
- * An abstract factory for creating {@link CacheManagerEventListener}s. Implementers should
- * provide their own concrete factory extending this factory. It can then be configured in
- * ehcache.xml
- *
- * @author Greg Luck
- * @version $Id: CacheManagerEventListenerFactory.java 5594 2012-05-07 16:04:31Z cdennis $
- * @see "http://ehcache.org/documentation/apis/cachemanager-event-listeners"
- */
-public abstract class CacheManagerEventListenerFactory {
-
- /**
- * Create a CacheEventListener
- *
- *
- * @param cacheManager the cache manager
- * @param properties implementation specific properties. These are configured as comma
- * separated name value pairs in ehcache.xml. Properties may be null
- * @return a constructed CacheManagerEventListener
- */
- public abstract CacheManagerEventListener
- createCacheManagerEventListener(CacheManager cacheManager, Properties properties);
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/StandardPassThroughStatistic.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/StandardPassThroughStatistic.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/StandardPassThroughStatistic.java (revision 0)
@@ -1,125 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.statistics.extended;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import net.sf.ehcache.Ehcache;
-import org.terracotta.context.query.Query;
-
-import static net.sf.ehcache.statistics.extended.EhcacheQueryBuilder.cache;
-import static net.sf.ehcache.statistics.extended.EhcacheQueryBuilder.descendants;
-
-/**
- *
- * @author cdennis
- */
-public enum StandardPassThroughStatistic {
-
- /** cache size */
- CACHE_SIZE(cache(), Integer.TYPE, null, "size", "cache"),
-
- /** local heap size in entries */
- LOCAL_HEAP_SIZE(cache().children().exclude(Ehcache.class).add(descendants()), Integer.TYPE, 0, "size", "local-heap"),
-
- /** local hea size in bytes*/
- LOCAL_HEAP_SIZE_BYTES(cache().children().exclude(Ehcache.class).add(descendants()), Long.TYPE, 0L, "size-in-bytes", "local-heap"),
-
- /** local off heap size in entry count */
- LOCAL_OFFHEAP_SIZE(cache().children().exclude(Ehcache.class).add(descendants()), Long.TYPE, 0L, "size", "local-offheap"),
-
- /** local offheap size in bytes */
- LOCAL_OFFHEAP_SIZE_BYTES(cache().children().exclude(Ehcache.class).add(descendants()), Long.TYPE, 0L, "size-in-bytes", "local-offheap"),
-
- /** local disk size in entries */
- LOCAL_DISK_SIZE(cache().children().exclude(Ehcache.class).add(descendants()), Integer.TYPE, 0, "size", "local-disk"),
-
- /** local disk size in bytes */
- LOCAL_DISK_SIZE_BYTES(cache().children().exclude(Ehcache.class).add(descendants()), Long.TYPE, 0L, "size-in-bytes", "local-disk"),
-
- /** writer queue length */
- WRITER_QUEUE_LENGTH(cache().descendants(), Long.TYPE, 0L, "queue-length", "write-behind"),
-
- /** remote size */
- REMOTE_SIZE(cache().descendants(), Long.TYPE, 0L, "size", "remote"),
-
- /** last rejoin time */
- LAST_REJOIN_TIMESTAMP(cache().descendants(), Long.TYPE, 0L, "lastRejoinTime", "cache");
-
- private static final int THIRTY = 30;
-
- private final Class extends Number> type;
- private final Query context;
- private final Number absentValue;
- private final String name;
- private final Set tags;
-
- private StandardPassThroughStatistic(Query context, Class type, T absentValue, String name, String ... tags) {
- this.context = context;
- this.type = type;
- this.absentValue = absentValue;
- this.name = name;
- this.tags = Collections.unmodifiableSet(new HashSet(Arrays.asList(tags)));
- }
-
- /**
- * Query that select context nodes for this statistic.
- *
- * @return context query
- */
- final Query context() {
- return context;
- }
-
- /**
- * Statistic value type.
- *
- * @return value type
- */
- public final Class extends Number> type() {
- return type;
- }
-
- /**
- * Statistic value when absent.
- *
- * @return absent value
- */
- public final Number absentValue() {
- return absentValue;
- }
-
- /**
- * The name of the statistic as found in the statistics context tree.
- *
- * @return the statistic name
- */
- public final String statisticName() {
- return name;
- }
-
- /**
- * A set of tags that will be on the statistic found in the statistics context tree.
- *
- * @return the statistic tags
- */
- public final Set tags() {
- return tags;
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache/src/test/resources/serializedforms/ClusteredTransactionIDSerializationTest.testBasic.ser
===================================================================
diff -u -N -r11085 -r11127
Binary files differ
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/TransactionIDImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/TransactionIDImpl.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/TransactionIDImpl.java (revision 0)
@@ -1,74 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction;
-
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * A transaction ID implementation with uniqueness across a single JVM
- *
- * @author Ludovic Orban
- */
-public class TransactionIDImpl implements TransactionID {
-
- private static final AtomicInteger ID_GENERATOR = new AtomicInteger();
-
- private final int id;
-
- /**
- * Create a new TransactionIDImpl instance
- */
- public TransactionIDImpl() {
- this.id = ID_GENERATOR.getAndIncrement();
- }
-
- /**
- * Create a new TransactionIDImpl instance from an existing one
- * @param transactionId the transaction Id to copy
- */
- protected TransactionIDImpl(TransactionIDImpl transactionId) {
- TransactionIDImpl txIdImpl = transactionId;
- this.id = txIdImpl.id;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public final boolean equals(Object obj) {
- if (obj instanceof TransactionIDImpl) {
- TransactionIDImpl otherId = (TransactionIDImpl) obj;
- return id == otherId.id;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public final int hashCode() {
- return id;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- return Integer.toString(id);
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/XaRollbackOutcome.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/XaRollbackOutcome.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/XaRollbackOutcome.java (revision 0)
@@ -1,30 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.xa;
-
-/**
- * The Enum XaRollbackOutcome.
- *
- * @author cdennis
- */
-public enum XaRollbackOutcome {
-
- /** The exception. */
- EXCEPTION,
-
- /** The rolledback. */
- ROLLEDBACK
-}
Index: rctags/ehcache-2.10.8.0.7/management-ehcache-v1/src/main/java/net/sf/ehcache/management/service/EntityResourceFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/management-ehcache-v1/src/main/java/net/sf/ehcache/management/service/EntityResourceFactory.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/management-ehcache-v1/src/main/java/net/sf/ehcache/management/service/EntityResourceFactory.java (revision 0)
@@ -1,82 +0,0 @@
-package net.sf.ehcache.management.service;
-
-import net.sf.ehcache.management.resource.CacheConfigEntity;
-import net.sf.ehcache.management.resource.CacheEntity;
-import net.sf.ehcache.management.resource.CacheManagerConfigEntity;
-import net.sf.ehcache.management.resource.CacheManagerEntity;
-import net.sf.ehcache.management.resource.CacheStatisticSampleEntity;
-
-import org.terracotta.management.ServiceExecutionException;
-
-import java.util.Collection;
-import java.util.Set;
-
-/**
- * A factory interface for resources related to Ehcache.
- *
- * @author brandony
- */
-public interface EntityResourceFactory {
-
- /**
- * A factory method for {@link CacheManagerEntity} objects.
- *
- * @param cacheManagerNames a {@code Set} of names for the CacheManager objects to be represented by the
- * returned resources
- * @param attributes a {@code Set} of specific cache manager attributes to include in the returned representations;
- * if null, all attributes will be included
- * @return a {@code Collection} of {@code CacheManagerEntity} objects
- */
- Collection createCacheManagerEntities(Set cacheManagerNames,
- Set attributes) throws ServiceExecutionException;
-
- /**
- * A factory method for {@link CacheManagerConfigEntity} objects.
- *
- * @param cacheManagerNames a {@code Set} of names for the CacheManager configurations to be represented by the
- * returned resources
- * @return a {@code Collection} of {@code CacheManagerConfigEntity} objects
- */
- Collection createCacheManagerConfigEntities(Set cacheManagerNames) throws ServiceExecutionException;
-
- /**
- * A factory method for {@link CacheEntity} objects.
- *
- * @param cacheManagerNames a {@code Set} of names for the CacheManagers that manage the Cache
- * objects to be represented by the returned resources
- * @param cacheNames a {@code Set} of names for the Cache objects to be represented by the
- * returned resources
- * @param attributes a {@code Set} of specific cache manager attributes to include in the returned representations;
- * if null, all attributes will be included
- * @return a {@code Collection} of {@code CacheEntity} objects
- */
- Collection createCacheEntities(Set cacheManagerNames,
- Set cacheNames,
- Set attributes) throws ServiceExecutionException;
-
- /**
- * A factory method for {@link CacheConfigEntity} objects.
- *
- * @param cacheManagerNames a {@code Set} of names for the CacheManagers that manage the Cache
- * objects to be represented by the returned resources
- * @param cacheNames a {@code Set} of names for the Cache objects to be represented by the
- * returned resources
- * @return a {@code Collection} of {@code CacheConfigEntity} objects
- */
- Collection createCacheConfigEntities(Set cacheManagerNames,
- Set cacheNames) throws ServiceExecutionException;
-
- /**
- * A factory method for {@link CacheStatisticSampleEntity} objects.
- *
- * @param cacheManagerNames a {@code Set} of names for the CacheManagers that manage the Caches whose
- * sampled statistics are to be represented by the returned resources
- * @param cacheNames a {@code Set} of names for the Caches whose sampled statistics are to be represented
- * by the returned resources
- * @param statNames a {@code Set} of names for the sampled statistics to be represented by the returned resources
- * @return a {@code Collection} of {@code CacheStatisticSampleEntity} objects
- */
- Collection createCacheStatisticSampleEntity(Set cacheManagerNames,
- Set cacheNames,
- Set statNames) throws ServiceExecutionException;
-}
Index: rctags/ehcache-2.10.8.0.7/distribution/events/src/assemble/bin/stop-sample.sh
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/distribution/events/src/assemble/bin/stop-sample.sh (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/distribution/events/src/assemble/bin/stop-sample.sh (revision 0)
@@ -1,18 +0,0 @@
-#!/bin/bash
-
-cygwin=false
-if [ `uname | grep CYGWIN` ]; then
- cygwin=true
-fi
-
-if [ "$JAVA_HOME" = "" ]; then
- echo "JAVA_HOME is not defined"
- exit 1
-fi
-
-unset CDPATH
-root=`dirname $0`/..
-root=`cd $root && pwd`
-
-$root/bin/stop-jetty.sh 9081
-$root/bin/stop-jetty.sh 9082
Index: rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/scheduled-refresh-cache-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/scheduled-refresh-cache-test.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/system-tests/src/test/resources/scheduled-refresh-cache-test.xml (revision 0)
@@ -1,23 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/ProcessingBucket.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/ProcessingBucket.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/ProcessingBucket.java (revision 0)
@@ -1,551 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.async;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.terracotta.modules.ehcache.async.AsyncCoordinatorImpl.Callback;
-import org.terracotta.modules.ehcache.async.exceptions.ProcessingException;
-import org.terracotta.toolkit.cluster.ClusterInfo;
-import org.terracotta.toolkit.internal.collections.ToolkitListInternal;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.locks.Condition;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-public class ProcessingBucket {
- private enum STOP_STATE {
- NORMAL, STOP_REQUESTED, STOPPED
- }
-
- private static final Logger LOGGER = LoggerFactory.getLogger(ProcessingBucket.class
- .getName());
- private static final int UNLIMITED_QUEUE_SIZE = 0;
- private static final String threadNamePrefix = "ProcessingWorker|";
- private final String bucketName;
- private final AsyncConfig config;
- private final ClusterInfo cluster;
- private final ItemProcessor processor;
- private volatile ItemsFilter filter;
- private final long baselineTimestampMillis;
- private final Lock bucketWriteLock;
- private final Lock bucketReadLock;
- private final Condition bucketNotEmpty;
- private final Condition bucketNotFull;
- private final Condition stoppedButBucketNotEmpty;
- private final ToolkitListInternal toolkitList;
- private long lastProcessingTimeMillis = -1;
- private long lastWorkDoneMillis = -1;
- private volatile STOP_STATE stopState = STOP_STATE.NORMAL;
- private final AtomicLong workDelay;
- private final ProcessingWorker processingWorkerRunnable;
- private volatile Thread processingWorkerThread;
- private Callback cleanupCallback;
- private final boolean workingOnDeadBucket;
- private volatile boolean destroyAfterStop;
-
- public ProcessingBucket(String bucketName, AsyncConfig config, ToolkitListInternal toolkitList,
- ClusterInfo cluster,
- ItemProcessor processor, boolean workingOnDeadBucket) {
- this.bucketName = bucketName;
- this.config = config;
- this.cluster = cluster;
- this.processor = processor;
- this.toolkitList = toolkitList;
- this.baselineTimestampMillis = System.currentTimeMillis();
- ReentrantReadWriteLock bucketLock = new ReentrantReadWriteLock();
- this.bucketReadLock = bucketLock.readLock();
- this.bucketWriteLock = bucketLock.writeLock();
- this.bucketNotEmpty = bucketWriteLock.newCondition();
- this.bucketNotFull = bucketWriteLock.newCondition();
- this.stoppedButBucketNotEmpty = bucketWriteLock.newCondition();
- this.workDelay = new AtomicLong(config.getWorkDelay());
- this.workingOnDeadBucket = workingOnDeadBucket;
- this.processingWorkerRunnable = new ProcessingWorker(threadNamePrefix + bucketName);
- this.destroyAfterStop = true;
- }
-
- public String getBucketName() {
- return bucketName;
- }
-
- /**
- * @return returns recent time stamp when processItems() executed.
- */
- public long getLastProcessing() {
- bucketReadLock.lock();
- try {
- return lastProcessingTimeMillis;
- } finally {
- bucketReadLock.unlock();
- }
- }
-
- public void setItemsFilter(ItemsFilter filter) {
- this.filter = filter;
- }
-
- private long baselinedCurrentTimeMillis() {
- return System.currentTimeMillis() - baselineTimestampMillis;
- }
-
- void start() {
- bucketWriteLock.lock();
- try {
- ensureNonExistingThread();
- processingWorkerThread = new Thread(processingWorkerRunnable);
- processingWorkerThread.setName(processingWorkerRunnable.getThreadName());
- processingWorkerThread.setDaemon(true);
- processingWorkerThread.start();
- } finally {
- bucketWriteLock.unlock();
- }
- }
-
- private void ensureNonExistingThread() {
- if (processingWorkerThread != null) { throw new AssertionError(processingWorkerRunnable.getThreadName()); }
- }
-
- private boolean isCancelled() {
- try {
- bucketReadLock.lock();
- try {
- return (stopState == STOP_STATE.STOPPED) || (workingOnDeadBucket && toolkitList.isEmpty());
- } finally {
- bucketReadLock.unlock();
- }
- } catch (RuntimeException e) {
- if (isTCNRE(e)) {
- return true;
- } else {
- throw e;
- }
- }
- }
-
- private boolean isTCNRE(Throwable th) {
- return th.getClass().getName().equals("com.tc.exception.TCNotRunningException");
- }
-
- public int getWaitCount() {
- bucketReadLock.lock();
- try {
- return toolkitList.size();
- } finally {
- bucketReadLock.unlock();
- }
- }
-
- public void stopNow() {
- bucketWriteLock.lock();
- try {
- destroyAfterStop = false;
- stopState = STOP_STATE.STOPPED;
- bucketNotEmpty.signalAll();
- bucketNotFull.signalAll();
- processingWorkerThread.interrupt();
- } finally {
- bucketWriteLock.unlock();
- }
- }
-
- public void stop() {
- bucketWriteLock.lock();
- try {
- workDelay.set(0);
- stopState = STOP_STATE.STOP_REQUESTED;
- while (!toolkitList.isEmpty()) {
- stoppedButBucketNotEmpty.await();
- }
- stopState = STOP_STATE.STOPPED;
- bucketNotEmpty.signalAll();
- bucketNotFull.signalAll();
- processingWorkerThread.interrupt();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- } finally {
- bucketWriteLock.unlock();
- }
- }
-
- public void destroy() {
- try {
- debug("destroying bucket " + bucketName + " " + toolkitList.size());
- toolkitList.destroy();
- } catch (Throwable t) {
- if (isTCNRE(t) && !cluster.areOperationsEnabled()) {
- LOGGER
- .warn("destroyToolkitList caught TCNotRunningException on processing thread, but looks like we were shut down. "
- + "This can safely be ignored!", t);
- }
- }
- }
-
- private String getThreadName() {
- return processingWorkerRunnable.getThreadName();
- }
-
- // Do not take any clustered write lock in this path.
- public void add(final E item) {
- if (null == item) return;
- int maxQueueSize = config.getMaxQueueSize();
- bucketWriteLock.lock();
- boolean interrupted = false;
- try {
- if (maxQueueSize != UNLIMITED_QUEUE_SIZE) {
- while (!isCancelled() && toolkitList.size() >= maxQueueSize) {
- try {
- bucketNotFull.await();
- } catch (final InterruptedException e) {
- interrupted = true;
- }
- }
- }
- boolean signalNotEmpty = toolkitList.isEmpty();
- toolkitList.unlockedAdd(item);
- if (signalNotEmpty) {
- bucketNotEmpty.signalAll();
- }
- } finally {
- bucketWriteLock.unlock();
- if (interrupted) {
- Thread.currentThread().interrupt();
- }
- }
- }
-
- private int determineBatchSize() {
- int batchSize = config.getBatchSize();
- int listSize = toolkitList.size();
- if (listSize < batchSize) {
- batchSize = listSize;
- }
- return batchSize;
- }
-
- private void debug(String message) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(message);
- }
- }
-
- private void filterQuarantined() {
- if (null == filter) { return; }
-
- bucketWriteLock.lock();
- try {
- ItemsFilter itemsFilter = this.filter;
- if (itemsFilter != null) {
- debug(getThreadName() + " : filterQuarantined: filtering " + toolkitList.size() + " quarantined items");
- itemsFilter.filter(toolkitList);
- debug(getThreadName() + " : filterQuarantined: retained " + toolkitList.size() + " quarantined items");
- }
- } finally {
- bucketWriteLock.unlock();
- }
- }
-
- /**
- * This method process items from bucket. Execution of this method does not guarantee that items from a non empty
- * bucket will be processed.
- */
- private void processItems() throws ProcessingException {
- final int workSize;
-
- bucketWriteLock.lock();
- try {
- // set some state related to this processing run
- lastProcessingTimeMillis = baselinedCurrentTimeMillis();
-
- workSize = toolkitList.size();
- // if there's no work that needs to be done, stop the processing
- if (0 == workSize) {
- debug(getThreadName() + " : processItems : nothing to process");
- return;
- }
- // filter might remove items from list, so this should be with-in writeLock
- filterQuarantined();
- } finally {
- bucketWriteLock.unlock();
- }
-
- // if the batching is enabled and work size is smaller than batch size, don't process anything as long as the max
- // allowed fall behind delay hasn't expired
- final int batchSize = config.getBatchSize();
- if (config.isBatchingEnabled() && batchSize > 0) {
- // wait for another round if the batch size hasn't been filled up yet and the max write delay hasn't expired yet
- if (workSize < batchSize && config.getMaxAllowedFallBehind() > lastProcessingTimeMillis - lastWorkDoneMillis) {
- bucketReadLock.lock();
- try {
- if (stopState == STOP_STATE.NORMAL) {
- debug(getThreadName() + " : processItems : only " + workSize + " work items available, waiting for "
- + batchSize + " items to fill up a batch");
- return;
- }
- } finally {
- bucketReadLock.unlock();
- }
- }
-
- // enforce the rate limit and wait for another round if too much would be processed compared to
- // the last time when a batch was executed
- final int rateLimit = config.getRateLimit();
- if (rateLimit > 0) {
- final long secondsSinceLastWorkDone;
- final int effectiveBatchSize;
- bucketReadLock.lock();
- try {
- if (stopState == STOP_STATE.NORMAL) {
- secondsSinceLastWorkDone = (baselinedCurrentTimeMillis() - lastWorkDoneMillis) / 1000;
- effectiveBatchSize = determineBatchSize();
- long maxBatchSizeSinceLastWorkDone = rateLimit * secondsSinceLastWorkDone;
- if (effectiveBatchSize > maxBatchSizeSinceLastWorkDone) {
- debug(getThreadName() + " : processItems() : last work was done " + secondsSinceLastWorkDone
- + " seconds ago, processing " + effectiveBatchSize
- + " batch items would exceed the rate limit of " + rateLimit + ", waiting for a while.");
- return;
- }
- }
- } finally {
- bucketReadLock.unlock();
- }
- }
- }
-
- bucketWriteLock.lock();
- try {
- lastWorkDoneMillis = baselinedCurrentTimeMillis();
- } finally {
- bucketWriteLock.unlock();
- }
-
- doProcessItems();
- }
-
- private void doProcessItems() throws ProcessingException {
- // process the quarantined items and remove them as they're processed
- // don't process work if this node's operations have been disabled
- if (!cluster.areOperationsEnabled()) {
- return;
- } else {
- if (config.isBatchingEnabled() && config.getBatchSize() > 0) {
- processBatchedItems();
- } else {
- processListSnapshot();
- }
- if (toolkitList.isEmpty() && stopState == STOP_STATE.STOP_REQUESTED) {
- signalStop();
- }
- }
- }
-
- private void signalStop() {
- bucketWriteLock.lock();
- try {
- stoppedButBucketNotEmpty.signalAll();
- } finally {
- bucketWriteLock.unlock();
- }
- }
-
- private void processListSnapshot() throws ProcessingException {
- int size = toolkitList.size();
- debug(getThreadName() + " : processListSnapshot size " + size + " quarantined items");
- while (size-- > 0) {
- processSingleItem();
- }
- }
-
- private void processSingleItem() throws ProcessingException {
- // process the next item
- final E item = getItemsFromQueue(1).get(0);
- final int retryAttempts = config.getRetryAttempts();
- int executionsLeft = retryAttempts + 1;
- while (executionsLeft-- > 0) {
- try {
- processor.process(item);
- break;
- } catch (final RuntimeException e) {
- if (executionsLeft <= 0) {
- try {
- processor.throwAway(item, e);
- } catch (final Throwable th) {
- LOGGER.warn("processSingleItem caught error while throwing away an item: " + item, th);
- }
- } else {
- LOGGER.warn(getThreadName() + " : processSingleItem() : exception during processing, retrying in "
- + retryAttempts + " milliseconds, " + executionsLeft + " retries left", e);
- try {
- Thread.sleep(config.getRetryAttemptDelay());
- } catch (InterruptedException e1) {
- Thread.currentThread().interrupt();
- throw e;
- }
- }
- }
- }
- removeFromQueue(1);
- }
-
- private void processBatchedItems() throws ProcessingException {
- final int effectiveBatchSize = determineBatchSize();
- List batch = getItemsFromQueue(effectiveBatchSize);
- final int retryAttempts = config.getRetryAttempts();
- int executionsLeft = retryAttempts + 1;
- while (executionsLeft-- > 0) {
- try {
- processor.process(batch);
- break;
- } catch (final RuntimeException e) {
- LOGGER.warn("processBatchedItems caught error while processing batch of " + batch.size(), e);
- if (executionsLeft <= 0) {
- for (E item : batch) {
- try {
- processor.throwAway(item, e);
- } catch (final Throwable th) {
- LOGGER.warn("processBatchedItems caught error while throwing away an item: " + item, th);
- }
- }
- } else {
- LOGGER.warn(getThreadName() + " : processBatchedItems() : exception during processing, retrying in "
- + retryAttempts + " milliseconds, " + executionsLeft + " retries left", e);
- try {
- Thread.sleep(config.getRetryAttemptDelay());
- } catch (InterruptedException e1) {
- Thread.currentThread().interrupt();
- throw e;
- }
- }
- }
- }
-
- removeFromQueue(effectiveBatchSize);
- }
-
- private List getItemsFromQueue(final int effectiveBatchSize) {
- bucketReadLock.lock();
- try {
- List batch = new ArrayList(effectiveBatchSize);
- for (int i = 0; i < effectiveBatchSize; i++) {
- final E item = toolkitList.get(i);
- batch.add(item);
- }
- return batch;
- } finally {
- bucketReadLock.unlock();
- }
- }
-
- private void removeFromQueue(final int effectiveBatchSize) {
- bucketWriteLock.lock();
- try {
- boolean signalNotFull = toolkitList.size() >= this.config.getMaxQueueSize();
-
- for (int i = 0; i < effectiveBatchSize; i++) {
- toolkitList.remove(0);
- }
-
- if (signalNotFull) {
- bucketNotFull.signalAll();
- }
- } finally {
- bucketWriteLock.unlock();
- }
- }
-
- void setCleanupCallback(Callback cleanupDeadBucket) {
- this.cleanupCallback = cleanupDeadBucket;
- }
-
- private final class ProcessingWorker implements Runnable {
- private final String threadName;
-
- public ProcessingWorker(String threadName) {
- this.threadName = threadName;
- }
-
- public String getThreadName() {
- return threadName;
- }
-
- @Override
- public void run() {
- try {
- while (!isCancelled()) {
- // process the items if this node's operations are enabled
- if (cluster.areOperationsEnabled()) {
- try {
- processItems();
- } catch (final Throwable e) {
- if (cluster.areOperationsEnabled()) {
- if (!isTCNRE(e)) {
- LOGGER.error("Caught error on processing bucket " + bucketName, e);
- }
- } else {
- LOGGER.warn("Caught error on processing items, but looks like we were shut down. "
- + "This can probably be safely ignored", e);
- }
- continue;
- }
- }
-
- final long currentLastProcessing = getLastProcessing();
-
- // Wait for new items or until the work delay has expired.
- // Do not continue if the actual work delay wasn't at least the one specified in the config
- // otherwise it's possible to create a new work list for just a couple of items in case
- // the item processor is very fast, causing a large amount of data churn and broadcasts.
- // However, if the work delay is expired, the processing should start immediately.
- bucketWriteLock.lock();
- try {
- try {
- long tmpWorkDelay = workDelay.get();
- if (tmpWorkDelay != 0) {
- do {
- bucketNotEmpty.await(tmpWorkDelay, TimeUnit.MILLISECONDS);
- long actualWorkDelay = baselinedCurrentTimeMillis() - currentLastProcessing;
- if (actualWorkDelay < tmpWorkDelay) {
- tmpWorkDelay -= actualWorkDelay;
- } else {
- tmpWorkDelay = 0;
- }
- } while (tmpWorkDelay > 0 && stopState == STOP_STATE.NORMAL);
- } else {
- while (!workingOnDeadBucket && stopState == STOP_STATE.NORMAL && toolkitList.isEmpty()) {
- bucketNotEmpty.await();
- }
- }
- } catch (final InterruptedException e) {
- // if the processing worker thread is interrupted, act as if the bucket was canceled
- stop();
- Thread.currentThread().interrupt();
- }
- } finally {
- bucketWriteLock.unlock();
- }
- }
- } catch (Throwable t) {
- if (isTCNRE(t) && !cluster.areOperationsEnabled()) {
- LOGGER.warn("Caught TCNotRunningException on processing thread, but looks like we were shut down. "
- + "This can safely be ignored!", t);
- }
- }
-
- if (destroyAfterStop) {
- // Destroy anyways, either stop happened or other dead-client bucket was finished processing
- if (workingOnDeadBucket) {
- cleanupCallback.callback();
- } else {
- destroy();
- }
- }
- }
- }
-
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/AtomikosSelector.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/AtomikosSelector.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/transaction/manager/selector/AtomikosSelector.java (revision 0)
@@ -1,31 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.transaction.manager.selector;
-
-/**
- * A Selector for the Atomikos transaction manager.
- *
- * @author Ludovic Orban
- */
-public class AtomikosSelector extends ClassSelector {
-
- /**
- * Constructor
- */
- public AtomikosSelector() {
- super("Atomikos", "com.atomikos.icatch.jta.UserTransactionManager");
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-tx-twopc.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-tx-twopc.xml (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/resources/ehcache-tx-twopc.xml (revision 0)
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.0.7/ehcache/src/test/resources/serializedforms/ReflectionAttributeExtractorSerializationTest.testFieldsKey.ser
===================================================================
diff -u -N -r11085 -r11127
Binary files differ
Index: rctags/ehcache-2.10.8.0.7/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/CacheEntity.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/CacheEntity.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/CacheEntity.java (revision 0)
@@ -1,23 +0,0 @@
-/* All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.*/
-
-package net.sf.ehcache.management.resource;
-
-import java.util.HashMap;
-import java.util.Map;
-
-
-/**
- *
- * An entity representing a cache resource from the management API.
- *
- *
- * @author brandony
- *
- */
-public class CacheEntity extends AbstractCacheEntity {
- private Map attributes = new HashMap();
-
- public Map getAttributes() {
- return attributes;
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/DynamicCacheConfigurationTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/DynamicCacheConfigurationTest.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/test/java/net/sf/ehcache/DynamicCacheConfigurationTest.java (revision 0)
@@ -1,330 +0,0 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-package net.sf.ehcache;
-
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.store.disk.DiskStoreHelper;
-
-import org.hamcrest.core.CombinableMatcher;
-import org.junit.Assert;
-import org.junit.Test;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.number.OrderingComparison.greaterThan;
-import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo;
-import static org.junit.Assert.assertThat;
-
-/**
- * @author cdennis
- */
-public class DynamicCacheConfigurationTest extends AbstractCacheTest {
-
- @Test
- public void testTTIChange() throws InterruptedException {
- Cache cache = new Cache("testTTIChange", 10, false, false, 0, 10);
-
- manager.addCache(cache);
-
- cache.put(new Element("key1", new Object()));
- cache.put(new Element("key2", new Object()));
-
- assertThat(cache.get("key1").getTimeToIdle(), is(10));
- assertThat(cache.get("key2").getTimeToIdle(), is(10));
- Element element2 = cache.get("key2");
- assertThat(element2.getExpirationTime(), is(element2.getLastAccessTime() + SECONDS.toMillis(10)));
- SECONDS.sleep(1);
-
- assertThat(cache.get("key2").getTimeToIdle(), is(10));
- element2 = cache.get("key2");
- assertThat(element2.getExpirationTime(), is(element2.getLastAccessTime() + SECONDS.toMillis(10)));
-
- cache.getCacheConfiguration().setTimeToIdleSeconds(20);
-
- cache.put(new Element("key1", new Object()));
- assertThat(cache.get("key1").getTimeToIdle(), is(20));
- assertThat(cache.get("key2").getTimeToIdle(), is(20));
-
- cache.getCacheConfiguration().setTimeToIdleSeconds(1);
-
- cache.put(new Element("key1", new Object()));
- cache.put(new Element("key2", new Object()));
-
- assertThat(cache.get("key1").getTimeToIdle(), is(1));
- assertThat(cache.get("key2").getTimeToIdle(), is(1));
- }
-
- @Test
- public void testTTLChange() throws InterruptedException {
- Cache cache = new Cache("testTTLChange", 10, false, false, 10, 0);
-
- manager.addCache(cache);
-
- cache.put(new Element("key1", new Object()));
- assertThat(cache.get("key1").getExpirationTime(), lessThanOrEqualTo(System.currentTimeMillis() + SECONDS.toMillis(10)));
- assertThat(cache.get("key1").getTimeToLive(), is(10));
-
- SECONDS.sleep(1);
- assertThat(cache.get("key1").getExpirationTime(), lessThanOrEqualTo(System.currentTimeMillis() + SECONDS.toMillis(9)));
-
- Assert.assertNotNull(cache.get("key1"));
- cache.put(new Element("key2", new Object()));
-
- assertThat(cache.get("key2").getTimeToLive(), is(10));
-
- cache.getCacheConfiguration().setTimeToLiveSeconds(20);
-
- cache.put(new Element("key1", new Object()));
-
- assertThat(cache.get("key1").getTimeToLive(), is(20));
- assertThat(cache.get("key2").getTimeToLive(), is(20));
-
- cache.getCacheConfiguration().setTimeToLiveSeconds(4);
-
- cache.put(new Element("key1", new Object()));
- cache.put(new Element("key2", new Object()));
-
- assertThat(cache.get("key1").getTimeToLive(), is(4));
- assertThat(cache.get("key2").getTimeToLive(), is(4));
- }
-
- @Test
- public void testTTIChangeWithCustomElements() throws InterruptedException {
- Cache cache = new Cache("testTTIChangeWithCustomElements", 10, false, false, 0, 10);
-
- manager.addCache(cache);
-
- cache.put(new Element("default", new Object()));
- cache.put(new Element("eternal", new Object(), true, 0, 0));
- cache.put(new Element("short", new Object(), false, 1, 1));
- cache.put(new Element("long", new Object(), false, 100, 100));
-
- assertThat(cache.get("default").getTimeToIdle(), is(10));
- assertThat(cache.get("default").isEternal(), is(false));
- assertThat(cache.get("eternal").isEternal(), is(true));
- assertThat(cache.get("short").getTimeToIdle(), is(1));
- assertThat(cache.get("long").getTimeToIdle(), is(100));
-
- cache.getCacheConfiguration().setTimeToIdleSeconds(4);
-
- cache.put(new Element("default", new Object()));
- cache.put(new Element("short", new Object(), false, 1, 1));
-
- assertThat(cache.get("default").getTimeToIdle(), is(4));
- assertThat(cache.get("default").isEternal(), is(false));
- assertThat(cache.get("eternal").isEternal(), is(true));
- assertThat(cache.get("short").getTimeToIdle(), is(1));
- assertThat(cache.get("long").getTimeToIdle(), is(100));
- }
-
- @Test
- public void testTTLChangeWithCustomElement() throws InterruptedException {
- Cache cache = new Cache("testTTLChangeWithCustomElements", 10, false, false, 10, 0);
-
- manager.addCache(cache);
-
- cache.put(new Element("default", new Object()));
- cache.put(new Element("eternal", new Object(), true, 0, 0));
- cache.put(new Element("short", new Object(), false, 1, 1));
- cache.put(new Element("long", new Object(), false, 100, 100));
-
- assertThat(cache.get("default").getTimeToLive(), is(10));
- assertThat(cache.get("default").isEternal(), is(false));
- assertThat(cache.get("eternal").isEternal(), is(true));
- assertThat(cache.get("short").getTimeToLive(), is(1));
- assertThat(cache.get("long").getTimeToLive(), is(100));
-
- cache.getCacheConfiguration().setTimeToLiveSeconds(20);
-
- cache.put(new Element("default", new Object()));
- cache.put(new Element("short", new Object(), false, 1, 1));
-
- assertThat(cache.get("default").getTimeToLive(), is(20));
- assertThat(cache.get("default").isEternal(), is(false));
- assertThat(cache.get("eternal").isEternal(), is(true));
- assertThat(cache.get("short").getTimeToLive(), is(1));
- assertThat(cache.get("long").getTimeToLive(), is(100));
-
- }
-
- @Test
- public void testMemoryCapacityChange() {
- Cache cache = new Cache("testMemoryCapacityChange", 10, false, true, 0, 0);
- manager.addCache(cache);
-
- for (int i = 0; i < 20; i++) {
- cache.put(new Element("key" + i, new Object()));
- Assert.assertTrue(cache.getSize() <= 10);
- Assert.assertTrue(cache.getStatistics().getLocalHeapSize() <= 10);
- }
-
- cache.getCacheConfiguration().setMaxElementsInMemory(20);
-
- for (int i = 20; i < 40; i++) {
- cache.put(new Element("key" + i, new Object()));
- Assert.assertTrue(cache.getSize() <= 20);
- Assert.assertTrue(cache.getSize() > 10);
- Assert.assertTrue(cache.getStatistics().getLocalHeapSize() <= 20);
- Assert.assertTrue(cache.getStatistics().getLocalHeapSize() > 10);
- }
-
- cache.getCacheConfiguration().setMaxElementsInMemory(5);
-
- for (int i = 40; i < 60; i++) {
- cache.put(new Element("key" + i, new Object()));
- }
-
- Assert.assertEquals(5, cache.getSize());
- Assert.assertEquals(5, cache.getStatistics().getLocalHeapSize());
- }
-
- @Test
- public void testDiskCapacityChange() throws Exception {
- final int DISK_WIGGLE = 2;
-
- Cache cache = new Cache("testDiskCapacityChange", 10, true, true, 0, 0);
- cache.getCacheConfiguration().setMaxElementsOnDisk(20);
- manager.addCache(cache);
-
- for (int i = 0; i < 40; i++) {
- cache.put(new Element("key" + i, new byte[0]));
- DiskStoreHelper.flushAllEntriesToDisk(cache).get();
- assertThat(cache.getSize(), lessThanOrEqualTo(20));
- assertThat(cache.getStatistics().getLocalHeapSize(), lessThanOrEqualTo(10L));
- assertThat(cache.getStatistics().getLocalDiskSize(), lessThanOrEqualTo(20L + DISK_WIGGLE));
- }
-
- cache.getCacheConfiguration().setMaxElementsOnDisk(20);
-
- for (int i = 40; i < 80; i++) {
- cache.put(new Element("key" + i, new byte[0]));
- DiskStoreHelper.flushAllEntriesToDisk(cache).get();
- assertThat(cache.getSize(), CombinableMatcher.both(lessThanOrEqualTo(30)).and(greaterThan(10)));
- assertThat(cache.getStatistics().getLocalHeapSize(), lessThanOrEqualTo(10L));
- assertThat(cache.getStatistics().getLocalDiskSize(), CombinableMatcher.both(lessThanOrEqualTo(20L + DISK_WIGGLE)).and(greaterThan(10L)));
- }
-
- cache.getCacheConfiguration().setMaxElementsOnDisk(10);
-
- for (int i = 80; i < 120; i++) {
- cache.put(new Element("key" + i, new byte[0]));
- DiskStoreHelper.flushAllEntriesToDisk(cache).get();
- }
-
- assertThat(cache.getSize(), lessThanOrEqualTo(10));
- assertThat(cache.getStatistics().getLocalHeapSize(), lessThanOrEqualTo(10L));
- Assert.assertEquals(10, cache.getStatistics().getLocalDiskSize());
- }
-
- @Test
- public void testCacheWithFrozenConfig() {
- Configuration managerConfig = new Configuration()
- .dynamicConfig(false)
- .defaultCache(new CacheConfiguration("definedCache1", 20))
- .cache(new CacheConfiguration("definedCache", 10).eternal(true)).name("new-cm");
-
- CacheManager manager = new CacheManager(managerConfig);
-
- Cache defined = manager.getCache("definedCache");
- try {
- defined.getCacheConfiguration().setTimeToIdleSeconds(99);
- Assert.fail();
- } catch (CacheException e) {
- // expected
- }
-
- try {
- defined.setDisabled(true);
- Assert.fail();
- } catch (CacheException e) {
- // expected
- }
-
- defined.put(new Element("key", "value"));
- Assert.assertNotNull(defined.get("key"));
-
- Cache programmatic = new Cache("programmatic", 10, false, true, 0, 0);
- manager.addCache(programmatic);
- try {
- programmatic.getCacheConfiguration().setTimeToIdleSeconds(99);
- Assert.fail();
- } catch (CacheException e) {
- // expected
- }
-
- try {
- programmatic.setDisabled(true);
- Assert.fail();
- } catch (CacheException e) {
- // expected
- }
-
- programmatic.put(new Element("key", "value"));
- Assert.assertNotNull(programmatic.get("key"));
- manager.shutdown();
- }
-
- @Test
- public void testConfiguringClonedCache() throws CloneNotSupportedException {
- Cache cache = new Cache("testConfiguringClonedCache", 10, false, true, 0, 0);
- Cache clone = cache.clone();
- clone.setName("testConfiguringClonedCacheCloned");
-
- manager.addCache(cache);
- manager.addCache(clone);
-
- Assert.assertEquals(10, cache.getCacheConfiguration().getMaxElementsInMemory());
- Assert.assertEquals(10, clone.getCacheConfiguration().getMaxElementsInMemory());
-
- for (int i = 0; i < 20; i++) {
- cache.put(new Element("key" + i, new Object()));
- Assert.assertTrue(cache.getSize() <= 10);
- Assert.assertTrue(cache.getStatistics().getLocalHeapSize() <= 10);
- }
-
- for (int i = 0; i < 20; i++) {
- clone.put(new Element("key" + i, new Object()));
- Assert.assertTrue(clone.getSize() <= 10);
- Assert.assertTrue(clone.getStatistics().getLocalHeapSize() <= 10);
- }
-
- cache.getCacheConfiguration().setMaxElementsInMemory(20);
- clone.getCacheConfiguration().setMaxElementsInMemory(5);
-
- for (int i = 20; i < 40; i++) {
- cache.put(new Element("key" + i, new Object()));
- Assert.assertTrue(cache.getSize() <= 20);
- Assert.assertTrue(cache.getSize() > 10);
- Assert.assertTrue(cache.getStatistics().getLocalHeapSize() <= 20);
- Assert.assertTrue(cache.getStatistics().getLocalHeapSize() > 10);
- }
-
- for (int i = 20; i < 40; i++) {
- clone.put(new Element("key" + i, new Object()));
- }
-
- Assert.assertEquals(5, clone.getSize());
- Assert.assertEquals(5, clone.getStatistics().getLocalHeapSize());
-
- cache.getCacheConfiguration().setMaxElementsInMemory(5);
- clone.getCacheConfiguration().setMaxElementsInMemory(20);
-
- for (int i = 40; i < 60; i++) {
- cache.put(new Element("key" + i, new Object()));
- }
-
- Assert.assertEquals(5, cache.getSize());
- Assert.assertEquals(5, cache.getStatistics().getLocalHeapSize());
-
- for (int i = 40; i < 60; i++) {
- clone.put(new Element("key" + i, new Object()));
- Assert.assertTrue(clone.getSize() <= 20);
- Assert.assertTrue(clone.getSize() > 5);
- Assert.assertTrue(clone.getStatistics().getLocalHeapSize() <= 20);
- Assert.assertTrue(clone.getStatistics().getLocalHeapSize() > 5);
- }
- }
-}
Index: rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/statistics/CoreStatisticsImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/statistics/CoreStatisticsImpl.java (revision 11085)
+++ rctags/ehcache-2.10.8.0.7/ehcache-core/src/main/java/net/sf/ehcache/statistics/CoreStatisticsImpl.java (revision 0)
@@ -1,291 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.statistics;
-
-import net.sf.ehcache.CacheOperationOutcomes;
-import net.sf.ehcache.CacheOperationOutcomes.ClusterEventOutcomes;
-import net.sf.ehcache.CacheOperationOutcomes.EvictionOutcome;
-import net.sf.ehcache.CacheOperationOutcomes.ExpiredOutcome;
-import net.sf.ehcache.statistics.extended.ExtendedStatistics;
-import net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation;
-import net.sf.ehcache.store.StoreOperationOutcomes.GetOutcome;
-import net.sf.ehcache.store.StoreOperationOutcomes.PutOutcome;
-import net.sf.ehcache.store.StoreOperationOutcomes.RemoveOutcome;
-import net.sf.ehcache.transaction.xa.XaCommitOutcome;
-import net.sf.ehcache.transaction.xa.XaRecoveryOutcome;
-import net.sf.ehcache.transaction.xa.XaRollbackOutcome;
-
-import java.util.Arrays;
-import java.util.EnumSet;
-
-/**
- * The CoreStatisticsImpl class.
- *
- * @author cschanck
- */
-public class CoreStatisticsImpl implements CoreStatistics {
-
- private final ExtendedStatistics extended;
- private final CountOperation cacheGet;
- private final CountOperation cachePut;
- private final CountOperation cacheRemove;
- private final CountOperation cacheReplace1;
- private final CountOperation cacheReplace2;
- private final CountOperation cachePutIfAbsent;
- private final CountOperation cacheRemoveElement;
- private final CountOperation localHeapGet;
- private final CountOperation localHeapPut;
-
- private final CountOperation localHeapRemove;
- private final CountOperation localOffHeapGet;
- private final CountOperation localOffHeapPut;
- private final CountOperation localOffHeapRemove;
- private final CountOperation localDiskGet;
- private final CountOperation localDiskPut;
- private final CountOperation localDiskRemove;
- private final CountOperation xaCommit;
- private final CountOperation xaRecovery;
- private final CountOperation xaRollback;
- private final CountOperation evicted;
- private final CountOperation expired;
-
- private final CountOperation cacheClusterEvent;
-
- /**
- * Instantiates a new core statistics impl.
- *
- * @param extended the extended
- */
- public CoreStatisticsImpl(ExtendedStatistics extended) {
- this.extended = extended;
- this.cacheGet = asCountOperation(extended.get());
- this.cachePut = asCountOperation(extended.put());
- this.cacheRemove = asCountOperation(extended.remove());
- this.cacheReplace1 = asCountOperation(extended.replaceOneArg());
- this.cacheReplace2 = asCountOperation(extended.replaceOneArg());
- this.cachePutIfAbsent = asCountOperation(extended.putIfAbsent());
- this.cacheRemoveElement = asCountOperation(extended.removeElement());
- this.localHeapGet = asCountOperation(extended.heapGet());
- this.localHeapPut = asCountOperation(extended.heapPut());
- this.localHeapRemove = asCountOperation(extended.heapRemove());
-
- this.localOffHeapGet = asCountOperation(extended.offheapGet());
- this.localOffHeapPut = asCountOperation(extended.offheapPut());
- this.localOffHeapRemove = asCountOperation(extended.offheapRemove());
-
- this.localDiskGet = asCountOperation(extended.diskGet());
- this.localDiskPut = asCountOperation(extended.diskPut());
- this.localDiskRemove = asCountOperation(extended.diskRemove());
-
- this.xaCommit = asCountOperation(extended.xaCommit());
- this.xaRecovery = asCountOperation(extended.xaRecovery());
- this.xaRollback = asCountOperation(extended.xaRollback());
-
- this.evicted = asCountOperation(extended.eviction());
- this.expired = asCountOperation(extended.expiry());
-
- this.cacheClusterEvent = asCountOperation(extended.clusterEvent());
- }
-
- private static > CountOperation asCountOperation(final Operation compoundOp) {
- return new CountOperation() {
- @Override
- public long value(T result) {
- return compoundOp.component(result).count().value();
- }
-
- @Override
- public long value(T... results) {
- return compoundOp.compound(EnumSet.copyOf(Arrays.asList(results))).count().value();
- }
-
- };
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#get()
- */
- @Override
- public CountOperation get() {
- return cacheGet;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#put()
- */
- @Override
- public CountOperation put() {
- return cachePut;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#remove()
- */
- @Override
- public CountOperation remove() {
- return cacheRemove;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#replaceOneArg()
- */
- @Override
- public CountOperation replaceOneArg() {
- return cacheReplace1;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#replaceTwoArg()
- */
- @Override
- public CountOperation replaceTwoArg() {
- return cacheReplace2;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#putIfAbsent()
- */
- @Override
- public CountOperation putIfAbsent() {
- return cachePutIfAbsent;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#removeElement()
- */
- @Override
- public CountOperation removeElement() {
- return cacheRemoveElement;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#localHeapGet()
- */
- @Override
- public CountOperation localHeapGet() {
- return localHeapGet;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#localHeapPut()
- */
- @Override
- public CountOperation localHeapPut() {
- return localHeapPut;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#localHeapRemove()
- */
- @Override
- public CountOperation localHeapRemove() {
- return localHeapRemove;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#localOffHeapGet()
- */
- @Override
- public CountOperation localOffHeapGet() {
- return localOffHeapGet;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#localOffHeapPut()
- */
- @Override
- public CountOperation localOffHeapPut() {
- return localOffHeapPut;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#localOffHeapRemove()
- */
- @Override
- public CountOperation localOffHeapRemove() {
- return localOffHeapRemove;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statistics.CoreStatistics#localDiskGet()
- */
- @Override
- public CountOperation |