source) {
- this.source = source;
- }
-
- private void complete(V value) {
- synchronized (this) {
- this.value = value;
- this.complete = true;
- notifyAll();
- }
- }
-
- private V get() {
- synchronized (this) {
- if (!complete) {
- try {
- complete(source.call());
- } catch (Throwable e) {
- fail(e);
- }
- }
- }
-
- return throwOrReturn();
- }
-
- private V throwOrReturn() {
- if (throwable != null) {
- if (throwable instanceof RuntimeException) {
- throw (RuntimeException) throwable;
- }
- throw new CacheException("Faulting from repository failed", throwable);
- }
- return value;
- }
-
- private void fail(final Throwable t) {
- synchronized (this) {
- this.throwable = t;
- this.complete = true;
- notifyAll();
- }
- throwOrReturn();
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/event/FireRejoinOperatorEventClusterListener.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/event/FireRejoinOperatorEventClusterListener.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/event/FireRejoinOperatorEventClusterListener.java (revision 0)
@@ -1,57 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.event;
-
-import net.sf.ehcache.cluster.ClusterNode;
-import net.sf.ehcache.cluster.ClusterTopologyListener;
-
-import org.terracotta.modules.ehcache.ToolkitInstanceFactory;
-import org.terracotta.toolkit.Toolkit;
-import org.terracotta.toolkit.monitoring.OperatorEventLevel;
-
-public class FireRejoinOperatorEventClusterListener implements ClusterTopologyListener {
- private static final String EHCACHE_OPERATOR_EVENT_APP_NAME = "ehcache";
- private volatile boolean clusterOnline = true;
- private volatile ClusterNode currentNode;
- private final Toolkit toolkit;
- private final ToolkitInstanceFactory toolkitInstanceFactory;
-
- public FireRejoinOperatorEventClusterListener(ToolkitInstanceFactory toolkitInstanceFactory) {
- this.toolkit = toolkitInstanceFactory.getToolkit();
- this.toolkitInstanceFactory = toolkitInstanceFactory;
- }
-
- @Override
- public void clusterOffline(ClusterNode node) {
- this.clusterOnline = false;
- }
-
- @Override
- public void clusterOnline(ClusterNode node) {
- this.clusterOnline = true;
- this.currentNode = new TerracottaNodeImpl(toolkit.getClusterInfo().getCurrentNode());
- }
-
- @Override
- public void clusterRejoined(ClusterNode oldNode, ClusterNode newNode) {
- if (clusterOnline) {
- toolkit.fireOperatorEvent(OperatorEventLevel.INFO, EHCACHE_OPERATOR_EVENT_APP_NAME,
- oldNode.getId() + " rejoined as " + newNode.getId());
- toolkitInstanceFactory.clusterRejoined();
- }
- }
-
- @Override
- public void nodeJoined(ClusterNode node) {
- //
- }
-
- @Override
- public void nodeLeft(ClusterNode node) {
- if (this.currentNode.equals(node)) {
- this.clusterOnline = false;
- }
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/event/NullCacheEventListener.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/event/NullCacheEventListener.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/event/NullCacheEventListener.java (revision 0)
@@ -1,129 +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.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-/**
- * A Null Object Pattern implementation of CacheEventListener. It simply logs the calls made.
- *
- * @author Greg Luck
- * @version $Id: NullCacheEventListener.java 10789 2018-04-26 02:08:13Z adahanne $
- * @since 1.2
- */
-public class NullCacheEventListener implements CacheEventListener {
-
- private static final Logger LOG = LoggerFactory.getLogger(NullCacheEventListener.class.getName());
-
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementRemoved(final Ehcache cache, final Element element) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("notifyElementRemoved called for cache " + cache + " for element with key " + element.getObjectKey());
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementPut(final Ehcache cache, final Element element) {
-
- Object key = null;
- if (element != null) {
- key = element.getObjectKey();
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("notifyElementPut called for cache " + cache.getName() + " for element with key " + key);
- }
- }
-
- /**
- * 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 {
-
- Object key = null;
- if (element != null) {
- key = element.getObjectKey();
- }
- if (LOG.isDebugEnabled()) {
- LOG.debug("notifyElementUpdated called for cache " + cache.getName() + " for element with key " + key);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementExpired(final Ehcache cache, final Element element) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("notifyElementExpired called for cache " + cache.getName() + " for element with key " + element.getObjectKey());
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementEvicted(final Ehcache cache, final Element element) {
- //
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyRemoveAll(final Ehcache cache) {
- //
- }
-
- /**
- * Give the replicator a chance to cleanup and free resources when no longer needed
- */
- public void dispose() {
- //nothing to do
- }
-
- /**
- * 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 {
- return super.clone();
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/cache-locks-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/cache-locks-test.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/cache-locks-test.xml (revision 0)
@@ -1,19 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/LockHolder.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/LockHolder.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/LockHolder.java (revision 0)
@@ -1,73 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.async;
-
-
-import org.terracotta.toolkit.concurrent.locks.ToolkitLock;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.BrokenBarrierException;
-import java.util.concurrent.CyclicBarrier;
-
-public class LockHolder {
- private static final int PARTIES = 2;
- private final Map holdings = new HashMap();
-
- public synchronized void hold(final ToolkitLock lock) {
- if (lock == null || holdings.containsKey(lock)) { return; }
- final CyclicBarrier barrier = new CyclicBarrier(PARTIES);
- Thread lockThread = new Thread(new Runnable() {
- @Override
- public void run() {
- lock.lock();
- try {
- await(barrier); // hit 1
- await(barrier); // hit 2
- } finally {
- try {
- lock.unlock();
- } catch (Throwable th) {
- // ignore any exception in unlock so that thread calling release() is not stuck at barrier.await()
- }
- await(barrier); // hit 3
- }
- }
- });
- holdings.put(lock.getName(), barrier);
- lockThread.start();
- await(barrier); // hit 1
- }
-
- public synchronized void release(ToolkitLock lock) {
- CyclicBarrier barrier = holdings.get(lock.getName());
- if (barrier != null) {
- releaseLock(barrier);
- holdings.remove(lock);
- }
- }
-
- private void releaseLock(CyclicBarrier barrier) {
- await(barrier); // hit 2
- await(barrier); // hit 3
- }
-
- public synchronized void reset() {
- for (CyclicBarrier barrier : holdings.values()) {
- releaseLock(barrier);
- }
- holdings.clear();
- }
-
- private void await(CyclicBarrier barrier) {
- try {
- barrier.await();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- } catch (BrokenBarrierException e) {
- // ignore
- }
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/one-cache-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/one-cache-test.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/one-cache-test.xml (revision 0)
@@ -1,14 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/ccs/EhcacheReadOnlyCache.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/ccs/EhcacheReadOnlyCache.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/ccs/EhcacheReadOnlyCache.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.hibernate.ccs;
-
-import java.util.Comparator;
-
-import org.hibernate.cache.CacheException;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.hibernate.cache.access.SoftLock;
-
-/**
- * Ehcache specific read-only cache concurrency strategy.
- *
- * This is the Ehcache specific equivalent to Hibernate's ReadOnlyCache.
- *
- * @author Chris Dennis
- */
-@Deprecated
-public class EhcacheReadOnlyCache extends AbstractEhcacheConcurrencyStrategy {
-
- private static final Logger LOG = LoggerFactory.getLogger(EhcacheReadOnlyCache.class);
-
- /**
- * {@inheritDoc}
- */
- public Object get(Object key, long timestamp) throws CacheException {
- return cache.get(key);
- }
-
- /**
- * Throws UnsupportedOperationException since items in a read-only cache should not be mutated.
- *
- * @throws UnsupportedOperationException always
- */
- public SoftLock lock(Object key, Object version) throws UnsupportedOperationException {
- LOG.error("Application attempted to edit read only item: " + key);
- throw new UnsupportedOperationException("Can't write to a readonly object");
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean put(Object key, Object value, long timestamp, Object version,
- Comparator versionComparator, boolean minimalPut) throws CacheException {
- if (minimalPut && cache.get(key) != null) {
- return false;
- } else {
- cache.put(key, value);
- return true;
- }
- }
-
- /**
- * Logs an error since items in a read-only cache should not be mutated.
- */
- public void release(Object key, SoftLock lock) {
- LOG.error("Application attempted to edit read only item: " + key);
- //throw new UnsupportedOperationException("Can't write to a readonly object");
- }
-
- /**
- * Throws UnsupportedOperationException since items in a read-only cache should not be mutated.
- *
- * @throws UnsupportedOperationException always
- */
- public boolean afterUpdate(Object key, Object value, Object version, SoftLock lock) throws UnsupportedOperationException {
- LOG.error("Application attempted to edit read only item: " + key);
- throw new UnsupportedOperationException("Can't write to a readonly object");
- }
-
- /**
- * Inserts the specified item into the cache.
- */
- public boolean afterInsert(Object key, Object value, Object version) throws CacheException {
- cache.update(key, value);
- return true;
- }
-
- /**
- * A No-Op, since we are an asynchronous cache concurrency strategy.
- */
- public void evict(Object key) throws CacheException {
- }
-
- /**
- * A No-Op, since we are an asynchronous cache concurrency strategy.
- */
- public boolean insert(Object key, Object value, Object currentVersion) {
- return false;
- }
-
- /**
- * Throws UnsupportedOperationException since items in a read-only cache should not be mutated.
- *
- * @throws UnsupportedOperationException always
- */
- public boolean update(Object key, Object value, Object currentVersion, Object previousVersion) throws UnsupportedOperationException {
- LOG.error("Application attempted to edit read only item: " + key);
- throw new UnsupportedOperationException("Can't write to a readonly object");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- return cache + "(read-only)";
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/compound/ReadWriteSerializationCopyStrategy.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/compound/ReadWriteSerializationCopyStrategy.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/compound/ReadWriteSerializationCopyStrategy.java (revision 0)
@@ -1,132 +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.compound;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.ElementIdHelper;
-import net.sf.ehcache.util.PreferredLoaderObjectInputStream;
-
-/**
- * A copy strategy that can use partial (if both copy on read and copy on write are set) or full Serialization to copy the object graph
- *
- * @author Alex Snaps
- * @author Ludovic Orban
- */
-public class ReadWriteSerializationCopyStrategy implements ReadWriteCopyStrategy {
-
- private static final long serialVersionUID = 2659269742281205622L;
-
- /**
- * Deep copies some object and returns an internal storage-ready copy
- *
- * @param value the value to copy
- * @return the storage-ready copy
- */
- public Element copyForWrite(Element value, ClassLoader loader) {
- if (value == null) {
- return null;
- } else {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- ObjectOutputStream oos = null;
-
- if (value.getObjectValue() == null) {
- return duplicateElementWithNewValue(value, null);
- }
-
- try {
- oos = new ObjectOutputStream(bout);
- oos.writeObject(value.getObjectValue());
- } catch (Exception e) {
- throw new CacheException("When configured copyOnRead or copyOnWrite, a Store will only accept Serializable values", e);
- } finally {
- try {
- if (oos != null) {
- oos.close();
- }
- } catch (Exception e) {
- //
- }
- }
-
- return duplicateElementWithNewValue(value, bout.toByteArray());
- }
- }
-
- /**
- * Reconstruct an object from its storage-ready copy.
- *
- * @param storedValue the storage-ready copy
- * @return the original object
- */
- public Element copyForRead(Element storedValue, ClassLoader loader) {
- if (storedValue == null) {
- return null;
- } else {
- if (storedValue.getObjectValue() == null) {
- return duplicateElementWithNewValue(storedValue, null);
- }
-
- ByteArrayInputStream bin = new ByteArrayInputStream((byte[]) storedValue.getObjectValue());
- ObjectInputStream ois = null;
- try {
- ois = new PreferredLoaderObjectInputStream(bin, loader);
- return duplicateElementWithNewValue(storedValue, ois.readObject());
- } catch (Exception e) {
- throw new CacheException("When configured copyOnRead or copyOnWrite, a Store will only accept Serializable values", e);
- } finally {
- try {
- if (ois != null) {
- ois.close();
- }
- } catch (Exception e) {
- //
- }
- }
- }
- }
-
- /**
- * Make a duplicate of an element but using the specified value
- *
- * @param element the element to duplicate
- * @param newValue the new element's value
- * @return the duplicated element
- */
- public Element duplicateElementWithNewValue(final Element element, final Object newValue) {
- Element newElement;
- if (element.usesCacheDefaultLifespan()) {
- newElement = new Element(element.getObjectKey(), newValue, element.getVersion(),
- element.getCreationTime(), element.getLastAccessTime(), element.getHitCount(), element.usesCacheDefaultLifespan(),
- Integer.MIN_VALUE, Integer.MIN_VALUE, element.getLastUpdateTime());
- } else {
- newElement = new Element(element.getObjectKey(), newValue, element.getVersion(),
- element.getCreationTime(), element.getLastAccessTime(), element.getHitCount(), element.usesCacheDefaultLifespan(),
- element.getTimeToLive(), element.getTimeToIdle(), element.getLastUpdateTime());
- }
- if (ElementIdHelper.hasId(element)) {
- ElementIdHelper.setId(newElement, ElementIdHelper.getId(element));
- }
- return newElement;
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/annotations/IgnoreSizeOf.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/annotations/IgnoreSizeOf.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/annotations/IgnoreSizeOf.java (revision 0)
@@ -1,38 +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.annotations;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * Annotation to ignore a field, type or entire package while doing a SizeOf measurement
- * @see net.sf.ehcache.pool.sizeof.SizeOf
- * @author Chris Dennis
- */
-@Retention(RetentionPolicy.RUNTIME)
-@Target({ElementType.FIELD, ElementType.TYPE, ElementType.PACKAGE })
-public @interface IgnoreSizeOf {
-
- /**
- * Controls whether the annotation, when applied to a {@link ElementType#TYPE type} is to be applied to all its subclasses
- * as well or solely on that type only. true if inherited by subtypes, false otherwise
- */
- boolean inherited() default false;
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/CachePinningFaultInvalidatedEntriesTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/CachePinningFaultInvalidatedEntriesTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/CachePinningFaultInvalidatedEntriesTest.java (revision 0)
@@ -1,107 +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.test.util.WaitUtil;
-import org.terracotta.toolkit.Toolkit;
-
-import com.tc.properties.TCPropertiesConsts;
-import com.tc.test.config.model.TestConfig;
-
-import java.util.concurrent.Callable;
-
-import junit.framework.Assert;
-
-public class CachePinningFaultInvalidatedEntriesTest extends AbstractCacheTestBase {
-
- private static final int ELEMENT_COUNT = 1000;
-
- public CachePinningFaultInvalidatedEntriesTest(TestConfig testConfig) {
- super("cache-pinning-test.xml", testConfig, App.class, App.class);
- testConfig.getClientConfig()
- .addExtraClientJvmArg("-Dcom.tc." + TCPropertiesConsts.L1_SERVERMAPMANAGER_FAULT_INVALIDATED_PINNED_ENTRIES
- + "=true");
- }
-
- public static class App extends ClientBase {
- public App(String[] args) {
- super("pinned", args);
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
-
- System.out.println("Testing with Eventual tier pinned cache");
- basicTestInvalidatedEntriesFaulted(cacheManager.getCache("pinnedEventual"), true);
- System.out.println("Testing with Strong tier pinned cache");
- basicTestInvalidatedEntriesFaulted(cacheManager.getCache("pinned"), true);
-
- }
-
- private void basicTestInvalidatedEntriesFaulted(final Cache cache, boolean tierPinned) throws Exception {
- int index = getBarrierForAllClients().await();
- if (index == 0) {
- for (int i = 0; i < ELEMENT_COUNT; i++) {
- cache.put(new Element(getKey(i), getValue(i)));
- }
- Assert.assertEquals(ELEMENT_COUNT, cache.getSize());
- for (int i = 0; i < ELEMENT_COUNT; i++) {
- assertNotNull(cache.get(getKey(i)));
- assertEquals(cache.get(getKey(i)).getValue(), getValue(i));
- }
- // All the gets on both the clients should be local as the pinned entries would have been faulted.
- Assert.assertEquals(ELEMENT_COUNT, cache.getMemoryStoreSize());
- Assert.assertEquals(ELEMENT_COUNT * 2, cache.getStatistics().localHeapHitCount());
- Assert.assertEquals(0, cache.getStatistics().cacheEvictedCount());
- }
- getBarrierForAllClients().await();
- if (index == 1) {
- // Update elements, invalidate entries on other client
- for (int i = 0; i < ELEMENT_COUNT; i++) {
- cache.put(new Element(getKey(i), getValue(i + 1)));
- }
- Assert.assertEquals(ELEMENT_COUNT, cache.getSize());
- }
-
- getBarrierForAllClients().await();
- WaitUtil.waitUntilCallableReturnsTrue(new Callable() {
-
- @Override
- public Boolean call() throws Exception {
- // wait until the client repopulates the local cache after receiving invalidations.
- long localsize = cache.getMemoryStoreSize();
- System.out.println("Local cache Size = " + localsize);
- return localsize == ELEMENT_COUNT;
- }
- });
-
- getBarrierForAllClients().await();
- for (int i = 0; i < ELEMENT_COUNT; i++) {
- assertNotNull(cache.get(getKey(i)));
- assertEquals(cache.get(getKey(i)).getValue(), getValue(i + 1));
- }
- // All the gets on both the clients should be local as the pinned entries would have been faulted.
- if (index == 0) {
- Assert.assertEquals(ELEMENT_COUNT, cache.getMemoryStoreSize());
- // Assert.assertEquals(ELEMENT_COUNT * 4, cache.getStatistics().localHeapHitCount());
- Assert.assertEquals(0, cache.getStatistics().cacheEvictedCount());
- }
- getBarrierForAllClients().await();
- }
-
- private Object getKey(int i) {
- return String.valueOf(i);
- }
-
- private Object getValue(int i) {
- return i;
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/expression/ILike.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/expression/ILike.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/expression/ILike.java (revision 0)
@@ -1,163 +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.expression;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import net.sf.ehcache.Element;
-import net.sf.ehcache.search.Attribute;
-import net.sf.ehcache.search.SearchException;
-import net.sf.ehcache.search.attribute.AttributeExtractor;
-
-/**
- * A regular expression criteria that matches attribute string values. For non java.lang.String attributes
,
- * the toString()
form is used in the comparison.
- *
- * Expressions are always case insensitive
- *
- * The following special characters are supported:
- *
- * '?' - match any one single character
- * '*' - match any multiple character(s) (including zero)
- *
- * The supported wildcard characters can be escaped with a backslash '\', and a literal backslash can be included with '\\'
- *
- * WARN: Expressions starting with a leading wildcard character are potentially very expensive (ie. full scan) for indexed caches
- *
- *
- * @author teck
- */
-public class ILike extends BaseCriteria {
-
- private final String attributeName;
- private final String regex;
- private final Pattern pattern;
-
- /**
- * Construct a "like" criteria for the given expression
- *
- * @param attributeName attribute name
- * @param regex expression
- */
- public ILike(String attributeName, String regex) {
- if ((attributeName == null) || (regex == null)) {
- throw new SearchException("Both the attribute name and regex must be non null.");
- }
-
- this.attributeName = attributeName;
- this.regex = regex;
- this.pattern = convertRegex(regex.trim());
- }
-
- /**
- * Return attribute name.
- *
- * @return String attribute name
- */
- public String getAttributeName() {
- return attributeName;
- }
-
- /**
- * Return regex string.
- *
- * @return String regex.
- */
- public String getRegex() {
- return regex;
- }
-
- private static Pattern convertRegex(final String expr) {
- if (expr.length() == 0) {
- throw new SearchException("Zero length regex");
- }
-
- StringBuilder javaRegex = new StringBuilder("^");
-
- boolean escape = false;
- for (int i = 0; i < expr.length(); i++) {
- char ch = expr.charAt(i);
-
- if (escape) {
- switch (ch) {
- case '\\':
- case '?':
- case '*': {
- javaRegex.append(Pattern.quote(lowerCase(ch)));
- break;
- }
-
- default: {
- throw new SearchException("Illegal escape character (" + ch + ") in regex: " + expr);
- }
- }
-
- escape = false;
- } else {
- switch (ch) {
- case '\\': {
- escape = true;
- break;
- }
- case '?': {
- javaRegex.append(".");
- break;
- }
- case '*': {
- javaRegex.append(".*");
- break;
- }
- default: {
- javaRegex.append(Pattern.quote(lowerCase(ch)));
- }
- }
- }
- }
-
- javaRegex.append("$");
-
- return Pattern.compile(javaRegex.toString(), Pattern.DOTALL);
- }
-
- private static String lowerCase(char ch) {
- // heeding the advice in Character.toLowerCase() and using String.toLowerCase() instead here
- return Character.toString(ch).toLowerCase();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean execute(Element e, Map attributeExtractors) {
- Object value = getExtractor(attributeName, attributeExtractors).attributeFor(e, attributeName);
- if (value == null) {
- return false;
- }
-
- String asString = value.toString().toLowerCase();
-
- return pattern.matcher(asString).matches();
- }
-
- @Override
- public Set> getAttributes() {
- return Collections.>singleton(new Attribute(attributeName));
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/terracotta/KeySnapshotter.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/terracotta/KeySnapshotter.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/terracotta/KeySnapshotter.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.terracotta;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.CacheStoreHelper;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.store.Store;
-import net.sf.ehcache.store.TerracottaStore;
-import net.sf.ehcache.util.WeakIdentityConcurrentMap;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-/**
- * A class that will snapshot the local keySet of a Terracotta clustered cache to disk
- *
- * @author Alex Snaps
- */
-class KeySnapshotter implements Runnable {
-
- private static final Logger LOG = LoggerFactory.getLogger(KeySnapshotter.class.getName());
- private static final int POOL_SIZE = Integer.getInteger("net.sf.ehcache.terracotta.KeySnapshotter.threadPoolSize", 10);
-
- private static final WeakIdentityConcurrentMap INSTANCES =
- new WeakIdentityConcurrentMap(
- new WeakIdentityConcurrentMap.CleanUpTask() {
- public void cleanUp(final ScheduledExecutorService executor) {
- executor.shutdownNow();
- }
- });
-
- private final String cacheName;
- private volatile TerracottaStore tcStore;
- private final RotatingSnapshotFile rotatingWriter;
- private final Thread thread;
-
- private volatile Runnable onSnapshot;
- private final ScheduledFuture> scheduledFuture;
-
- /**
- * Default Constructor
- *
- * @param cache the Terracotta clustered Cache to snapshot
- * @param interval the interval to do the snapshots on
- * @param doKeySnapshotOnDedicatedThread whether the snapshots have to be done on a dedicated thread
- * @param rotatingWriter the RotatingSnapshotFile to write to
- * @throws IllegalArgumentException if interval is less than or equal to zero
- */
- KeySnapshotter(final Ehcache cache, final long interval,
- final boolean doKeySnapshotOnDedicatedThread,
- final RotatingSnapshotFile rotatingWriter)
- throws IllegalArgumentException {
- final Store store = new CacheStoreHelper((Cache)cache).getStore();
- if (!(store instanceof TerracottaStore)) {
- throw new IllegalArgumentException("Cache '" + cache.getName() + "' isn't backed by a " + TerracottaStore.class.getSimpleName()
- + " but uses a " + store.getClass().getName() + " instead");
- }
-
- if (interval <= 0) {
- throw new IllegalArgumentException("Interval needs to be a positive & non-zero value");
- }
-
- if (rotatingWriter == null) {
- throw new NullPointerException();
- }
-
- this.cacheName = cache.getName();
- this.rotatingWriter = rotatingWriter;
- this.tcStore = (TerracottaStore)store;
-
- if (doKeySnapshotOnDedicatedThread) {
- scheduledFuture = null;
- thread = new SnapShottingThread(this, interval, "KeySnapshotter for cache " + cacheName);
- thread.start();
- } else {
- scheduledFuture = getScheduledExecutorService(cache.getCacheManager())
- .scheduleWithFixedDelay(this, interval, interval, TimeUnit.SECONDS);
- thread = null;
- }
- }
-
- private ScheduledExecutorService getScheduledExecutorService(final CacheManager cacheManager) {
- ScheduledExecutorService scheduledExecutorService = INSTANCES.get(cacheManager);
- if (scheduledExecutorService == null) {
- scheduledExecutorService = new ScheduledThreadPoolExecutor(POOL_SIZE);
- final ScheduledExecutorService previous = INSTANCES.putIfAbsent(cacheManager, scheduledExecutorService);
- if (previous != null) {
- scheduledExecutorService.shutdownNow();
- scheduledExecutorService = previous;
- }
- }
- return scheduledExecutorService;
- }
-
- /**
- * Shuts down the writer thread and cleans up resources
- *
- * @param immediately whether to leave the writer finish or shut down immediately
- */
- void dispose(boolean immediately) {
- if (thread != null) {
- rotatingWriter.setShutdownOnThreadInterrupted(immediately);
- thread.interrupt();
- try {
- thread.join();
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- } else {
- scheduledFuture.cancel(immediately);
- }
- tcStore = null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void run() {
- try {
- INSTANCES.cleanUp();
- rotatingWriter.writeAll(tcStore.getLocalKeys());
- onSnapshot();
- } catch (Throwable e) {
- LOG.error("Couldn't snapshot local keySet for Cache {}", cacheName, e);
- }
- }
-
- private void onSnapshot() {
- if (onSnapshot != null) {
- try {
- onSnapshot.run();
- } catch (Exception e) {
- LOG.warn("Error occurred in onSnapshot callback", e);
- }
- }
- }
-
- /**
- * Accessor to all known cacheManagers (which are also bound to a ScheduledExecutorService)
- *
- * @return the collection of known CacheManagers
- */
- static Collection getKnownCacheManagers() {
- return INSTANCES.keySet();
- }
-
- /**
- * 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
- */
- void doSnapshot() throws IOException {
- rotatingWriter.snapshotNowOrWaitForCurrentToFinish(tcStore.getLocalKeys());
- onSnapshot();
- }
-
- /**
- * Let register a Runnable that will be called on every snapshot happening
- * @param onSnapshot the runnable
- */
- void setOnSnapshot(final Runnable onSnapshot) {
- this.onSnapshot = onSnapshot;
- }
-
- /**
- * Returns the name of the underlying cache for which this snapshots
- * @return The name of the cache
- */
- public String getCacheName() {
- return cacheName;
- }
-
- /**
- * Thread doing background snapshots of the local key set
- */
- private static class SnapShottingThread extends Thread {
-
- private long lastRun;
- private final long interval;
-
- public SnapShottingThread(final Runnable runnable, final long interval, final String threadName) {
- super(runnable, threadName);
- this.interval = interval;
- lastRun = System.currentTimeMillis();
- this.setDaemon(true);
- }
-
- @Override
- public void run() {
- while (!isInterrupted()) {
- final long nextTime = lastRun + TimeUnit.SECONDS.toMillis(interval);
- final long now = System.currentTimeMillis();
- if (nextTime <= now) {
- super.run();
- lastRun = System.currentTimeMillis();
- } else {
- try {
- sleep(nextTime - now);
- } catch (InterruptedException e) {
- interrupt();
- }
- }
- }
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/stop-jetty.bat
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/stop-jetty.bat (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/stop-jetty.bat (revision 0)
@@ -1,38 +0,0 @@
-@echo off
-
-if not defined JAVA_HOME (
- echo JAVA_HOME is not defined
- exit /b 1
-)
-
-setlocal
-
-set jetty_instance=%1
-
-if "%jetty_instance%" == "" (
- echo Need to specify which instance of Jetty: 9081 or 9082
- exit /b 1
-)
-
-pushd "%~d0%~p0"
-for /f "tokens=*" %%a in ('call relative-paths.bat tc_install_dir') do set tc_install_dir=%%a
-pushd
-cd %tc_install_dir%
-set tc_install_dir=%CD%
-set tc_install_dir="%tc_install_dir:"=%"
-popd
-popd
-
-set JAVA_HOME="%JAVA_HOME:"=%"
-set root=%~d0%~p0..
-set root="%root:"=%"
-set jetty_work_dir=%root%\jetty6.1\%jetty_instance%
-set jetty_home=%tc_install_dir%\third-party\jetty-6.1.15
-set start_jar=%jetty_home%\start.jar
-set /a stop_port=jetty_instance + 2
-
-cd %jetty_work_dir%
-echo Stopping Jetty %jetty_instance%...
-%JAVA_HOME%\bin\java -Djetty.home=%jetty_home% -DSTOP.PORT=%stop_port% -DSTOP.KEY=secret -jar %start_jar% --stop
-
-endlocal
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/SizeOfTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/SizeOfTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/SizeOfTest.java (revision 0)
@@ -1,236 +0,0 @@
-package net.sf.ehcache.pool.sizeof;
-
-import static net.sf.ehcache.pool.sizeof.JvmInformation.CURRENT_JVM_INFORMATION;
-import static net.sf.ehcache.pool.sizeof.JvmInformation.UNKNOWN_32_BIT;
-import static net.sf.ehcache.pool.sizeof.JvmInformation.UNKNOWN_64_BIT;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.core.IsNot.not;
-import static org.hamcrest.core.StringContains.containsString;
-import static org.junit.Assume.assumeThat;
-
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.math.MathContext;
-import java.net.Proxy;
-import java.nio.charset.CodingErrorAction;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.logging.Logger;
-
-import org.junit.Assert;
-import javax.xml.datatype.DatatypeConstants;
-
-import org.junit.Assume;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-/**
- * @author Alex Snaps
- */
-public class SizeOfTest extends AbstractSizeOfTest {
-
- public Object[] container;
-
- private static long deepSizeOf(SizeOf sizeOf, Object... obj) {
- return sizeOf.deepSizeOf(1000, true, obj).getCalculated();
- }
-
- @BeforeClass
- public static void setup() {
- System.err.println("java.vm.name:\t" + System.getProperty("java.vm.name", ""));
- System.err.println("java.vm.vendor:\t" + System.getProperty("java.vm.vendor", ""));
- assumeThat(System.getProperty("os.name"), not(containsString("AIX")));
- deepSizeOf(new CrossCheckingSizeOf(), null);
- System.err.println("JVM identified as: " + JvmInformation.CURRENT_JVM_INFORMATION);
- if (JvmInformation.CURRENT_JVM_INFORMATION == UNKNOWN_64_BIT || JvmInformation.CURRENT_JVM_INFORMATION == UNKNOWN_32_BIT) {
- System.getProperties().list(System.err);
- }
- }
-
- private final Collection sizeOfFailures = new LinkedList();
-
- @Test
- public void testSizeOf() throws Exception {
- Assume.assumeThat(CURRENT_JVM_INFORMATION.getMinimumObjectSize(), is(CURRENT_JVM_INFORMATION.getObjectAlignment()));
-
- SizeOf sizeOf = new CrossCheckingSizeOf();
- Assert.assertThat(deepSizeOf(sizeOf, TimeUnit.SECONDS), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, Object.class), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, 1), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, BigInteger.ZERO), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, BigDecimal.ZERO), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, MathContext.UNLIMITED), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, Locale.ENGLISH), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, Logger.global), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, Collections.EMPTY_SET), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, Collections.EMPTY_LIST), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, Collections.EMPTY_MAP), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, String.CASE_INSENSITIVE_ORDER), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, System.err), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, Proxy.NO_PROXY), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, CodingErrorAction.REPORT), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, DatatypeConstants.DAYS), is(0L));
- Assert.assertThat(deepSizeOf(sizeOf, DatatypeConstants.TIME), is(0L));
-
- assertThat(sizeOf.sizeOf(new Object()), "sizeOf(new Object())");
- assertThat(sizeOf.sizeOf(new Integer(1)), "sizeOf(new Integer(1))");
- assertThat(sizeOf.sizeOf(1000), "sizeOf(1000)");
- assertThat(deepSizeOf(sizeOf, new SomeClass(false)), "deepSizeOf(new SomeClass(false))");
- assertThat(deepSizeOf(sizeOf, new SomeClass(true)), "deepSizeOf(new SomeClass(true))");
- assertThat(sizeOf.sizeOf(new Object[] { }), "sizeOf(new Object[] { })");
- assertThat(sizeOf.sizeOf(new Object[] { new Object(), new Object(), new Object(), new Object() }), "sizeOf(new Object[] { new Object(), new Object(), new Object(), new Object() })");
- assertThat(sizeOf.sizeOf(new int[] { }), "sizeOf(new int[] { })");
- assertThat(sizeOf.sizeOf(new int[] { 987654, 876543, 765432, 654321 }), "sizeOf(new int[] { 987654, 876543, 765432, 654321 })");
- assertThat(deepSizeOf(sizeOf, new Pair(null, null)), "deepSizeOf(new Pair(null, null))");
- assertThat(deepSizeOf(sizeOf, new Pair(new Object(), null)), "deepSizeOf(new Pair(new Object(), null))");
- assertThat(deepSizeOf(sizeOf, new Pair(new Object(), new Object())), "deepSizeOf(new Pair(new Object(), new Object()))");
- assertThat(deepSizeOf(sizeOf, new ReentrantReadWriteLock()), "deepSizeOf(new ReentrantReadWriteLock())");
-
- if (!sizeOfFailures.isEmpty()) {
- StringBuilder sb = new StringBuilder();
- for (AssertionError e : sizeOfFailures) {
- sb.append(e.toString()).append('\n');
- }
- Assert.fail(sb.toString());
- }
-
- List list1 = new ArrayList();
- List list2 = new ArrayList();
-
- Object someInstance = new Object();
- list1.add(someInstance);
- list2.add(someInstance);
-
- Assert.assertThat(deepSizeOf(sizeOf, list1), is(deepSizeOf(sizeOf, list2)));
- Assert.assertThat(deepSizeOf(sizeOf, list1, list2) < (deepSizeOf(sizeOf, list1) + deepSizeOf(sizeOf, list2)), is(true));
- list2.add(new Object());
- Assert.assertThat(deepSizeOf(sizeOf, list2) > deepSizeOf(sizeOf, list1), is(true));
- }
-
- private void assertThat(Long size, String expression) {
- try {
- Assert.assertThat(expression, size, is(SizeOfTestValues.get(expression)));
- } catch (AssertionError e) {
- sizeOfFailures.add(e);
- }
- }
-
- @Test
- public void testOnHeapConsumption() throws Exception {
- SizeOf sizeOf = new CrossCheckingSizeOf();
-
- int size = 80000;
- int perfectMatches = 0;
- for (int j = 0; j < 5; j++) {
- container = new Object[size];
- long usedBefore = measureMemoryUse();
- for (int i = 0; i < size; i++) {
- container[i] = new EvilPair(new Object(), new SomeClass(i % 2 == 0));
- }
-
- long mem = 0;
- for (Object s : container) {
- mem += deepSizeOf(sizeOf, s);
- }
-
- long used = measureMemoryUse() - usedBefore;
- float percentage = 1 - (mem / (float) used);
- System.err.println("Run # " + (j + 1) + ": Deviation of " + String.format("%.3f", percentage * -100) +
- "%\n" + used +
- " bytes are actually being used, while we believe " + mem + " are");
- if (j > 1) {
- Assert.assertThat("Run # " + (j + 1) + ": Deviation of " + String.format("%.3f", percentage * -100) +
- "% was above the +/-1.5% delta threshold \n" + used +
- " bytes are actually being used, while we believe " + mem + " are (" +
- (used - mem) / size + ")",
- Math.abs(percentage) < .015f, is(true));
- }
- if(used == mem && ++perfectMatches > 1) {
- System.err.println("Two perfect matches, that's good enough... bye y'all!");
- break;
- }
- }
- }
-
- private long measureMemoryUse() throws InterruptedException {
- long total;
- long freeAfter;
- long freeBefore;
- Runtime runtime = Runtime.getRuntime();
- do {
- total = runtime.totalMemory();
- freeBefore = runtime.freeMemory();
- System.gc();
- Thread.sleep(100);
- freeAfter = runtime.freeMemory();
- } while (total != runtime.totalMemory() || freeAfter > freeBefore);
- return total - freeAfter;
- }
-
- public static class SomeClass {
-
- public Object ref;
-
- public SomeClass(final boolean init) {
- if (init) {
- ref = new Object();
- }
- }
- }
-
- public static class Pair {
- private final Object one;
- private final Object two;
-
- public Pair(final Object one, final Object two) {
- this.one = one;
- this.two = two;
- }
- }
-
- public static final class Stupid {
-
- public static class internal {
- private int someValue;
- private long otherValue;
- }
-
- internal internalVar = new internal();
- int someValue;
- long someOther;
- long otherValue;
- boolean bool;
- }
-
- public static final class EvilPair extends Pair {
-
- private static final AtomicLong counter = new AtomicLong(Long.MIN_VALUE);
-
- private final Object oneHidden;
- private final Object twoHidden;
- private final Object copyOne;
- private final Object copyTwo;
- private final long instanceNumber;
-
- private EvilPair(final Object one, final Object two) {
- super(one, two);
- instanceNumber = counter.getAndIncrement();
- if (instanceNumber % 4 == 0) {
- oneHidden = new Object();
- twoHidden = new Object();
- } else {
- oneHidden = null;
- twoHidden = null;
- }
- this.copyOne = one;
- this.copyTwo = two;
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncCoordinator.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncCoordinator.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncCoordinator.java (revision 0)
@@ -1,43 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.async;
-
-import org.terracotta.modules.ehcache.async.scatterpolicies.ItemScatterPolicy;
-
-import java.io.Serializable;
-
-public interface AsyncCoordinator {
-
- /**
- * @throws IllegalArgumentException if processingConcurrency is less than 1 OR processor is null
- */
- public void start(final ItemProcessor processor, final int processingConcurrency,
- ItemScatterPolicy super E> policy);
-
- /**
- * @param item null item are ignored.
- */
- public void add(E item);
-
- /**
- * Stops and waits for the current processing to finish.
- * Calling this multiple times will result in {@link IllegalStateException}
- */
- public void stop();
-
- /**
- * Sets a filter to filter out the items.
- */
- public void setOperationsFilter(ItemsFilter filter);
-
- /**
- * @return the current items to be processed
- */
- public long getQueueSize();
-
- /**
- * Destroy all clustered state associated with the given async coordinator.
- */
- void destroy();
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/impl/OrderComparator.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/impl/OrderComparator.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/impl/OrderComparator.java (revision 0)
@@ -1,137 +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.impl;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Comparator;
-import java.util.List;
-
-import net.sf.ehcache.store.StoreQuery.Ordering;
-
-/**
- * Compound sort ordering comparactor
- *
- * @author teck
- * @param
- */
-public class OrderComparator implements Comparator {
-
- private final List> comparators;
-
- /**
- * Constructor
- *
- * @param orderings
- */
- public OrderComparator(List orderings) {
- comparators = new ArrayList>();
- int pos = 0;
- for (Ordering ordering : orderings) {
- switch (ordering.getDirection()) {
- case ASCENDING: {
- comparators.add(new AscendingComparator(pos));
- break;
- }
- case DESCENDING: {
- comparators.add(new DescendingComparator(pos));
- break;
- }
- default: {
- throw new AssertionError(ordering.getDirection());
- }
- }
-
- pos++;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public int compare(T o1, T o2) {
- for (Comparator c : comparators) {
- int cmp = c.compare(o1, o2);
- if (cmp != 0) {
- return cmp;
- }
- }
- return 0;
- }
-
- /**
- * Simple ascending comparator
- */
- private class AscendingComparator implements Comparator, Serializable {
-
- private final int pos;
-
- AscendingComparator(int pos) {
- this.pos = pos;
- }
-
- public int compare(T o1, T o2) {
- Object attr1 = o1.getSortAttribute(pos);
- Object attr2 = o2.getSortAttribute(pos);
-
- if ((attr1 == null) && (attr2 == null)) {
- return 0;
- }
-
- if (attr1 == null) {
- return -1;
- }
-
- if (attr2 == null) {
- return 1;
- }
-
- return ((Comparable) attr1).compareTo(attr2);
- }
- }
-
- /**
- * Simple descending comparator
- */
- private class DescendingComparator implements Comparator, Serializable {
-
- private final int pos;
-
- DescendingComparator(int pos) {
- this.pos = pos;
- }
-
- public int compare(T o1, T o2) {
- Object attr1 = o1.getSortAttribute(pos);
- Object attr2 = o2.getSortAttribute(pos);
-
- if ((attr1 == null) && (attr2 == null)) {
- return 0;
- }
-
- if (attr1 == null) {
- return 1;
- }
-
- if (attr2 == null) {
- return -1;
- }
-
- return ((Comparable) attr2).compareTo(attr1);
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/Size.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/Size.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/Size.java (revision 0)
@@ -1,58 +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;
-
-/**
- * Holder for the size calculated by the SizeOf engine
- *
- * @author Ludovic Orban
- */
-public final class Size {
-
- private final long calculated;
- private final boolean exact;
-
- /**
- * Constructor
- *
- * @param calculated the calculated size
- * @param exact true if the calculated size is exact, false if it's an estimate or known to be inaccurate in some way
- */
- public Size(long calculated, boolean exact) {
- this.calculated = calculated;
- this.exact = exact;
- }
-
- /**
- * Get the calculated size
- *
- * @return the calculated size
- */
- public long getCalculated() {
- return calculated;
- }
-
- /**
- * Check if the calculated size is exact
- *
- * @return true if the calculated size is exact, false if it's an estimate or known to be inaccurate in some way
- */
- public boolean isExact() {
- return exact;
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/regions/EhcacheEntityRegion.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/regions/EhcacheEntityRegion.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/regions/EhcacheEntityRegion.java (revision 0)
@@ -1,61 +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.regions;
-
-import java.util.Properties;
-
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.hibernate.strategy.EhcacheAccessStrategyFactory;
-
-import org.hibernate.cache.CacheDataDescription;
-import org.hibernate.cache.CacheException;
-import org.hibernate.cache.EntityRegion;
-import org.hibernate.cache.access.AccessType;
-import org.hibernate.cache.access.EntityRegionAccessStrategy;
-import org.hibernate.cfg.Settings;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * An entity region specific wrapper around an Ehcache instance.
- *
- * This implementation returns Ehcache specific access strategy instances for all the non-transactional access types. Transactional access
- * is not supported.
- *
- * @author Chris Dennis
- * @author Abhishek Sanoujam
- */
-public class EhcacheEntityRegion extends EhcacheTransactionalDataRegion implements EntityRegion {
-
- private static final Logger LOG = LoggerFactory.getLogger(EhcacheEntityRegion.class);
-
- /**
- * Constructs an EhcacheEntityRegion around the given underlying cache.
- *
- * @param accessStrategyFactory
- */
- public EhcacheEntityRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache underlyingCache, Settings settings,
- CacheDataDescription metadata, Properties properties) {
- super(accessStrategyFactory, underlyingCache, settings, metadata, properties);
- }
-
- /**
- * {@inheritDoc}
- */
- public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException {
- return accessStrategyFactory.createEntityRegionAccessStrategy(this, accessType);
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/config/generator/DecoratedCacheConfigTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/config/generator/DecoratedCacheConfigTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/config/generator/DecoratedCacheConfigTest.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.config.generator;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import junit.framework.Assert;
-import net.sf.ehcache.CacheManager;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.terracotta.test.categories.CheckShorts;
-
-@Category(CheckShorts.class)
-public class DecoratedCacheConfigTest {
-
- private static final List ALL_CACHE_NAMES = Arrays.asList(new String[] {"noDecoratorCache", "oneDecoratorCache",
- "oneDecoratorCacheFirst", "twoDecoratorCache", "twoDecoratorCacheSecond", "twoDecoratorCacheFirst"});
-
- @Test
- public void testDecoratedCacheConfig() {
- CacheManager cm = CacheManager.newInstance(DecoratedCacheConfigTest.class.getClassLoader().getResource(
- "ehcache-decorator-noname-test.xml"));
- try {
- List names = new ArrayList(Arrays.asList(cm.getCacheNames()));
- names.removeAll(ALL_CACHE_NAMES);
- Assert.assertEquals("This list should be empty - " + names, 0, names.size());
- // System.out.println("Original config: " + cm.getOriginalConfigurationText());
- String text = cm.getActiveConfigurationText();
- // System.out.println("Cache manager config: " + text);
- for (String name : ALL_CACHE_NAMES) {
- Assert.assertTrue("Config not generated for cache name: " + name, text.contains("name=\"" + name + "\""));
- String cacheConfigTest = cm.getActiveConfigurationText(name);
- // System.out.println("Config for cache: '"+name+"': " + cacheConfigTest);
- Assert.assertTrue("Config not generated for cache name: " + name + ", with explicit call: ",
- cacheConfigTest.contains("name=\"" + name + "\""));
- }
-
- } finally {
- cm.shutdown();
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/management-ehcache-impl/management-ehcache-impl-v2/src/main/java/net/sf/ehcache/management/service/impl/CacheStatisticSampleEntityBuilderV2.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/management-ehcache-impl/management-ehcache-impl-v2/src/main/java/net/sf/ehcache/management/service/impl/CacheStatisticSampleEntityBuilderV2.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/management-ehcache-impl/management-ehcache-impl-v2/src/main/java/net/sf/ehcache/management/service/impl/CacheStatisticSampleEntityBuilderV2.java (revision 0)
@@ -1,162 +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 java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import net.sf.ehcache.management.resource.CacheStatisticSampleEntityV2;
-import net.sf.ehcache.management.sampled.CacheSampler;
-import net.sf.ehcache.management.service.AccessorPrefix;
-import net.sf.ehcache.util.counter.sampled.SampledCounter;
-import net.sf.ehcache.util.counter.sampled.TimeStampedCounterValue;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.terracotta.management.resource.AgentEntityV2;
-
-/**
- * A builder for {@link CacheStatisticSampleEntityV2} resource objects.
- *
- * @author brandony
- */
-final class CacheStatisticSampleEntityBuilderV2 {
- private static final Logger LOG = LoggerFactory.getLogger(CacheStatisticSampleEntityBuilderV2.class);
-
- private static final String SAMPLE_SUFFIX = "Sample";
-
- private final Set sampleNames;
-
- private final Map> samplersByCMName = new HashMap>();
-
- static CacheStatisticSampleEntityBuilderV2 createWith(Set statisticSampleName) {
- return new CacheStatisticSampleEntityBuilderV2(statisticSampleName);
- }
-
- private CacheStatisticSampleEntityBuilderV2(Set sampleNames) {
- this.sampleNames = sampleNames;
- }
-
- CacheStatisticSampleEntityBuilderV2 add(CacheSampler sampler,
- String cacheManagerName) {
- addSampler(sampler, cacheManagerName);
- return this;
- }
-
- Collection build() {
- Collection csses = new ArrayList();
-
- for (Map.Entry> entry : samplersByCMName.entrySet()) {
- for (CacheSampler sampler : entry.getValue()) {
- if (sampleNames == null) {
- for (Method m : CacheSampler.class.getMethods()) {
- if (AccessorPrefix.isAccessor(m.getName()) && SampledCounter.class.isAssignableFrom(m.getReturnType())) {
- CacheStatisticSampleEntityV2 csse = makeStatResource(m, sampler, entry.getKey());
- if (csse != null) {
- csses.add(csse);
- }
- }
- }
- } else {
- for (String sampleName : sampleNames) {
- Method sampleMethod;
- try {
- sampleMethod = CacheSampler.class.getMethod(AccessorPrefix.get + sampleName + SAMPLE_SUFFIX);
- } catch (NoSuchMethodException e) {
- LOG.warn("A statistic sample with the name '{}' does not exist.", sampleName);
- continue;
- }
-
- if (SampledCounter.class.isAssignableFrom(sampleMethod.getReturnType())) {
- CacheStatisticSampleEntityV2 csse = makeStatResource(sampleMethod, sampler, entry.getKey());
- if (csse != null) {
- csses.add(csse);
- }
- }
- }
- }
- }
- }
-
- return csses;
- }
-
- private CacheStatisticSampleEntityV2 makeStatResource(Method sampleMethod,
- CacheSampler sampler,
- String cmName) {
- SampledCounter sCntr;
- try {
- sCntr = SampledCounter.class.cast(sampleMethod.invoke(sampler));
- } catch (IllegalAccessException e) {
- LOG.warn("Failed to invoke method '{}' while constructing entity due to access restriction.",
- sampleMethod.getName());
- sCntr = null;
- } catch (InvocationTargetException e) {
- LOG.warn(String.format("Failed to invoke method %s while constructing entity.", sampleMethod.getName()), e);
- sCntr = null;
- }
-
- if (sCntr != null) {
- CacheStatisticSampleEntityV2 csse = new CacheStatisticSampleEntityV2();
- csse.setCacheManagerName(cmName);
- csse.setName(sampler.getCacheName());
- csse.setAgentId(AgentEntityV2.EMBEDDED_AGENT_ID);
- // csse.setVersion(this.getClass().getPackage().getImplementationVersion());
- csse.setStatName(AccessorPrefix.trimPrefix(sampleMethod.getName()).replace(SAMPLE_SUFFIX, ""));
-
- TimeStampedCounterValue[] tscvs;
- if (getExcludedMethodNames(sampler).contains(sampleMethod.getName())) {
- tscvs = new TimeStampedCounterValue[0];
- } else {
- tscvs = sCntr.getAllSampleValues();
- }
-
- Map statValueByTime = new TreeMap();
- csse.setStatValueByTimeMillis(statValueByTime);
-
- for (TimeStampedCounterValue tscv : tscvs) {
- statValueByTime.put(tscv.getTimestamp(), tscv.getCounterValue());
- }
- return csse;
- }
-
- return null;
- }
-
- private Set getExcludedMethodNames(CacheSampler sampler) {
- if (sampler.isLocalHeapCountBased()) {
- return Collections.singleton("getLocalHeapSizeInBytesSample");
- }
- return Collections.emptySet();
- }
-
- private void addSampler(CacheSampler sampler,
- String cacheManagerName) {
- if (sampler == null) {
- throw new IllegalArgumentException("sampler == null");
- }
-
- if (cacheManagerName == null) {
- throw new IllegalArgumentException("cacheManagerName == null");
- }
-
- Set samplers = samplersByCMName.get(cacheManagerName);
-
- if (samplers == null) {
- samplers = new HashSet();
- samplersByCMName.put(cacheManagerName, samplers);
- }
-
- samplers.add(sampler);
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/hibernate/domain/Person.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/hibernate/domain/Person.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/hibernate/domain/Person.java (revision 0)
@@ -1,108 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-
-package org.terracotta.modules.ehcache.hibernate.domain;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-public class Person {
-
- private Long id;
- private int age;
- private String firstname;
- private String lastname;
- private List events = new ArrayList(); // list semantics, e.g., indexed
- private Set emailAddresses = new HashSet();
- private Set phoneNumbers = new HashSet();
- private List talismans = new ArrayList(); // a Bag of good-luck charms.
-
- public Person() {
- //
- }
-
- public List getEvents() {
- return events;
- }
-
- protected void setEvents(List events) {
- this.events = events;
- }
-
- public void addToEvent(Event event) {
- this.getEvents().add(event);
- event.getParticipants().add(this);
- }
-
- public void removeFromEvent(Event event) {
- this.getEvents().remove(event);
- event.getParticipants().remove(this);
- }
-
- public int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public String getFirstname() {
- return firstname;
- }
-
- public void setFirstname(String firstname) {
- this.firstname = firstname;
- }
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getLastname() {
- return lastname;
- }
-
- public void setLastname(String lastname) {
- this.lastname = lastname;
- }
-
- public Set getEmailAddresses() {
- return emailAddresses;
- }
-
- public void setEmailAddresses(Set emailAddresses) {
- this.emailAddresses = emailAddresses;
- }
-
- public Set getPhoneNumbers() {
- return phoneNumbers;
- }
-
- public void setPhoneNumbers(Set phoneNumbers) {
- this.phoneNumbers = phoneNumbers;
- }
-
- public void addTalisman(String name) {
- talismans.add(name);
- }
-
- public List getTalismans() {
- return talismans;
- }
-
- public void setTalismans(List talismans) {
- this.talismans = talismans;
- }
-
- public String toString() {
- return getFirstname() + " " + getLastname();
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/ExpiredTransactionIDImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/ExpiredTransactionIDImpl.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/ExpiredTransactionIDImpl.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.transaction;
-
-
-/**
- * @author Ludovic Orban
- */
-public class ExpiredTransactionIDImpl extends TransactionIDImpl {
-
- /**
- * Create an expired transaction ID
- * @param transactionId the non-expired transaction ID to copy
- */
- public ExpiredTransactionIDImpl(TransactionIDImpl transactionId) {
- super(transactionId);
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/DefaultAsyncConfig.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/DefaultAsyncConfig.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/DefaultAsyncConfig.java (revision 0)
@@ -1,78 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.async;
-
-import java.util.concurrent.TimeUnit;
-
-public class DefaultAsyncConfig implements AsyncConfig {
- private final static AsyncConfig INSTANCE = new DefaultAsyncConfig();
-
- public final static long WORK_DELAY = TimeUnit.SECONDS.toMillis(1L); // 1 second
- public final static long MAX_ALLOWED_FALLBEHIND = TimeUnit.SECONDS.toMillis(2L); // 2 seconds
- public final static int BATCH_SIZE = 1;
- public final static boolean BATCHING_ENABLED = false;
- public final static boolean SYNCHRONOUS_WRITE = false;
- public final static int RETRY_ATTEMPTS = 0;
- public final static long RETRY_ATTEMPT_DELAY = TimeUnit.SECONDS.toMillis(1L); // 1 second
- public final static int RATE_LIMIT = 0;
- public final static int MAX_QUEUE_SIZE = 0;
-
- /**
- * Return an {@code AsyncConfig} instance representing the default configuration.
- *
- * @return the default configuration
- */
- public static AsyncConfig getInstance() {
- return INSTANCE;
- }
-
- protected DefaultAsyncConfig() {
- // private constructor for singleton
- }
-
- @Override
- public long getWorkDelay() {
- return WORK_DELAY;
- }
-
- @Override
- public long getMaxAllowedFallBehind() {
- return MAX_ALLOWED_FALLBEHIND;
- }
-
- @Override
- public int getBatchSize() {
- return BATCH_SIZE;
- }
-
- @Override
- public boolean isBatchingEnabled() {
- return BATCHING_ENABLED;
- }
-
- @Override
- public boolean isSynchronousWrite() {
- return SYNCHRONOUS_WRITE;
- }
-
- @Override
- public int getRetryAttempts() {
- return RETRY_ATTEMPTS;
- }
-
- @Override
- public long getRetryAttemptDelay() {
- return RETRY_ATTEMPT_DELAY;
- }
-
- @Override
- public int getRateLimit() {
- return RATE_LIMIT;
- }
-
- @Override
- public int getMaxQueueSize() {
- return MAX_QUEUE_SIZE;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/l1bm/L1BMOnHeapReadWriteTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/l1bm/L1BMOnHeapReadWriteTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/l1bm/L1BMOnHeapReadWriteTest.java (revision 0)
@@ -1,149 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.l1bm;
-
-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 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.Random;
-import java.util.concurrent.BrokenBarrierException;
-
-import junit.framework.Assert;
-
-public class L1BMOnHeapReadWriteTest extends AbstractCacheTestBase {
- private static final int NODE_COUNT = 2;
- private static final int NUM_OF_ELEMENTS = 1000;
- private static final int NUM_OF_THREADS = 10;
- private static final int WRITE_PERCENTAGE = 5;
-
- public L1BMOnHeapReadWriteTest(TestConfig testConfig) {
- super(testConfig, L1BMOnHeapReadWriteTestApp.class, L1BMOnHeapReadWriteTestApp.class);
- }
-
- public static class L1BMOnHeapReadWriteTestApp extends ClientBase {
- private final ToolkitBarrier barrier;
-
- public L1BMOnHeapReadWriteTestApp(String[] args) {
- super(args);
- this.barrier = getClusteringToolkit().getBarrier("test-barrier", NODE_COUNT);
- }
-
- public static void main(String[] args) {
- new L1BMOnHeapReadWriteTestApp(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- boolean shouldWait = true;
- Cache eventualWithStatsCache = createCache("eventualWithStatsCache", cacheManager, "EVENTUAL", true);
- testL1BigMemorySanity(eventualWithStatsCache, shouldWait);
- eventualWithStatsCache.removeAll();
-
- Cache eventualWithoutStatsCache = createCache("eventualWithoutStatsCache", cacheManager, "EVENTUAL", false);
- testL1BigMemorySanity(eventualWithoutStatsCache, shouldWait);
- eventualWithoutStatsCache.removeAll();
-
- shouldWait = false;
- Cache strongWithStatsCache = createCache("strongWithStatsCache", cacheManager, "STRONG", true);
- testL1BigMemorySanity(strongWithStatsCache, shouldWait);
- strongWithStatsCache.removeAll();
-
- shouldWait = false;
- Cache strongWithoutStatsCache = createCache("strongWithoutStatsCache", cacheManager, "STRONG", false);
- testL1BigMemorySanity(strongWithoutStatsCache, shouldWait);
- strongWithoutStatsCache.removeAll();
- }
-
- private void testL1BigMemorySanity(Cache cache, boolean shouldWait) throws InterruptedException,
- BrokenBarrierException {
- int index = barrier.await();
- if (index == 0) {
- System.out.println("XXXXXX putting " + NUM_OF_ELEMENTS + " in the cache");
- for (int i = 0; i < NUM_OF_ELEMENTS; i++) {
- cache.put(new Element("key" + i, "val" + i));
- }
- System.out.println("XXXXX done with putting " + cache.getSize() + " entries");
- }
- barrier.await();
- if (shouldWait) {
- while (cache.getSize() != NUM_OF_ELEMENTS) {
- Thread.sleep(1000);
- }
- }
- Assert.assertEquals(NUM_OF_ELEMENTS, cache.getSize());
- System.out.println("XXXXXX client " + index + " cache size: " + cache.getSize() + " local: "
- + cache.getStatistics().getLocalHeapSize());
- if (index == 0) {
- Assert.assertTrue(cache.getStatistics().getLocalHeapSize() > 0);
- } else {
- Assert.assertEquals(0, cache.getStatistics().getLocalHeapSize());
- }
-
- System.out.println("XXXXX starting test threads....");
- Thread ths[] = new Thread[NUM_OF_THREADS];
- for (int i = 0; i < NUM_OF_THREADS; i++) {
- ths[i] = new Thread(new TestThread(cache, i, index), "testThread" + i);
- ths[i].start();
- }
-
- for (Thread th : ths) {
- th.join();
- }
- barrier.await();
- System.out.println("XXXXXX done with " + cache.getName());
- }
-
- private Cache createCache(String cacheName, CacheManager cm, String consistency, boolean isWithStats) {
- CacheConfiguration cacheConfiguration = new CacheConfiguration();
- cacheConfiguration.setName(cacheName);
- cacheConfiguration.setMaxBytesLocalHeap(10485760L);
-
- TerracottaConfiguration tcConfiguration = new TerracottaConfiguration();
- tcConfiguration.setConsistency(consistency);
- cacheConfiguration.addTerracotta(tcConfiguration);
-
- Cache cache = new Cache(cacheConfiguration);
- cm.addCache(cache);
- return cache;
- }
-
- private static class TestThread implements Runnable {
- private final long TIME_TO_RUN = 1 * 60 * 1000;
- private final Cache cache;
- private final int threadIndex;
- private final int clientIndex;
-
- public TestThread(Cache cache, int threadIndex, int clientIndex) {
- this.cache = cache;
- this.threadIndex = threadIndex;
- this.clientIndex = clientIndex;
- }
-
- @Override
- public void run() {
- System.out.println("XXXXX client[" + clientIndex + "] started thread " + threadIndex);
- long start = System.currentTimeMillis();
- Random rand = new Random(start);
- while (System.currentTimeMillis() - start < TIME_TO_RUN) {
- if (rand.nextInt(100) < WRITE_PERCENTAGE) {
- this.cache.put(new Element("key" + rand.nextInt(NUM_OF_ELEMENTS), "val" + rand.nextInt(NUM_OF_ELEMENTS)));
- } else {
- String key = "key" + rand.nextInt(NUM_OF_ELEMENTS);
- Assert.assertNotNull("value for " + key + " is null", this.cache.get(key));
- }
- }
- }
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/wan/Watchable.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/wan/Watchable.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/wan/Watchable.java (revision 0)
@@ -1,32 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-
-package org.terracotta.modules.ehcache.wan;
-
-/**
- * @author Eugene Shelestovich
- */
-public interface Watchable {
-
- /**
- *
- */
- void goLive();
-
- void die();
-
- /**
- * Checks whether or not a given Watchable is alive.
- *
- * @return {@code true} if a given Watchable is alive, {@code false} otherwise
- */
- boolean probeLiveness();
-
- /**
- * Returns a name which uniquely identifies the Watchable.
- *
- * @return unique name
- */
- String name();
-}
Index: rctags/ehcache-2.10.7.0.58/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheConfigEntityV2.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheConfigEntityV2.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheConfigEntityV2.java (revision 0)
@@ -1,44 +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 org.terracotta.management.resource.AbstractEntityV2;
-
-/**
- *
- * A {@link AbstractEntityV2} representing a cache configuration resource from the management API.
- *
- *
- * @author brandony
- *
- */
-public class CacheConfigEntityV2 extends AbstractEntityV2 {
- private String cacheName;
- private String cacheManagerName;
-
- private String xml;
-
- public String getCacheManagerName() {
- return cacheManagerName;
- }
-
- public void setCacheManagerName(String cacheManagerName) {
- this.cacheManagerName = cacheManagerName;
- }
-
- public String getXml() {
- return xml;
- }
-
- public void setXml(String xml) {
- this.xml = xml;
- }
-
- public String getCacheName() {
- return cacheName;
- }
-
- public void setCacheName(String cacheName) {
- this.cacheName = cacheName;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/blocking/UpdatingSelfPopulatingCacheTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/blocking/UpdatingSelfPopulatingCacheTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/blocking/UpdatingSelfPopulatingCacheTest.java (revision 0)
@@ -1,147 +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;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheException;
-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.DiskStoreConfiguration;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
-
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.sameInstance;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.fail;
-
-
-/**
- * Test cases for the {@link UpdatingSelfPopulatingCache}.
- *
- * @author Greg Luck
- * @version $Id: UpdatingSelfPopulatingCacheTest.java 8281 2013-10-04 08:41:51Z ljacomet $
- */
-public class UpdatingSelfPopulatingCacheTest {
-
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
- private CacheManager cacheManager;
- private Cache cache;
-
- @Before
- public void setUp() throws Exception {
- Configuration configuration = new Configuration();
- configuration.name("upSelfPopCM")
- .diskStore(new DiskStoreConfiguration().path(temporaryFolder.newFolder().getAbsolutePath()))
- .addCache(new CacheConfiguration("cache", 1).timeToIdleSeconds(2)
- .timeToLiveSeconds(5)
- .overflowToDisk(true)
- .diskPersistent(true));
- cacheManager = CacheManager.newInstance(configuration);
- cache = cacheManager.getCache("cache");
- }
-
- @After
- public void tearDown() {
- cacheManager.shutdown();
- }
-
- /**
- * Tests fetching an entry, and then an update.
- */
- @Test
- public void testFetchAndUpdate() throws Exception {
- final Object value = "value";
- final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value);
- UpdatingSelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory);
-
-
- //test null
- Element element = selfPopulatingCache.get(null);
-
- // Lookup
- element = selfPopulatingCache.get("key");
- assertThat(element.getObjectValue(), sameInstance(value));
- assertThat(factory.getCount(), is(2));
-
- Object actualValue = selfPopulatingCache.get("key").getObjectValue();
- assertThat(actualValue, sameInstance(value));
- assertThat(factory.getCount(), is(3));
-
- actualValue = selfPopulatingCache.get("key").getObjectValue();
- assertThat(actualValue, sameInstance(value));
- assertThat(factory.getCount(), is(4));
- }
-
- /**
- * Tests when fetch fails.
- */
- @Test
- public void testFetchFail() throws Exception {
- final Exception exception = new Exception("Failed.");
- final UpdatingCacheEntryFactory factory = new UpdatingCacheEntryFactory() {
- public Object createEntry(final Object key)
- throws Exception {
- throw exception;
- }
-
- public void updateEntryValue(Object key, Object value)
- throws Exception {
- throw exception;
- }
- };
-
- UpdatingSelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory);
-
- // Lookup
- try {
- selfPopulatingCache.get("key");
- fail();
- } catch (final Exception e) {
- // Check the error
- assertEquals("Could not update object for cache entry with key \"key\".", e.getMessage());
- }
- }
-
- /**
- * Tests refreshing the entries.
- */
- @Test
- public void testRefresh() throws Exception {
- final String value = "value";
- final CountingCacheEntryFactory factory = new CountingCacheEntryFactory(value);
- UpdatingSelfPopulatingCache selfPopulatingCache = new UpdatingSelfPopulatingCache(cache, factory);
-
- // Refresh
- try {
- selfPopulatingCache.refresh();
- fail();
- } catch (CacheException e) {
- //expected.
- assertEquals("UpdatingSelfPopulatingCache objects should not be refreshed.", e.getMessage());
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/search/DynamicAttributeExtractorTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/search/DynamicAttributeExtractorTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/search/DynamicAttributeExtractorTest.java (revision 0)
@@ -1,180 +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;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import static junit.framework.Assert.*;
-
-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.SearchAttribute;
-import net.sf.ehcache.config.Searchable;
-import net.sf.ehcache.search.Person.Gender;
-import net.sf.ehcache.search.aggregator.Aggregators;
-import net.sf.ehcache.search.attribute.DynamicAttributesExtractor;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class DynamicAttributeExtractorTest {
-
- private CacheManager cm;
- private Ehcache cache;
-
- private Attribute age;
- private Attribute name;
- private Attribute dept;
-
- private final Attribute gender = new Attribute("gender"); // dynamically extracted
-
- private final DynamicAttributesExtractor indexer = new DynamicAttributesExtractor() {
-
- @Override
- public Map attributesFor(Element element) {
- Person p = (Person) element.getObjectValue();
- return Collections.singletonMap("gender", p.getGender());
- }
- };
-
- @Before
- public void setUp() throws Exception {
- Configuration cfg = new Configuration();
- CacheConfiguration cacheCfg = new CacheConfiguration("searchCache", 1000);
- Searchable s = new Searchable();
- s.keys(true);
- s.allowDynamicIndexing(true);
- s.addSearchAttribute(new SearchAttribute().name("age"));
- s.addSearchAttribute(new SearchAttribute().name("name"));
- s.addSearchAttribute(new SearchAttribute().name("department"));
- cacheCfg.searchable(s);
- cfg.addCache(cacheCfg);
-
- cm = new CacheManager(cfg);
- cache = cm.getCache("searchCache");
- cache.registerDynamicAttributesExtractor(indexer);
- SearchTestUtil.populateData(cache);
-
- age = cache.getSearchAttribute("age");
- dept = cache.getSearchAttribute("department");
- name = cache.getSearchAttribute("name");
- }
-
- @After
- public void tearDown() throws Exception {
- cm.shutdown();
- }
-
- private void verifyOrdered(Query q, int... expectedKeys) {
- Results results = q.execute();
- assertEquals(expectedKeys.length, results.size());
- if (expectedKeys.length == 0) {
- assertFalse(results.hasKeys());
- } else {
- assertTrue(results.hasKeys());
- }
- assertFalse(results.hasAttributes());
-
- int i = 0;
- for (Result result : results.all()) {
-
- int key = (Integer) result.getKey();
- assertEquals(expectedKeys[i++], key);
- }
- }
-
- private void verify(Query q, Integer... expectedKeys) {
- Results results = q.execute();
- assertEquals(expectedKeys.length, results.size());
- if (expectedKeys.length == 0) {
- assertFalse(results.hasKeys());
- } else {
- assertTrue(results.hasKeys());
- }
- assertFalse(results.hasAttributes());
-
- Set keys = new HashSet(Arrays.asList(expectedKeys));
- for (Result result : results.all()) {
-
- int key = (Integer) result.getKey();
- if (!keys.remove(key)) {
- throw new AssertionError("unexpected key: " + key);
- }
- }
- }
-
- @Test
- public void testBasicCriteria() {
- Query q = cache.createQuery();
- q.addCriteria(gender.eq(Gender.MALE));
- q.includeKeys();
- verify(q, 1, 3, 4);
-
- q.addCriteria(age.lt(31));
- verify(q, 4);
-
- q = cache.createQuery();
- q.includeKeys();
- q.addCriteria(gender.ne(Gender.MALE).and(dept.ilike("eng?")));
- verify(q, 2);
-
- }
-
- @Test
- public void testSorting() {
- Query q = cache.createQuery().includeKeys();
- q.addOrderBy(gender, Direction.DESCENDING);
- q.addOrderBy(name, Direction.ASCENDING);
- verifyOrdered(q, 2, 3, 4, 1);
- }
-
- @Test
- public void testGroupBy() {
- Query q = cache.createQuery().addGroupBy(gender);
- q.includeAggregator(age.max());
- Results res = q.execute();
- assertEquals(2, res.size());
- }
-
- @Test
- public void testAggregators() {
- Query q = cache.createQuery().addCriteria(gender.eq(Gender.MALE));
- q.includeAggregator(Aggregators.count());
- q.addCriteria(dept.ilike("sales*").not());
- Results res = q.execute();
- assertEquals(1, res.size());
- assertEquals(3, res.all().get(0).getAggregatorResults().get(0));
- }
-
- @Test
- public void testAttributeSelect() {
- Query q = cache.createQuery().includeAttribute(gender, age).addCriteria(gender.ne(Gender.MALE));
- Results res = q.execute();
- assertEquals(1, res.size());
- Result r = res.all().get(0);
- assertEquals(Gender.FEMALE, r.getAttribute(gender));
- assertEquals(23, r.getAttribute(age).intValue());
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapElementTTLExpressTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapElementTTLExpressTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapElementTTLExpressTest.java (revision 0)
@@ -1,37 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.servermap;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-
-import com.tc.properties.TCPropertiesConsts;
-import com.tc.test.config.model.TestConfig;
-
-import java.util.Iterator;
-
-public class ServerMapElementTTLExpressTest extends AbstractCacheTestBase {
-
- public ServerMapElementTTLExpressTest(TestConfig testConfig) {
- super("/servermap/basic-servermap-cache-test.xml", testConfig, ServerMapElementTTLExpressTestClient.class);
- testConfig.setDgcEnabled(true);
- testConfig.setDgcIntervalInSec(60);
- testConfig.addTcProperty("ehcache.evictor.logging.enabled", "true");
- testConfig.addTcProperty(TCPropertiesConsts.EHCACHE_EVICTOR_LOGGING_ENABLED, "true");
- testConfig.addTcProperty(TCPropertiesConsts.EHCACHE_STORAGESTRATEGY_DCV2_EVICT_UNEXPIRED_ENTRIES_ENABLED, "false");
- testConfig.addTcProperty(TCPropertiesConsts.EHCACHE_STORAGESTRATEGY_DCV2_PERELEMENT_TTI_TTL_ENABLED, "true");
-
- final Iterator iter = testConfig.getClientConfig().getExtraClientJvmArgs().iterator();
- while (iter.hasNext()) {
- final String prop = iter.next();
- if (prop.contains("ehcache.storageStrategy.dcv2.localcache.enabled")) {
- // remove it and always disable localcache for this test
- iter.remove();
- }
- }
- // always disable local cache
- testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.ehcache.storageStrategy.dcv2.localcache.enabled=false");
- testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.ehcache.evictor.logging.enabled=true");
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/TxCopyStrategyHandler.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/TxCopyStrategyHandler.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/TxCopyStrategyHandler.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.store;
-
-import net.sf.ehcache.Element;
-import net.sf.ehcache.store.compound.ReadWriteCopyStrategy;
-import net.sf.ehcache.transaction.SoftLockID;
-
-/**
- * @author Alex Snaps
- */
-public class TxCopyStrategyHandler extends CopyStrategyHandler {
-
- /**
- * Creates a TxCopyStrategyHandler based on the copy configuration
- *
- * @param copyOnRead copy on read flag
- * @param copyOnWrite copy on write flag
- * @param copyStrategy the copy strategy to use
- * @param loader
- */
- public TxCopyStrategyHandler(final boolean copyOnRead, final boolean copyOnWrite,
- final ReadWriteCopyStrategy copyStrategy, final ClassLoader loader) {
- super(copyOnRead, copyOnWrite, copyStrategy, loader);
- }
-
- @Override
- public Element copyElementForReadIfNeeded(final Element element) {
- final Object objectValue = element.getObjectValue();
- if (objectValue instanceof SoftLockID) {
- return super.copyElementForReadIfNeeded(((SoftLockID)objectValue).getOldElement());
- }
- return super.copyElementForReadIfNeeded(element);
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/bootstrap/BootstrapCacheLoader.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/bootstrap/BootstrapCacheLoader.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/bootstrap/BootstrapCacheLoader.java (revision 0)
@@ -1,48 +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.bootstrap;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-
-/**
- * @author Greg Luck
- * @version $Id: BootstrapCacheLoader.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public interface BootstrapCacheLoader {
-
- /**
- * Instructs the loader to load the given cache
- * @param cache cache to load
- */
- void load(Ehcache cache) throws CacheException;
-
- /**
- *
- * @return true if this bootstrap loader is asynchronous
- */
- boolean isAsynchronous();
-
- /**
- * Clones the loader
- *
- * @return clone of this instance
- * @throws CloneNotSupportedException if the object's class does not support the {@code Cloneable} interface.
- */
- Object clone() throws CloneNotSupportedException;
-
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/ToolkitInstanceFactoryImplTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/ToolkitInstanceFactoryImplTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/ToolkitInstanceFactoryImplTest.java (revision 0)
@@ -1,433 +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;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.not;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyString;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.inOrder;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyNoMoreInteractions;
-import static org.mockito.Mockito.when;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.mockito.ArgumentCaptor;
-import org.mockito.InOrder;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.terracotta.modules.ehcache.wan.WANUtil;
-import org.terracotta.modules.ehcache.wan.Watchdog;
-import org.terracotta.test.categories.CheckShorts;
-import org.terracotta.toolkit.Toolkit;
-import org.terracotta.toolkit.ToolkitFeatureType;
-import org.terracotta.toolkit.collections.ToolkitMap;
-import org.terracotta.toolkit.concurrent.locks.ToolkitLock;
-import org.terracotta.toolkit.concurrent.locks.ToolkitReadWriteLock;
-import org.terracotta.toolkit.config.Configuration;
-import org.terracotta.toolkit.feature.NonStopFeature;
-import org.terracotta.toolkit.internal.ToolkitInternal;
-import org.terracotta.toolkit.internal.ToolkitLogger;
-import org.terracotta.toolkit.internal.cache.BufferingToolkitCache;
-import org.terracotta.toolkit.internal.cache.ToolkitCacheInternal;
-import org.terracotta.toolkit.nonstop.NonStopConfigurationRegistry;
-import org.terracotta.toolkit.store.ToolkitConfigFields;
-
-import com.terracotta.entity.ClusteredEntityManager;
-import com.terracotta.entity.EntityLockHandler;
-import com.terracotta.entity.ehcache.ClusteredCache;
-import com.terracotta.entity.ehcache.ClusteredCacheManager;
-import com.terracotta.entity.ehcache.ClusteredCacheManagerConfiguration;
-import com.terracotta.entity.ehcache.EhcacheEntitiesNaming;
-import com.terracotta.entity.ehcache.ToolkitBackedClusteredCacheManager;
-
-import java.io.Serializable;
-
-import junit.framework.Assert;
-
-/**
- * ToolkitInstanceFactoryImplTest
- */
-@Category(CheckShorts.class)
-public class ToolkitInstanceFactoryImplTest {
-
- private static final String CACHE_MANAGER_NAME = "CACHE_MANAGER_NAME";
- private static final String CACHE_NAME = "CACHE_NAME";
-
- @Mock private Toolkit toolkit;
- @Mock private WANUtil wanUtil;
- @Mock private Ehcache ehcache;
- @Mock private CacheManager cacheManager;
-
- private ToolkitInstanceFactoryImpl factory;
- private ToolkitCacheInternal resultantCache;
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
- toolkit = getMockToolkit();
- final ToolkitMap toolkitMap = mockMap();
- when(toolkit.getMap(anyString(), any(Class.class), any(Class.class))).thenReturn(toolkitMap);
- when(toolkit.getCache(anyString(), any(Configuration.class), any(Class.class)))
- .thenReturn(mock(BufferingToolkitCache.class));
- ToolkitReadWriteLock rwLock = mockReadWriteLock();
- when(toolkit.getReadWriteLock(any(String.class))).thenReturn(rwLock);
- makeToolkitReturnNonStopConfigurationRegistry();
-
- wanUtil = mock(WANUtil.class);
- final Watchdog wanWatchdog = mock(Watchdog.class);
- ehcache = mock(Ehcache.class);
- when(cacheManager.isNamed()).thenReturn(true);
- when(cacheManager.getName()).thenReturn(CACHE_MANAGER_NAME);
- when(ehcache.getCacheManager()).thenReturn(cacheManager);
- when(ehcache.getName()).thenReturn(CACHE_NAME);
- CacheConfiguration configuration = new CacheConfiguration().terracotta(new TerracottaConfiguration());
- when(ehcache.getCacheConfiguration()).thenReturn(configuration);
-
- ClusteredEntityManager clusteredEntityManager = mock(ClusteredEntityManager.class);
- ToolkitBackedClusteredCacheManager clusteredCacheManager = new ToolkitBackedClusteredCacheManager("aName", new ClusteredCacheManagerConfiguration(defaultCMConfig));
- clusteredCacheManager.setToolkit(toolkit);
- clusteredCacheManager.setEntityLockHandler(mock(EntityLockHandler.class));
- when(clusteredEntityManager.getRootEntity(any(String.class), any(Class.class))).thenReturn(clusteredCacheManager);
- when(clusteredEntityManager.getEntityLock(anyString())).thenReturn(mock(ToolkitReadWriteLock.class));
- factory = new ToolkitInstanceFactoryImpl(toolkit, clusteredEntityManager, wanUtil, wanWatchdog);
- factory.linkClusteredCacheManager(CACHE_MANAGER_NAME, null);
- }
-
- private ToolkitMap mockMap() {
- ToolkitMap map = mock(ToolkitMap.class);
- ToolkitReadWriteLock readWriteLock = mockReadWriteLock();
- when(map.getReadWriteLock()).thenReturn(readWriteLock);
- return map;
- }
-
- private ToolkitReadWriteLock mockReadWriteLock() {
- ToolkitReadWriteLock readWriteLock = mock(ToolkitReadWriteLock.class);
- ToolkitLock lock = mockLock();
- when(readWriteLock.readLock()).thenReturn(lock);
- when(readWriteLock.writeLock()).thenReturn(lock);
- return readWriteLock;
- }
-
- private ToolkitLock mockLock() {
- return when(mock(ToolkitLock.class).tryLock()).thenReturn(true).getMock();
- }
-
- @Test
- public void testGetOrCreateToolkitCacheForWanEnabled() throws Exception {
- whenCacheIsWanEnabled().callGetOrCreateToolkitCache().assertInstanceOfWanAwareToolkitCache(true);
- }
-
- @Test
- public void testGetOrCreateToolkitCacheForWanDisabled() throws Exception {
- whenCacheIsWanDisabled().callGetOrCreateToolkitCache().assertInstanceOfWanAwareToolkitCache(false);
- }
-
- @Test(expected = CacheException.class)
- public void testWanAwareToolkitCacheDoesNotSupportDynamicConfigChange() throws Exception {
- whenCacheIsWanEnabled().callGetOrCreateToolkitCache().assertInstanceOfWanAwareToolkitCache(true).updateTimeToLive();
- }
-
- @Test
- public void testMaxEntriesInCacheToMaxTotalCountTransformation() {
- CacheConfiguration configuration = new CacheConfiguration().terracotta(new TerracottaConfiguration()).maxEntriesInCache(10);
- forEhcacheConfig(configuration).callGetOrCreateToolkitCache().validateMaxTotalCountForToolkitCacheIs(10);
- }
-
- private void updateTimeToLive() {
- ehcache.getCacheConfiguration().setTimeToLiveSeconds(10);
- }
-
- private void validateMaxTotalCountForToolkitCacheIs(int maxTotalCount) {
- ArgumentCaptor captor = ArgumentCaptor.forClass(Configuration.class);
- verify(toolkit).getCache(anyString(), captor.capture(), eq(Serializable.class));
- assertThat(captor.getValue().getInt(ToolkitConfigFields.MAX_TOTAL_COUNT_FIELD_NAME), is(10));
- }
-
- private ToolkitInstanceFactoryImplTest forEhcacheConfig(CacheConfiguration configuration) {
- when(ehcache.getCacheConfiguration()).thenReturn(configuration);
- return this;
- }
-
-
- private void makeToolkitReturnNonStopConfigurationRegistry() {
- NonStopFeature feature = mock(NonStopFeature.class);
- when(toolkit.getFeature(any(ToolkitFeatureType.class))).thenReturn(feature);
- when(feature.getNonStopConfigurationRegistry()).thenReturn(mock(NonStopConfigurationRegistry.class));
- }
-
- /**
- * This test case was added while fixing DEV-9223. From now on, we assume that the default value for maxTotalCount in
- * Toolkit (-1), and the default value for maxEntriesInCache in EhCache (0) will be aligned. That is, they both will
- * mean the same thing. Currently they mean no-limit cache. If someone changes the default value of one of those, then
- * this test case will fail and we would need to handle it.
- */
- @Test
- public void testToolkitAndEhCacheDefaultsAreAligned() {
- Assert.assertEquals(0, CacheConfiguration.DEFAULT_MAX_ENTRIES_IN_CACHE);
- Assert.assertEquals(-1, ToolkitConfigFields.DEFAULT_MAX_TOTAL_COUNT);
- }
-
-
- private ToolkitInstanceFactoryImplTest assertInstanceOfWanAwareToolkitCache(boolean expectedResult) {
- Assert.assertEquals(expectedResult, (resultantCache instanceof WanAwareToolkitCache));
- return this;
- }
-
- private ToolkitInstanceFactoryImplTest callGetOrCreateToolkitCache() {
- resultantCache = factory.getOrCreateToolkitCache(ehcache);
- return this;
- }
-
- private ToolkitInstanceFactoryImplTest whenCacheIsWanEnabled() {
- when(wanUtil.isWanEnabledCache(CACHE_MANAGER_NAME, CACHE_NAME)).thenReturn(true);
- return this;
- }
-
- private ToolkitInstanceFactoryImplTest whenCacheIsWanDisabled() {
- when(wanUtil.isWanEnabledCache(CACHE_MANAGER_NAME, CACHE_NAME)).thenReturn(false);
- return this;
- }
-
- @Test
- public void testAddCacheEntityInfo() {
- factory.addCacheEntityInfo(CACHE_NAME, new CacheConfiguration(), "testTKCacheName");
- }
-
- @Test
- public void testRetrievingExistingClusteredCacheManagerEntity() {
- String name = "existing";
- net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
-
- Toolkit toolkit = getMockToolkit();
- when(toolkit.getMap(anyString(), eq(String.class), eq(ClusteredCache.class))).thenReturn(mock(ToolkitMap.class));
-
- ClusteredEntityManager clusteredEntityManager = mock(ClusteredEntityManager.class);
- ToolkitBackedClusteredCacheManager cacheManagerEntity = new ToolkitBackedClusteredCacheManager(name, new ClusteredCacheManagerConfiguration("test"));
- cacheManagerEntity.setEntityLockHandler(mock(EntityLockHandler.class));
- when(clusteredEntityManager.getRootEntity(name, ClusteredCacheManager.class))
- .thenReturn(cacheManagerEntity);
- when(clusteredEntityManager.getEntityLock(anyString())).thenReturn(mock(ToolkitReadWriteLock.class));
- ToolkitInstanceFactoryImpl toolkitInstanceFactory = new ToolkitInstanceFactoryImpl(getMockToolkit(),
- clusteredEntityManager);
-
- toolkitInstanceFactory.linkClusteredCacheManager(name, configuration);
- verify(clusteredEntityManager).getRootEntity(name, ClusteredCacheManager.class);
- verify(clusteredEntityManager).getEntityLock(anyString());
- verifyNoMoreInteractions(clusteredEntityManager);
- }
-
- @Test
- public void testCreatingNewClusteredCacheManagerEntity() {
- String name = "newCM";
-
- net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
-
- ClusteredEntityManager clusteredEntityManager = mock(ClusteredEntityManager.class);
- doAnswer(new Answer() {
- @Override
- public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
- Object[] arguments = invocationOnMock.getArguments();
- ((ToolkitBackedClusteredCacheManager)arguments[2]).setEntityLockHandler(mock(EntityLockHandler.class));
- return null;
- }
- }).when(clusteredEntityManager).addRootEntityIfAbsent(eq(name), eq(ClusteredCacheManager.class), any(ClusteredCacheManager.class));
- ToolkitReadWriteLock rwLock = mock(ToolkitReadWriteLock.class);
- ToolkitLock writeLock = mock(ToolkitLock.class);
- when(writeLock.tryLock()).thenReturn(true);
- when(rwLock.writeLock()).thenReturn(writeLock);
- when(clusteredEntityManager.getEntityLock(any(String.class))).thenReturn(rwLock);
-
- ToolkitInstanceFactoryImpl toolkitInstanceFactory = new ToolkitInstanceFactoryImpl(getMockToolkit(),
- clusteredEntityManager);
-
- toolkitInstanceFactory.linkClusteredCacheManager(name, configuration);
- verify(clusteredEntityManager).getRootEntity(name, ClusteredCacheManager.class);
- verify(clusteredEntityManager).getEntityLock(EhcacheEntitiesNaming.getCacheManagerLockNameFor(name));
- verify(clusteredEntityManager).addRootEntityIfAbsent(eq(name), any(Class.class), any(ClusteredCacheManager.class));
- verifyNoMoreInteractions(clusteredEntityManager);
- }
-
- @Test
- public void testTryingToCreateNewClusteredCacheManagerEntityButLooseRace() {
- String name = "newCM";
-
- net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
-
- ClusteredEntityManager clusteredEntityManager = mock(ClusteredEntityManager.class);
- when(clusteredEntityManager.addRootEntityIfAbsent(eq(name), any(Class.class), any(ClusteredCacheManager.class))).thenReturn(mock(ClusteredCacheManager.class));
- when(clusteredEntityManager.getRootEntity(name, ClusteredCacheManager.class)).thenReturn(null, mock(ClusteredCacheManager.class));
- ToolkitReadWriteLock rwLock = mock(ToolkitReadWriteLock.class);
- ToolkitLock writeLock = mock(ToolkitLock.class);
- when(writeLock.tryLock()).thenReturn(true);
- when(rwLock.writeLock()).thenReturn(writeLock);
- when(clusteredEntityManager.getEntityLock(any(String.class))).thenReturn(rwLock);
-
- ToolkitInstanceFactoryImpl toolkitInstanceFactory = new ToolkitInstanceFactoryImpl(getMockToolkit(),
- clusteredEntityManager);
-
- toolkitInstanceFactory.linkClusteredCacheManager(name, configuration);
- InOrder inOrder = inOrder(clusteredEntityManager);
- inOrder.verify(clusteredEntityManager).getRootEntity(name, ClusteredCacheManager.class);
- inOrder.verify(clusteredEntityManager).getEntityLock(EhcacheEntitiesNaming.getCacheManagerLockNameFor(name));
- inOrder.verify(clusteredEntityManager).addRootEntityIfAbsent(eq(name), any(Class.class), any(ClusteredCacheManager.class));
- verifyNoMoreInteractions(clusteredEntityManager);
- }
-
- @Test
- public void testConfigurationSavedContainsNoCachesAnymore() {
- String name = "newCM";
-
- net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
- configuration.addCache(new CacheConfiguration("test", 1));
-
- ClusteredEntityManager clusteredEntityManager = mock(ClusteredEntityManager.class);
- doAnswer(new Answer() {
- @Override
- public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
- Object[] arguments = invocationOnMock.getArguments();
- ((ToolkitBackedClusteredCacheManager)arguments[2]).setEntityLockHandler(mock(EntityLockHandler.class));
- return null;
- }
- }).when(clusteredEntityManager).addRootEntityIfAbsent(eq(name), eq(ClusteredCacheManager.class), any(ClusteredCacheManager.class));
- ToolkitReadWriteLock rwLock = mock(ToolkitReadWriteLock.class);
- ToolkitLock writeLock = mock(ToolkitLock.class);
- when(writeLock.tryLock()).thenReturn(true);
- when(rwLock.writeLock()).thenReturn(writeLock);
- when(clusteredEntityManager.getEntityLock(any(String.class))).thenReturn(rwLock);
-
- ToolkitInstanceFactoryImpl toolkitInstanceFactory = new ToolkitInstanceFactoryImpl(getMockToolkit(),
- clusteredEntityManager);
-
- toolkitInstanceFactory.linkClusteredCacheManager(name, configuration);
- ArgumentCaptor captor = ArgumentCaptor.forClass(ClusteredCacheManager.class);
- verify(clusteredEntityManager).addRootEntityIfAbsent(eq(name), any(Class.class), captor.capture());
-
- assertThat(captor.getValue().getConfiguration().getConfigurationAsText(), not(containsString(" captor = ArgumentCaptor.forClass(ClusteredCacheManager.class);
- verify(clusteredEntityManager).addRootEntityIfAbsent(eq(name), any(Class.class), captor.capture());
-
- assertThat(captor.getValue().getConfiguration().getConfigurationAsText(), containsString("name=\"" + name));
- }
-
- @Test
- public void testClusterRejoinedCacheManagerDestroyed() {
- Toolkit toolkit = getMockToolkit();
- ClusteredEntityManager entityManager = mock(ClusteredEntityManager.class);
- ToolkitInstanceFactoryImpl toolkitInstanceFactory = new ToolkitInstanceFactoryImpl(toolkit, entityManager);
-
- toolkitInstanceFactory.clusterRejoined();
-
- verify(entityManager).dispose();
- verify(toolkit).shutdown();
- }
-
- @Test
- public void testClusterRejoinedCMDestroyedBetweenGetAndLock() {
- Toolkit toolkit = getMockToolkit();
- ClusteredEntityManager entityManager = mock(ClusteredEntityManager.class);
- ClusteredCacheManager cmEntity = mock(ClusteredCacheManager.class);
- ClusteredCache cEntity = mock(ClusteredCache.class);
- when(cmEntity.getCache(CACHE_NAME)).thenReturn(cEntity);
-
- when(entityManager.getRootEntity(CACHE_MANAGER_NAME, ClusteredCacheManager.class)).thenReturn(cmEntity, cmEntity, null);
- when(entityManager.getEntityLock(any(String.class))).thenReturn(mock(ToolkitReadWriteLock.class));
-
- ToolkitInstanceFactoryImpl toolkitInstanceFactory = new ToolkitInstanceFactoryImpl(toolkit, entityManager);
- toolkitInstanceFactory.linkClusteredCacheManager(CACHE_MANAGER_NAME, null);
- toolkitInstanceFactory.addCacheEntityInfo(CACHE_NAME, null, EhcacheEntitiesNaming.getToolkitCacheNameFor(CACHE_MANAGER_NAME, CACHE_NAME));
-
- toolkitInstanceFactory.clusterRejoined();
-
- verify(cmEntity, times(2)).markInUse();
- verify(entityManager).dispose();
- verify(toolkit).shutdown();
- }
-
- private Toolkit getMockToolkit() {
- ToolkitInternal toolkitInternal = mock(ToolkitInternal.class);
- when(toolkitInternal.getLogger(anyString())).thenReturn(mock(ToolkitLogger.class));
-
- return toolkitInternal;
- }
-
- @Test
- public void testClusterRejoined() {
- Toolkit toolkit = getMockToolkit();
- ClusteredEntityManager entityManager = mock(ClusteredEntityManager.class);
- ClusteredCacheManager cmEntity = mock(ClusteredCacheManager.class);
- ClusteredCache cEntity = mock(ClusteredCache.class);
- when(cmEntity.getCache(CACHE_NAME)).thenReturn(cEntity);
-
- when(entityManager.getRootEntity(CACHE_MANAGER_NAME, ClusteredCacheManager.class)).thenReturn(cmEntity);
- when(entityManager.getEntityLock(any(String.class))).thenReturn(mock(ToolkitReadWriteLock.class));
-
- ToolkitInstanceFactoryImpl toolkitInstanceFactory = new ToolkitInstanceFactoryImpl(toolkit, entityManager);
- toolkitInstanceFactory.linkClusteredCacheManager(CACHE_MANAGER_NAME, null);
- toolkitInstanceFactory.addCacheEntityInfo(CACHE_NAME, null, EhcacheEntitiesNaming.getToolkitCacheNameFor(CACHE_MANAGER_NAME, CACHE_NAME));
-
- toolkitInstanceFactory.clusterRejoined();
-
- verify(cmEntity, times(2)).markInUse();
- verify(cmEntity, times(2)).markCacheInUse(cEntity);
- }
-
- private final String defaultCMConfig = "" +
- " " +
- " " +
- " ";
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/LocalRecoveryManager.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/LocalRecoveryManager.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/local/LocalRecoveryManager.java (revision 0)
@@ -1,90 +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.TransactionID;
-import net.sf.ehcache.transaction.TransactionIDFactory;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-/**
- * The local transactions mode recovery manager which is used to trigger full recovery of all
- * caches configured with local transaction mode.
- *
- * @author Ludovic Orban
- */
-public class LocalRecoveryManager {
-
- private final TransactionIDFactory transactionIdFactory;
- private final List localTransactionStores = new CopyOnWriteArrayList();
- private volatile Set previouslyRecoveredTransactionIDs = Collections.emptySet();
-
- /**
- * Create a LocalRecoveryManager instance
- * @param transactionIdFactory the TransactionIDFactory
- */
- public LocalRecoveryManager(TransactionIDFactory transactionIdFactory) {
- this.transactionIdFactory = transactionIdFactory;
- }
-
- /**
- * Register a LocalTransactionStore from the recovery manager
- * @param localTransactionStore the LocalTransactionStore
- */
- void register(LocalTransactionStore localTransactionStore) {
- localTransactionStores.add(localTransactionStore);
- }
-
- /**
- * Unregister a LocalTransactionStore from the recovery manager
- * @param localTransactionStore the LocalTransactionStore
- */
- void unregister(LocalTransactionStore localTransactionStore) {
- localTransactionStores.remove(localTransactionStore);
- }
-
- /**
- * Run recovery on all registered local transaction stores. The latter
- * are used internally by caches when they're configured with local transaction mode.
- * @return the set of recovered TransactionIDs
- */
- public Set recover() {
- Set recovered = new HashSet();
- // first ask all stores to cleanup their soft locks
- for (LocalTransactionStore localTransactionStore : localTransactionStores) {
- recovered.addAll(localTransactionStore.recover());
- }
- // then clear the transaction ID
- for (TransactionID transactionId : recovered) {
- transactionIdFactory.clear(transactionId);
- }
-
- previouslyRecoveredTransactionIDs = recovered;
- return recovered;
- }
-
- /**
- * Get the set of transaction IDs collected by the previous recover() call
- * @return the set of previously recovered TransactionIDs
- */
- public Set getPreviouslyRecoveredTransactionIDs() {
- return previouslyRecoveredTransactionIDs;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesOneL1Test.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesOneL1Test.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesOneL1Test.java (revision 0)
@@ -1,21 +0,0 @@
-package org.terracotta.ehcache.tests.servermap;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-
-import com.tc.test.config.model.TestConfig;
-
-public class ServerMapL2EvictionReachesOneL1Test extends AbstractCacheTestBase {
-
- public ServerMapL2EvictionReachesOneL1Test(TestConfig testConfig) {
- super("/servermap/servermap-l2-eviction-reaches-one-l1-test.xml", testConfig,
- ServerMapL2EvictionReachesOneL1TestClient.class, ServerMapL2EvictionReachesOneL1Verifier.class);
- testConfig.setDgcEnabled(true);
- testConfig.setDgcIntervalInSec(60);
- testConfig.addTcProperty("ehcache.evictor.logging.enabled", "true");
-
- testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.l1.cachemanager.enabled=false");
- testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.ehcache.evictor.logging.enabled=true");
- testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.l1.lockmanager.timeout.interval=60000");
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/DynamicCacheConfigurationTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/DynamicCacheConfigurationTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/DynamicCacheConfigurationTest.java (revision 0)
@@ -1,368 +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.CacheManager;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration;
-import net.sf.ehcache.config.TerracottaConfiguration.Consistency;
-import org.junit.Assert;
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-import org.terracotta.test.util.WaitUtil;
-import org.terracotta.toolkit.Toolkit;
-
-import com.tc.properties.TCPropertiesConsts;
-import com.tc.test.config.model.TestConfig;
-
-import java.util.concurrent.Callable;
-
-import static java.util.concurrent.TimeUnit.SECONDS;
-
-/**
- * @author cdennis
- */
-public class DynamicCacheConfigurationTest extends AbstractCacheTestBase {
- public DynamicCacheConfigurationTest(TestConfig testConfig) {
- super(testConfig, App.class);
- testConfig.addTcProperty(TCPropertiesConsts.L2_SERVERMAP_EVICTION_CLIENTOBJECT_REFERENCES_REFRESH_INTERVAL, "5000");
- testConfig.addTcProperty(TCPropertiesConsts.EHCACHE_EVICTOR_LOGGING_ENABLED, "true");
- }
-
- public static class App extends ClientBase {
- private static final double TOLERANCE = 0.1;
-
- public App(String[] args) {
- super(args);
- }
-
- public static void main(String[] args) {
- new App(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- testTTIChange(cacheManager);
- testTTLChange(cacheManager);
- testDiskCapacityChange(cacheManager);
- testMemoryCapacityChange(cacheManager);
- testTTIChangeWithCustomElements(cacheManager);
- testTTLChangeWithCustomElements(cacheManager);
- }
-
- private Cache createCache(String cacheName, int maxMemory, boolean eternal, long ttl, long tti) {
- return new Cache(new CacheConfiguration(cacheName, maxMemory)
- .eternal(eternal)
- .timeToLiveSeconds(ttl)
- .timeToIdleSeconds(tti)
- .clearOnFlush(true)
- .terracotta(new TerracottaConfiguration().clustered(true).consistency(Consistency.STRONG)
- .coherentReads(true).orphanEviction(true).orphanEvictionPeriod(4).localKeyCache(false)
- .localKeyCacheSize(0).copyOnRead(false)).logging(true));
- }
-
- private void testTTIChange(CacheManager manager) throws InterruptedException {
- Cache cache = createCache("testTTIChange", 10, false, 0, 10);
- manager.addCache(cache);
-
- cache.put(new Element("key1", new byte[0]));
- cache.put(new Element("key2", new byte[0]));
-
- SECONDS.sleep(6);
-
- cache.get("key2");
-
- SECONDS.sleep(6);
-
- Assert.assertNull(cache.get("key1"));
- Assert.assertNotNull(cache.get("key2"));
-
- cache.getCacheConfiguration().setTimeToIdleSeconds(20);
- long currentTime = System.currentTimeMillis();
-
- cache.put(new Element("key1", new byte[0]));
-
- SECONDS.sleep(15);
-
- Assert.assertNotNull(cache.get("key1"));
- if (System.currentTimeMillis() - currentTime < 20000 ) {
- Assert.assertNotNull(cache.get("key2"));
- } else {
- Assert.assertNull(cache.get("key2"));
- }
-
- SECONDS.sleep(25);
-
- Assert.assertNull(cache.get("key1"));
- Assert.assertNull(cache.get("key2"));
-
- cache.getCacheConfiguration().setTimeToIdleSeconds(4);
-
- cache.put(new Element("key1", new byte[0]));
- cache.put(new Element("key2", new byte[0]));
-
- SECONDS.sleep(8);
-
- Assert.assertNull(cache.get("key1"));
- Assert.assertNull(cache.get("key2"));
-
- cache.removeAll();
- }
-
- private void testTTLChange(CacheManager cm) throws InterruptedException {
- Cache cache = createCache("testTTLChange", 10, false, 10, 0);
- cm.addCache(cache);
-
- cache.put(new Element("key1", new byte[0]));
-
- SECONDS.sleep(6);
-
- Assert.assertNotNull(cache.get("key1"));
- cache.put(new Element("key2", new byte[0]));
-
- SECONDS.sleep(6);
-
- Assert.assertNull(cache.get("key1"));
- Assert.assertNotNull(cache.get("key2"));
-
- cache.getCacheConfiguration().setTimeToLiveSeconds(20);
-
- cache.put(new Element("key1", new byte[0]));
-
- SECONDS.sleep(8);
-
- Assert.assertNotNull(cache.get("key1"));
- Assert.assertNotNull(cache.get("key2"));
-
- SECONDS.sleep(8);
-
- Assert.assertNotNull(cache.get("key1"));
- Assert.assertNull(cache.get("key2"));
-
- SECONDS.sleep(10);
-
- Assert.assertNull(cache.get("key1"));
-
- cache.getCacheConfiguration().setTimeToLiveSeconds(4);
-
- cache.put(new Element("key1", new byte[0]));
- cache.put(new Element("key2", new byte[0]));
-
- SECONDS.sleep(8);
-
- Assert.assertNull(cache.get("key1"));
- Assert.assertNull(cache.get("key2"));
-
- cache.removeAll();
- }
-
- public void testTTIChangeWithCustomElements(CacheManager cm) throws InterruptedException {
- Cache cache = createCache("testTTIChangeWithCustomElements", 10, false, 0, 10);
- cm.addCache(cache);
-
- cache.put(new Element("default", new byte[0]));
- cache.put(new Element("eternal", new byte[0], true, 0, 0));
- cache.put(new Element("short", new byte[0], false, 1, 1));
- cache.put(new Element("long", new byte[0], true, 100, 100));
-
- SECONDS.sleep(6);
-
- Assert.assertNull(cache.get("short"));
-
- SECONDS.sleep(6);
-
- Assert.assertNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- cache.getCacheConfiguration().setTimeToIdleSeconds(20);
-
- cache.put(new Element("default", new byte[0]));
- cache.put(new Element("short", new byte[0], false, 1, 1));
-
- SECONDS.sleep(15);
-
- Assert.assertNotNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- SECONDS.sleep(25);
-
- Assert.assertNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- cache.getCacheConfiguration().setTimeToIdleSeconds(4);
-
- cache.put(new Element("default", new byte[0]));
- cache.put(new Element("short", new byte[0], false, 1, 1));
-
- SECONDS.sleep(8);
-
- Assert.assertNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- cache.removeAll();
- }
-
- public void testTTLChangeWithCustomElements(CacheManager cm) throws InterruptedException {
- Cache cache = createCache("testTTLChangeWithCustomElements", 10, false, 10, 0);
- cm.addCache(cache);
-
- cache.put(new Element("default", new byte[0]));
- cache.put(new Element("eternal", new byte[0], true, 0, 0));
- cache.put(new Element("short", new byte[0], false, 1, 1));
- cache.put(new Element("long", new byte[0], true, 100, 100));
-
- SECONDS.sleep(6);
-
- Assert.assertNotNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- SECONDS.sleep(6);
-
- Assert.assertNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- cache.getCacheConfiguration().setTimeToLiveSeconds(20);
-
- cache.put(new Element("default", new byte[0]));
- cache.put(new Element("short", new byte[0], false, 1, 1));
-
- SECONDS.sleep(6);
-
- Assert.assertNotNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- SECONDS.sleep(6);
-
- Assert.assertNotNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- SECONDS.sleep(10);
-
- Assert.assertNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- cache.getCacheConfiguration().setTimeToLiveSeconds(4);
-
- cache.put(new Element("default", new byte[0]));
- cache.put(new Element("short", new byte[0], false, 1, 1));
-
- SECONDS.sleep(8);
-
- Assert.assertNull(cache.get("default"));
- Assert.assertNotNull(cache.get("eternal"));
- Assert.assertNull(cache.get("short"));
- Assert.assertNotNull(cache.get("long"));
-
- cache.removeAll();
- }
-
- private void testMemoryCapacityChange(CacheManager cm) throws Exception {
- final Cache cache = createCache("testMemoryCapacityChange", 100, true, 0, 0);
- cache.getCacheConfiguration().getTerracottaConfiguration()
- .consistency(TerracottaConfiguration.Consistency.STRONG);
- cm.addCache(cache);
-
- int i = 0;
- for (; i < 150; i++) {
- cache.put(new Element("key" + i, new byte[0]));
- }
-
- waitForCacheMemoryStoreSize(cache, 100);
-
- cache.getCacheConfiguration().setMaxEntriesLocalHeap(200);
-
- for (; i < 250; i++) {
- cache.put(new Element("key" + i, new byte[0]));
- }
-
- waitForCacheMemoryStoreSize(cache, 100, 200);
-
- cache.getCacheConfiguration().setMaxEntriesLocalHeap(50);
-
- for (; i < 350; i++) {
- cache.put(new Element("key" + i, new byte[0]));
- }
-
- waitForCacheMemoryStoreSize(cache, 50);
-
- cache.removeAll();
- }
-
- private void waitForCacheMemoryStoreSize(final Cache cache, final int lowerBound, final int upperBound)
- throws Exception {
- final int min = (int) ((1 - TOLERANCE) * lowerBound);
- final int max = (int) ((1 + TOLERANCE) * upperBound);
- WaitUtil.waitUntilCallableReturnsTrue(new Callable() {
- @Override
- public Boolean call() throws Exception {
- if (cache.getStatistics().getLocalHeapSize() <= max && cache.getStatistics().getLocalHeapSize() >= min) {
- return true;
- }
- System.out.println("Still waiting for memory store size to fall in bounds [" + lowerBound + ", " + upperBound
- + "] current=" + cache.getStatistics().getLocalHeapSize());
- return false;
- }
- });
- }
-
- private void waitForCacheMemoryStoreSize(final Cache cache, final int upperBound) throws Exception {
- waitForCacheMemoryStoreSize(cache, 0, upperBound);
- }
-
- public void testDiskCapacityChange(CacheManager cm) throws Exception {
- final Cache cache = createCache("testDiskCapacityChange", 10, true, 0, 0);
- cache.getCacheConfiguration().maxEntriesLocalHeap(1).maxEntriesInCache(100).getTerracottaConfiguration()
- .consistency(TerracottaConfiguration.Consistency.STRONG).concurrency(16);
- cm.addCache(cache);
-
- testCacheDiskCapacity(cache, 100);
-
- cache.getCacheConfiguration().setMaxEntriesInCache(200);
-
- testCacheDiskCapacity(cache, 200);
-
- cache.getCacheConfiguration().setMaxEntriesInCache(50);
-
- testCacheDiskCapacity(cache, 50);
-
- cache.removeAll();
- }
-
- private void testCacheDiskCapacity(final Cache cache, final int capacity) throws Exception {
- for (int i = 0; i < 1000; i++) {
- cache.put(new Element("key" + i, new byte[0]));
- }
- System.out.println("Waiting on capacoty of " + capacity);
- WaitUtil.waitUntilCallableReturnsTrue(new Callable() {
- @Override
- public Boolean call() throws Exception {
- System.out.println("Current cache size " + cache.getSize());
- Assert.assertTrue(cache.getSize() > capacity * .85);
- return cache.getSize() >= capacity * 0.9 && cache.getSize() <= capacity * 1.1;
- }
- });
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsBasicSerializationSanityTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsBasicSerializationSanityTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsBasicSerializationSanityTest.java (revision 0)
@@ -1,233 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.bulkops;
-
-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.config.TerracottaConfiguration.Consistency;
-
-import org.junit.Assert;
-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.io.Serializable;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.BrokenBarrierException;
-import java.util.concurrent.TimeUnit;
-
-public class BulkOpsBasicSerializationSanityTest extends AbstractCacheTestBase {
- private static final int NODE_COUNT = 2;
-
- public BulkOpsBasicSerializationSanityTest(TestConfig testConfig) {
- super(testConfig, 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 {
- Cache dcv2StrongSerialization = createCache("dcv2StrongSerialization", cacheManager, Consistency.STRONG);
- testBulkOpsSanity(dcv2StrongSerialization);
- barrier.await();
-
- Cache dcv2EventualSerialization = createCache("dcv2EventualSerialization", cacheManager, Consistency.EVENTUAL);
- testBulkOpsSanity(dcv2EventualSerialization);
- barrier.await();
-
- barrier.await();
-
- }
-
- private void testBulkOpsSanity(Cache cache) throws InterruptedException, BrokenBarrierException {
- int index = barrier.await();
- int numOfElements = 100;
- Set elements = new HashSet();
- for (int i = 0; i < numOfElements; i++) {
- elements.add(new Element(new Key("key" + i, i), new Value("val" + i, i)));
- }
- if (index == 0) {
- cache.putAll(elements);
- }
-
- barrier.await();
- while (cache.getSize() != numOfElements) {
- Thread.sleep(1000);
- }
- Assert.assertEquals(numOfElements, cache.getSize());
-
- Set keySet1 = new HashSet();
- for (int i = 0; i < numOfElements; i++) {
- keySet1.add(new Key("key" + i, i));
- }
-
- Map rv = cache.getAll(keySet1);
- Assert.assertEquals(numOfElements, rv.size());
-
- Collection values = new HashSet();
- for (Entry entry : rv.entrySet()) {
- Assert.assertTrue(elements.contains(entry.getValue()));
- values.add(entry.getValue());
- }
-
- for (Element element : elements) {
- Assert.assertTrue(values.contains(element));
- }
-
- Set keySet2 = new HashSet();
- for (int i = 0; i < numOfElements; i++) {
- if (i % 2 == 0) {
- keySet2.add(new Key("key" + i, i));
- }
- }
-
- rv = cache.getAll(keySet2);
- Assert.assertEquals(keySet2.size(), rv.size());
-
- for (Entry entry : rv.entrySet()) {
- Assert.assertTrue(elements.contains(entry.getValue()));
- }
-
- Assert.assertEquals(keySet2, rv.keySet());
- System.out.println("verified by client now waiting for others...");
- barrier.await();
-
- if (index != 0) {
- cache.removeAll(keySet2);
- System.out.println("client " + index + " removed " + keySet2.size() + " keys from " + cache.getName()
- + ". Now waiting for others...");
- // sleep for 60 seconds for eventual caches
- if (cache.getCacheConfiguration().getTerracottaConfiguration().getConsistency() == Consistency.EVENTUAL) {
- Thread.sleep(TimeUnit.MILLISECONDS.convert(60, TimeUnit.SECONDS));
- }
- }
- index = barrier.await();
- while (cache.getSize() != numOfElements - keySet2.size()) {
- Thread.sleep(1000);
- }
-
- Assert.assertEquals(numOfElements - keySet2.size(), cache.getSize());
- System.out.println("client " + index + "now checking removed in " + cache.getName() + " by client");
- for (Object key : keySet2) {
- Assert.assertNull(cache.get(key));
- }
- System.out.println("client " + index + " done with " + cache.getName());
- }
-
- private Cache createCache(String cacheName, CacheManager cm, Consistency consistency) {
- CacheConfiguration cacheConfiguration = new CacheConfiguration();
- cacheConfiguration.setName(cacheName);
- cacheConfiguration.setMaxElementsInMemory(100000);
- cacheConfiguration.setEternal(false);
- cacheConfiguration.setTimeToLiveSeconds(100000);
- cacheConfiguration.setTimeToIdleSeconds(200000);
-
- TerracottaConfiguration tcConfiguration = new TerracottaConfiguration();
- tcConfiguration.setConsistency(consistency);
- cacheConfiguration.addTerracotta(tcConfiguration);
-
- Cache cache = new Cache(cacheConfiguration);
- cm.addCache(cache);
- System.out.println("\n\ncache " + cacheName + " created with consistency " + consistency);
- return cache;
- }
- }
-
- private static class Key implements Serializable {
- private final String stringKey;
- private final int intKey;
-
- public Key(String stringKey, int intKey) {
- super();
- this.stringKey = stringKey;
- this.intKey = intKey;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + intKey;
- result = prime * result + ((stringKey == null) ? 0 : stringKey.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) return true;
- if (obj == null) return false;
- if (getClass() != obj.getClass()) return false;
- Key other = (Key) obj;
- if (intKey != other.intKey) return false;
- if (stringKey == null) {
- if (other.stringKey != null) return false;
- } else if (!stringKey.equals(other.stringKey)) return false;
- return true;
- }
-
- @Override
- public String toString() {
- return stringKey;
- }
-
- }
-
- private static class Value implements Serializable {
- private final String keyVal;
- private final int intVal;
-
- public Value(String keyVal, int intVal) {
- this.keyVal = keyVal;
- this.intVal = intVal;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + intVal;
- result = prime * result + ((keyVal == null) ? 0 : keyVal.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) return true;
- if (obj == null) return false;
- if (getClass() != obj.getClass()) return false;
- Value other = (Value) obj;
- if (intVal != other.intVal) return false;
- if (keyVal == null) {
- if (other.keyVal != null) return false;
- } else if (!keyVal.equals(other.keyVal)) return false;
- return true;
- }
-
- @Override
- public String toString() {
- return keyVal;
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/OverflowToDiskStandaloneCacheTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/OverflowToDiskStandaloneCacheTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/OverflowToDiskStandaloneCacheTest.java (revision 0)
@@ -1,45 +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.ehcache.tests;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-
-/**
- * @author cdennis
- */
-public class OverflowToDiskStandaloneCacheTest extends AbstractCacheTestBase {
-
- public OverflowToDiskStandaloneCacheTest(TestConfig testConfig) {
- super("overflow-to-disk-cache-test.xml", testConfig);
- }
-
- @Override
- protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable {
- if ((exitCode == 0)) { throw new AssertionError("Client " + clientName + " exited with exit code: " + exitCode); }
-
- FileReader fr = null;
- try {
- fr = new FileReader(output);
- BufferedReader reader = new BufferedReader(fr);
- String st = "";
- while ((st = reader.readLine()) != null) {
- if (st.contains("InvalidConfigurationException")) return;
- }
- throw new AssertionError("Client " + clientName + " did not pass");
- } catch (Exception e) {
- throw new AssertionError(e);
- } finally {
- try {
- fr.close();
- } catch (Exception e) {
- //
- }
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/servermaplocalcache/ServerMapLocalCache.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/servermaplocalcache/ServerMapLocalCache.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/servermaplocalcache/ServerMapLocalCache.java (revision 0)
@@ -1,194 +0,0 @@
-/**
- * All content copyright 2010 (c) Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All
- * rights reserved.
- */
-package net.sf.ehcache.servermaplocalcache;
-
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.event.CacheEventListenerAdapter;
-
-public class ServerMapLocalCache {
-
- private final static int CONCURRENCY = 256;
- private volatile TCObjectSelfStore tcoSelfStore;
- private volatile Cache ehcache;
- private final ReentrantReadWriteLock[] locks = new ReentrantReadWriteLock[CONCURRENCY];
- private final Object localSync = new Object();
- private static final ExecutorService evictionHandlerStage = Executors.newFixedThreadPool(4, new ThreadFactory() {
- private final AtomicInteger count = new AtomicInteger();
-
- public Thread newThread(Runnable r) {
- Thread t = new Thread(r, "eviction_handler_stage_thread_" + count.incrementAndGet());
- t.setDaemon(true);
- return t;
- }
- });
-
- public ServerMapLocalCache(TCObjectSelfStore tcoSelfStore, Cache ehcache) {
- this.tcoSelfStore = tcoSelfStore;
- this.ehcache = ehcache;
- ehcache.getCacheEventNotificationService().registerListener(new EvictionListener(this));
- for (int i = 0; i < CONCURRENCY; i++) {
- locks[i] = new ReentrantReadWriteLock();
- }
- }
-
- private ReentrantReadWriteLock getLock(Object key) {
- return locks[Math.abs(key.hashCode() % CONCURRENCY)];
- }
-
- public void put(TCObjectSelf tcoSelf) {
- synchronized (localSync) {
- tcoSelfStore.addTCObjectSelf(tcoSelf);
- addToCache(tcoSelf);
- }
- }
-
- public TCObjectSelf getFromTCObjectSelfStore(Long oid) {
- synchronized (localSync) {
- return tcoSelfStore.getById(oid);
- }
- }
-
- // public void remove(String key) {
- // synchronized (localSync) {
- // removeFromCache(key);
- // }
- // }
- //
- // private void removeFromCache(String key) {
- // WriteLock writeLock = getLock(key).writeLock();
- // writeLock.lock();
- // try {
- // // remove key-value mapping: key->value
- // Element element = ehcache.removeAndReturnElement(key);
- // if (element != null) {
- // TCObjectSelf tcoSelf = (TCObjectSelf) element.getObjectValue();
- // if (tcoSelf != null) {
- // handleKeyValueMappingRemoved(key, tcoSelf);
- // }
- // }
- //
- // } finally {
- // writeLock.unlock();
- // }
- // }
-
- private void handleKeyValueMappingRemoved(String key, TCObjectSelf tcoSelf) {
- // remote remove
- tcoSelfStore.removeTCObjectSelf(tcoSelf);
- if (tcoSelf != null) {
- // clean up meta-mapping: id->key
- ehcache.remove(tcoSelf.getOid());
- }
- }
-
- private void addToCache(TCObjectSelf tcoSelf) {
- ReentrantReadWriteLock lock = getLock(tcoSelf.getKey());
- lock.writeLock().lock();
- try {
- if (DebugUtil.DEBUG) {
- DebugUtil.debug("Add to cache: " + tcoSelf);
- }
-
- // add meta mapping: oid->key
- ehcache.put(new Element(tcoSelf.getOid(), tcoSelf.getKey()));
-
- // add the key->value mapping
- ehcache.put(new Element(tcoSelf.getKey(), tcoSelf));
-
- } finally {
- lock.writeLock().unlock();
- }
- }
-
- public void entryEvicted(Object objectKey, Object objectValue) {
- if (DebugUtil.DEBUG) {
- DebugUtil.debug("Entry evicted; evictedKey: " + objectKey + ", evictedValue: " + objectValue);
- }
- if (objectValue instanceof TCObjectSelf) {
- // key-value mapping evicted
- keyValueMappingEvicted((String) objectKey, (TCObjectSelf) objectValue);
- } else {
- // oid-> key mapping removed
- objectIdMappingEvicted((Long) objectKey, (String) objectValue);
- }
- }
-
- private void objectIdMappingEvicted(Long oid, String key) {
- WriteLock writeLock = getLock(key).writeLock();
- writeLock.lock();
- Element element = null;
- try {
- element = ehcache.get(key);
- if (element != null) {
- TCObjectSelf tcoSelf = (TCObjectSelf) element.getObjectValue();
- if (tcoSelf != null && tcoSelf.getOid() == oid) {
- // clean up key-value mapping
- ehcache.remove(key);
- tcoSelfStore.removeTCObjectSelf(tcoSelf);
- }
- }
- } finally {
- writeLock.unlock();
- }
- if (DebugUtil.DEBUG) {
- DebugUtil.debug("[objectIdEvicted] oid: " + oid + ", key: " + key + ", was mapped to value: "
- + (element == null ? "null" : element.getObjectValue()));
- }
- }
-
- private void keyValueMappingEvicted(String objectKey, TCObjectSelf objectValue) {
- WriteLock writeLock = getLock(objectKey).writeLock();
- writeLock.lock();
- try {
- if (DebugUtil.DEBUG) {
- DebugUtil.debug("[keyValueMappingEvicted] key: " + objectKey + ", value: " + objectValue);
- }
- handleKeyValueMappingRemoved(objectKey, objectValue);
- } finally {
- writeLock.unlock();
- }
- }
-
- private static class EvictionListener extends CacheEventListenerAdapter {
- private final ServerMapLocalCache serverMapLocalCache;
-
- public EvictionListener(ServerMapLocalCache serverMapLocalCache) {
- this.serverMapLocalCache = serverMapLocalCache;
- }
-
- @Override
- public void notifyElementExpired(Ehcache cache, final Element element) {
- if (DebugUtil.DEBUG) {
- DebugUtil.debug("[ElementExpired] expiredKey: " + element.getObjectKey() + ", expiredValue: " + element.getObjectValue());
- }
- evictionHandlerStage.submit(new Runnable() {
- public void run() {
- serverMapLocalCache.entryEvicted(element.getObjectKey(), element.getObjectValue());
- }
- });
- }
-
- @Override
- public void notifyElementEvicted(Ehcache cache, final Element element) {
- if (DebugUtil.DEBUG) {
- DebugUtil.debug("[ElementEvicted] expiredKey: " + element.getObjectKey() + ", expiredValue: " + element.getObjectValue());
- }
- evictionHandlerStage.submit(new Runnable() {
- public void run() {
- serverMapLocalCache.entryEvicted(element.getObjectKey(), element.getObjectValue());
- }
- });
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncCoordinatorFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncCoordinatorFactory.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncCoordinatorFactory.java (revision 0)
@@ -1,12 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.async;
-
-import net.sf.ehcache.Ehcache;
-
-public interface AsyncCoordinatorFactory {
- AsyncCoordinator getOrCreateAsyncCoordinator(final Ehcache cache, final AsyncConfig config);
-
- boolean destroy(String cacheManagerName, String cacheName);
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/net/sf/ehcache/osgi/OsgiScheduledRefreshTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/net/sf/ehcache/osgi/OsgiScheduledRefreshTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/net/sf/ehcache/osgi/OsgiScheduledRefreshTest.java (revision 0)
@@ -1,223 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package net.sf.ehcache.osgi;
-
-import static org.ops4j.pax.exam.CoreOptions.maven;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.options;
-import static org.ops4j.pax.exam.CoreOptions.wrappedBundle;
-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.ConfigurationFactory;
-import net.sf.ehcache.constructs.scheduledrefresh.ScheduledRefreshCacheExtension;
-import net.sf.ehcache.constructs.scheduledrefresh.ScheduledRefreshConfiguration;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.ops4j.pax.exam.Configuration;
-import org.ops4j.pax.exam.Option;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
-import org.ops4j.pax.exam.spi.reactors.PerMethod;
-import org.terracotta.test.OsgiUtil;
-
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-
-import junit.framework.Assert;
-
-/**
- * Adapt ScheduledRefreshCacheExtensionTest to run with OSGi.
- *
- * This test duplicates a few test classes in ehcache-scheduled-refresh to simplify bundle loading for osgi deployment
- *
- *
- * @author cschanck
- * @author hhuynh
- */
-@RunWith(PaxExam.class)
-@ExamReactorStrategy(PerMethod.class)
-public class OsgiScheduledRefreshTest {
-
- private static OddCacheLoader stupidCacheLoaderOdds = new OddCacheLoader();
- private static EvenCacheLoader stupidCacheLoaderEvens = new EvenCacheLoader();
-
- public OsgiScheduledRefreshTest() {
- //
- }
-
- @Configuration
- public Option[] config() {
- return options(OsgiUtil.getMavenBundle("net.sf.ehcache", "ehcache-ee", "ehcache"),
- mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(),
- mavenBundle("org.slf4j", "slf4j-simple").versionAsInProject().noStart(),
- OsgiUtil.getMavenBundle("org.quartz-scheduler", "quartz"), wrappedBundle(maven("c3p0", "c3p0")
- .versionAsInProject()), OsgiUtil.commonOptions());
- }
-
- private static void sleepySeconds(int secs) {
- sleepy(secs * 1000);
- }
-
- private static void sleepy(int millis) {
- try {
- Thread.sleep(millis);
- } catch (InterruptedException e) {
- //
- }
- }
-
- // OK. we want to create an ehcache, then programmitically decorate it with
- // locks.
- @Test
- public void testIllegalCronExpression() {
-
- CacheManager manager = new CacheManager();
- manager.removeAllCaches();
-
- manager.addCache(new Cache(new CacheConfiguration().name("test").eternal(true).maxEntriesLocalHeap(5000)));
- Ehcache cache = manager.getEhcache("test");
- cache.registerCacheLoader(stupidCacheLoaderEvens);
- cache.registerCacheLoader(stupidCacheLoaderOdds);
-
- ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration().batchSize(100).quartzThreadCount(4)
- .cronExpression("go to your happy place").build();
- ScheduledRefreshCacheExtension cacheExtension = new ScheduledRefreshCacheExtension(config, cache);
- cache.registerCacheExtension(cacheExtension);
- cacheExtension.init();
- // there will havebeen an exception logged.
- Assert.assertEquals(cacheExtension.getStatus(), Status.STATUS_UNINITIALISED);
-
- manager.removeAllCaches();
- manager.shutdown();
- }
-
- @Test
- public void testSimpleCaseProgrammatic() {
-
- CacheManager manager = new CacheManager();
- manager.removeAllCaches();
-
- manager.addCache(new Cache(new CacheConfiguration().name("test").eternal(true).maxEntriesLocalHeap(5000)));
- Ehcache cache = manager.getEhcache("test");
- cache.registerCacheLoader(stupidCacheLoaderEvens);
- cache.registerCacheLoader(stupidCacheLoaderOdds);
-
- int second = (new GregorianCalendar().get(Calendar.SECOND) + 5) % 60;
- ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration().batchSize(100).quartzThreadCount(4)
- .cronExpression(second + "/5 * * * * ?").build();
- ScheduledRefreshCacheExtension cacheExtension = new ScheduledRefreshCacheExtension(config, cache);
- cache.registerCacheExtension(cacheExtension);
- cacheExtension.init();
- Assert.assertEquals(cacheExtension.getStatus(), Status.STATUS_ALIVE);
-
- for (int i = 0; i < 10; i++) {
- cache.put(new Element(new Integer(i), i + ""));
- }
-
- second = Math.max(8, 60 - second + 3);
- System.out.println("Scheduled delay is :: " + second);
- sleepySeconds(second);
-
- for (Object key : cache.getKeys()) {
- Element val = cache.get(key);
- // System.out.println("["+key+", "+cache.get(key).getObjectValue()+"]");
- int iVal = ((Number) key).intValue();
- if ((iVal & 0x01) == 0) {
- // even
- Assert.assertEquals(iVal + 20000, Long.parseLong((String) val.getObjectValue()));
- } else {
- Assert.assertEquals(iVal + 10000, Long.parseLong((String) val.getObjectValue()));
- // odd
- }
-
- }
-
- // cacheExtension.dispose();
- manager.removeAllCaches();
- manager.shutdown();
- }
-
- // OK. we want to create an ehcache, then programmitaclly decorate it with
- // locks.
- @Test
- public void testSimpleCaseXML() throws Exception {
- net.sf.ehcache.config.Configuration cmConfig = ConfigurationFactory
- .parseConfiguration(OsgiScheduledRefreshTest.class
- .getResource("/net/sf/ehcache/osgi/ehcache-scheduled-refresh.xml"));
- cmConfig.setClassLoader(getClass().getClassLoader());
- CacheManager manager = new CacheManager(cmConfig);
-
- Cache cache = manager.getCache("sr-test");
-
- int second = (new GregorianCalendar().get(Calendar.SECOND) + 5) % 60;
-
- for (int i = 0; i < 10; i++) {
- cache.put(new Element(new Integer(i), i + ""));
- }
-
- second = Math.max(8, 60 - second + 3);
- System.out.println("Scheduled delay is :: " + second);
- sleepySeconds(second);
-
- for (Object key : cache.getKeys()) {
- Element val = cache.get(key);
- // System.out.println("["+key+", "+cache.get(key).getObjectValue()+"]");
- int iVal = ((Number) key).intValue();
- if ((iVal & 0x01) == 0) {
- // even
- Assert.assertEquals(iVal + 20000, Long.parseLong((String) val.getObjectValue()));
- } else {
- Assert.assertEquals(iVal + 10000, Long.parseLong((String) val.getObjectValue()));
- // odd
- }
-
- }
- manager.removeAllCaches();
-
- manager.shutdown();
- }
-
- // OK. we want to create an ehcache, then programmitically decorate it with
- // locks.
- @Test
- public void testPolling() {
-
- CacheManager manager = new CacheManager();
- manager.removeAllCaches();
-
- manager.addCache(new Cache(new CacheConfiguration().name("tt").eternal(true).maxEntriesLocalHeap(5000)
- .overflowToDisk(false)));
- Ehcache cache = manager.getEhcache("tt");
- stupidCacheLoaderEvens.setMsDelay(100);
- cache.registerCacheLoader(stupidCacheLoaderEvens);
- cache.registerCacheLoader(stupidCacheLoaderOdds);
-
- int second = (new GregorianCalendar().get(Calendar.SECOND) + 5) % 60;
- ScheduledRefreshConfiguration config = new ScheduledRefreshConfiguration().batchSize(2).quartzThreadCount(2)
- .pollTimeMs(100).cronExpression(second + "/1 * * * * ?").build();
- ScheduledRefreshCacheExtension cacheExtension = new ScheduledRefreshCacheExtension(config, cache);
- cache.registerCacheExtension(cacheExtension);
- cacheExtension.init();
- Assert.assertEquals(cacheExtension.getStatus(), Status.STATUS_ALIVE);
-
- final int ELEMENT_COUNT = 50;
- long[] orig = new long[ELEMENT_COUNT];
- for (int i = 0; i < ELEMENT_COUNT; i++) {
- Element elem = new Element(new Integer(i), i + "");
- orig[i] = elem.getCreationTime();
- cache.put(elem);
- }
-
- sleepySeconds(20);
-
- // cacheExtension.dispose();
- manager.removeAllCaches();
- manager.shutdown();
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/VersionedItem.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/VersionedItem.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/VersionedItem.java (revision 0)
@@ -1,28 +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.domain;
-
-public class VersionedItem extends Item {
- private Long version;
-
- public Long getVersion() {
- return version;
- }
-
- public void setVersion(Long version) {
- this.version = version;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/double-config-cache-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/double-config-cache-test.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/double-config-cache-test.xml (revision 0)
@@ -1,25 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- PORT
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/clustered-events-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/clustered-events-test.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/clustered-events-test.xml (revision 0)
@@ -1,62 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/loader/NullCountingCacheLoaderFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/loader/NullCountingCacheLoaderFactory.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/loader/NullCountingCacheLoaderFactory.java (revision 0)
@@ -1,52 +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.Ehcache;
-
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * A factory for creating counting cache loaders. This can be hooked up to the JCacheFactory by
- * specifying "cacheLoaderFactoryClassName" in the environment
- *
- * @author Greg Luck
- * @version $Id: NullCountingCacheLoaderFactory.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class NullCountingCacheLoaderFactory extends CacheLoaderFactory {
-
-
- /**
- */
- public CacheLoader createCacheLoader(Map environment) {
- return new NullCountingCacheLoader();
- }
-
- /**
- * Creates a CacheLoader using the Ehcache configuration mechanism at the time the associated cache is created.
- *
- * @param properties implementation specific properties. These are configured as comma
- * separated name value pairs in ehcache.xml
- * @return a constructed CacheLoader
- */
- public CacheLoader createCacheLoader(Ehcache cache, Properties properties) {
- return new NullCountingCacheLoader();
- }
-
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/MAggregate.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/MAggregate.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/MAggregate.java (revision 0)
@@ -1,130 +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;
-
-import net.sf.ehcache.search.aggregator.Aggregator;
-
-public class MAggregate implements ModelElement {
-
- /**
- * The aggregation type enum.
- */
- public static enum AggOp {
- /**
- * The Sum.
- */
- Sum,
- /**
- * The Min.
- */
- Min,
- /**
- * The Max.
- */
- Max,
- /**
- * The Average.
- */
- Average,
- /**
- * The Count.
- */
- Count
- }
-
- ;
-
- /**
- * The op.
- */
- private final AggOp op;
-
- /**
- * The attribute.
- */
- private final MAttribute ma;
-
- /**
- * Instantiates a new m aggregate.
- *
- * @param op the operation
- * @param ma the attribute
- */
- public MAggregate(AggOp op, MAttribute ma) {
- this.op = op;
- this.ma = ma;
- }
-
- /*
- * (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return op.toString().toLowerCase() + "(" + ma + ")";
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((ma == null) ? 0 : ma.hashCode());
- result = prime * result + ((op == null) ? 0 : op.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) return true;
- if (obj == null) return false;
- if (getClass() != obj.getClass()) return false;
- MAggregate other = (MAggregate)obj;
- if (ma == null) {
- if (other.ma != null) return false;
- } else if (!ma.equals(other.ma)) return false;
- if (op != other.op) return false;
- return true;
- }
-
- public AggOp getOp() {
- return op;
- }
-
- public MAttribute getAttribute() {
- return ma;
- }
-
- /**
- * Return this model aggregator as an ehacache aggregator.
- *
- * @return the aggregator
- */
- public Aggregator asEhcacheObject(ClassLoader loader) {
- switch (op) {
- case Sum:
- return ma.asEhcacheObject(loader).sum();
- case Min:
- return ma.asEhcacheObject(loader).min();
- case Max:
- return ma.asEhcacheObject(loader).max();
- case Count:
- return ma.asEhcacheObject(loader).count();
- case Average:
- return ma.asEhcacheObject(loader).average();
- }
- throw new IllegalStateException("Unknown agg operator: " + op);
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/package.html
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/package.html (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/package.html (revision 0)
@@ -1,8 +0,0 @@
-
-
-
-
-This package contains classes related to LiveCacheStatistics and its implementation.
-
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/hibernate-config/shutdowntest/domain/Item.hbm.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/hibernate-config/shutdowntest/domain/Item.hbm.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/hibernate-config/shutdowntest/domain/Item.hbm.xml (revision 0)
@@ -1,28 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/Decision.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/Decision.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/transaction/Decision.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;
-
-/**
- * The decision types a Transaction ID can be in
- *
- * @author Ludovic Orban
- */
-public enum Decision {
-
- /**
- * Transaction decision not yet made.
- */
- IN_DOUBT,
-
- /**
- * Transaction has been marked for commit.
- */
- COMMIT,
-
- /**
- * Transaction has been marked for rollback.
- */
- ROLLBACK
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/event/ClusterTopologyTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/event/ClusterTopologyTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/event/ClusterTopologyTest.java (revision 0)
@@ -1,47 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.event;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.cluster.CacheCluster;
-import net.sf.ehcache.cluster.ClusterNode;
-import net.sf.ehcache.cluster.ClusterScheme;
-
-import org.junit.Assert;
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-import org.terracotta.toolkit.Toolkit;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.util.Collection;
-
-public class ClusterTopologyTest extends AbstractCacheTestBase {
-
- public ClusterTopologyTest(TestConfig testConfig) {
- super("clustered-events-test.xml", testConfig, App.class, App.class, App.class);
- }
-
- public static class App extends ClientBase {
-
- public App(String[] args) {
- super(args);
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- getBarrierForAllClients().await();
-
- CacheCluster cluster = cacheManager.getCluster(ClusterScheme.TERRACOTTA);
- Assert.assertTrue(cluster != null);
- Assert.assertTrue(cluster.getScheme().equals(ClusterScheme.TERRACOTTA));
- getBarrierForAllClients().await();
- Collection nodes = cluster.getNodes();
- // There will be 2 clients per node. ( 1 for cache+ 1 for toolkit)
- Assert.assertEquals(getParticipantCount() * 2, nodes.size());
- getBarrierForAllClients().await();
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/RefreshBatchJob.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/RefreshBatchJob.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/RefreshBatchJob.java (revision 0)
@@ -1,157 +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.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.loader.CacheLoader;
-import org.quartz.Job;
-import org.quartz.JobDataMap;
-import org.quartz.JobExecutionContext;
-import org.quartz.JobExecutionException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.concurrent.locks.ReentrantLock;
-
-/**
- * This class is used to actually process a batch of keys for refreshing.
- * Instances of this job are scheduled by the {@link OverseerJob} class.
- *
- * @author cschanck
- */
-public class RefreshBatchJob implements Job {
-
- private static final Logger LOG = LoggerFactory.getLogger(OverseerJob.class);
- private static HashMap bulkLoadTrackingMap = new HashMap(1);
- private static ReentrantLock bulkloadLock = new ReentrantLock();
-
- private static void requestBulkLoadEnabled(Ehcache cache) {
- bulkloadLock.lock();
- try {
- boolean prior = cache.isNodeBulkLoadEnabled();
- // yes, this is racy. we can do no better until we have per-thread bulk loading
- if (prior) {
- String key = cache.getCacheManager().getName() + "/" + cache.getName();
- AtomicInteger permits = bulkLoadTrackingMap.get(key);
- if (permits == null) {
- // first time in. actually switch it
- permits = new AtomicInteger(1);
- bulkLoadTrackingMap.put(key, permits);
- cache.setNodeBulkLoadEnabled(true);
- } else {
- permits.incrementAndGet();
- }
- }
- } finally {
- bulkloadLock.unlock();
- }
- }
-
- private static void requestBulkLoadRestored(Ehcache cache) {
- bulkloadLock.lock();
- try {
- String key = cache.getCacheManager().getName() + "/" + cache.getName();
- AtomicInteger permits = bulkLoadTrackingMap.get(key);
- if (permits != null) {
- if (permits.decrementAndGet() == 0) {
- // last one out. reset it to true
- bulkLoadTrackingMap.remove(key);
- cache.setNodeBulkLoadEnabled(true);
- }
- }
- } finally {
- bulkloadLock.unlock();
- }
- }
-
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- public void execute(JobExecutionContext context) throws JobExecutionException {
- try {
- JobDataMap jdm = context.getMergedJobDataMap();
- ScheduledRefreshConfiguration config = (ScheduledRefreshConfiguration) jdm.get(ScheduledRefreshCacheExtension
- .PROP_CONFIG_OBJECT);
- String cacheManagerName = jdm.getString(ScheduledRefreshCacheExtension.PROP_CACHE_MGR_NAME);
- String cacheName = jdm.getString(ScheduledRefreshCacheExtension.PROP_CACHE_NAME);
-
- CacheManager cacheManager = CacheManager.getCacheManager(cacheManagerName);
- Ehcache underlyingCache = cacheManager.getEhcache(cacheName);
-
- HashSet extends Object> keysToProcess = new HashSet((Collection extends Object>) jdm.get(
- ScheduledRefreshCacheExtension.PROP_KEYS_TO_PROCESS));
-
- ScheduledRefreshCacheExtension extension = ScheduledRefreshCacheExtension.findExtensionFromCache(underlyingCache,
- context.getJobDetail().getKey().getGroup());
- boolean keepingStats=false;
- if (extension != null) {
- extension.incrementJobCount();
- extension.incrementProcessedCount(keysToProcess.size());
- keepingStats=true;
- }
-
- LOG.info("Scheduled refresh batch job: " + context.getJobDetail().getKey() + " size: " + keysToProcess.size()+" "+OverseerJob.statsNote(keepingStats));
- try {
- if (config.isUseBulkload()) {
- requestBulkLoadEnabled(underlyingCache);
- }
- } catch (UnsupportedOperationException e) {
- LOG.warn("Bulk Load requested for cache that does not support bulk load.");
- }
-
- // iterate through the loaders
- for (CacheLoader loader : underlyingCache.getRegisteredCacheLoaders()) {
- // if we are out of keys, punt
- if (keysToProcess.isEmpty()) {
- break;
- }
-
- // try and load them all
- Map extends Object, ? extends Object> values = loader.loadAll(keysToProcess);
- // subtract the ones that were loaded
- keysToProcess.removeAll(values.keySet());
- for (Map.Entry extends Object, ? extends Object> entry : values.entrySet()) {
- Element newElement = new Element(entry.getKey(), entry.getValue());
- underlyingCache.put(newElement);
- }
- }
- // assume we got here ok, now evict any that don't evict
- if (config.isEvictOnLoadMiss() && !keysToProcess.isEmpty()) {
- underlyingCache.removeAll(keysToProcess);
- }
-
- try {
- if (config.isUseBulkload()) {
- requestBulkLoadRestored(underlyingCache);
- }
- } catch (UnsupportedOperationException e) {
- // warned above.
- }
- }
- catch(Throwable t) {
- LOG.warn("Scheduled refresh batch job failure: " + context.getJobDetail().getKey(), t);
- }
-
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/scatterpolicies/SingleBucketScatterPolicy.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/scatterpolicies/SingleBucketScatterPolicy.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/scatterpolicies/SingleBucketScatterPolicy.java (revision 0)
@@ -1,15 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.async.scatterpolicies;
-
-
-import java.io.Serializable;
-
-public class SingleBucketScatterPolicy implements ItemScatterPolicy {
-
- public int selectBucket(final int count, final E item) {
- return 0;
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/distribution/colorcache/src/assemble/bin/package.sh
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/distribution/colorcache/src/assemble/bin/package.sh (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/distribution/colorcache/src/assemble/bin/package.sh (revision 0)
@@ -1,53 +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
-
-appname=colorcache
-
-
-unset CDPATH
-root=`dirname $0`/..
-root=`cd $root && pwd`
-
-jetty1=$root/jetty6.1/9081
-jetty2=$root/jetty6.1/9082
-webapp_lib=$root/webapps/$appname/WEB-INF/lib
-
-tc_install_dir=$root/bin/`$root/bin/relative-paths.sh tc_install_dir`
-ehcache_jars_dir=$root/bin/`$root/bin/relative-paths.sh ehcache_jars_dir`
-
-# package ehcache-core and ehcache-terracotta
-cp $ehcache_jars_dir/lib/ehcache*.jar $webapp_lib
-
-# package toolkit runtime. It could be in 2 different places depending on which kit (ehcache vs tc)
-toolkit_runtime=$tc_install_dir/common/terracotta-toolkit*-runtime*.jar
-
-if [ ! -f $toolkit_runtime ]; then
- # not found under 'common', try 'lib'
- toolkit_runtime=$ehcache_jars_dir/lib/terracotta-toolkit*-runtime*.jar
- if [ ! -f $toolkit_runtime ]; then
- echo "Couldn't locate toolkit runtime jar"
- exit 1
- fi
-fi
-
-cp $toolkit_runtime $webapp_lib
-
-if [ $? -eq 0 ]; then
- echo "Deploying demo..."
- cp -r $root/webapps $jetty1
- cp -r $root/webapps $jetty2
- echo "Done."
- exit 0
-else
- echo "Error packaging the sample"
- exit 1
-fi
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/services/net.sf.ehcache.pool.SizeOfEngineFactory.txt
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/services/net.sf.ehcache.pool.SizeOfEngineFactory.txt (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/services/net.sf.ehcache.pool.SizeOfEngineFactory.txt (revision 0)
@@ -1 +0,0 @@
-net.sf.ehcache.pool.SizeOfEngineLoaderTest$MyRealFactory
\ No newline at end of file
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/CoalescingDeadBucketWriteBehindTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/CoalescingDeadBucketWriteBehindTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/CoalescingDeadBucketWriteBehindTest.java (revision 0)
@@ -1,88 +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 CoalescingDeadBucketWriteBehindTest extends AbstractCacheTestBase {
- private int totalWriteCount = 0;
- private int totalDeleteCount = 0;
-
- public CoalescingDeadBucketWriteBehindTest(TestConfig testConfig) {
- super("coalescing-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 < 180 || totalWriteCount > 1001) { throw new AssertionError(totalWriteCount); }
-
- System.out.println("[Clients processed a total of " + totalDeleteCount + " deletes]");
- if (totalDeleteCount < 20 || totalDeleteCount > 101) { throw new AssertionError(totalDeleteCount); }
- }
-
- @Override
- protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable {
- super.evaluateClientOutput(clientName, exitCode, output);
- BufferedReader reader = null;
- FileReader fr = 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.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/MOrderBy.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/MOrderBy.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/MOrderBy.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.search.parser;
-
-public class MOrderBy {
-
- /**
- * The attr.
- */
- private final MAttribute attr;
-
- /**
- * The asc.
- */
- private final boolean asc;
-
- /**
- * Instantiates a new model order by.
- *
- * @param attr the attr
- * @param asc the asc
- */
- public MOrderBy(MAttribute attr, boolean asc) {
- this.attr = attr;
- this.asc = asc;
- }
-
- /**
- * Gets the attribute.
- *
- * @return the attribute
- */
- public MAttribute getAttribute() {
- return attr;
- }
-
- /**
- * Checks if is order ascending.
- *
- * @return true, if is order ascending
- */
- public boolean isOrderAscending() {
- return asc;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#toString()
- */
- @Override
- public String toString() {
- return "order by " + attr + (asc ? " ascending" : " descending");
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (asc ? 1231 : 1237);
- result = prime * result + ((attr == null) ? 0 : attr.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj) return true;
- if (obj == null) return false;
- if (getClass() != obj.getClass()) return false;
- MOrderBy other = (MOrderBy)obj;
- if (asc != other.asc) return false;
- if (attr == null) {
- if (other.attr != null) return false;
- } else if (!attr.equals(other.attr)) return false;
- return true;
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/refreshahead/StringifyCacheLoaderFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/refreshahead/StringifyCacheLoaderFactory.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/refreshahead/StringifyCacheLoaderFactory.java (revision 0)
@@ -1,95 +0,0 @@
-package net.sf.ehcache.constructs.refreshahead;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.loader.CacheLoader;
-import net.sf.ehcache.loader.CacheLoaderFactory;
-
-public class StringifyCacheLoaderFactory extends CacheLoaderFactory {
-
- @Override
- public CacheLoader createCacheLoader(Ehcache cache, Properties properties) {
- return new StringifyCacheLoader(properties);
- }
-
- public static class StringifyCacheLoader implements CacheLoader {
-
- private long delayMS = 0;
-
- public StringifyCacheLoader(Properties properties) {
- if (properties != null) {
- delayMS = Long.parseLong(properties.getProperty("delayMS", "0"));
- }
- }
-
- @Override
- public Map loadAll(Collection keys, Object argument) {
- return loadAll(keys);
- }
-
- @Override
- public Map loadAll(Collection keys) {
- try {
- Thread.sleep(delayMS);
- } catch (InterruptedException e) {
-
- }
- HashMap ret=new HashMap();
- for(Object k:keys) {
- ret.put(k, k.toString());
- }
- return ret;
- }
-
- @Override
- public Object load(Object key, Object argument) {
- return load(key);
- }
-
- @Override
- public Object load(Object key) throws CacheException {
- try {
- Thread.sleep(delayMS);
- } catch (InterruptedException e) {
-
- }
- return key.toString();
- }
-
- @Override
- public void init() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public Status getStatus() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public String getName() {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public void dispose() throws CacheException {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public CacheLoader clone(Ehcache cache) throws CloneNotSupportedException {
- // TODO Auto-generated method stub
- return null;
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/distribution/src/main/assembly/root/README.html
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/distribution/src/main/assembly/root/README.html (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/distribution/src/main/assembly/root/README.html (revision 0)
@@ -1,151 +0,0 @@
-
-
-
- README Notes For Ehcache ${project.version}
-
- The project home page is http://ehcache.org. Please see http://ehcache.org for a full change log, usage, product versions
- and comprehensive documentation.
-
-
- Introduction
- ============
- Ehcache is a pure Java, in-process cache with the following features:
-
- 1. Fast and Light Weight
- 1.1 Fast
- 1.2 Simple
- 1.3 Small foot print
- 1.4 Minimal dependencies
- 2. Scalable
- 2.1 Provides Memory and Disk stores for scalabilty into gigabytes
- 2.4 Scalable to hundreds of caches
- 2.3 Tuned for high concurrent load on large multi-cpu servers
- 2.4 Multiple CacheManagers per virtual machine
- 3. Flexible
- 3.1 Supports Object or Serializable caching
- 3.2 Support cache-wide or Element-based expiry policies
- 3.3 Provides LRU, LFU and FIFO cache eviction policies
- 3.4 Provides Memory and Disk stores
- 3.5 Distributed
- 3.6 Dynamic, Runtime Configuration of Caches
- 4. Standards Based
- 4.1 Full implementation of JSR107 JCACHE API
- 5. Extensible
- 5.1 Listeners may be plugged in
- 5.2 Peer Discovery, Replicators and Listeners may be plugged in
- 5.3 Cache Extensions may be plugged in
- 5.4 Cache Loaders may be plugged in
- 5.5 Cache Exception Handlers may be plugged in
- 6. Application Persistence
- 6.1 Persistent disk store which stores data between VM restarts
- 6.2 Flush to disk on demand
- 7. Listeners
- 7.1 CacheManager listeners
- 7.2 Cache event listeners
- 8. JMX Enabled
- 9. Distributed Caching
- 10. Support for replication via RMI or JGroups
- 10.1 Peer Discovery
- 10.2 Reliable Delivery
- 10.3 Synchronous Or Asynchronous Replication
- 10.4 Copy Or Invalidate Replication
- 10.5 Transparent Replication
- 10.6 Extensible
- 10.7 Bootstrapping from Peers
- 11. Cache Server
- 11.1 RESTful cache server
- 11.2 SOAP cache server
- 11.3 comes as a WAR or as a complete server
- 12. Java EE and Applied Caching
- 12.1 Blocking Cache to avoid duplicate processing for concurrent operations
- 12.2 SelfPopulating Cache for pull through caching of expensive operations
- 12.3 Java EE Gzipping Servlet Filter
- 12.4 Cacheable Commands
- 12.5 Works with Hibernate
- 12.6 Works with Google App Engine
- 12.7 Transactional support through JTA
- 13. High Quality
- 13.1 High Test Coverage
- 13.2 Automated Load, Limit and Performance System Tests
- 13.3 Specific Concurrency Testing
- 13.4 Production tested
- 13.5 Fully documented
- 13.6 Trusted by Popular Frameworks
- 13.7 Conservative Commit policy
- 13.8 Full public information on the history of every bug
- 13.9 Responsiveness to serious bugs
- 14. Open Source Licensing
- 14.1 Apache 2.0 license
-
- Java Requirements
- =================
-
- Ehcache 1.7.2 and above supports Java 1.5 and 1.6 at runtime. Ehcache final releases are compiled with -target 1.5.
-
- The Ehcache 1.5 branch is being maintained for Java 1.4 users.
-
- Dependencies
- ============
-
- SLF4J API and one concrete logging implementation. The API jar and the JDK14 logging jar are included in the distribution.
-
- Maven POM snippet
- =================
-
- All Ehcache releases are placed in the central Maven repository.
-
- The Maven snippet for Ehcache is:
-
- <dependency>
- <groupid>net.sf.ehcache</groupid>
- <artifactid>ehcache</artifactid>
- <version>${project.version}</version>
- </dependency>
-
- Installation
- ============
- Place the ehcache-core.jar, slf4j-api.jar and slf4j-jdk14.jar, or the concrete SLF4J logging implementation library of your choice into your classpath.
-
- For use with Terracotta, copy the ehcache-terracotta.jar to your classpath.
-
- Create an ehcache.xml configuration from the one supplied in the distribution and place it in the root of your classpath.
-
- The Terracotta server is in the terracotta directory. It includes start and stop scripts.
-
- For Maven based development, there is a tc-maven-plugin which works much like the Jetty plugin. See UsingWithMaven.txt,
- which shows how to add the server to your integration test phase and interactive command use.
-
- For Ant based development, the tc-maven-plugin can be called from Ant. See UsingWithAnt.txt,
- which shows how to add the server to your Ant build, and how to use the server interactively from Ant.
-
-
- Samples
- =======
- See the samples directory for ready-to-run samples which show to use the full features of Ehcache, including use with Terracotta.
-
-
-
- Documentation
- =============
- See http://ehcache.org/documentation for full documentation.
-
- The JavaDoc is in the distribution and also online at http://ehcache.org/apidocs
-
- Licenses
- ========
- This kit contains ehcache code which is governed by the Apache License, version 2.0. The license is in the licenses folder.
-
- Ehcache 1.7.1 and higher uses SLF4J for logging. The SLF4J license is included in the licenses folder.
-
- Known Issues
- ============
-
- 1. There are a number of known issues and workarounds for Tomcat. See the Using Ehcache with Tomcat chapter
- in the online documentation.
-
- 2. See the FAQ online for a current list.
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/HolidayCalendar.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/HolidayCalendar.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/HolidayCalendar.java (revision 0)
@@ -1,59 +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.ehcache.tests.container.hibernate.domain;
-
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Map;
-
-public class HolidayCalendar {
- private Long id;
- private Map holidays = new HashMap(); // Date -> String
-
- public HolidayCalendar init() {
- DateFormat df = new SimpleDateFormat("yyyy.MM.dd");
- try {
- holidays.clear();
- holidays.put(df.parse("2009.01.01"), "New Year's Day");
- holidays.put(df.parse("2009.02.14"), "Valentine's Day");
- holidays.put(df.parse("2009.11.11"), "Armistice Day");
- } catch (ParseException e) {
- System.out.println("Error parsing date string");
- throw new RuntimeException(e);
- }
- return this;
- }
-
- public Map getHolidays() {
- return holidays;
- }
-
- protected void setHolidays(Map holidays) {
- this.holidays = holidays;
- }
-
- public void addHoliday(Date d, String name) {
- holidays.put(d, name);
- }
-
- public String getHoliday(Date d) {
- return (String)holidays.get(d);
- }
-
- public boolean isHoliday(Date d) {
- return holidays.containsKey(d);
- }
-
- protected Long getId() {
- return id;
- }
-
- protected void setId(Long id) {
- this.id = id;
- }
-}
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/CacheManagerSampler.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/CacheManagerSampler.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/CacheManagerSampler.java (revision 0)
@@ -1,334 +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 java.util.Map;
-
-import net.sf.ehcache.util.ManagementAttribute;
-
-/**
- * An abstraction for sampled cache manager usage statistics.
- *
- * @author Abhishek Sanoujam
- * @author byoukste
- */
-public interface CacheManagerSampler {
- /**
- * Gets the actual name of the cache manager.
- */
- @ManagementAttribute
- String getName();
-
- /**
- * Gets the cluster uuid if applicable.
- *
- * @return the cluster uuid
- */
- @ManagementAttribute
- String getClusterUUID();
-
- /**
- * Gets the status attribute of the Ehcache
- *
- * @return The status value, as a String from the Status enum class
- */
- @ManagementAttribute
- String getStatus();
-
- /**
- * Enables/disables each cache contained by this CacheManager
- *
- * @param enabled
- */
- void setEnabled(boolean enabled);
-
- /**
- * Returns if each cache is enabled.
- *
- * @return boolean indicating that each cache is enabled
- */
- @ManagementAttribute
- boolean isEnabled();
-
- /**
- * Shuts down the CacheManager.
- *
- * If the shutdown occurs on the singleton, then the singleton is removed, so that if a singleton access method is called, a new
- * singleton will be created.
- */
- void shutdown();
-
- /**
- * Clears the contents of all caches in the CacheManager, but without
- * removing any caches.
- *
- * This method is not synchronized. It only guarantees to clear those elements in a cache at the time that the
- * {@link net.sf.ehcache.Ehcache#removeAll()} mehod on each cache is called.
- */
- void clearAll();
-
- /**
- * Gets the cache names managed by the CacheManager
- */
- @ManagementAttribute
- String[] getCacheNames() throws IllegalStateException;
-
- /**
- * Get a map of cache name to performance metrics (hits, misses).
- *
- * @return a map of cache metrics
- */
- Map getCacheMetrics();
-
- /**
- * @return aggregate hit rate
- */
- long getCacheHitRate();
-
- /**
- * @return aggregate in-memory hit rate
- */
- long getCacheInMemoryHitRate();
-
- /**
- * @return aggregate off-heap hit rate
- */
- long getCacheOffHeapHitRate();
-
- /**
- * @return aggregate on-disk hit rate
- */
- long getCacheOnDiskHitRate();
-
- /**
- * @return aggregate miss rate
- */
- long getCacheMissRate();
-
- /**
- * @return aggregate in-memory miss rate
- */
- long getCacheInMemoryMissRate();
-
- /**
- * @return aggregate off-heap miss rate
- */
- long getCacheOffHeapMissRate();
-
- /**
- * @return aggregate on-disk miss rate
- */
- long getCacheOnDiskMissRate();
-
- /**
- * @return aggregate put rate
- */
- long getCachePutRate();
-
- /**
- * @return aggregate update rate
- */
- long getCacheUpdateRate();
-
- /**
- * @return aggregate remove rate
- */
- long getCacheRemoveRate();
-
- /**
- * @return aggregate eviction rate
- */
- long getCacheEvictionRate();
-
- /**
- * @return aggregate expiration rate
- */
- long getCacheExpirationRate();
-
- /**
- * @return aggregate average get time (ms.)
- */
- float getCacheAverageGetTime();
-
- /**
- * @return if any contained caches are configured for search
- */
- @ManagementAttribute
- boolean getSearchable();
-
- /**
- * @return aggregate search rate
- */
- long getCacheSearchRate();
-
- /**
- * @return aggregate search time
- */
- long getCacheAverageSearchTime();
-
- /**
- * generateActiveConfigDeclaration
- *
- * @return CacheManager configuration as String
- */
- String generateActiveConfigDeclaration();
-
- /**
- * generateActiveConfigDeclaration
- *
- * @param cacheName
- * @return Cache configuration as String
- */
- String generateActiveConfigDeclaration(String cacheName);
-
- /**
- * Are any of the caches transactional
- *
- * @see net.sf.ehcache.config.CacheConfiguration.TransactionalMode
- */
- @ManagementAttribute
- boolean getTransactional();
-
- /**
- * Get the committed transactions count
- *
- * @return the committed transactions count
- */
- long getTransactionCommittedCount();
-
- /**
- * @return aggregate Xa commit rate
- */
- long getTransactionCommitRate();
-
- /**
- * Get the rolled back transactions count
- *
- * @return the rolled back transactions count
- */
- long getTransactionRolledBackCount();
-
- /**
- * @return aggregate Xa rollback rate
- */
- long getTransactionRollbackRate();
-
- /**
- * Get the timed out transactions count. Note that only transactions which failed to
- * commit due to a timeout are taken into account
- *
- * @return the timed out transactions count
- */
- long getTransactionTimedOutCount();
-
- /**
- * Returns whether any caches are configured for write-behind
- */
- @ManagementAttribute
- boolean getHasWriteBehindWriter();
-
- /**
- * Returns the total length of all write-behind queues across all caches
- *
- * @return aggregate writer-behind queue length
- */
- long getWriterQueueLength();
-
- /**
- * Maximum elements that can be queued for processing by the write-behind writer
- *
- * @return aggregate of the maximum elements that can be waiting to be processed
- * by the write-behind writer across all caches
- */
- @ManagementAttribute
- int getWriterMaxQueueSize();
-
- /**
- * Maximum number of bytes of entries in the disk stores of all caches that
- * did not declare their own max size.
- *
- * @return maximum number of bytes in the disk stores of all caches that
- * did not declare their own max size.
- */
- @ManagementAttribute
- long getMaxBytesLocalDisk();
-
- /**
- * @param maxBytes
- */
- void setMaxBytesLocalDisk(long maxBytes);
-
- /**
- * @param maxBytes
- */
- void setMaxBytesLocalDiskAsString(String maxBytes);
-
- /**
- * @return Original input for maxBytesLocalDisk
- */
- @ManagementAttribute
- String getMaxBytesLocalDiskAsString();
-
- /**
- * Maximum number of bytes of entries in the heap memory stores of all caches that
- * did not declare their own max size.
- *
- * @return maximum number of bytes in the heap memory stores of all caches that
- * did not declare their own max size.
- */
- @ManagementAttribute
- long getMaxBytesLocalHeap();
-
- /**
- * @return Original input for maxBytesLocalHeap
- */
- @ManagementAttribute
- String getMaxBytesLocalHeapAsString();
-
- /**
- * @param maxBytes
- */
- void setMaxBytesLocalHeap(long maxBytes);
-
- /**
- * @param maxBytes
- */
- void setMaxBytesLocalHeapAsString(String maxBytes);
-
- /**
- * Maximum number of bytes of entries in the off-heap stores of all caches that
- * did not declare their own max size.
- *
- * @return maximum number of bytes in the off-heap stores of all caches that
- * did not declare their own max size.
- */
- @ManagementAttribute
- long getMaxBytesLocalOffHeap();
-
- /**
- * @return Original input for maxBytesLocalOffHeap
- */
- @ManagementAttribute
- String getMaxBytesLocalOffHeapAsString();
-
- /**
- * Execute a BMSQL query against the CacheManager and return result grid.
- *
- * @param queryString
- * @return query result grid
- */
- Object[][] executeQuery(String queryString);
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/KeyObjectAttributeExtractorSerializationTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/KeyObjectAttributeExtractorSerializationTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/KeyObjectAttributeExtractorSerializationTest.java (revision 0)
@@ -1,46 +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 net.sf.ehcache.search.attribute.KeyObjectAttributeExtractor;
-
-import org.junit.Test;
-
-import static org.terracotta.upgradability.serialization.SerializationUpgradabilityTesting.validateSerializedForm;
-
-/**
- *
- * @author cdennis
- */
-public class KeyObjectAttributeExtractorSerializationTest {
-
- private static final Comparator COMPARATOR = new Comparator() {
-
- @Override
- public int compare(KeyObjectAttributeExtractor o1, KeyObjectAttributeExtractor o2) {
- return 0;
- }
- };
-
- @Test
- public void testBasic() throws IOException, ClassNotFoundException {
- validateSerializedForm(new KeyObjectAttributeExtractor(), COMPARATOR, "serializedforms/KeyObjectAttributeExtractorSerializationTest.testBasic.ser");
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/SampledStatisticTimerTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/SampledStatisticTimerTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/SampledStatisticTimerTest.java (revision 0)
@@ -1,52 +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 org.terracotta.toolkit.Toolkit;
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.util.Map;
-
-import junit.framework.Assert;
-
-public class SampledStatisticTimerTest extends AbstractCacheTestBase {
-
- public SampledStatisticTimerTest(TestConfig testConfig) {
- super("sampled-statistic-timer-test.xml", testConfig, App.class);
- }
-
- public static class App extends ClientBase {
-
- public App(String[] args) {
- super(args);
- }
-
- public static void main(String[] args) {
- new App(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- for (int i = 0; i < 10; i++) {
- String cacheName = "cache-" + i;
- cacheManager.addCache(cacheName);
- }
-
- Map liveThreads = Thread.getAllStackTraces();
- int samplerThreadCount = 0;
- for (Thread t : liveThreads.keySet()) {
- String threadName = t.getName();
- if (threadName.contains("SampledStatisticsManager Timer")) {
- samplerThreadCount++;
- }
- }
- Assert.assertEquals("Found statistic sampler threads!.", 0, samplerThreadCount);
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/exceptionhandler/CacheExceptionHandlerTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/exceptionhandler/CacheExceptionHandlerTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/exceptionhandler/CacheExceptionHandlerTest.java (revision 0)
@@ -1,224 +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.exceptionhandler;
-
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import net.sf.ehcache.AbstractCacheTest;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.loader.CacheLoader;
-import net.sf.ehcache.loader.ExceptionThrowingLoader;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * @author Greg Luck
- * @version $Id: CacheExceptionHandlerTest.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class CacheExceptionHandlerTest {
-
- /**
- * manager
- */
- protected CacheManager manager;
- /**
- * the cache name we wish to test
- */
- protected String cacheName = "exceptionHandlingCache";
- /**
- * the cache we wish to test
- */
- protected Ehcache cache;
-
- /**
- * {@inheritDoc}
- *
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- manager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache.xml");
- cache = manager.getEhcache(cacheName);
- cache.removeAll();
- }
-
-
- /**
- * {@inheritDoc}
- *
- * @throws Exception
- */
- @After
- public void tearDown() throws Exception {
- CountingExceptionHandler.resetCounters();
- manager.shutdown();
- }
-
- /**
- * Test a cache which has been configured to have a CountingExceptionHandler configured
- */
- @Test
- public void testConfiguredCache() {
- manager.removeCache("exceptionHandlingCache");
- //Would normally throw an IllegalStateException
- cache.get("key1");
-
- assertEquals(1, CountingExceptionHandler.HANDLED_EXCEPTIONS.size());
- assertEquals(null, ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS.get(0)).getKey());
- assertEquals(IllegalStateException.class, ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS
- .get(0)).getException().getClass());
- }
-
- /**
- * Test a cache which has been configured to have an ExceptionThrowingLoader screw up loading.
- * This one should have a key set.
- */
- @Test
- public void testKeyWithConfiguredCache() {
-
- List loaders = new ArrayList(cache.getRegisteredCacheLoaders());
- for (CacheLoader loader : loaders) {
- cache.unregisterCacheLoader(loader);
- }
-
- cache.registerCacheLoader(new ExceptionThrowingLoader());
- cache.getWithLoader("key1", null, null);
-
- assertEquals(1, CountingExceptionHandler.HANDLED_EXCEPTIONS.size());
- assertEquals("key1", ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS.get(0)).getKey());
- assertEquals(CacheException.class, ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS
- .get(0)).getException().getClass());
- }
-
- /**
- * Double proxy test
- */
- @Test
- public void testCacheExceptionHandler() {
- Ehcache proxiedCache = ExceptionHandlingDynamicCacheProxy.createProxy(cache);
-
- List loaders = new ArrayList(cache.getRegisteredCacheLoaders());
- for (CacheLoader loader : loaders) {
- cache.unregisterCacheLoader(loader);
- }
- cache.registerCacheLoader(new CustomExceptionThrowingLoader());
- proxiedCache.getWithLoader("key1", null, null);
-
-
- //Would normally throw an IllegalArgumentException
-// proxiedCache.put(null);
-
- assertEquals(1, CountingExceptionHandler.HANDLED_EXCEPTIONS.size());
- assertEquals("key1", ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS.get(0)).getKey());
- assertEquals(CacheException.class, ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS
- .get(0)).getException().getClass());
- }
-
-
- /**
- * Test some gnarly parsing code
- */
- @Test
- public void testKeyExtraction() {
-
- String testMessage = "For key 1234";
- String key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals("1234", key);
-
- testMessage = "key 1234";
- key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals("1234", key);
-
- testMessage = null;
- key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals(null, key);
-
- testMessage = "";
- key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals(null, key);
-
- testMessage = "key 1234 ";
- key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals("1234", key);
-
- testMessage = "key 1234 .";
- key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals("1234", key);
-
- testMessage = "key .";
- key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals(".", key);
-
- testMessage = "key";
- key = ExceptionHandlingDynamicCacheProxy.extractKey(testMessage);
- assertEquals(null, key);
-
- }
-
- /**
- * Tests that the exception thrown by a configured loader, is
- * actually passed on to exception handler
- */
- @Test
- public void testExceptionThrown() {
-
- List loaders = new ArrayList(cache.getRegisteredCacheLoaders());
- for (CacheLoader loader : loaders) {
- cache.unregisterCacheLoader(loader);
- }
- cache.registerCacheLoader(new CustomExceptionThrowingLoader());
-
- cache.getWithLoader("key1", null, null);
-
- assertEquals(1, CountingExceptionHandler.HANDLED_EXCEPTIONS.size());
- assertEquals("key1", ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS.get(0)).getKey());
-
-
- Class expectedExceptionClass = UnsupportedOperationException.class;
-
- Exception e = ((CountingExceptionHandler.HandledException) CountingExceptionHandler.HANDLED_EXCEPTIONS
- .get(0)).getException();
-
- Throwable cause = e;
- boolean foundExceptionInChain = false;
-
-
- //Recurse through the chain
- while ((cause = cause.getCause()) != null) {
-
- if (cause.getClass().equals(expectedExceptionClass)) {
- foundExceptionInChain = true;
- break;
- }
- }
-
- if (!foundExceptionInChain) {
- fail();
- }
-
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/stop-db.bat
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/stop-db.bat (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/stop-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
-
-call %JAVA_HOME%\bin\java -cp %h2_jar% org.h2.tools.Server -tcpShutdown tcp://localhost:9092
-
-endlocal
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/META-INF/services/net.sf.ehcache.management.ManagementServer
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/META-INF/services/net.sf.ehcache.management.ManagementServer (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/META-INF/services/net.sf.ehcache.management.ManagementServer (revision 0)
@@ -1,2 +0,0 @@
-#used by ManagementServerLoaderTest
-net.sf.ehcache.management.DummyManagementServerImpl
\ No newline at end of file
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/checkstyle/suppressions.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/checkstyle/suppressions.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/checkstyle/suppressions.xml (revision 0)
@@ -1,451 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/cache-event-eviction-exception-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/cache-event-eviction-exception-test.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/cache-event-eviction-exception-test.xml (revision 0)
@@ -1,9 +0,0 @@
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/BoundedPool.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/BoundedPool.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/BoundedPool.java (revision 0)
@@ -1,52 +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 net.sf.ehcache.pool.PoolParticipant;
-import net.sf.ehcache.pool.SizeOfEngine;
-import net.sf.ehcache.pool.PoolAccessor;
-import net.sf.ehcache.pool.PoolEvictor;
-
-/**
- * A pool which loosely obeys to its bound: it can allow the accessors to consume more bytes than what
- * has been configured if that helps concurrency.
-
- * @author Ludovic Orban
- * @author Chris Dennis
- */
-public class BoundedPool extends AbstractPool {
-
- /**
- * Create a BoundedPool instance
- *
- * @param maximumPoolSize the maximum size of the pool, in bytes.
- * @param evictor the pool evictor, for cross-store eviction.
- * @param defaultSizeOfEngine the default SizeOf engine used by the accessors.
- */
- public BoundedPool(long maximumPoolSize, PoolEvictor evictor, SizeOfEngine defaultSizeOfEngine) {
- super(maximumPoolSize, evictor, defaultSizeOfEngine);
- }
-
- /**
- * {@inheritDoc}
- */
- public PoolAccessor createPoolAccessor(PoolParticipant participant, SizeOfEngine sizeOfEngine) {
- AtomicPoolAccessor accessor = new AtomicPoolAccessor(this, participant, sizeOfEngine, 0);
- registerPoolAccessor(accessor);
- return accessor;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapElementTTIExpressTestClient.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapElementTTIExpressTestClient.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapElementTTIExpressTestClient.java (revision 0)
@@ -1,90 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.servermap;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-
-import org.terracotta.toolkit.Toolkit;
-
-import java.util.Date;
-
-import junit.framework.Assert;
-
-public class ServerMapElementTTIExpressTestClient extends ServerMapClientBase {
-
- public ServerMapElementTTIExpressTestClient(String[] args) {
- super("testWithElementEvictionTTI", args);
- }
-
- public static void main(String[] args) {
- new ServerMapElementTTIExpressTestClient(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- int size = cache.getSize();
- assertEquals(0, size);
- System.out.println("Client populating cache.");
-
- for (int i = 0; i < 1500; i++) {
- cache.put(new Element("key-" + i, "value-" + i));
- }
-
- for (int i = 1500; i < 2000; i++) {
- Element element = new Element("key-" + i, "value-" + i);
- element.setTimeToIdle(60 * 4); // setting TTI of 1500-2000 keys as 4 min
- cache.put(element);
- }
-
- System.out.println("Cache populate. Size: " + cache.getSize());
-
- Date date = new Date();
- System.out.println("Sleeping for 2 mins (now=" + date + ", " + date.getTime() + ") ... ");
- // Sleep for TTI to kick in:
- Thread.sleep(2 * 60 * 1000);
-
- date = new Date();
- System.out.println("After sleeping 2 mins. Size: " + cache.getSize() + " (now=" + date + ", " + date.getTime()
- + ")");
-
- for (int i = 0; i < 1500; i++) {
- Element element = cache.get("key-" + i);
- Assert.assertNull("Element should be null of key-" + i + " actual: " + element, element);
- }
-
- date = new Date();
- System.out.println("Touching elements from 1500-2000 (now=" + date + ", " + date.getTime() + ")");
- for (int i = 1500; i < 2000; i++) {
- Element element = cache.get("key-" + i);
- Assert.assertTrue(element.getValue().equals("value-" + i));
- }
-
- for (int i = 2000; i < 2500; i++) {
- Element element = new Element("key-" + i, "value-" + i);
- element.setTimeToIdle(15 * 60); // setting TTI of 2000-2500 keys as 15 min
- cache.put(element);
- }
-
- date = new Date();
- System.out.println("Sleeping for 5 mins (now=" + date + ", " + date.getTime() + ") ... ");
- // Sleep for TTI to kick in:
- Thread.sleep(5 * 60 * 1000);
-
- date = new Date();
- System.out.println("After sleeping 5 mins. Size: " + cache.getSize() + " (now=" + date + ", " + date.getTime()
- + ")");
-
- for (int i = 1500; i < 2000; i++) {
- Element element = cache.get("key-" + i);
- Assert.assertNull("Element should be null of key-" + i + " actual: " + element, element);
- }
-
- for (int i = 2000; i < 2500; i++) {
- Element element = cache.get("key-" + i);
- Assert.assertTrue(element.getValue().equals("value-" + i));
- }
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/OverflowCacheTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/OverflowCacheTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/OverflowCacheTest.java (revision 0)
@@ -1,73 +0,0 @@
-package net.sf.ehcache;
-
-import net.sf.ehcache.config.CacheConfiguration;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
-
-/**
- * @author Alex Snaps
- */
-public class OverflowCacheTest {
-
- private static final Logger LOG = LoggerFactory.getLogger(CacheTest.class.getName());
-
- private CacheManager manager;
-
- @Before
- public void setUp() throws Exception {
- manager = CacheManager.create();
- }
-
- /**
- * teardown
- */
- @After
- public void tearDown() throws Exception {
- if (manager != null) {
- manager.shutdown();
- }
- }
-
-
- /**
- * Shows the effect of jamming large amounts of puts into a cache that overflows to disk.
- * The DiskStore should cause puts to back off and avoid an out of memory error.
- */
- @Test
- public void testBehaviourOnDiskStoreBackUp() throws Exception {
- Cache cache = new Cache(new CacheConfiguration().name("testBehaviourOnDiskStoreBackUp")
- .maxElementsInMemory(1000)
- .overflowToDisk(true)
- .eternal(false)
- .timeToLiveSeconds(100)
- .timeToIdleSeconds(200)
- .diskPersistent(false)
- .diskExpiryThreadIntervalSeconds(0)
- .diskSpoolBufferSizeMB(10));
- manager.addCache(cache);
-
- assertEquals(0, cache.getStatistics().getLocalHeapSize());
-
- Element a;
- int i = 0;
- try {
- for (; i < 150000; i++) {
- String key = i + "";
- String value = key;
- a = new Element(key, value + "DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD");
- cache.put(a);
- }
- } catch (OutOfMemoryError e) {
- LOG.info("OutOfMemoryError: " + e.getMessage() + " " + i);
- fail();
- }
- }
-
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/UuidItem.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/UuidItem.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/UuidItem.java (revision 0)
@@ -1,46 +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.domain;
-
-public class UuidItem {
- private String id;
- private String name;
- private String description;
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
-
- public String getId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/basic-xa-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/basic-xa-test.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/basic-xa-test.xml (revision 0)
@@ -1,27 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/constructs/blocking/package.html
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/constructs/blocking/package.html (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/constructs/blocking/package.html (revision 0)
@@ -1,11 +0,0 @@
-
-
-
-
- Doug Lea in his book Concurrent Programming in Java talks about concurrency support constructs.
- One meaning of a construct is "an abstract or general idea inferred or derived from specific instances".
- Just like patterns emerge from noting the similarities of problems and gradually finding a solution to
- classes of them, so to constructs are general solutions to commond problems. With the constructs package,
- concrete, extensible implementations are offered to solve these common problems.
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/FeaturesManager.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/FeaturesManager.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/FeaturesManager.java (revision 0)
@@ -1,79 +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.pool.Pool;
-import net.sf.ehcache.store.Store;
-import net.sf.ehcache.transaction.SoftLockFactory;
-import net.sf.ehcache.transaction.SoftLockManager;
-import net.sf.ehcache.transaction.TransactionIDFactory;
-import net.sf.ehcache.writer.writebehind.WriteBehind;
-
-/**
- * Interface implemented by classes providing access to extended functionality.
- *
- * @author Chris Dennis
- */
-public interface FeaturesManager {
-
- /**
- * Fully qualified classname of the enterprise features manager
- */
- public static final String ENTERPRISE_FM_CLASSNAME = "net.sf.ehcache.EnterpriseFeaturesManager";
-
- /**
- * Create a WriteBehind instance for the given cache.
- *
- * @param cache cache to create write behind for
- * @return a write behind instance
- */
- WriteBehind createWriteBehind(Cache cache);
-
- /**
- * Create a store for the given cache.
- *
- * @param cache cache to create a store for
- * @param onHeapPool on-heap pool
- * @param onDiskPool on-disk pool
- * @return a store for the given cache
- */
- Store createStore(Cache cache, Pool onHeapPool, Pool onDiskPool);
-
- /**
- * Create a transaction map for the associated cache manager
- *
- * @return a transaction map for the cache manager
- */
- TransactionIDFactory createTransactionIDFactory();
-
- /**
- * Create a soft-lock map for the given cache
- *
- * @return a soft-lcok map for the given cache
- */
- SoftLockManager createSoftLockManager(Ehcache cache, SoftLockFactory lockFactory);
-
- /**
- * Called on {@code CacheManager} creation.
- */
- void startup();
-
- /**
- * Called on {@code CacheManager} shutdown and on exception during CacheManager bootstrapping.
- */
- void dispose();
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/TerracottaConfigConfigurationElement.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/TerracottaConfigConfigurationElement.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/TerracottaConfigConfigurationElement.java (revision 0)
@@ -1,84 +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.generator.model.elements;
-
-import net.sf.ehcache.config.TerracottaClientConfiguration;
-import net.sf.ehcache.config.generator.model.NodeElement;
-import net.sf.ehcache.config.generator.model.SimpleNodeAttribute;
-import net.sf.ehcache.config.generator.model.SimpleNodeElement;
-
-/**
- * {@link NodeElement} representing the {@link TerracottaClientConfiguration}
- *
- * @author Abhishek Sanoujam
- *
- */
-public class TerracottaConfigConfigurationElement extends SimpleNodeElement {
-
- private final TerracottaClientConfiguration tcConfigConfiguration;
-
- /**
- * Constructor accepting the parent and the {@link TerracottaClientConfiguration}
- *
- * @param parent
- * @param tcConfigConfiguration
- */
- public TerracottaConfigConfigurationElement(NodeElement parent, TerracottaClientConfiguration tcConfigConfiguration) {
- super(parent, "terracottaConfig");
- this.tcConfigConfiguration = tcConfigConfiguration;
- init();
- }
-
- private void init() {
- if (tcConfigConfiguration == null) {
- return;
- }
- if (tcConfigConfiguration.getUrl() != null) {
- addAttribute(new SimpleNodeAttribute("url", tcConfigConfiguration.getUrl()).optional(true));
- }
- addAttribute(new SimpleNodeAttribute("rejoin", tcConfigConfiguration.isRejoin()).optional(true).defaultValue(
- TerracottaClientConfiguration.DEFAULT_REJOIN_VALUE));
-
- addAttribute(new SimpleNodeAttribute("wanEnabledTSA", tcConfigConfiguration.isWanEnabledTSA()).optional(true).defaultValue(
- TerracottaClientConfiguration.DEFAULT_WAN_ENABLED_TSA_VALUE));
-
- if (tcConfigConfiguration.getOriginalEmbeddedConfig() != null) {
- addChildElement(new TCConfigElement(this, tcConfigConfiguration.getOriginalEmbeddedConfig()));
- }
- }
-
- /**
- * Element representing the "tc-config" element inside "terracottaConfig"
- *
- * @author Abhishek Sanoujam
- *
- */
- private static class TCConfigElement extends SimpleNodeElement {
-
- /**
- * Constructor accepting the {@link TerracottaConfigConfigurationElement} parent and the inner string content
- *
- * @param parent
- * @param content
- */
- public TCConfigElement(TerracottaConfigConfigurationElement parent, String content) {
- super(parent, "tc-config");
- this.setInnerContent(content);
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/Element.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/Element.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/Element.java (revision 0)
@@ -1,889 +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.config.CacheConfiguration;
-import net.sf.ehcache.pool.sizeof.annotations.IgnoreSizeOf;
-import net.sf.ehcache.util.TimeUtil;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.concurrent.atomic.AtomicLongFieldUpdater;
-
-/**
- * A Cache Element, consisting of a key, value and attributes.
- *
- * From ehcache-1.2, Elements can have keys and values that are Serializable or Objects. To preserve backward
- * compatibility, special accessor methods for Object keys and values are provided: {@link #getObjectKey()} and
- * {@link #getObjectValue()}. If placing Objects in ehcache, developers must use the new getObject... methods to
- * avoid CacheExceptions. The get... methods are reserved for Serializable keys and values.
- *
- * @author Greg Luck
- * @version $Id: Element.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class Element implements Serializable, Cloneable {
-
- /**
- * serial version
- * Updated for version 1.2, 1.2.1 and 1.7
- */
- private static final long serialVersionUID = 1098572221246444544L;
-
- private static final Logger LOG = LoggerFactory.getLogger(Element.class.getName());
-
- private static final AtomicLongFieldUpdater HIT_COUNT_UPDATER = AtomicLongFieldUpdater.newUpdater(Element.class, "hitCount");
-
- private static final boolean ELEMENT_VERSION_AUTO = Boolean.getBoolean("net.sf.ehcache.element.version.auto");
-
- private static final long NOT_SET_ID = 0;
-
- static {
- if (ELEMENT_VERSION_AUTO) {
- LOG.warn("Note that net.sf.ehcache.element.version.auto is set and user provided version will not be honored");
- }
- }
-
- /**
- * the cache key.
- */
- @IgnoreSizeOf
- private final Object key;
-
- /**
- * the value.
- */
- private final Object value;
-
- /**
- * version of the element. System.currentTimeMillis() is used to compute version for updated elements. That
- * way, the actual version of the updated element does not need to be checked.
- */
- private volatile long version;
-
- /**
- * The number of times the element was hit.
- */
- private volatile long hitCount;
-
- /**
- * The amount of time for the element to live, in seconds. 0 indicates unlimited.
- */
- private volatile int timeToLive = Integer.MIN_VALUE;
-
- /**
- * The amount of time for the element to idle, in seconds. 0 indicates unlimited.
- */
- private volatile int timeToIdle = Integer.MIN_VALUE;
-
- /**
- * The creation time.
- */
- private transient long creationTime;
-
- /**
- * The last access time.
- */
- private transient long lastAccessTime;
-
- /**
- * If there is an Element in the Cache and it is replaced with a new Element for the same key,
- * then both the version number and lastUpdateTime should be updated to reflect that. The creation time
- * will be the creation time of the new Element, not the original one, so that TTL concepts still work.
- */
- private volatile long lastUpdateTime;
-
- private volatile boolean cacheDefaultLifespan = true;
-
- private volatile long id = NOT_SET_ID;
-
- /**
- * A full constructor.
- *
- * Creation time is set to the current time. Last Access Time is not set.
- *
- * @since .4
- */
- public Element(final Serializable key, final Serializable value, final long version) {
- this((Object) key, (Object) value, version);
-
- }
-
- /**
- * A full constructor.
- *
- * Creation time is set to the current time. Last Access Time and Previous To Last Access Time
- * are not set.
- *
- * @since 1.2
- */
- public Element(final Object key, final Object value, final long version) {
- this.key = key;
- this.value = value;
- this.version = version;
- HIT_COUNT_UPDATER.set(this, 0);
- this.creationTime = getCurrentTime();
- }
-
- /**
- * Constructor.
- *
- * @deprecated The {@code nextToLastAccessTime} field is unused since
- * version 1.7, setting it will have no effect. Use
- * #Element(Object, Object, long, long, long, long, long)
- * instead
- * @since 1.3
- * @see #Element(Object, Object, long, long, long, long, long)
- */
- @Deprecated
- public Element(final Object key, final Object value, final long version,
- final long creationTime, final long lastAccessTime, final long nextToLastAccessTime,
- final long lastUpdateTime, final long hitCount) {
- this(key, value, version, creationTime, lastAccessTime, lastUpdateTime, hitCount);
- }
-
- /**
- * Constructor.
- *
- * @since 1.7
- */
- public Element(final Object key, final Object value, final long version,
- final long creationTime, final long lastAccessTime,
- final long lastUpdateTime, final long hitCount) {
- this.key = key;
- this.value = value;
- this.version = version;
- this.lastUpdateTime = lastUpdateTime;
- HIT_COUNT_UPDATER.set(this, hitCount);
- this.creationTime = creationTime;
- this.lastAccessTime = lastAccessTime;
- }
-
- /**
- * Constructor used by ElementData. Needs to be public since ElementData might be in another classloader
- *
- * @since 1.7
- */
- public Element(final Object key, final Object value, final long version, final long creationTime,
- final long lastAccessTime, final long hitCount, final boolean cacheDefaultLifespan,
- final int timeToLive, final int timeToIdle, final long lastUpdateTime) {
- this.key = key;
- this.value = value;
- this.version = version;
- HIT_COUNT_UPDATER.set(this, hitCount);
- this.cacheDefaultLifespan = cacheDefaultLifespan;
- this.timeToLive = timeToLive;
- this.timeToIdle = timeToIdle;
- this.lastUpdateTime = lastUpdateTime;
- this.creationTime = creationTime;
- this.lastAccessTime = lastAccessTime;
- }
-
- /**
- * Constructor
- *
- * @param key any non null value
- * @param value any value, including nulls
- * @param timeToIdleSeconds seconds to idle
- * @param timeToLiveSeconds seconds to live
- * @since 2.7.1
- */
- public Element(final Object key, final Object value,
- final int timeToIdleSeconds, final int timeToLiveSeconds) {
- this(key, value);
- setTimeToIdle(timeToIdleSeconds);
- setTimeToLive(timeToLiveSeconds);
- }
-
- /**
- * Constructor
- *
- * @param key any non null value
- * @param value any value, including nulls
- * @param eternal whether this element is eternal
- * @since 2.7.1
- */
- public Element(final Object key, final Object value, final boolean eternal) {
- this(key, value);
- setEternal(eternal);
- }
-
- /**
- * Constructor used by ehcache-server
- *
- * timeToIdleSeconds and timeToLiveSeconds will have precedence over eternal. Which means that what ever eternal says, non-null
- * timeToIdleSeconds or timeToLiveSeconds will result in the element not being eternal
- *
- * @param key any non null value
- * @param value any value, including nulls
- * @param eternal specify as non-null to override cache configuration
- * @param timeToIdleSeconds specify as non-null to override cache configuration
- * @param timeToLiveSeconds specify as non-null to override cache configuration
- *
- * @deprecated
- */
- @Deprecated
- public Element(final Object key, final Object value,
- final Boolean eternal, final Integer timeToIdleSeconds, final Integer timeToLiveSeconds) {
- this.key = key;
- this.value = value;
- if (eternal != null) {
- setEternal(eternal.booleanValue());
- }
- if (timeToIdleSeconds != null) {
- setTimeToIdle(timeToIdleSeconds.intValue());
- }
- if (timeToLiveSeconds != null) {
- setTimeToLive(timeToLiveSeconds.intValue());
- }
- this.creationTime = getCurrentTime();
- }
-
- /**
- * Constructor.
- *
- * @param key
- * @param value
- */
- public Element(final Serializable key, final Serializable value) {
- this((Object) key, (Object) value, 1L);
- }
-
- /**
- * Constructor.
- *
- * @param key
- * @param value
- * @since 1.2
- */
- public Element(final Object key, final Object value) {
- this(key, value, 1L);
- }
-
- /**
- * Gets the key attribute of the Element object.
- *
- * @return The key value.
- * @throws CacheException if the key is not {@code Serializable}.
- * @deprecated Please use {@link #getObjectKey()} instead.
- */
- @Deprecated
- public final Serializable getKey() throws CacheException {
- try {
- return (Serializable) getObjectKey();
- } catch (ClassCastException e) {
- throw new CacheException("The key " + getObjectKey() + " is not Serializable. Consider using Element.getObjectKey()");
- }
- }
-
- /**
- * Gets the key attribute of the Element object.
- *
- * This method is provided for those wishing to use ehcache as a memory only cache
- * and enables retrieval of non-Serializable values from elements.
- *
- * @return The key as an Object. i.e no restriction is placed on it
- * @see #getKey()
- */
- public final Object getObjectKey() {
- return key;
- }
-
- /**
- * Gets the value attribute of the Element object.
- *
- * @return The value which must be {@code Serializable}. If not use {@link #getObjectValue}.
- * @throws CacheException if the value is not {@code Serializable}.
- * @deprecated Please use {@link #getObjectValue()} instead.
- */
- @Deprecated
- public final Serializable getValue() throws CacheException {
- try {
- return (Serializable) getObjectValue();
- } catch (ClassCastException e) {
- throw new CacheException("The value " + getObjectValue() + " for key " + getObjectKey() +
- " is not Serializable. Consider using Element.getObjectValue()");
- }
- }
-
- /**
- * Gets the value attribute of the Element object as an Object.
- *
- * This method is provided for those wishing to use ehcache as a memory only cache
- * and enables retrieval of non-Serializable values from elements.
- *
- * @return The value as an Object. i.e no restriction is placed on it
- * @see #getValue()
- * @since 1.2
- */
- public final Object getObjectValue() {
- return value;
- }
-
- /**
- * Equals comparison with another element, based on the key.
- */
- @Override
- public final boolean equals(final Object object) {
- if (object == null || !(object instanceof Element)) {
- return false;
- }
-
- Element element = (Element) object;
- if (key == null || element.getObjectKey() == null) {
- return false;
- }
-
- return key.equals(element.getObjectKey());
- }
-
- /**
- * Sets time to Live
- *
- * Value must be a positive integer, 0 means infinite time to live.
- *
- * If calling this method with 0 as the parameter, consider using {@link #setEternal(boolean)}
- * or make sure you also explicitly call {@link #setTimeToIdle(int)}.
- *
- * @param timeToLiveSeconds the number of seconds to live
- */
- public void setTimeToLive(final int timeToLiveSeconds) {
- if (timeToLiveSeconds < 0) {
- throw new IllegalArgumentException("timeToLive can't be negative");
- }
- this.cacheDefaultLifespan = false;
- this.timeToLive = timeToLiveSeconds;
- }
-
- /**
- * Sets time to idle
- *
- * Value must be a positive integer, 0 means infinite time to idle.
- *
- * If calling this method with 0 as the parameter, consider using {@link #setEternal(boolean)}
- * or make sure you also explicitly call {@link #setTimeToLive(int)}.
- *
- * @param timeToIdleSeconds the number of seconds to idle
- */
- public void setTimeToIdle(final int timeToIdleSeconds) {
- if (timeToIdleSeconds < 0) {
- throw new IllegalArgumentException("timeToIdle can't be negative");
- }
- this.cacheDefaultLifespan = false;
- this.timeToIdle = timeToIdleSeconds;
- }
-
- /**
- * Gets the hashcode, based on the key.
- */
- @Override
- public final int hashCode() {
- return key.hashCode();
- }
-
- /**
- * Sets the version attribute of the ElementAttributes object.
- *
- * @param version The new version value
- */
- public final void setVersion(final long version) {
- this.version = version;
- }
-
- /**
- * Sets the element identifier (this field is used internally by ehcache). Setting this field in application code will not be preserved
- *
- * @param id The new id value
- */
- void setId(final long id) {
- if (id == NOT_SET_ID) {
- throw new IllegalArgumentException("Id cannot be set to " + id);
- }
- this.id = id;
- }
-
- /**
- * Gets the element identifier (this field is used internally by ehcache)
- *
- * @return id the id
- */
- long getId() {
- final long v = id;
- if (v == NOT_SET_ID) {
- throw new IllegalStateException("Id not set");
- }
- return v;
- }
-
- /**
- * Determines if an Id has been set on this element
- *
- * @return true if this element has an Id
- */
- boolean hasId() {
- return id != NOT_SET_ID;
- }
-
- /**
- * Sets the creationTime attribute of the ElementAttributes object.
- *
- * Note that in a Terracotta clustered environment, resetting the creation
- * time will not have any effect.
- *
- * @deprecated Resetting the creation time is not recommended as of version
- * 1.7
- */
- @Deprecated
- public final void setCreateTime() {
- creationTime = getCurrentTime();
- }
-
- /**
- * Gets the creationTime of the Element
- *
- * @return The creationTime value
- */
- public final long getCreationTime() {
- return creationTime;
- }
-
- /**
- * Calculates the latest of creation and update time
- * @return if never updated, creation time is returned, otherwise updated time
- */
- public final long getLatestOfCreationAndUpdateTime() {
- if (0 == lastUpdateTime) {
- return creationTime;
- } else {
- return lastUpdateTime;
- }
- }
-
- /**
- * Gets the version attribute of the ElementAttributes object.
- *
- * @return The version value
- */
- public final long getVersion() {
- return version;
- }
-
- /**
- * Gets the last access time of this element.
- *
- * Access means the element was written into a cache or read from it.
- * When first instantiated an {@link Element} has a lastAccessTime of 0, unless passed into the constructor.
- *
- * @return last access time in unix epoch
- * @see #Element(Object, Object, long, long, long, long, boolean, int, int, long)
- * @see #Element(Object, Object, long, long, long, long, long)
- * @see #resetAccessStatistics()
- * @see #updateAccessStatistics()
- */
- public final long getLastAccessTime() {
- return lastAccessTime;
- }
-
- /**
- * Gets the next to last access time.
- *
- * @deprecated The {@code nextToLastAccessTime} field is unused since
- * version 1.7, retrieving it will return the {@code
- * lastAccessTime}. Use #getLastAccessTime() instead.
- * @see #getLastAccessTime()
- */
- @Deprecated
- public final long getNextToLastAccessTime() {
- return getLastAccessTime();
- }
-
- /**
- * Gets the hit count on this element.
- */
- public final long getHitCount() {
- return hitCount;
- }
-
- /**
- * Resets the hit count to 0 and the last access time to now. Used when an Element is put into a cache.
- */
- public final void resetAccessStatistics() {
- lastAccessTime = getCurrentTime();
- HIT_COUNT_UPDATER.set(this, 0);
- }
-
- /**
- * Sets the last access time to now and increase the hit count.
- */
- public final void updateAccessStatistics() {
- lastAccessTime = getCurrentTime();
- HIT_COUNT_UPDATER.incrementAndGet(this);
- }
-
- /**
- * Sets the last access time to now without updating the hit count.
- */
- public final void updateUpdateStatistics() {
- lastUpdateTime = getCurrentTime();
- if (ELEMENT_VERSION_AUTO) {
- version = lastUpdateTime;
- }
- }
-
-
- /**
- * Returns a {@link String} representation of the {@link Element}.
- */
- @Override
- public final String toString() {
- StringBuilder sb = new StringBuilder();
-
- sb.append("[ key = ").append(key)
- .append(", value=").append(value)
- .append(", version=").append(version)
- .append(", hitCount=").append(hitCount)
- .append(", CreationTime = ").append(this.getCreationTime())
- .append(", LastAccessTime = ").append(this.getLastAccessTime())
- .append(" ]");
-
- return sb.toString();
- }
-
- /**
- * Clones an Element. A completely new object is created, with no common references with the
- * existing one.
- *
- * This method will not work unless the Object is Serializable
- *
- * Warning: This can be very slow on large object graphs. If you use this method
- * you should write a performance test to verify suitability.
- *
- * @return a new {@link Element}, with exactly the same field values as the one it was cloned from.
- * @throws CloneNotSupportedException
- */
- @Override
- public final Object clone() throws CloneNotSupportedException {
- //Not used. Just to get code inspectors to shut up
- super.clone();
-
- try {
- return new Element(deepCopy(key), deepCopy(value), version, creationTime, lastAccessTime, 0L, hitCount);
- } catch (IOException e) {
- LOG.error("Error cloning Element with key " + key
- + " during serialization and deserialization of value");
- throw new CloneNotSupportedException();
- } catch (ClassNotFoundException e) {
- LOG.error("Error cloning Element with key " + key
- + " during serialization and deserialization of value");
- throw new CloneNotSupportedException();
- }
- }
-
- private static Object deepCopy(final Object oldValue) throws IOException, ClassNotFoundException {
- Serializable newValue = null;
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- ObjectOutputStream oos = null;
- ObjectInputStream ois = null;
- try {
- oos = new ObjectOutputStream(bout);
- oos.writeObject(oldValue);
- ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
- ois = new ObjectInputStream(bin);
- newValue = (Serializable) ois.readObject();
- } finally {
- try {
- if (oos != null) {
- oos.close();
- }
- if (ois != null) {
- ois.close();
- }
- } catch (Exception e) {
- LOG.error("Error closing Stream");
- }
- }
- return newValue;
- }
-
- /**
- * The size of this object in serialized form. This is not the same
- * thing as the memory size, which is JVM dependent. Relative values should be meaningful,
- * however.
- *
- * Warning: This method can be very slow for values which contain large object graphs.
- *
- * If the key or value of the Element is not Serializable, an error will be logged and 0 will be returned.
- *
- * @return The serialized size in bytes
- */
- public final long getSerializedSize() {
-
- if (!isSerializable()) {
- return 0;
- }
- long size = 0;
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- ObjectOutputStream oos = null;
- try {
- oos = new ObjectOutputStream(bout);
- oos.writeObject(this);
- size = bout.size();
- return size;
- } catch (IOException e) {
- LOG.debug("Error measuring element size for element with key " + key + ". Cause was: " + e.getMessage());
- } finally {
- try {
- if (oos != null) {
- oos.close();
- }
- } catch (Exception e) {
- LOG.error("Error closing ObjectOutputStream");
- }
- }
-
- return size;
- }
-
- /**
- * Whether the element may be Serialized.
- *
- * While Element implements Serializable, it is possible to create non Serializable elements
- * for use in MemoryStores. This method checks that an instance of Element really is Serializable
- * and will not throw a NonSerializableException if Serialized.
- *
- * This method was tweaked in 1.6 as it has been shown that Serializable classes can be serializaed as can
- * null, regardless of what class it is a null of. ObjectOutputStream.write(null) works and ObjectInputStream.read()
- * will read null back.
- *
- * @return true if the element is Serializable
- * @since 1.2
- */
- public final boolean isSerializable() {
- return isKeySerializable()
- && (value instanceof Serializable || value == null);
- }
-
- /**
- * Whether the element's key may be Serialized.
- *
- * While Element implements Serializable, it is possible to create non Serializable elements and/or
- * non Serializable keys for use in MemoryStores.
- *
- * This method checks that an instance of an Element's key really is Serializable
- * and will not throw a NonSerializableException if Serialized.
- *
- * @return true if the element's key is Serializable
- * @since 1.2
- */
- public final boolean isKeySerializable() {
- return key instanceof Serializable || key == null;
- }
-
- /**
- * If there is an Element in the Cache and it is replaced with a new Element for the same key,
- * then both the version number and lastUpdateTime should be updated to reflect that. The creation time
- * will be the creation time of the new Element, not the original one, so that TTL concepts still work.
- *
- * @return the time when the last update occured. If this is the original Element, the time will be null
- */
- public long getLastUpdateTime() {
- return lastUpdateTime;
- }
-
- /**
- * An element is expired if the expiration time as given by {@link #getExpirationTime()} is in the past.
- *
- * @return true if the Element is expired, otherwise false. If no lifespan has been set for the Element it is
- * considered not able to expire.
- * @see #getExpirationTime()
- */
- public boolean isExpired() {
- if (!isLifespanSet() || isEternal()) {
- return false;
- }
-
- long now = getCurrentTime();
- long expirationTime = getExpirationTime();
-
- return now > expirationTime;
- }
-
- /**
- * An element is expired if the expiration time as given by {@link #getExpirationTime()} is in the past.
- *
- * This method in addition propogates the default TTI/TTL values of the supplied cache into this element.
- *
- * @param config config to take default parameters from
- * @return true if the Element is expired, otherwise false. If no lifespan has been set for the Element it is
- * considered not able to expire.
- * @see #getExpirationTime()
- */
- public boolean isExpired(CacheConfiguration config) {
- if (cacheDefaultLifespan) {
- if (config.isEternal()) {
- timeToIdle = 0;
- timeToLive = 0;
- } else {
- timeToIdle = TimeUtil.convertTimeToInt(config.getTimeToIdleSeconds());
- timeToLive = TimeUtil.convertTimeToInt(config.getTimeToLiveSeconds());
- }
- }
- return isExpired();
- }
-
- /**
- * Returns the expiration time based on time to live. If this element also has a time to idle setting, the expiry
- * time will vary depending on whether the element is accessed.
- *
- * @return the time to expiration
- */
- public long getExpirationTime() {
- if (!isLifespanSet() || isEternal()) {
- return Long.MAX_VALUE;
- }
-
- long expirationTime = 0;
- long ttlExpiry = creationTime + TimeUtil.toMillis(getTimeToLive());
-
- long mostRecentTime = Math.max(creationTime, lastAccessTime);
- long ttiExpiry = mostRecentTime + TimeUtil.toMillis(getTimeToIdle());
-
- if (getTimeToLive() != 0 && (getTimeToIdle() == 0 || lastAccessTime == 0)) {
- expirationTime = ttlExpiry;
- } else if (getTimeToLive() == 0) {
- expirationTime = ttiExpiry;
- } else {
- expirationTime = Math.min(ttlExpiry, ttiExpiry);
- }
- return expirationTime;
- }
-
- /**
- * @return true if the element is eternal
- */
- public boolean isEternal() {
- return (0 == timeToIdle) && (0 == timeToLive);
- }
-
- /**
- * Sets whether the element is eternal.
- *
- * @param eternal
- */
- public void setEternal(final boolean eternal) {
- if (eternal) {
- this.cacheDefaultLifespan = false;
- this.timeToIdle = 0;
- this.timeToLive = 0;
- } else if (isEternal()) {
- this.cacheDefaultLifespan = false;
- this.timeToIdle = Integer.MIN_VALUE;
- this.timeToLive = Integer.MIN_VALUE;
- }
- }
-
- /**
- * Whether any combination of eternal, TTL or TTI has been set.
- *
- * @return true if set.
- */
- public boolean isLifespanSet() {
- return this.timeToIdle != Integer.MIN_VALUE || this.timeToLive != Integer.MIN_VALUE;
- }
-
- /**
- * @return the time to live, in seconds
- */
- public int getTimeToLive() {
- if (Integer.MIN_VALUE == timeToLive) {
- return 0;
- } else {
- return timeToLive;
- }
- }
-
- /**
- * @return the time to idle, in seconds
- */
- public int getTimeToIdle() {
- if (Integer.MIN_VALUE == timeToIdle) {
- return 0;
- } else {
- return timeToIdle;
- }
- }
-
- /**
- * @return false
if this Element has a custom lifespan
- */
- public boolean usesCacheDefaultLifespan() {
- return cacheDefaultLifespan;
- }
-
- /**
- * Set the default parameters of this element - those from its enclosing cache.
- * @param tti TTI in seconds
- * @param ttl TTL in seconds
- * @param eternal true
if the element is eternal.
- */
- protected void setLifespanDefaults(int tti, int ttl, boolean eternal) {
- if (eternal) {
- this.timeToIdle = 0;
- this.timeToLive = 0;
- } else if (isEternal()) {
- this.timeToIdle = Integer.MIN_VALUE;
- this.timeToLive = Integer.MIN_VALUE;
- } else {
- timeToIdle = tti;
- timeToLive = ttl;
- }
- }
-
- /**
- * Seam for testing purposes
- * @return System.currentTimeMillis() by default
- */
- long getCurrentTime() {
- return System.currentTimeMillis();
- }
-
- /**
- * Custom serialization write logic
- */
- private void writeObject(ObjectOutputStream out) throws IOException {
- out.defaultWriteObject();
- out.writeInt(TimeUtil.toSecs(creationTime));
- out.writeInt(TimeUtil.toSecs(lastAccessTime));
- }
-
- /**
- * Custom serialization read logic
- */
- private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
- in.defaultReadObject();
- creationTime = TimeUtil.toMillis(in.readInt());
- lastAccessTime = TimeUtil.toMillis(in.readInt());
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/MemoryStoreEvictionPolicy.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/MemoryStoreEvictionPolicy.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/MemoryStoreEvictionPolicy.java (revision 0)
@@ -1,123 +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.io.Serializable;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A typesafe enumeration of eviction policies.
- * The policy used to evict elements from the {@link net.sf.ehcache.store.MemoryStore}.
- * This can be one of:
- *
- * LRU - least recently used
- * LFU - least frequently used
- * FIFO - first in first out, the oldest element by creation time
- *
- * The default value is LRU
- *
- * @author Greg Luck
- * @version $Id: MemoryStoreEvictionPolicy.java 5594 2012-05-07 16:04:31Z cdennis $
- * @since 1.2
- */
-public final class MemoryStoreEvictionPolicy implements Serializable {
-
- /**
- * LRU - least recently used.
- */
- public static final MemoryStoreEvictionPolicy LRU = new MemoryStoreEvictionPolicy("LRU");
-
- /**
- * LFU - least frequently used.
- */
-
- public static final MemoryStoreEvictionPolicy LFU = new MemoryStoreEvictionPolicy("LFU");
-
- /**
- * FIFO - first in first out, the oldest element by creation time.
- */
- public static final MemoryStoreEvictionPolicy FIFO = new MemoryStoreEvictionPolicy("FIFO");
-
- /**
- * FIFO - first in first out, the oldest element by creation time.
- */
- public static final MemoryStoreEvictionPolicy CLOCK = new MemoryStoreEvictionPolicy("CLOCK");
-
- private static final Logger LOG = LoggerFactory.getLogger(MemoryStoreEvictionPolicy.class.getName());
-
- private final String myName;
-
- /**
- * This class should not be subclassed or have instances created.
- * @param policy
- */
- private MemoryStoreEvictionPolicy(String policy) {
- myName = policy;
- }
-
- /**
- * @return a String representation of the policy
- */
- @Override
- public String toString() {
- return myName;
- }
-
- /**
- * Converts a string representation of the policy into a policy.
- *
- * @param policy either LRU, LFU or FIFO
- * @return one of the static instances
- */
- public static MemoryStoreEvictionPolicy fromString(String policy) {
- if (policy != null) {
- if (policy.equalsIgnoreCase("LRU")) {
- return LRU;
- } else if (policy.equalsIgnoreCase("LFU")) {
- return LFU;
- } else if (policy.equalsIgnoreCase("FIFO")) {
- return FIFO;
- } else if (policy.equalsIgnoreCase("CLOCK")) {
- return CLOCK;
- }
- }
- LOG.warn("The memoryStoreEvictionPolicy of {} cannot be resolved. The policy will be set to LRU", policy);
- return LRU;
- }
-
- /**
- * Enum for {@link MemoryStoreEvictionPolicy}
- *
- */
- public static enum MemoryStoreEvictionPolicyEnum {
- /**
- * Value for {@link MemoryStoreEvictionPolicy#LFU}
- */
- LFU,
- /**
- * Value for {@link MemoryStoreEvictionPolicy#LRU}
- */
- LRU,
- /**
- * Value for {@link MemoryStoreEvictionPolicy#FIFO}
- */
- FIFO;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/store/PoolableMemoryStoreTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/store/PoolableMemoryStoreTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/store/PoolableMemoryStoreTest.java (revision 0)
@@ -1,234 +0,0 @@
-package net.sf.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.config.CacheConfiguration;
-import net.sf.ehcache.event.CacheEventListener;
-import net.sf.ehcache.pool.impl.BoundedPool;
-import net.sf.ehcache.pool.impl.ConstantSizeOfEngine;
-import net.sf.ehcache.pool.impl.RoundRobinOnHeapPoolEvictor;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.util.Collection;
-import java.util.concurrent.ConcurrentLinkedQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.atomic.AtomicReference;
-import org.hamcrest.number.OrderingComparison;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-/**
- * @author Ludovic Orban
- */
-public class PoolableMemoryStoreTest {
-
- private static final int ENTRIES = 2;
- private volatile Cache cache;
- private volatile BoundedPool onHeapPool;
- private volatile Store memoryStore;
-
- private static Collection keysOfOnHeapElements(Store store) {
- return (Collection) store.getKeys();
- }
-
- private static int countElementsOnHeap(Store store) {
- return keysOfOnHeapElements(store).size();
- }
-
- private void dump() {
- System.out.println("# # # # # #");
- System.out.println(memoryStore.getSize() + " elements in cache");
- System.out.println("on heap: " + keysOfOnHeapElements(memoryStore));
- System.out.println("on heap size: " + onHeapPool.getSize());
- System.out.println("# # # # # #");
- }
-
- @Before
- public void setUp() {
- cache = new Cache(new CacheConfiguration("myCache1", 0).eternal(true));
-
- cache.getCacheEventNotificationService().registerListener(new CacheEventListener() {
- public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException { }
-
- public void notifyElementPut(Ehcache cache, Element element) throws CacheException { }
-
- 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 {
- return super.clone();
- }
- });
-
- onHeapPool = new BoundedPool(
- 16384 * ENTRIES, // == 2 elements
- new RoundRobinOnHeapPoolEvictor(),
- new ConstantSizeOfEngine(
- 1536, /* 1.5 KB*/
- 14336, /* 14 KB */
- 512 /* 0.5 KB */
- )
- );
-
- memoryStore = MemoryStore.create(cache, onHeapPool);
- }
-
- @After
- public void tearDown() {
- cache.dispose();
- memoryStore.dispose();
- }
-
-
- @Test
- public void testPutNew() throws Exception {
- // put 20 new elements in, making sure eviction is working
- for (int i = 0; i < 20; i++) {
- Element e = new Element(i, "" + i);
- memoryStore.put(e);
- assertTrue("#" + i, countElementsOnHeap(memoryStore) <= ENTRIES);
- }
-
- assertEquals(ENTRIES, countElementsOnHeap(memoryStore));
- assertEquals(16384 * ENTRIES, onHeapPool.getSize());
-
- // get an on-heap element
- Object key = keysOfOnHeapElements(memoryStore).iterator().next();
- memoryStore.get(key);
-
- assertEquals(ENTRIES, countElementsOnHeap(memoryStore));
- assertEquals(16384 * ENTRIES, onHeapPool.getSize());
-
- // put a new element on-heap
- memoryStore.put(new Element(-1, "-1"));
-
- assertEquals(ENTRIES, countElementsOnHeap(memoryStore));
- assertEquals(16384 * ENTRIES, onHeapPool.getSize());
- }
-
- @Test
- public void testPutUpdate() throws Exception {
- // warm up
- memoryStore.put(new Element(1, "1"));
- memoryStore.put(new Element(2, "2"));
- memoryStore.put(new Element(3, "3"));
-
- assertEquals(2, memoryStore.getSize());
- assertEquals(16384 * 2, onHeapPool.getSize());
-
- // update element in memory
- Object key = keysOfOnHeapElements(memoryStore).iterator().next();
- memoryStore.put(new Element(key, key.toString()));
-
- // size can be 1 or 2, depending if the evicted element is the updated one or not
- if (memoryStore.getSize() == 2) {
- assertEquals(16384 * 2, onHeapPool.getSize());
- } else if (memoryStore.getSize() == 1) {
- assertEquals(16384, onHeapPool.getSize());
- } else {
- fail();
- }
- }
-
- @Test
- public void testRemove() throws Exception {
- // warm up
- memoryStore.put(new Element(1, "1"));
- memoryStore.put(new Element(2, "2"));
- memoryStore.put(new Element(3, "3"));
-
- assertEquals(2, memoryStore.getSize());
- assertEquals(16384 * 2, onHeapPool.getSize());
-
- // remove element on heap
- Object key = keysOfOnHeapElements(memoryStore).iterator().next();
- memoryStore.remove(key);
-
- assertEquals(1, memoryStore.getSize());
- assertEquals(16384, onHeapPool.getSize());
- }
-
- @Test
- public void testRemoveAll() throws Exception {
- // warm up
- memoryStore.put(new Element(1, "1"));
- memoryStore.put(new Element(2, "2"));
- memoryStore.put(new Element(3, "3"));
-
- assertEquals(2, memoryStore.getSize());
- assertEquals(16384 * 2, onHeapPool.getSize());
-
- memoryStore.removeAll();
-
- assertEquals(0, memoryStore.getSize());
- assertEquals(0, onHeapPool.getSize());
- }
-
- @Test
- public void testStabilityUnderMutation() throws Exception {
- memoryStore.put(new Element(1, new AtomicReference()));
- assertEquals(1, memoryStore.getSize());
- assertThat(memoryStore.getInMemorySizeInBytes(), OrderingComparison.greaterThan(0L));
- assertThat(onHeapPool.getSize(), OrderingComparison.greaterThan(0L));
-
- ((AtomicReference) memoryStore.get(1).getObjectValue()).set(new byte[1024]);
- memoryStore.remove(1);
-
- assertEquals(0, memoryStore.getSize());
- assertEquals(0, memoryStore.getInMemorySizeInBytes());
- assertEquals(0, onHeapPool.getSize());
- }
-
- @Test
- @Ignore
- public void testMultithreaded() throws Exception {
- final int nThreads = 16;
-
- final ExecutorService executor = Executors.newFixedThreadPool(nThreads);
- final ConcurrentLinkedQueue> queue = new ConcurrentLinkedQueue>();
-
- for (int i = 0; i < nThreads; i++) {
- final int threadId = i;
- Future> f = executor.submit(new Runnable() {
- public void run() {
- for (int i = 0; i < 10000; i++) {
- Element e = new Element(i, "" + i);
- memoryStore.put(e);
-
- assertTrue(threadId + "#" + i + " - " + onHeapPool.getSize(), 16384 * 2 >= onHeapPool.getSize());
-
- Thread.yield();
- if ((i + 1) % 1000 == 0) { dump(); memoryStore.removeAll(); }
- }
- }
- });
- queue.add(f);
- }
-
- while (!queue.isEmpty()) {
- Future> f = queue.poll();
- f.get();
- }
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/lifecycle/cache-listing.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/lifecycle/cache-listing.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/lifecycle/cache-listing.xml (revision 0)
@@ -1,41 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/OperationImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/OperationImpl.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/OperationImpl.java (revision 0)
@@ -1,130 +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.Set;
-import java.util.concurrent.ScheduledExecutorService;
-
-import net.sf.ehcache.statistics.extended.ExtendedStatistics.Latency;
-import net.sf.ehcache.statistics.extended.ExtendedStatistics.Result;
-import net.sf.ehcache.statistics.extended.ExtendedStatistics.Statistic;
-
-import org.terracotta.statistics.OperationStatistic;
-
-/**
- * The Class OperationImpl.
- *
- * @param the generic type
- * @author cdennis
- */
-class OperationImpl> implements Result {
-
- /** The source. */
- private final OperationStatistic source;
-
- /** The count. */
- private final SemiExpiringStatistic count;
-
- /** The rate. */
- private final RateImpl rate;
-
- /** The latency. */
- private final LatencyImpl latency;
-
- /**
- * Instantiates a new operation impl.
- *
- * @param source the source
- * @param targets the targets
- * @param averageNanos the average nanos
- * @param executor the executor
- * @param historySize the history size
- * @param historyNanos the history nanos
- */
- public OperationImpl(OperationStatistic source, Set targets, long averageNanos,
- ScheduledExecutorService executor, int historySize, long historyNanos) {
- this.source = source;
- this.count = new SemiExpiringStatistic(source.statistic(targets), executor, historySize, historyNanos);
- this.latency = new LatencyImpl(source, targets, averageNanos, executor, historySize, historyNanos);
- this.rate = new RateImpl(source, targets, averageNanos, executor, historySize, historyNanos);
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statisticsV2.extended.ExtendedStatistics.Result#rate()
- */
- @Override
- public Statistic rate() {
- return rate;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statisticsV2.extended.ExtendedStatistics.Result#latency()
- */
- @Override
- public Latency latency() throws UnsupportedOperationException {
- return latency;
- }
-
- /* (non-Javadoc)
- * @see net.sf.ehcache.statisticsV2.extended.ExtendedStatistics.Result#count()
- */
- @Override
- public Statistic count() {
- return count;
- }
-
- /**
- * Start.
- */
- void start() {
- count.start();
- rate.start();
- latency.start();
- }
-
- /**
- * Expire.
- *
- * @param expiryTime the expiry time
- * @return true, if successful
- */
- boolean expire(long expiryTime) {
- return (count.expire(expiryTime) & rate.expire(expiryTime) & latency.expire(expiryTime));
- }
-
- /**
- * Sets the window.
- *
- * @param averageNanos the new window
- */
- void setWindow(long averageNanos) {
- rate.setWindow(averageNanos);
- latency.setWindow(averageNanos);
- }
-
- /**
- * Sets the history.
- *
- * @param historySize the history size
- * @param historyNanos the history nanos
- */
- void setHistory(int historySize, long historyNanos) {
- count.setHistory(historySize, historyNanos);
- rate.setHistory(historySize, historyNanos);
- latency.setHistory(historySize, historyNanos);
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/expression/NotEqualTo.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/expression/NotEqualTo.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/expression/NotEqualTo.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.search.expression;
-
-import java.util.Map;
-
-import net.sf.ehcache.Element;
-import net.sf.ehcache.search.attribute.AttributeExtractor;
-
-/**
- * Criteria for plain "not equals to" condition
- *
- * @author teck
- */
-public class NotEqualTo extends EqualTo {
-
- /**
- * Constructor
- *
- * @param attributeName attribute name
- * @param value
- */
- public NotEqualTo(String attributeName, Object value) {
- super(attributeName, value);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean execute(Element e, Map attributeExtractors) {
- return !super.execute(e, attributeExtractors);
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/ExplicitlyUnclusteredStandaloneCacheTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/ExplicitlyUnclusteredStandaloneCacheTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/ExplicitlyUnclusteredStandaloneCacheTest.java (revision 0)
@@ -1,18 +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.ehcache.tests;
-
-import com.tc.test.config.model.TestConfig;
-
-/**
- * @author cdennis
- */
-public class ExplicitlyUnclusteredStandaloneCacheTest extends AbstractCacheTestBase {
-
- public ExplicitlyUnclusteredStandaloneCacheTest(TestConfig testConfig) {
- super("explicitly-unclustered-cache-test.xml", testConfig, UnclusteredClient.class, UnclusteredClient.class);
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/distribution/ehcache-distributed-big-payload-3.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/distribution/ehcache-distributed-big-payload-3.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/distribution/ehcache-distributed-big-payload-3.xml (revision 0)
@@ -1,425 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapTTLExpressTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapTTLExpressTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapTTLExpressTest.java (revision 0)
@@ -1,33 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.servermap;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.util.Iterator;
-
-public class ServerMapTTLExpressTest extends AbstractCacheTestBase {
-
- public ServerMapTTLExpressTest(TestConfig testConfig) {
- super("/servermap/basic-servermap-cache-test.xml", testConfig, ServerMapTTLExpressTestClient.class);
- testConfig.setDgcEnabled(true);
- testConfig.setDgcIntervalInSec(60);
- testConfig.addTcProperty("ehcache.evictor.logging.enabled", "true");
-
- // L1 properties
- final Iterator iter = testConfig.getClientConfig().getExtraClientJvmArgs().iterator();
- while (iter.hasNext()) {
- final String prop = iter.next();
- if (prop.contains("ehcache.storageStrategy.dcv2.localcache.enabled")) {
- // remove it and always disable localcache for this test
- iter.remove();
- }
- }
- // always disable local cache
- testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.ehcache.storageStrategy.dcv2.localcache.enabled=false");
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/package.html
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/package.html (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/package.html (revision 0)
@@ -1,7 +0,0 @@
-
-
-
-
-This package contains classes for ehcache search attributes
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/ConcurrencyValueTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/ConcurrencyValueTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/ConcurrencyValueTest.java (revision 0)
@@ -1,56 +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.ehcache.tests;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-
-public class ConcurrencyValueTest extends AbstractCacheTestBase {
- private static final int CDM_DEFAULT_CONCURRENCY = 256;
-
- public ConcurrencyValueTest(TestConfig testConfig) {
- super("basic-cache-test.xml", testConfig, Client1.class);
- }
-
- @Override
- protected void evaluateClientOutput(String clientName, int exitCode, File clientOutput) throws Throwable {
- super.evaluateClientOutput(clientName, exitCode, clientOutput);
-
- FileReader fr = null;
- boolean currencyValueLogged1 = false;
- boolean currencyValueLogged2 = false;
- String currencyValueLogMsg1 = getConcurrencyValueLogMsg("defaultConcurrencyCache", CDM_DEFAULT_CONCURRENCY);
- String currencyValueLogMsg2 = getConcurrencyValueLogMsg("configuredConcurrencyCache", 123);
- try {
- fr = new FileReader(clientOutput);
- BufferedReader reader = new BufferedReader(fr);
- String st = "";
- while ((st = reader.readLine()) != null) {
- if (st.contains(currencyValueLogMsg1)) currencyValueLogged1 = true;
- if (st.contains(currencyValueLogMsg2)) currencyValueLogged2 = true;
- }
- } catch (Exception e) {
- throw new AssertionError(e);
- } finally {
- try {
- fr.close();
- } catch (Exception e) {
- //
- }
- }
-
- if (!currencyValueLogged1) { throw new AssertionError(); }
-
- if (!currencyValueLogged2) { throw new AssertionError(); }
- }
-
- private static String getConcurrencyValueLogMsg(String name, int concurrency) {
- return "Cache [" + name + "] using concurrency: " + concurrency;
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/CacheCopyOnRwReplaceRemoveTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/CacheCopyOnRwReplaceRemoveTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/CacheCopyOnRwReplaceRemoveTest.java (revision 0)
@@ -1,113 +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.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.DiskStoreConfiguration;
-import net.sf.ehcache.config.MemoryUnit;
-import net.sf.ehcache.config.PersistenceConfiguration;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-import org.terracotta.test.categories.CheckShorts;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-@Category(CheckShorts.class)
-@RunWith(Parameterized.class)
-public class CacheCopyOnRwReplaceRemoveTest {
-
- public static final String MEMORY_CACHE = "memoryCache";
- public static final String DISK_CACHE = "diskCache";
-
- @Parameters(name = "copyOnRead:{0}, copyOnWrite:{1}")
- public static Collection data() {
- Object[][] data = new Object[][] { { true, false }, { false, true }, { true, true } };
- return Arrays.asList(data);
- }
-
- private final boolean copyOnRead;
- private final boolean copyOnWrite;
-
- private CacheManager cacheManager;
-
- public CacheCopyOnRwReplaceRemoveTest(boolean copyOnRead, boolean copyOnWrite) {
- this.copyOnRead = copyOnRead;
- this.copyOnWrite = copyOnWrite;
- }
-
- @Before
- public void setUp() throws Exception {
- cacheManager = CacheManager.create( new Configuration()
- .name("copyOnRWReplaceRemoveManager")
- .diskStore(new DiskStoreConfiguration().path(System.getProperty("java.io.tmpdir")))
- .maxBytesLocalHeap(100, MemoryUnit.KILOBYTES)
- .maxBytesLocalDisk(200, MemoryUnit.KILOBYTES));
- cacheManager.addCache(new Cache(new CacheConfiguration().name(MEMORY_CACHE)
- .copyOnRead(copyOnRead)
- .copyOnWrite(copyOnWrite)));
- cacheManager.addCache(new Cache(new CacheConfiguration().name(DISK_CACHE)
- .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.LOCALTEMPSWAP))
- .copyOnRead(copyOnRead)
- .copyOnWrite(copyOnWrite)));
- }
-
- @After
- public void tearDown() {
- cacheManager.shutdown();
- }
-
- @Test
- public void testMemoryCache() throws Exception {
- Ehcache cache = cacheManager.getCache(MEMORY_CACHE);
- testReplaceElement(cache);
- testRemoveElement(cache);
- }
-
- @Test
- public void testDiskCache() throws Exception {
- Ehcache cache = cacheManager.getCache(DISK_CACHE);
- testReplaceElement(cache);
- testRemoveElement(cache);
- }
-
- private void testReplaceElement(Ehcache cache) {
- Long key = System.nanoTime();
- String value = "value" + key;
- cache.put(new Element(new Long(key), new String(value)));
- Assert.assertEquals(cache.get(key).getValue(), new Element(new Long(key), new String(value)).getValue());
- String nextValue = value + "1";
- Assert.assertTrue(cache.replace(new Element(new Long(key), new String(value)), new Element(new Long(key), new String(nextValue))));
- }
-
- private void testRemoveElement(Ehcache cache) {
- Long key = System.nanoTime();
- String value = "value" + key;
- cache.put(new Element(new Long(key), new String(value)));
- Assert.assertEquals(cache.get(key).getValue(), new Element(new Long(key), new String(value)).getValue());
- Assert.assertTrue(cache.removeElement(new Element(new Long(key), new String(value))));
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/config/generator/StandaloneEntryBasedConfigAttributesValueFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/config/generator/StandaloneEntryBasedConfigAttributesValueFactory.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/config/generator/StandaloneEntryBasedConfigAttributesValueFactory.java (revision 0)
@@ -1,98 +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.generator;
-
-import net.sf.ehcache.config.generator.model.NodeAttribute;
-import net.sf.ehcache.config.generator.model.NodeElement;
-import net.sf.ehcache.config.generator.xsom.XSDAttributeValueFactory;
-import net.sf.ehcache.config.generator.xsom.XSDAttributeValueType;
-
-public class StandaloneEntryBasedConfigAttributesValueFactory implements XSDAttributeValueFactory {
-
- public String createValueForAttribute(NodeElement element, NodeAttribute attribute, XSDAttributeValueType xsdAttributeValueType) {
- if ("terracotta".equals(element.getName())) {
- if("coherent".equals(attribute.getName())) {
- // returning null will skip this attribute
- // can skip "coherent" attribute as its deprecated by consistency attribute
- return null;
- }
- if("clustered".equals(attribute.getName())) {
- return "false";
- }
- }
- if ("pinning".equals(element.getName())) {
- if ("storage".equals(attribute.getName())) {
- return "inMemory";
- }
- }
- if ("sizeOfPolicy".equals(element.getName())) {
- if ("maxDepth".equals(attribute.getName())) {
- return "100";
- } else if ("maxDepthExceededBehavior".equals(attribute.getName())) {
- return "continue";
- }
- }
- // always generate with eternal=false
- if ("defaultCache".equals(element.getName()) || "cache".equals(element.getName())) {
- if("eternal".equals(attribute.getName())) {
- return "false";
- }
- if("transactionalMode".equals(attribute.getName())) {
- return "off";
- }
- // these are deprecated
- if ("maxElementsInMemory".equals(attribute.getName()) ||
- "maxMemoryOffHeap".equals(attribute.getName()) ||
- "diskPersistent".equals(attribute.getName()) ||
- "overflowToDisk".equals(attribute.getName())) {
- return null;
- }
- if ("maxElementsOnDisk".equals(attribute.getName()) ||
- "maxBytesLocalHeap".equals(attribute.getName()) ||
- "maxBytesLocalOffHeap".equals(attribute.getName()) ||
- "maxBytesLocalDisk".equals(attribute.getName())) {
- return null;
- }
- if("maxEntriesLocalHeap".equals(attribute.getName()) ||
- "maxEntriesLocalOffHeap".equals(attribute.getName()) ||
- "maxEntriesLocalDisk".equals(attribute.getName())) {
- return "10000";
- }
- if("maxEntriesInCache".equals(attribute.getName())) {
- return null;
- }
- }
- if ("ehcache".equals(element.getName())) {
- if("maxBytesLocalHeap".equals(attribute.getName()) ||
- "maxBytesLocalOffHeap".equals(attribute.getName()) ||
- "maxBytesLocalDisk".equals(attribute.getName())) {
- return null;
- }
- }
- if ("searchAttribute".equals(element.getName())) {
- if ("expression".equals(attribute.getName())) {
- return "value.toString()";
- } else if ("name".equals(attribute.getName())) {
- return "name";
- } else {
- return null;
- }
- }
-
- return xsdAttributeValueType.getRandomAllowedValue();
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/SimpleNodeAttribute.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/SimpleNodeAttribute.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/SimpleNodeAttribute.java (revision 0)
@@ -1,256 +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.generator.model;
-
-/**
- * Implementation of the {@link NodeAttribute} interface
- *
- * @author Abhishek Sanoujam
- *
- */
-public class SimpleNodeAttribute implements NodeAttribute {
-
- private final String name;
- private String value;
- private String defaultValue;
- private boolean optional = true;
-
- /**
- * Constructor accepting the name of the attribute
- *
- * @param name
- * the name of the attribute
- */
- public SimpleNodeAttribute(String name) {
- this(name, (String) null);
- }
-
- /**
- * Constructor accepting name and Enum value of the attribute
- *
- * @param name
- * the name of the attribute
- * @param value
- * the Enum value of the attribute
- */
- public SimpleNodeAttribute(String name, Enum value) {
- this(name, value.name().toLowerCase());
- }
-
- /**
- * Constructor accepting name and int value of the attribute
- *
- * @param name
- * the name of the attribute
- * @param value
- * the int value of the attribute
- */
- public SimpleNodeAttribute(String name, int value) {
- this(name, String.valueOf(value));
- }
-
- /**
- * Constructor accepting name and long value of the attribute
- *
- * @param name
- * the name of the attribute
- * @param value
- * the long value of the attribute
- */
- public SimpleNodeAttribute(String name, long value) {
- this(name, String.valueOf(value));
- }
-
- /**
- * Constructor accepting name and boolean value of the attribute
- *
- * @param name
- * the name of the attribute
- * @param value
- * the boolean value of the attribute
- */
- public SimpleNodeAttribute(String name, boolean value) {
- this(name, String.valueOf(value));
- }
-
- /**
- * Constructor accepting name and String value of the attribute
- *
- * @param name
- * the name of the attribute
- * @param value
- * the String value of the attribute
- */
- public SimpleNodeAttribute(String name, String value) {
- this.name = name;
- this.value = value;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getName() {
- return name;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getValue() {
- return value;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isOptional() {
- return optional;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setOptional(boolean optional) {
- this.optional = optional;
- }
-
- /**
- * {@inheritDoc}
- */
- public String getDefaultValue() {
- return defaultValue;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setDefaultValue(String defaultValue) {
- this.defaultValue = defaultValue;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setValue(String value) {
- this.value = value;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
- if (obj == null) {
- return false;
- }
- if (!(obj instanceof NodeAttribute)) {
- return false;
- }
- NodeAttribute other = (NodeAttribute) obj;
- if (name == null) {
- if (other.getName() != null) {
- return false;
- }
- } else if (!name.equals(other.getName())) {
- return false;
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String toString() {
- return "SimpleAttribute [name=" + name + "]";
- }
-
- /**
- * {@inheritDoc}
- */
- public SimpleNodeAttribute optional(boolean optional) {
- this.optional = optional;
- return this;
- }
-
- /**
- * {@inheritDoc}
- */
- public SimpleNodeAttribute defaultValue(String defaultValue) {
- this.defaultValue = defaultValue;
- return this;
- }
-
- /**
- * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue)
- *
- * @param defaultValue
- * the default value
- * @return the same instance
- */
- public SimpleNodeAttribute defaultValue(boolean defaultValue) {
- return this.defaultValue(String.valueOf(defaultValue));
- }
-
- /**
- * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue)
- *
- * @param defaultValue
- * the default value
- * @return the same instance
- */
- public SimpleNodeAttribute defaultValue(int defaultValue) {
- return this.defaultValue(String.valueOf(defaultValue));
- }
-
- /**
- * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue)
- *
- * @param defaultValue
- * the default value
- * @return the same instance
- */
- public SimpleNodeAttribute defaultValue(Enum defaultValue) {
- return this.defaultValue(defaultValue.name().toLowerCase());
- }
-
- /**
- * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue)
- *
- * @param defaultValue
- * the default value
- * @return the same instance
- */
- public SimpleNodeAttribute defaultValue(long defaultValue) {
- return this.defaultValue(String.valueOf(defaultValue));
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/ToolkitNonStopExceptionOnTimeoutConfiguration.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/ToolkitNonStopExceptionOnTimeoutConfiguration.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/ToolkitNonStopExceptionOnTimeoutConfiguration.java (revision 0)
@@ -1,27 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.store;
-
-import net.sf.ehcache.config.NonstopConfiguration;
-
-import org.terracotta.toolkit.nonstop.NonStopConfigurationFields.NonStopReadTimeoutBehavior;
-import org.terracotta.toolkit.nonstop.NonStopConfigurationFields.NonStopWriteTimeoutBehavior;
-
-public class ToolkitNonStopExceptionOnTimeoutConfiguration extends ToolkitNonStopConfiguration {
-
- public ToolkitNonStopExceptionOnTimeoutConfiguration(NonstopConfiguration ehcacheNonStopConfig) {
- super(ehcacheNonStopConfig);
- }
-
- @Override
- public NonStopReadTimeoutBehavior getReadOpNonStopTimeoutBehavior() {
- return NonStopReadTimeoutBehavior.EXCEPTION;
- }
-
- @Override
- public NonStopWriteTimeoutBehavior getWriteOpNonStopTimeoutBehavior() {
- return NonStopWriteTimeoutBehavior.EXCEPTION;
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/SizeOfPolicyConfigurationElement.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/SizeOfPolicyConfigurationElement.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/SizeOfPolicyConfigurationElement.java (revision 0)
@@ -1,67 +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.generator.model.elements;
-
-import net.sf.ehcache.config.SizeOfPolicyConfiguration;
-import net.sf.ehcache.config.generator.model.NodeElement;
-import net.sf.ehcache.config.generator.model.SimpleNodeAttribute;
-import net.sf.ehcache.config.generator.model.SimpleNodeElement;
-
-/**
- * Element representing the {@link net.sf.ehcache.config.SizeOfPolicyConfiguration}
- *
- * @author Ludovic Orban
- *
- */
-public class SizeOfPolicyConfigurationElement extends SimpleNodeElement {
- private final SizeOfPolicyConfiguration sizeOfPolicyConfiguration;
-
- /**
- * Construtor accepting the parent and the {@link net.sf.ehcache.config.SizeOfPolicyConfiguration}
- *
- * @param parent
- * @param sizeOfPolicyConfiguration
- */
- public SizeOfPolicyConfigurationElement(ConfigurationElement parent, SizeOfPolicyConfiguration sizeOfPolicyConfiguration) {
- super(parent, "sizeOfPolicy");
- this.sizeOfPolicyConfiguration = sizeOfPolicyConfiguration;
- init();
- }
-
- /**
- * Construtor accepting the element and the {@link net.sf.ehcache.config.SizeOfPolicyConfiguration}
- *
- * @param element
- * @param sizeOfPolicyConfiguration
- */
- public SizeOfPolicyConfigurationElement(NodeElement element, SizeOfPolicyConfiguration sizeOfPolicyConfiguration) {
- super(element, "sizeOfPolicy");
- this.sizeOfPolicyConfiguration = sizeOfPolicyConfiguration;
- init();
- }
-
- private void init() {
- if (sizeOfPolicyConfiguration == null) {
- return;
- }
- addAttribute(new SimpleNodeAttribute("maxDepth", sizeOfPolicyConfiguration.getMaxDepth())
- .optional(true).defaultValue(SizeOfPolicyConfiguration.DEFAULT_MAX_SIZEOF_DEPTH));
- addAttribute(new SimpleNodeAttribute("maxDepthExceededBehavior", sizeOfPolicyConfiguration.getMaxDepthExceededBehavior())
- .optional(true).defaultValue(SizeOfPolicyConfiguration.DEFAULT_MAX_DEPTH_EXCEEDED_BEHAVIOR));
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-search-parser/.classpath
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-search-parser/.classpath (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-search-parser/.classpath (revision 0)
@@ -1,37 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/TwoResourceBTMXATest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/TwoResourceBTMXATest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/TwoResourceBTMXATest.java (revision 0)
@@ -1,33 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.txns;
-
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.test.util.TestBaseUtil;
-
-import bitronix.tm.TransactionManagerServices;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class TwoResourceBTMXATest extends AbstractCacheTestBase {
-
- public TwoResourceBTMXATest(TestConfig testConfig) {
- super("two-resource-xa-test.xml", testConfig, BTMTwoResourceTx1.class, BTMTwoResourceTx2.class);
- testConfig.getClientConfig().setParallelClients(true);
-
- // DEV-3930
- // disableAllUntil("2010-03-31");
- }
-
- @Override
- protected List getExtraJars() {
- List extraJars = new ArrayList();
- extraJars.add(TestBaseUtil.jarFor(TransactionManagerServices.class));
- return extraJars;
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/byteman/debugEhcacheTxnsState.btm
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/byteman/debugEhcacheTxnsState.btm (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/byteman/debugEhcacheTxnsState.btm (revision 0)
@@ -1,44 +0,0 @@
-
-
-RULE trace EhcacheTxnsClusteredStateFacadeImpl getXATransactionDecision
-CLASS EhcacheTxnsClusteredStateFacadeImpl
-METHOD getXATransactionDecision
-AT EXIT
-IF true
-DO traceln("[ehcache txns facade] getXATransactionDecision - key.hashCode(): " + $key.hashCode() + " returning:-> " + $!);
-ENDRULE
-
-RULE trace EhcacheTxnsClusteredStateFacadeImpl updateXATransactionDecision
-CLASS EhcacheTxnsClusteredStateFacadeImpl
-METHOD updateXATransactionDecision
-AT EXIT
-IF true
-DO traceln("[ehcache txns facade] updateXATransactionDecision - key.hashCode(): " + $key.hashCode() + ", newDecision: " + $newDecision);
-ENDRULE
-
-RULE trace EhcacheTxnsClusteredStateFacadeImpl getSoftLockState
-CLASS EhcacheTxnsClusteredStateFacadeImpl
-METHOD getSoftLockState
-AT EXIT
-IF true
-DO traceln("[ehcache txns facade] getSoftLockState - key.hashCode(): " + $key.hashCode() + " returning:-> " + $!);
-ENDRULE
-
-RULE trace EhcacheTxnsClusteredStateFacadeImpl updateSoftLockState
-CLASS EhcacheTxnsClusteredStateFacadeImpl
-METHOD updateSoftLockState
-AFTER INVOKE put
-IF true
-DO traceln("[ehcache txns facade] updateSoftLockState, after put - key.hashCode(): " + $key.hashCode() + ", newSoftLockState: " + $newSoftLockState);
-AT EXIT
-IF true
-DO traceln("[ehcache txns facade] updateSoftLockState, returning for key.hashCode(): " + $key.hashCode() + " returning:-> " + $!);
-ENDRULE
-
-RULE trace EhcacheTxnsClusteredStateFacadeImpl isExpired
-CLASS EhcacheTxnsClusteredStateFacadeImpl
-METHOD isExpired
-AT EXIT
-IF true
-DO traceln("[ehcache txns facade] isExpired - softLockId.hashCode(): " + serializeToString($softLockId).hashCode() + " returning:-> " + $!);
-ENDRULE
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/lifecycle/CacheManagerDestroyCrashTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/lifecycle/CacheManagerDestroyCrashTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/lifecycle/CacheManagerDestroyCrashTest.java (revision 0)
@@ -1,159 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.lifecycle;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ConfigurationFactory;
-import net.sf.ehcache.config.TerracottaConfiguration;
-
-import org.mockito.Mockito;
-import org.objenesis.ObjenesisStd;
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-import org.terracotta.test.util.TestBaseUtil;
-import org.terracotta.toolkit.Toolkit;
-
-import com.tc.test.config.model.TestConfig;
-import com.terracotta.entity.ClusteredEntityManager;
-import com.terracotta.entity.ehcache.ClusteredCacheManager;
-
-import java.io.IOException;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.verify;
-
-public class CacheManagerDestroyCrashTest extends AbstractCacheTestBase {
- private static final String CACHE_NAME = "cache1";
-
- public CacheManagerDestroyCrashTest(TestConfig testConfig) {
- super("lifecycle/cache-destroy.xml", testConfig, CacheManagerCreateClient.class,
- CacheManagerEntityDestroyCrashClient.class);
- }
-
- @Override
- protected String createClassPath(Class client) throws IOException {
- String classpath = super.createClassPath(client);
- classpath = addToClasspath(classpath, TestBaseUtil.jarFor(Mockito.class));
- classpath = addToClasspath(classpath, TestBaseUtil.jarFor(ObjenesisStd.class));
- return classpath;
- }
-
- public static class CacheManagerCreateClient extends ClientBase {
-
- public CacheManagerCreateClient(String[] mainArgs) {
- super(mainArgs);
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit myToolkit) throws Throwable {
-
- CacheConfiguration cacheConfig = new CacheConfiguration(CACHE_NAME, 100)
- .terracotta(new TerracottaConfiguration());
- cacheManager.addCache(new Cache(cacheConfig));
- cache = cacheManager.getCache(CACHE_NAME);
- cache.put(new Element("key", "value", true));
-
- cacheManager.shutdown();
-
- // Notify client to destroy
- getBarrierForAllClients().await(10, TimeUnit.SECONDS); // hit 1
-
- // Waiting for other client to signal destroy done
- getBarrierForAllClients().await(1, TimeUnit.MINUTES); // hit 2
-
- // Making sure adding back cache does not resurrect old data structures
- setupCacheManager();
- cacheManager.addCache(new Cache(cacheConfig));
- cache = cacheManager.getCache(CACHE_NAME);
- assertNull(cache.get("key"));
- }
-
- @Override
- protected Cache getCache() {
- return null;
- }
-
- }
-
- public static class CacheManagerEntityDestroyCrashClient extends ClientBase {
-
- public CacheManagerEntityDestroyCrashClient(String[] mainArgs) {
- super(mainArgs);
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit myToolkit) throws Throwable {
- // Waiting for CM to be created
-
- waitForAllClients(); // hit 1
-
- Toolkit spiedToolkit = spy(getClusteringToolkit());
-
- ClusteredEntityManager clusteredEntityManager1 = new ClusteredEntityManager(spiedToolkit);
- Configuration configuration = ConfigurationFactory.parseConfiguration(getEhcacheXmlAsStream());
- String cmName = configuration.getName();
-
- Map cacheManagers = clusteredEntityManager1
- .getRootEntities(ClusteredCacheManager.class);
-
- ClusteredCacheManager clusteredCacheManager = cacheManagers.get(cmName);
-
- while(clusteredCacheManager.isUsed()) {
- TimeUnit.MILLISECONDS.sleep(200);
- }
-
-
- doThrow(new TestDestroyCrashException("Crashing destroy"))
- .when(spiedToolkit)
- .getCache(any(String.class), any(org.terracotta.toolkit.config.Configuration.class), any(Class.class));
- try {
- clusteredEntityManager1.destroyRootEntity(cmName, ClusteredCacheManager.class, clusteredCacheManager);
- fail("Destroy should have thrown an exception");
- } catch(TestDestroyCrashException e) {
- // Expected as we want destroy to crash
- e.printStackTrace();
- }
- reset(spiedToolkit);
-
- clusteredEntityManager1.getRootEntity(cmName, ClusteredCacheManager.class);
- // Shows inline clean up performed
- verify(spiedToolkit).getCache(any(String.class), any(org.terracotta.toolkit.config.Configuration.class), any(Class.class));
-
- reset(spiedToolkit);
-
- ClusteredEntityManager clusteredEntityManager2 = new ClusteredEntityManager(spiedToolkit);
- assertNull(clusteredEntityManager2.getRootEntity(cmName, ClusteredCacheManager.class));
-
- verify(spiedToolkit, never()).getCache(any(String.class), any(org.terracotta.toolkit.config.Configuration.class), any(Class.class));
-
- getBarrierForAllClients().await(10, TimeUnit.SECONDS); // hit 2
- }
-
- @Override
- protected void setupCacheManager() {
- // Do nothing here
- }
-
- @Override
- protected Cache getCache() {
- // Do nothing here
- return null;
- }
- }
-
- public static class TestDestroyCrashException extends RuntimeException {
- public TestDestroyCrashException(String msg) {
- super(msg);
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/wan/WANUtilTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/wan/WANUtilTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/wan/WANUtilTest.java (revision 0)
@@ -1,109 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.wan;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-
-import java.io.Serializable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-public class WANUtilTest {
- private static final String CACHE_MANAGER_NAME = "CACHE_MANAGER_NAME";
- private static final String CACHE_NAME = "CACHE_NAME";
-
- private WANUtil wanUtil;
- private ConcurrentMap cacheConfigMap;
- private ConcurrentMap cacheManagerConfigMap;
- private boolean testResult;
-
- @Before
- public void setUp() {
- cacheConfigMap = new ConcurrentHashMap();
- cacheManagerConfigMap = new ConcurrentHashMap();
-
- wanUtil = getTestableWANUtil();
- }
-
-
- @Test
- public void testIsWANReadyWhenOrchestratorWasUp() throws Exception {
- whenWANReady().callIsWANReady().assertResultIs(true);
- }
-
- @Test
- public void testIsWANReadyWhenOrchestratorWasDown() throws Exception {
- callIsWANReady().assertResultIs(false);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testIsWanEnabledCacheForNullParameters() throws Exception {
- callIsWanEnabledCache(CACHE_NAME, null).assertResultIs(false);
- callIsWanEnabledCache(null, CACHE_MANAGER_NAME).assertResultIs(false);
- }
-
- @Test
- public void testIsWanEnabledCacheWhenCacheMarkedWanEnabled() {
- whenCacheMarkedWanEnabled().callIsWanEnabledCache(CACHE_MANAGER_NAME, CACHE_NAME).assertResultIs(true);
- }
-
- @Test
- public void testaddCurrentOrchestrator() throws Exception {
- final String ORCHESTRATOR = "localhost:1000";
- final String WAN_CURRENT_ORCHESTRATOR = "__WAN__CURRENT_ORCHESTRATOR";
- wanUtil.addCurrentOrchestrator(CACHE_MANAGER_NAME, CACHE_NAME, ORCHESTRATOR);
- Assert.assertEquals(cacheConfigMap.get(WAN_CURRENT_ORCHESTRATOR), ORCHESTRATOR);
- }
-
- @Test
- public void testIsWanEnabledCacheWhenCacheMarkedWanDisabled() throws Exception {
- callIsWanEnabledCache(CACHE_MANAGER_NAME, CACHE_NAME).assertResultIs(false);
- }
-
- private WANUtilTest whenCacheMarkedWanEnabled() {
- wanUtil.markCacheWanEnabled(CACHE_MANAGER_NAME, CACHE_NAME);
- return this;
- }
-
- private WANUtilTest callIsWanEnabledCache(String cacheManagerName, String cacheName) {
- testResult = wanUtil.isWanEnabledCache(cacheManagerName, cacheName);
- return this;
- }
-
- private WANUtilTest callIsWANReady() {
- testResult = wanUtil.isWANReady(CACHE_MANAGER_NAME);
- return this;
- }
-
- private WANUtilTest whenWANReady() {
- wanUtil.markWANReady(CACHE_MANAGER_NAME);
- return this;
- }
-
- private void assertResultIs(boolean expectedResult) {
- Assert.assertEquals(expectedResult, testResult);
- }
-
- private WANUtil getTestableWANUtil() {
- return new WANUtil(null) {
- @Override
- ConcurrentMap getCacheConfigMap(String cacheManagerName, String cacheName) {
- return cacheConfigMap;
- }
-
- @Override
- ConcurrentMap getCacheManagerConfigMap(String cacheManagerName) {
- return cacheManagerConfigMap;
- }
-
- @Override
- void notifyClients(String cacheManagerName) {
- // Do Nothing
- }
- };
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/net/sf/ehcache/osgi/Event.hbm.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/net/sf/ehcache/osgi/Event.hbm.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/net/sf/ehcache/osgi/Event.hbm.xml (revision 0)
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/writebehind/operations/SingleAsyncOperation.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/writebehind/operations/SingleAsyncOperation.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/writebehind/operations/SingleAsyncOperation.java (revision 0)
@@ -1,50 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.writebehind.operations;
-
-import net.sf.ehcache.Element;
-import net.sf.ehcache.writer.CacheWriter;
-
-import java.io.IOException;
-import java.io.Serializable;
-
-/**
- * Interface to implement single operations that are performed in the write behind implementation that using an
- * AsyncCoordinator underneath
- *
- * @author Abhishek Maheshwari
- */
-public interface SingleAsyncOperation extends Serializable {
- /**
- * Perform this operation as a single execution with the provided cache writer
- *
- * @param cacheWriter the cache writer this operation should be performed upon
- */
- public void performSingleOperation(CacheWriter cacheWriter) throws ClassNotFoundException, IOException;
-
- /**
- * Retrieves the key for this operation.
- *
- * @return this operation's key
- */
- Object getKey();
-
- Element getElement();
-
- /**
- * Retrieves the moment when the operation was created.
- *
- * @return the creation time in milliseconds
- */
- public long getCreationTime();
-
- /**
- * This method will be called to throw the item away.
- *
- * @param cacheWriter
- * @param e
- */
- void throwAwayElement(CacheWriter cacheWriter, RuntimeException e);
-
-}
Index: rctags/ehcache-2.10.7.0.58/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/CachesResourceServiceImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/CachesResourceServiceImpl.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/CachesResourceServiceImpl.java (revision 0)
@@ -1,122 +0,0 @@
-package net.sf.ehcache.management.resource.services;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.PUT;
-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.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-
-import net.sf.ehcache.management.resource.CacheEntity;
-import net.sf.ehcache.management.service.CacheService;
-import net.sf.ehcache.management.service.EntityResourceFactory;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.terracotta.management.ServiceExecutionException;
-import org.terracotta.management.ServiceLocator;
-import org.terracotta.management.resource.exceptions.ResourceRuntimeException;
-import org.terracotta.management.resource.services.validator.RequestValidator;
-
-/**
- *
- *
- * A resource service for interacting with ehcache caches via the {@link CacheEntity}.
- *
- *
- * @author brandony
- */
-@Path("/agents/cacheManagers/caches")
-public final class CachesResourceServiceImpl {
-
- public static final String ATTR_QUERY_KEY = "show";
-
- private final static Logger LOG = LoggerFactory.getLogger(CachesResourceServiceImpl.class);
-
- private final EntityResourceFactory entityResourceFactory;
-
- private final CacheService cacheSvc;
-
- private final RequestValidator validator;
-
- public CachesResourceServiceImpl() {
- this.entityResourceFactory = ServiceLocator.locate(EntityResourceFactory.class);
- this.validator = ServiceLocator.locate(RequestValidator.class);
- this.cacheSvc = ServiceLocator.locate(CacheService.class);
- }
-
- /**
- *
- * Get a {@code Collection} of {@link CacheEntity} objects representing the cache information provided by the
- * associated monitorable entity's agent given the request path.
- *
- *
- * @param info
- * {@link UriInfo} for this resource request
- * @return a collection of {@link CacheEntity} objects when successful.
- */
- @GET
- @Produces(MediaType.APPLICATION_JSON)
- public Collection getCaches(@Context UriInfo info) {
- LOG.debug(String.format("Invoking CachesResourceServiceImpl.getCaches: %s", info.getRequestUri()));
-
- validator.validateSafe(info);
-
- String cacheManagerNames = info.getPathSegments().get(1).getMatrixParameters().getFirst("names");
- Set cmNames = cacheManagerNames == null ? null : new HashSet(
- Arrays.asList(cacheManagerNames.split(",")));
-
- String cacheNames = info.getPathSegments().get(2).getMatrixParameters().getFirst("names");
- Set cNames = cacheNames == null ? null : new HashSet(Arrays.asList(cacheNames.split(",")));
-
- MultivaluedMap qParams = info.getQueryParameters();
- List attrs = qParams.get(ATTR_QUERY_KEY);
- Set cAttrs = attrs == null || attrs.isEmpty() ? null : new HashSet(attrs);
-
- try {
- return entityResourceFactory.createCacheEntities(cmNames, cNames, cAttrs);
- } catch (ServiceExecutionException e) {
- throw new ResourceRuntimeException("Failed to get caches", e, Response.Status.BAD_REQUEST.getStatusCode());
- }
- }
-
- /**
- *
- * Create or update a cache with the name specified in the request path, for a specific agent and cache manager. The
- * request path that does not identify a unique cache resource for creation or identifies a cache that already exists
- * will constitute a bad request and will be denied, resulting in a response with a 400 and 409 respectively.
- *
- *
- * @param info
- * {@link UriInfo} for this resource request
- * @param resource
- * {@code CacheEntity} resource for update or creation
- */
- @PUT
- @Consumes(MediaType.APPLICATION_JSON)
- public void createOrUpdateCache(@Context UriInfo info, CacheEntity resource) {
- LOG.debug(String.format("Invoking CachesResourceServiceImpl.createOrUpdateCache: %s", info.getRequestUri()));
-
- validator.validate(info);
-
- String cacheManagerName = info.getPathSegments().get(1).getMatrixParameters().getFirst("names");
-
- String cacheName = info.getPathSegments().get(2).getMatrixParameters().getFirst("names");
-
- try {
- cacheSvc.createOrUpdateCache(cacheManagerName, cacheName, resource);
- } catch (ServiceExecutionException e) {
- throw new ResourceRuntimeException("Failed to create or update cache", e, Response.Status.BAD_REQUEST.getStatusCode());
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesL1TestClient.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesL1TestClient.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesL1TestClient.java (revision 0)
@@ -1,91 +0,0 @@
-package org.terracotta.ehcache.tests.servermap;
-
-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.toolkit.Toolkit;
-
-import java.util.Calendar;
-import java.util.concurrent.atomic.AtomicInteger;
-
-public class ServerMapL2EvictionReachesL1TestClient extends ServerMapClientBase {
-
- public ServerMapL2EvictionReachesL1TestClient(String[] args) {
- super("test", args);
- }
-
- public static void main(String[] args) {
- new ServerMapL2EvictionReachesL1TestClient(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- System.out.println("Running test with concurrency=1");
- testWith(cache, 3000, 100);
-
- System.out.println("Testing with higher concurrency value.");
- // 100 maxElementsOnDisk, 50 stripes -> targetMaxTotalCount of 2 for each stripe
- // add 5000 (100 per stripe), at least one per stripe should be evicted
- // use 25 just in case
- testWith(cache.getCacheManager().getCache("testWithConcurrency"), 5000, 50);
- }
-
- private void testWith(final Cache cache, final int maxElements, final int expectedEvictionCount)
- throws InterruptedException {
- EvictionCountingEventListener countingListener = new EvictionCountingEventListener();
- cache.getCacheEventNotificationService().registerListener(countingListener);
-
- for (int i = 0; i < maxElements; i++) {
- cache.put(new Element("key-" + i, "value-" + i));
- }
-
- Calendar timeoutTime = Calendar.getInstance();
- timeoutTime.add(Calendar.MINUTE, 5);
- System.out.println("Waiting 5 minutes for evictions to reach the expected count of " + expectedEvictionCount);
- assertRange(expectedEvictionCount, maxElements, cache);
- }
-
- public class EvictionCountingEventListener implements CacheEventListener {
- private final AtomicInteger count = new AtomicInteger();
-
- public void notifyElementEvicted(Ehcache cache, Element element) {
- int val = count.incrementAndGet();
- if (val % 100 == 0) {
- System.out.println("EvictionListener: number of elements evicted till now: " + val);
- }
- }
-
- public void dispose() {
- //
- }
-
- public void notifyElementExpired(Ehcache cache, Element element) {
- //
- }
-
- public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
- //
- }
-
- public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
- //
- }
-
- public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
- //
- }
-
- public void notifyRemoveAll(Ehcache cache) {
- //
- }
-
- @Override
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/AttributeExtractor.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/AttributeExtractor.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/AttributeExtractor.java (revision 0)
@@ -1,59 +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.attribute;
-
-import java.io.Serializable;
-
-import net.sf.ehcache.Element;
-
-/**
- * Used to extract a search attribute value for a given cache element.
- *
- * Instances must be {@link Serializable} in order to ensure identical
- * extractors are used in distributed caches
- *
- * @author teck
- */
-public interface AttributeExtractor extends Serializable {
-
- /**
- * Extract the attribute value. The instance returned from this method must
- * be one of:
- *
- * java.lang.Boolean
- * java.lang.Byte
- * java.lang.Character
- * java.lang.Double
- * java.lang.Float
- * java.lang.Integer
- * java.lang.Long
- * java.lang.Short
- * java.lang.String
- * java.util.Date
- * java.sql.Date
- * java.lang.Enum
- *
- *
- * NOTE: null is a legal return here as well indicating that this attribute will not be available for the given element
- *
- * @param element the cache element to inspect
- * @param attributeName the name of the requested attribute
- * @return the attribute value
- * @throws AttributeExtractorException if the attribute cannot be found or extracted
- */
- Object attributeFor(Element element, String attributeName) throws AttributeExtractorException;
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/Harness.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/Harness.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/Harness.java (revision 0)
@@ -1,34 +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;
-
-import java.io.StringReader;
-
-public class Harness {
- public static void main(String[] args) throws Exception {
- {
- EhcacheSearchParser parser = new EhcacheSearchParser(new StringReader("select * " +
- " where ('name' = 'tom' and (not ('age' = (class foo.bar.Baz)'10' or 'foo' > 11 )) and 'zip' = '21104') group by key order by " +
- "'name' desc limit 10"
- ));
- ParseModel model = parser.QueryStatement();
- System.out.println(model);
- }
-
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EntityStats.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EntityStats.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EntityStats.java (revision 0)
@@ -1,266 +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.management.impl;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.management.openmbean.CompositeData;
-import javax.management.openmbean.CompositeDataSupport;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.OpenDataException;
-import javax.management.openmbean.OpenType;
-import javax.management.openmbean.SimpleType;
-import javax.management.openmbean.TabularData;
-import javax.management.openmbean.TabularDataSupport;
-import javax.management.openmbean.TabularType;
-
-import org.hibernate.stat.EntityStatistics;
-
-/**
- * When we only support Java 6, all of this OpenMBean scaffolding can be removed in favor or MXBeans.
- *
- * @author gkeim
- */
-public class EntityStats implements Serializable {
- private static final String COMPOSITE_TYPE_NAME = "EntityStats";
- private static final String COMPOSITE_TYPE_DESCRIPTION = "Statistics per Entity";
- private static final String[] ITEM_NAMES = new String[] {"name", "shortName", "loadCount",
- "updateCount", "insertCount", "deleteCount", "fetchCount", "optimisticFailureCount", };
- private static final String[] ITEM_DESCRIPTIONS = new String[] {"name", "shortName", "loadCount",
- "updateCount", "insertCount", "deleteCount", "fetchCount", "optimisticFailureCount", };
- private static final OpenType[] ITEM_TYPES = new OpenType[] {SimpleType.STRING,
- SimpleType.STRING, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG, SimpleType.LONG,
- SimpleType.LONG, };
- private static final CompositeType COMPOSITE_TYPE;
- private static final String TABULAR_TYPE_NAME = "Statistics by Entity";
- private static final String TABULAR_TYPE_DESCRIPTION = "All Entity Statistics";
- private static final String[] INDEX_NAMES = new String[] {"name", };
- private static final TabularType TABULAR_TYPE;
-
- static {
- try {
- COMPOSITE_TYPE = new CompositeType(COMPOSITE_TYPE_NAME, COMPOSITE_TYPE_DESCRIPTION, ITEM_NAMES,
- ITEM_DESCRIPTIONS, ITEM_TYPES);
- TABULAR_TYPE = new TabularType(TABULAR_TYPE_NAME, TABULAR_TYPE_DESCRIPTION, COMPOSITE_TYPE, INDEX_NAMES);
- } catch (OpenDataException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * name
- */
- protected final String name;
-
- /**
- * shortName
- */
- protected final String shortName;
-
- /**
- * loadCount
- */
- protected long loadCount;
-
- /**
- * updateCount
- */
- protected long updateCount;
-
- /**
- * insertCount
- */
- protected long insertCount;
-
- /**
- * deleteCount
- */
- protected long deleteCount;
-
- /**
- * fetchCount
- */
- protected long fetchCount;
-
- /**
- * optimisticFailureCount
- */
- protected long optimisticFailureCount;
-
- /**
- * @param name
- */
- public EntityStats(String name) {
- this.name = name;
- this.shortName = CacheRegionUtils.determineShortName(name);
- }
-
- /**
- * @param name
- * @param src
- */
- public EntityStats(String name, EntityStatistics src) {
- this(name);
-
- try {
- this.loadCount = BeanUtils.getLongBeanProperty(src, "loadCount");
- this.updateCount = BeanUtils.getLongBeanProperty(src, "updateCount");
- this.insertCount = BeanUtils.getLongBeanProperty(src, "insertCount");
- this.deleteCount = BeanUtils.getLongBeanProperty(src, "deleteCount");
- this.fetchCount = BeanUtils.getLongBeanProperty(src, "fetchCount");
- this.optimisticFailureCount = BeanUtils.getLongBeanProperty(src, "optimisticFailureCount");
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException("Exception retrieving statistics", e);
- }
- }
-
- /**
- * @param cData
- */
- public EntityStats(final CompositeData cData) {
- int i = 0;
- name = (String) cData.get(ITEM_NAMES[i++]);
- shortName = (String) cData.get(ITEM_NAMES[i++]);
- loadCount = (Long) cData.get(ITEM_NAMES[i++]);
- updateCount = (Long) cData.get(ITEM_NAMES[i++]);
- insertCount = (Long) cData.get(ITEM_NAMES[i++]);
- deleteCount = (Long) cData.get(ITEM_NAMES[i++]);
- fetchCount = (Long) cData.get(ITEM_NAMES[i++]);
- optimisticFailureCount = (Long) cData.get(ITEM_NAMES[i++]);
- }
-
- private static int safeParseInt(String s) {
- try {
- return Integer.parseInt(s);
- } catch (Exception e) {
- return -1;
- }
- }
-
- /**
- * @param stats
- */
- public void add(EntityStats stats) {
- loadCount += stats.getLoadCount();
- updateCount += stats.getUpdateCount();
- insertCount += stats.getInsertCount();
- deleteCount += stats.getDeleteCount();
- fetchCount += stats.getFetchCount();
- optimisticFailureCount += stats.getOptimisticFailureCount();
- }
-
- /**
- * toString
- */
- @Override
- public String toString() {
- return "name=" + name + ", shortName=" + shortName + ",loadCount=" + loadCount + ", updateCount=" + updateCount
- + ", insertCount=" + insertCount + ", deleteCount=" + deleteCount + ", fetchCount=" + fetchCount
- + ", optimisticFailureCount" + optimisticFailureCount;
- }
-
- /**
- * getName
- */
- public String getName() {
- return name;
- }
-
- /**
- * getShortName
- */
- public String getShortName() {
- return shortName;
- }
-
- /**
- * getLoadCount
- */
- public long getLoadCount() {
- return loadCount;
- }
-
- /**
- * getUpdateCount
- */
- public long getUpdateCount() {
- return updateCount;
- }
-
- /**
- * getInsertCount
- */
- public long getInsertCount() {
- return insertCount;
- }
-
- /**
- * getDeleteCount
- */
- public long getDeleteCount() {
- return deleteCount;
- }
-
- /**
- * getFetchCount
- */
- public long getFetchCount() {
- return fetchCount;
- }
-
- /**
- * getOptimisticFailureCount
- */
- public long getOptimisticFailureCount() {
- return optimisticFailureCount;
- }
-
- /**
- * toCompositeData
- */
- public CompositeData toCompositeData() {
- try {
- return new CompositeDataSupport(COMPOSITE_TYPE, ITEM_NAMES, new Object[] {name, shortName, loadCount,
- updateCount, insertCount, deleteCount, fetchCount, optimisticFailureCount, });
- } catch (OpenDataException e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * newTabularDataInstance
- */
- public static TabularData newTabularDataInstance() {
- return new TabularDataSupport(TABULAR_TYPE);
- }
-
- /**
- * fromTabularData
- */
- public static EntityStats[] fromTabularData(final TabularData tabularData) {
- final List countList = new ArrayList(tabularData.size());
- for (final Iterator pos = tabularData.values().iterator(); pos.hasNext();) {
- countList.add(new EntityStats((CompositeData) pos.next()));
- }
- return countList.toArray(new EntityStats[countList.size()]);
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/terracotta/RotatingSnapshotFile.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/terracotta/RotatingSnapshotFile.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/terracotta/RotatingSnapshotFile.java (revision 0)
@@ -1,279 +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.EOFException;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import net.sf.ehcache.DiskStorePathManager;
-import net.sf.ehcache.util.PreferredLoaderObjectInputStream;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A file will rotate on every write, so to never loose older values in case of a JVM crash
- *
- * @author Alex Snaps
- */
-class RotatingSnapshotFile {
-
- private static final Logger LOG = LoggerFactory.getLogger(RotatingSnapshotFile.class);
-
- private static final String SUFFIX_OK = ".keySet";
- private static final String SUFFIX_PROGRESS = SUFFIX_OK + ".temp";
- private static final String SUFFIX_MOVE = SUFFIX_OK + ".old";
-
- private volatile boolean shutdownOnThreadInterrupted;
- private final String cacheName;
-
- private final Lock readLock;
- private final Lock writeLock;
- private final DiskStorePathManager diskStorePathManager;
-
- private final ClassLoader classLoader;
-
- {
- ReadWriteLock rwl = new ReentrantReadWriteLock();
- readLock = rwl.readLock();
- writeLock = rwl.writeLock();
- }
-
- /**
- * Constructor
- *
- * @param cacheName use as base name of the files
- */
- RotatingSnapshotFile(final DiskStorePathManager diskStorePathManager, final String cacheName, final ClassLoader classLoader) {
- this.diskStorePathManager = diskStorePathManager;
- this.cacheName = cacheName;
- this.classLoader = classLoader;
- }
-
- /**
- * Writes all values of the iterable to a new file and does the necessary clean up when done
- *
- * @param localKeys the iterable of entries to write to disk
- * @throws IOException If the underlying OutputStream do throw
- */
- void writeAll(final Iterable localKeys) throws IOException {
- writeLock.lock();
- long writtenKeys = 0;
- try {
- File inProgress = newSnapshotFile();
-
- cleanUp(inProgress);
- if (!inProgress.createNewFile()) {
- throw new AssertionError("The file '" + inProgress.getAbsolutePath() + "' exists already!");
- }
-
- final FileOutputStream fileOutputStream = new FileOutputStream(inProgress);
- final ObjectOutputStream oos = new ObjectOutputStream(fileOutputStream);
-
- try {
- for (Object localKey : localKeys) {
- if (shutdownOnThreadInterrupted && Thread.currentThread().isInterrupted()) {
- return;
- }
- oos.writeObject(localKey);
- ++writtenKeys;
- }
- } finally {
- fileOutputStream.close();
- }
-
- swapForOldWithNewSnapshot(inProgress);
- } finally {
- LOG.info("Did a snapshot of " + writtenKeys + " local keys");
- writeLock.unlock();
- }
- }
-
- /**
- * Reads all the keys from the file on disk, doing cleanup if required of previously unterminated file written to
- *
- * @param the type of the each element
- * @return the Set of all entries in the latest uncorrupted file on disk
- * @throws IOException If the underlying FileInputStream does throw
- */
- Set readAll() throws IOException {
-
- cleanUp();
-
- readLock.lock();
- try {
-
- final File currentSnapshot = currentSnapshotFile();
- if (!currentSnapshot.exists()) {
- return Collections.emptySet();
- }
-
- final Set values = new HashSet();
- FileInputStream fis = new FileInputStream(currentSnapshot);
- try {
- ObjectInputStream ois = new PreferredLoaderObjectInputStream(fis, classLoader);
- boolean eof = false;
- while (!eof) {
- try {
- values.add((T)ois.readObject());
- } catch (Exception e) {
- if (e instanceof EOFException) {
- eof = true;
- }
- // Ignore all other errors, and keep on trying to load keys
- }
- }
- try {
- ois.close();
- } catch (IOException e) {
- LOG.error("Error closing ObjectInputStream", e);
- closeAndDeleteAssociatedFileOnFailure(fis, currentSnapshot);
- }
-
- } catch (IOException e) {
- closeAndDeleteAssociatedFileOnFailure(fis, currentSnapshot);
- }
- return Collections.unmodifiableSet(values);
- } finally {
- readLock.unlock();
- }
- }
-
- private void cleanUp() {
- if (requiresCleanUp()) {
- writeLock.lock();
- try {
- cleanUp(newSnapshotFile());
- } finally {
- writeLock.unlock();
- }
- }
- }
-
- private void cleanUp(final File inProgress) {
- if (requiresCleanUp()) {
- final File dest = currentSnapshotFile();
- if (dest.exists() && !inProgress.delete()) {
- throw new RuntimeException("Couldn't cleanup old file " + inProgress.getAbsolutePath());
- } else {
- final File tempFile = tempSnapshotFile();
- if (tempFile.exists() && !tempFile.delete()) {
- throw new RuntimeException("Couldn't cleanup temp file " + tempFile.getAbsolutePath());
- }
- if (inProgress.exists() && !inProgress.renameTo(dest)) {
- throw new RuntimeException("Couldn't rename new snapshot: " + dest.getAbsolutePath());
- }
- }
- }
- }
-
- private boolean requiresCleanUp() {
- return newSnapshotFile().exists();
- }
-
- private void swapForOldWithNewSnapshot(final File inProgress) {
- File currentSnapshot = currentSnapshotFile();
- final File tempFile = tempSnapshotFile();
- if (currentSnapshot.exists() && !currentSnapshot.renameTo(tempFile)) {
- throw new RuntimeException("Couldn't rename previous snapshot: " + currentSnapshot.getAbsolutePath());
- }
- if (!inProgress.renameTo(currentSnapshot)) {
- throw new RuntimeException("Couldn't rename new snapshot: " + currentSnapshot.getAbsolutePath());
- }
- if (tempFile.exists() && !tempFile.delete()) {
- throw new RuntimeException("Couldn't delete temp file " + tempFile.getAbsolutePath());
- }
- }
-
- /**
- * Creates a File representing the uncorrupted file on disk
- *
- * @return the file to read from
- */
- File currentSnapshotFile() {
- return diskStorePathManager.getFile(cacheName, SUFFIX_OK);
- }
-
- /**
- * Creates a File representing the one to write new entries to
- *
- * @return the File to write to
- */
- File newSnapshotFile() {
- return diskStorePathManager.getFile(cacheName, SUFFIX_PROGRESS);
- }
-
- /**
- * Creates a File representing the old uncorrupted file, when the new one has successfully been written to disk
- *
- * @return the File representing the previous successful snapshot (temp file to be deleted)
- */
- File tempSnapshotFile() {
- return diskStorePathManager.getFile(cacheName, SUFFIX_MOVE);
- }
-
- /**
- * Whether to shutdown as soon as the writer Thread is interrupted, or to let all keys be written to disk first
- *
- * @param shutdownOnThreadInterrupted true, if shutdown needs to happen in the middle of a write
- */
- void setShutdownOnThreadInterrupted(final boolean shutdownOnThreadInterrupted) {
- this.shutdownOnThreadInterrupted = shutdownOnThreadInterrupted;
- }
-
- private void closeAndDeleteAssociatedFileOnFailure(final FileInputStream fis, final File associatedFile) {
- try {
- fis.close();
- } catch (IOException e) {
- LOG.error("Couldn't close FileInputStream on {}, deleting the file!", associatedFile.getAbsolutePath(), e);
- if (associatedFile.exists() && !associatedFile.delete()) {
- LOG.error("Couldn't delete file {}", associatedFile.getAbsolutePath(), e);
- }
- }
- }
-
- /**
- * Calling this method will result in writing all keys to be written to disk
- * or wait for the one in progress to finish
- *
- * @param localKeys the latest current local set
- * @throws IOException On exception being thrown while doing the snapshot
- */
- void snapshotNowOrWaitForCurrentToFinish(final Set localKeys) throws IOException {
- if (writeLock.tryLock()) {
- try {
- writeAll(localKeys);
- } finally {
- writeLock.unlock();
- }
- } else {
- writeLock.lock();
- writeLock.unlock();
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/PersistenceConfiguration.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/PersistenceConfiguration.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/PersistenceConfiguration.java (revision 0)
@@ -1,129 +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;
-
-/**
- * Class to hold the persistence policy configuration.
- *
- * @author Chris Dennis
- */
-public class PersistenceConfiguration {
-
- /**
- * Default synchronous writes setting
- */
- public static final boolean DEFAULT_SYNCHRONOUS_WRITES = false;
-
- /**
- * Enumeration of the legal persistence strategies
- */
- public static enum Strategy {
- /**
- * Standard open source (non fault-tolerant) on-disk persistence
- */
- LOCALTEMPSWAP,
- /**
- * Enterprise fault tolerant persistence
- */
- LOCALRESTARTABLE,
- /**
- * No persistence
- */
- NONE,
- /**
- * Terracotta clustered persistence (requires a Terracotta clustered cache).
- */
- DISTRIBUTED;
- }
-
- private volatile Strategy strategy;
- private volatile boolean synchronousWrites;
-
- /**
- * Gets the persistence strategy
- *
- * @return the persistence strategy
- */
- public Strategy getStrategy() {
- return strategy;
- }
-
- /**
- * Sets the persistence strategy
- *
- * @param strategy the persistence strategy
- */
- public void setStrategy(String strategy) {
- if (strategy == null) {
- throw new IllegalArgumentException("strategy must be non-null");
- }
- strategy(Strategy.valueOf(strategy.toUpperCase()));
- }
-
- /**
- * Builder method to set the persistence strategy
- *
- * @param strategy the persistence strategy
- * @return this PersistenceConfiguration object
- */
- public PersistenceConfiguration strategy(Strategy strategy) {
- this.strategy = strategy;
- return this;
- }
-
- /**
- * Builder method to set the persistence strategy using a String object
- *
- * @param strategy the persistence strategy
- * @return this PersistenceConfiguration object
- */
- public PersistenceConfiguration strategy(String strategy) {
- setStrategy(strategy);
- return this;
- }
-
- /**
- * Gets the persistence write mode
- *
- * @return the persistence write mode
- */
- public boolean getSynchronousWrites() {
- return synchronousWrites;
- }
-
- /**
- * Sets the persistence write mode
- *
- * @param synchronousWrites the persistence write mode
- */
- public void setSynchronousWrites(boolean synchronousWrites) {
- this.synchronousWrites = synchronousWrites;
- }
-
- /**
- * Builder method to set the persistence write mode
- *
- * @param synchronousWrites the persistence write mode
- * @return this PersistenceConfiguration object
- */
- public PersistenceConfiguration synchronousWrites(boolean synchronousWrites) {
- setSynchronousWrites(synchronousWrites);
- return this;
- }
-
-
-}
Index: rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/start-sample.sh
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/start-sample.sh (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/distribution/events/src/assemble/bin/start-sample.sh (revision 0)
@@ -1,31 +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
-
-appname=events
-
-unset CDPATH
-root=`dirname $0`/..
-root=`cd $root && pwd`
-
-$root/bin/package.sh
-
-if [ $? -ne 0 ]; then
- exit 1
-fi
-
-$root/bin/start-jetty.sh 9081
-echo "Go to: http://localhost:9081/$appname"
-echo
-sleep 3
-$root/bin/start-jetty.sh 9082
-echo "Go to: http://localhost:9082/$appname"
-echo
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMIBootstrapCacheLoaderFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMIBootstrapCacheLoaderFactory.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/distribution/RMIBootstrapCacheLoaderFactory.java (revision 0)
@@ -1,100 +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.bootstrap.BootstrapCacheLoaderFactory;
-import net.sf.ehcache.util.PropertyUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Properties;
-
-
-/**
- * A factory to create a configured RMIBootstrapCacheLoader
- * @author Greg Luck
- * @version $Id: RMIBootstrapCacheLoaderFactory.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class RMIBootstrapCacheLoaderFactory extends BootstrapCacheLoaderFactory {
-
-
- /**
- * The property name expected in ehcache.xml for the maximum chunk size in bytes
- */
- public static final String MAXIMUM_CHUNK_SIZE_BYTES = "maximumChunkSizeBytes";
-
- /**
- * The default maximum serialized size of the elements to request from a remote cache peer during bootstrap.
- */
- protected static final int DEFAULT_MAXIMUM_CHUNK_SIZE_BYTES = 5000000;
-
- /**
- * The highest reasonable chunk size in bytes
- */
- protected static final int ONE_HUNDRED_MB = 100000000;
-
- /**
- * The lowest reasonable chunk size in bytes
- */
- protected static final int FIVE_KB = 5000;
-
- private static final Logger LOG = LoggerFactory.getLogger(RMIBootstrapCacheLoaderFactory.class.getName());
-
-
- /**
- * Create a BootstrapCacheLoader
- *
- * @param properties implementation specific properties. These are configured as comma
- * separated name value pairs in ehcache.xml
- * @return a constructed BootstrapCacheLoader
- */
- public RMIBootstrapCacheLoader createBootstrapCacheLoader(Properties properties) {
- boolean bootstrapAsynchronously = extractBootstrapAsynchronously(properties);
- int maximumChunkSizeBytes = extractMaximumChunkSizeBytes(properties);
- return new RMIBootstrapCacheLoader(bootstrapAsynchronously, maximumChunkSizeBytes);
- }
-
- /**
- *
- * @param properties the properties passed by the CacheManager, read from the configuration file
- * @return the max chunk size in bytes
- */
- protected int extractMaximumChunkSizeBytes(Properties properties) {
- int maximumChunkSizeBytes;
- String maximumChunkSizeBytesString = PropertyUtil.extractAndLogProperty(MAXIMUM_CHUNK_SIZE_BYTES, properties);
- if (maximumChunkSizeBytesString != null) {
- try {
- int maximumChunkSizeBytesCandidate = Integer.parseInt(maximumChunkSizeBytesString);
- if ((maximumChunkSizeBytesCandidate < FIVE_KB) || (maximumChunkSizeBytesCandidate > ONE_HUNDRED_MB)) {
- LOG.warn("Trying to set the chunk size to an unreasonable number. Using the default instead.");
- maximumChunkSizeBytes = DEFAULT_MAXIMUM_CHUNK_SIZE_BYTES;
- } else {
- maximumChunkSizeBytes = maximumChunkSizeBytesCandidate;
- }
- } catch (NumberFormatException e) {
- LOG.warn("Number format exception trying to set chunk size. Using the default instead.");
- maximumChunkSizeBytes = DEFAULT_MAXIMUM_CHUNK_SIZE_BYTES;
- }
-
- } else {
- maximumChunkSizeBytes = DEFAULT_MAXIMUM_CHUNK_SIZE_BYTES;
- }
- return maximumChunkSizeBytes;
- }
-
-
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/CoalescingWriteBehindTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/CoalescingWriteBehindTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/CoalescingWriteBehindTest.java (revision 0)
@@ -1,97 +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;
-
-public class CoalescingWriteBehindTest extends AbstractCacheTestBase {
-
- private static final int NODE_COUNT = 2;
-
- public CoalescingWriteBehindTest(TestConfig testConfig) {
- super("coalescing-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("key" + i % 200, "value" + i)); // 200 different keys, 1000 write operation
- if (0 == i % 10) {
- cache.removeWithWriter("key" + i % 200 / 10); // 20 different keys, 100 delete operation
- }
- }
- } else {
- writer = new WriteBehindCacheWriter("WriteBehindCacheWriter", index, 10L);
- cache.registerCacheWriter(writer);
-
- cache.putWithWriter(new Element("key", "value"));
- cache.removeWithWriter("key");
- }
-
- cache.dispose();
- 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]");
-
- if (totalWriteCount.get() < 180 || totalWriteCount.get() > 1001) { throw new AssertionError(
- totalWriteCount
- .get()); }
-
- if (totalDeleteCount.get() < 20 || totalDeleteCount.get() > 101) { throw new AssertionError(
- totalDeleteCount
- .get()); }
- }
-
- barrier.await();
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/ConcurrencyProblemCachePerfTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/ConcurrencyProblemCachePerfTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/ConcurrencyProblemCachePerfTest.java (revision 0)
@@ -1,88 +0,0 @@
-package net.sf.ehcache;
-
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.List;
-
-import net.sf.ehcache.AbstractCacheTest.Executable;
-import net.sf.ehcache.config.Configuration;
-import static org.junit.Assert.assertTrue;
-
-/**
- * @author Alex Snaps
- */
-public class ConcurrencyProblemCachePerfTest {
-
- private static final Logger LOG = LoggerFactory.getLogger(ConcurrencyProblemCachePerfTest.class.getName());
-
- @Test
- public void testContinuousThrashProgrammatic() throws Exception {
- CacheManager manager = new CacheManager(new Configuration().name("testContinuousThrashConfiguration"));
- try {
- Cache cache = new Cache("thrashcache", 5, false, false, 2, 5);
- manager.addCache(cache);
- for (int i = 0; i < 5; i++) {
- thrashCache(cache, 1500L);
- LOG.info("Finished run.");
-
- }
- } finally {
- manager.shutdown();
- }
- }
-
- /**
- * This method tries to get the cache to slow up.
- * It creates 10 threads, does gets and puts.
- */
- private long thrashCache(final Cache cache, final long retrievalTime)
- throws Exception {
- StopWatch stopWatch = new StopWatch();
-
- // Create threads that do gets
- final List executables = new ArrayList();
- for (int i = 0; i < 10; i++) {
- final Executable executable = new Executable() {
- public void execute() throws Exception {
- for (int i = 0; i < 10; i++) {
- final String key = "key" + i;
- Object value = cache.get(key);
- if (value == null) {
- cache.put(new Element(key, "value" + i));
- }
- //The key will be in. Now check we can get it quickly
- checkRetrievalOnKnownKey(cache, retrievalTime, key);
- }
- }
- };
- executables.add(executable);
- }
-
- AbstractCacheTest.runThreads(executables);
- cache.removeAll();
- return stopWatch.getElapsedTime();
- }
-
-
- /**
- * Checks that the liveness method returns in less than a given amount of time.
- * liveness() is a method that simply returns a String. It should be very fast. It can be
- * delayed because it is a synchronized method, and must acquire
- * an object lock before continuing. The old blocking cache was taking up to several minutes in production
- *
- * @param cache a BlockingCache
- */
- private void checkRetrievalOnKnownKey(Cache cache, long requiredRetrievalTime, Serializable key) {
- StopWatch stopWatch = new StopWatch();
- cache.get(key);
- long measuredRetrievalTime = stopWatch.getElapsedTime();
- assertTrue("Retrieval time on known key is " + measuredRetrievalTime
- + " but should be less than " + requiredRetrievalTime + "ms",
- measuredRetrievalTime < requiredRetrievalTime);
- }
-}
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/loader/CacheLoaderTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/loader/CacheLoaderTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/loader/CacheLoaderTest.java (revision 0)
@@ -1,193 +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.AbstractCacheTest;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.extension.TestCacheExtension;
-import org.junit.After;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author Greg Luck
- * @version $Id: CacheLoaderTest.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class CacheLoaderTest {
-
- /**
- * manager
- */
- protected CacheManager manager;
-
-
- /**
- * {@inheritDoc}
- *
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- manager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-loaderinteractions.xml");
- }
-
-
- /**
- * {@inheritDoc}
- *
- * @throws Exception
- */
- @After
- public void tearDown() throws Exception {
- if (!manager.getStatus().equals(Status.STATUS_SHUTDOWN)) {
- manager.shutdown();
- }
- }
-
- @Test
- public void testWorksWithTransactionalCaches() {
- Cache cache = new Cache(new CacheConfiguration("txLoaderCache", 100)
- .transactionalMode(CacheConfiguration.TransactionalMode.LOCAL));
- manager.addCache(cache);
- manager.getTransactionController().begin();
- final Element element = cache.getWithLoader(10, new CountingCacheLoader(), null);
- assertThat((Integer) element.getValue(), equalTo(0));
- manager.getTransactionController().commit();
- }
-
- @Test
- public void testGetAllWithLoaderExpiredKey() throws Exception {
- Cache cache = manager.getCache("CCache");
- cache.put(new Element(1, "one"));
- Thread.sleep(1100); // make Element 1 expire, see EHC-809
- cache.put(new Element(2, "two"));
- cache.put(new Element(3, null));
-
- Map cachedObjects = cache.getAllWithLoader(Arrays.asList(1, 2, 3), null);
-
- assertTrue(cachedObjects.get(1).toString().equals("C(1)"));
- assertTrue(cachedObjects.get(2).toString().equals("two"));
- assertNull(cachedObjects.get(3));
- assertTrue(cachedObjects.containsKey(3));
- }
-
- @Test
- public void testLoaderChainNullFirst() {
- Cache cache = manager.getCache("NullLoaderFirstCache");
- assertNotNull(cache.getWithLoader("key", null, null));
- NullCountingCacheLoader nullCountingCacheLoader = getNullCountingCacheLoader(cache);
- assertEquals(1, nullCountingCacheLoader.getLoadCounter());
- CountingCacheLoader countingCacheLoader = getCountingCacheLoader(cache);
- assertEquals(1, countingCacheLoader.getLoadCounter());
- }
-
- @Test
- public void testLoaderChainNullLast() {
- Cache cache = manager.getCache("NullLoaderLastCache");
- assertNotNull(cache.getWithLoader("key", null, null));
- CountingCacheLoader countingCacheLoader = getCountingCacheLoader(cache);
- assertEquals(1, countingCacheLoader.getLoadCounter());
- NullCountingCacheLoader nullCountingCacheLoader = getNullCountingCacheLoader(cache);
- assertEquals(0, nullCountingCacheLoader.getLoadCounter());
- }
-
- @Test
- public void testLoaderChainNullBoth() {
- Cache cache = manager.getCache("NullLoaderTwiceCache");
- Element element = cache.getWithLoader("key", null, null);
- assertNull(element);
- NullCountingCacheLoader nullCountingCacheLoader = getNullCountingCacheLoader(cache);
- List list = cache.getRegisteredCacheLoaders();
- assertEquals(2, list.size());
- for (CacheLoader cacheLoader : list) {
- if (cacheLoader instanceof NullCountingCacheLoader) {
- nullCountingCacheLoader = (NullCountingCacheLoader) cacheLoader;
- assertEquals(1, nullCountingCacheLoader.getLoadCounter());
- }
- }
-
- }
-
- private CountingCacheLoader getCountingCacheLoader(Cache cache) {
- List list = cache.getRegisteredCacheLoaders();
- for (CacheLoader cacheLoader : list) {
- if (cacheLoader instanceof CountingCacheLoader) {
- return (CountingCacheLoader) cacheLoader;
- }
- }
- return null;
- }
-
- private NullCountingCacheLoader getNullCountingCacheLoader(Cache cache) {
- List list = cache.getRegisteredCacheLoaders();
- for (CacheLoader cacheLoader : list) {
- if (cacheLoader instanceof NullCountingCacheLoader) {
- return (NullCountingCacheLoader) cacheLoader;
- }
- }
- return null;
- }
-
-
- /**
- * Tests the put listener.
- */
- @Test
- public void testExtensionDirectly() {
-
- manager.addCache("test");
- TestCacheExtension testCacheExtension = new TestCacheExtension(manager.getCache("test"), "valueA");
- assertEquals(Status.STATUS_UNINITIALISED, testCacheExtension.getStatus());
- assertEquals("valueA", testCacheExtension.getPropertyA());
-
- testCacheExtension.init();
- assertEquals(Status.STATUS_ALIVE, testCacheExtension.getStatus());
-
- testCacheExtension.dispose();
- assertEquals(Status.STATUS_SHUTDOWN, testCacheExtension.getStatus());
-
- }
-
-
- /**
- * We need to make sure that cloning a default cache results in a new cache with its own
- * set of cache extensions.
- */
- @Test
- public void testClone() {
-
- //just test it does not blow up
- manager.addCache("clonedCache");
- }
-}
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/RealObjectKeySet.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/RealObjectKeySet.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/RealObjectKeySet.java (revision 0)
@@ -1,87 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-
-package org.terracotta.modules.ehcache.store;
-
-import java.io.IOException;
-import java.util.AbstractSet;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-/**
- * @author cdennis
- */
-class RealObjectKeySet extends AbstractSet {
-
- private final ValueModeHandler mode;
- private final Collection keys;
-
- public RealObjectKeySet(ValueModeHandler mode, Collection keys) {
- this.mode = mode;
- this.keys = keys;
- }
-
- @Override
- public int size() {
- return keys.size();
- }
-
- @Override
- public boolean contains(Object o) {
- try {
- return keys.contains(mode.createPortableKey(o));
- } catch (IOException e) {
- return false;
- }
- }
-
- @Override
- public Iterator iterator() {
- return new KeyIterator(mode, keys.iterator());
- }
-
- static class KeyIterator implements Iterator {
-
- private static final Object NO_OBJECT = new Object();
-
- private final Iterator keysIterator;
- private final ValueModeHandler mode;
- private Object next;
-
- private KeyIterator(ValueModeHandler mode, Iterator iterator) {
- this.mode = mode;
- this.keysIterator = iterator;
- advance();
- }
-
- private void advance() {
- if (keysIterator.hasNext()) {
- final Object real;
- real = mode.getRealKeyObject((String) keysIterator.next());
- next = real;
- } else {
- next = NO_OBJECT;
- }
- }
-
- @Override
- public boolean hasNext() {
- return next != NO_OBJECT;
- }
-
- @Override
- public Object next() {
- Object rv = next;
- if (rv == NO_OBJECT) { throw new NoSuchElementException(); }
- advance();
- return rv;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/LruPolicy.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/LruPolicy.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/LruPolicy.java (revision 0)
@@ -1,57 +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.Element;
-
-
-/**
- * Contains common LFU policy code for use between the LfuMemoryStore and the DiskStore, which also
- * uses an LfuPolicy for evictions.
- *
- * @author Greg Luck
- * @version $Id: LruPolicy.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class LruPolicy extends AbstractPolicy {
-
- /**
- * The name of this policy as a string literal
- */
- public static final String NAME = "LRU";
-
- /**
- * @return the name of the Policy. Inbuilt examples are LRU, LFU and FIFO.
- */
- public String getName() {
- return NAME;
- }
-
- /**
- * Compares the desirableness for eviction of two elements
- *
- * Compares hit counts. If both zero,
- *
- * @param element1 the element to compare against
- * @param element2 the element to compare
- * @return true if the second element is preferable to the first element for ths policy
- */
- public boolean compare(Element element1, Element element2) {
- return element2.getLastAccessTime() < element1.getLastAccessTime();
-
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/ehcache-nodisk.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/ehcache-nodisk.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/ehcache-nodisk.xml (revision 0)
@@ -1,29 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/ehcache/src/test/resources/serializedforms/SerializationCopyStrategySerializationTest.testBasic.ser
===================================================================
diff -u -N -r11014 -r11048
Binary files differ
Index: rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/RejoinWithoutNonStopStore.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/RejoinWithoutNonStopStore.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/RejoinWithoutNonStopStore.java (revision 0)
@@ -1,614 +0,0 @@
-/*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
-package org.terracotta.modules.ehcache.store.nonstop;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.constructs.nonstop.RejoinCacheException;
-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;
-
-/**
- *
- * @author cdennis
- */
-public final class RejoinWithoutNonStopStore implements TerracottaStore {
-
- /**
- * the singleton instance
- */
- private static final RejoinWithoutNonStopStore INSTANCE = new RejoinWithoutNonStopStore();
-
- /**
- * private constructor
- */
- private RejoinWithoutNonStopStore() {
- //
- }
-
- /**
- * returns the singleton instance
- */
- public static RejoinWithoutNonStopStore getInstance() {
- return INSTANCE;
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Element get(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during get(Object key)");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Element getQuiet(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getQuiet(Object key)");
- }
-
- /**
- * {@inheritDoc}
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Map getAllQuiet(Collection> keys) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getAllQuiet(Collection> keys)");
- }
-
- /**
- * {@inheritDoc}
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Map getAll(Collection> keys) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getAll(Collection> keys)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public List getKeys() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getKeys()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean put(Element element) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during put(Element element)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void putAll(Collection elements) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during putAll(Collection elements)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Element remove(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during remove(Object key)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void removeAll(Collection> keys) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during removeAll(Collection> keys)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void removeAll() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during removeAll()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void flush() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during flush()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Object getInternalContext() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getInternalContext()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public int getSize() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getSize()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Element putIfAbsent(Element element) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during putIfAbsent(Element element)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Element replace(Element element) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during replace(Element element)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void addStoreListener(StoreListener listener) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during addStoreListener(StoreListener listener)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean bufferFull() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during bufferFull()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean containsKey(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during containsKey(Object key)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean containsKeyInMemory(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during containsKeyInMemory(Object key)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean containsKeyOffHeap(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during containsKeyOffHeap(Object key)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean containsKeyOnDisk(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during containsKeyOnDisk(Object key)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void dispose() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during dispose()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Results executeQuery(StoreQuery query) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during executeQuery(StoreQuery query)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void expireElements() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during expireElements()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Policy getInMemoryEvictionPolicy() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getInMemoryEvictionPolicy()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public int getInMemorySize() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getInMemorySize()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public long getInMemorySizeInBytes() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getInMemorySizeInBytes()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Object getMBean() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getMBean()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public int getOffHeapSize() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getOffHeapSize()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public long getOffHeapSizeInBytes() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getOffHeapSizeInBytes()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public int getOnDiskSize() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getOnDiskSize()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public long getOnDiskSizeInBytes() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getOnDiskSizeInBytes()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean hasAbortedSizeOf() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during hasAbortedSizeOf()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Status getStatus() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getStatus()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public int getTerracottaClusteredSize() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getTerracottaClusteredSize()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean isCacheCoherent() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during isCacheCoherent()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean isClusterCoherent() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during isClusterCoherent()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean isNodeCoherent() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during isNodeCoherent()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during putWithWriter(Element element, CacheWriterManager writerManager)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Element removeElement(Element element, ElementValueComparator comparator) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during removeElement(Element element, ElementValueComparator comparator)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void removeStoreListener(StoreListener listener) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during removeStoreListener(StoreListener listener)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Element removeWithWriter(Object key, CacheWriterManager writerManager) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during removeWithWriter(Object key, CacheWriterManager writerManager)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException,
- IllegalArgumentException {
- throw new RejoinCacheException("Client started rejoin during replace(Element old, Element element, ElementValueComparator comparator)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void setAttributeExtractors(Map extractors) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during setAttributeExtractors(Map extractors)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void setInMemoryEvictionPolicy(Policy policy) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during setInMemoryEvictionPolicy(Policy policy)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void setNodeCoherent(boolean coherent) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during setNodeCoherent(boolean coherent)");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public void waitUntilClusterCoherent() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during waitUntilClusterCoherent()");
- }
-
- @Override
- public Set getSearchAttributes() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getSearchAttributes()");
- }
-
- /**
- * {@inheritDoc}.
- *
- * Throws {@link RejoinCacheException}
- */
- @Override
- public Attribute getSearchAttribute(String attributeName) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getSearchAttribute(String attributeName)");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Set getLocalKeys() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getLocalKeys()");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public CacheConfiguration.TransactionalMode getTransactionalMode() throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during getTransactionalMode()");
- }
-
- /**
- * {@inheritDoc}
- */
- public Element unlockedGet(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during unlockedGet(Object key)");
- }
-
- /**
- * {@inheritDoc}
- */
- public Element unlockedGetQuiet(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during unlockedGetQuiet(Object key)");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Element unsafeGet(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during unsafeGet(Object key)");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void quickClear() {
- throw new RejoinCacheException("Client started rejoin during quickClear()");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int quickSize() {
- throw new RejoinCacheException("Client started rejoin during quickSize()");
- }
-
- /**
- * {@inheritDoc}
- */
- public Element unsafeGetQuiet(Object key) throws RejoinCacheException {
- throw new RejoinCacheException("Client started rejoin during unsafeGetQuiet(Object key)");
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void recalculateSize(Object key) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public WriteBehind createWriteBehind() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public void notifyCacheEventListenersChanged() {
- throw new RejoinCacheException("Client started rejoin during notifyCacheEventListenersChanged()");
- }
-}
Index: rctags/ehcache-2.10.7.0.58/distribution/events/.settings/org.eclipse.jdt.core.prefs
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/distribution/events/.settings/org.eclipse.jdt.core.prefs (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/distribution/events/.settings/org.eclipse.jdt.core.prefs (revision 0)
@@ -1,6 +0,0 @@
-#Mon Apr 02 19:16:29 PDT 2012
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
-org.eclipse.jdt.core.compiler.source=1.6
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/blocking/BlockingCacheEntryFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/blocking/BlockingCacheEntryFactory.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/constructs/blocking/BlockingCacheEntryFactory.java (revision 0)
@@ -1,69 +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 cache entry factory that blocks until signaled.
- *
- * This is useful for writing tests.
- *
- * @author Greg Luck
- * @version $Id: BlockingCacheEntryFactory.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class BlockingCacheEntryFactory implements CacheEntryFactory {
-
- private final Object value;
- private int count;
-
- /**
- * Constructs a new object
- *
- * @param value the factory always creates values equal to this value
- */
- public BlockingCacheEntryFactory(final Object value) {
- this.value = value;
- }
-
-
- /**
- * @return number of entries the factory has created.
- */
- public int getCount() {
- return count;
- }
-
-
- /**
- * Signals the factory.
- */
- public synchronized void signal(final int count) {
- this.count += count;
- notify();
- }
-
- /**
- * Fetches an entry.
- */
- public synchronized Object createEntry(final Object key) throws Exception {
- // Wait until signalled
- while (count == 0) {
- wait();
- }
- count--;
- return value;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/AbstractCopyingCacheStore.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/AbstractCopyingCacheStore.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/AbstractCopyingCacheStore.java (revision 0)
@@ -1,348 +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.search.Attribute;
-import net.sf.ehcache.search.Results;
-import net.sf.ehcache.search.SearchException;
-import net.sf.ehcache.search.attribute.AttributeExtractor;
-import net.sf.ehcache.store.compound.ReadWriteCopyStrategy;
-import net.sf.ehcache.terracotta.TerracottaNotRunningException;
-import net.sf.ehcache.writer.CacheWriterManager;
-
-import org.terracotta.context.annotations.ContextChild;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Copies elements, either on read, write or both before using the underlying store to actually store things
- * When copying both ways, the store might not see the same types being stored
- * @param the store type it wraps
- *
- * @author Alex Snaps
- */
-abstract class AbstractCopyingCacheStore implements Store {
-
- @ContextChild
- private final T store;
- private final CopyStrategyHandler copyStrategyHandler;
-
- /**
- * Creates a copying instance of store, that wraps the actual storage
- * @param store the real store
- * @param copyOnRead whether to copy on reads
- * @param copyOnWrite whether to copy on writes
- * @param copyStrategyInstance the copy strategy to use on every copy operation
- * @param loader classloader of the containing cache
- */
- public AbstractCopyingCacheStore(final T store, final boolean copyOnRead, final boolean copyOnWrite,
- final ReadWriteCopyStrategy copyStrategyInstance, ClassLoader loader) {
-
- this.store = store;
- copyStrategyHandler = new CopyStrategyHandler(copyOnRead, copyOnWrite, copyStrategyInstance, loader);
- }
-
- @Override
- public void addStoreListener(final StoreListener listener) {
- store.addStoreListener(listener);
- }
-
- @Override
- public void removeStoreListener(final StoreListener listener) {
- store.removeStoreListener(listener);
- }
-
- @Override
- public boolean put(final Element e) throws CacheException {
- return e == null || store.put(copyStrategyHandler.copyElementForWriteIfNeeded(e));
- }
-
- @Override
- public void putAll(final Collection elements) throws CacheException {
- for (Element element : elements) {
- put(element);
- }
- }
-
- @Override
- public boolean putWithWriter(final Element element, final CacheWriterManager writerManager) throws CacheException {
- return store.putWithWriter(copyStrategyHandler.copyElementForWriteIfNeeded(element), writerManager);
- }
-
- @Override
- public Element get(final Object key) {
- return copyStrategyHandler.copyElementForReadIfNeeded(store.get(key));
- }
-
- @Override
- public Element getQuiet(final Object key) {
- return copyStrategyHandler.copyElementForReadIfNeeded(store.getQuiet(key));
- }
-
- @Override
- public List getKeys() {
- return store.getKeys();
- }
-
- @Override
- public Element remove(final Object key) {
- return copyStrategyHandler.copyElementForReadIfNeeded(store.remove(key));
- }
-
- @Override
- public void removeAll(final Collection> keys) {
- for (Object key : keys) {
- remove(key);
- }
- }
-
- @Override
- public Element removeWithWriter(final Object key, final CacheWriterManager writerManager) throws CacheException {
- return copyStrategyHandler.copyElementForReadIfNeeded(store.removeWithWriter(key, writerManager));
- }
-
- @Override
- public void removeAll() throws CacheException {
- store.removeAll();
- }
-
- @Override
- public Element putIfAbsent(final Element element) throws NullPointerException {
- return copyStrategyHandler.copyElementForReadIfNeeded(store.putIfAbsent(copyStrategyHandler.copyElementForWriteIfNeeded(element)));
- }
-
- @Override
- public Element removeElement(final Element element, final ElementValueComparator comparator) throws NullPointerException {
- Element removed = store.removeElement(copyStrategyHandler.copyElementForRemovalIfNeeded(element), comparator);
- return copyStrategyHandler.copyElementForReadIfNeeded(removed);
- }
-
- @Override
- public boolean replace(final Element old, final Element element,
- final ElementValueComparator comparator) throws NullPointerException, IllegalArgumentException {
- Element oldElement = copyStrategyHandler.copyElementForRemovalIfNeeded(old);
- Element newElement = copyStrategyHandler.copyElementForWriteIfNeeded(element);
- return store.replace(oldElement, newElement, comparator);
- }
-
- @Override
- public Element replace(final Element element) throws NullPointerException {
- return copyStrategyHandler.copyElementForReadIfNeeded(store.replace(copyStrategyHandler.copyElementForWriteIfNeeded(element)));
- }
-
- @Override
- public void dispose() {
- store.dispose();
- }
-
- @Override
- public int getSize() {
- return store.getSize();
- }
-
- @Override
- public int getInMemorySize() {
- return store.getInMemorySize();
- }
-
- @Override
- public int getOffHeapSize() {
- return store.getOffHeapSize();
- }
-
- @Override
- public int getOnDiskSize() {
- return store.getOnDiskSize();
- }
-
- @Override
- public int getTerracottaClusteredSize() {
- return store.getTerracottaClusteredSize();
- }
-
- @Override
- public long getInMemorySizeInBytes() {
- return store.getInMemorySizeInBytes();
- }
-
- @Override
- public long getOffHeapSizeInBytes() {
- return store.getOffHeapSizeInBytes();
- }
-
- @Override
- public long getOnDiskSizeInBytes() {
- return store.getOnDiskSizeInBytes();
- }
-
- @Override
- public boolean hasAbortedSizeOf() {
- return store.hasAbortedSizeOf();
- }
-
- @Override
- public Status getStatus() {
- return store.getStatus();
- }
-
- @Override
- public boolean containsKey(final Object key) {
- return store.containsKey(key);
- }
-
- @Override
- public boolean containsKeyOnDisk(final Object key) {
- return store.containsKeyOnDisk(key);
- }
-
- @Override
- public boolean containsKeyOffHeap(final Object key) {
- return store.containsKeyOffHeap(key);
- }
-
- @Override
- public boolean containsKeyInMemory(final Object key) {
- return store.containsKeyInMemory(key);
- }
-
- @Override
- public void expireElements() {
- store.expireElements();
- }
-
- @Override
- public void flush() throws IOException {
- store.flush();
- }
-
- @Override
- public boolean bufferFull() {
- return store.bufferFull();
- }
-
- @Override
- public Policy getInMemoryEvictionPolicy() {
- return store.getInMemoryEvictionPolicy();
- }
-
- @Override
- public void setInMemoryEvictionPolicy(final Policy policy) {
- store.setInMemoryEvictionPolicy(policy);
- }
-
- @Override
- public Object getInternalContext() {
- return store.getInternalContext();
- }
-
- @Override
- public boolean isCacheCoherent() {
- return store.isCacheCoherent();
- }
-
- @Override
- public boolean isClusterCoherent() throws TerracottaNotRunningException {
- return store.isClusterCoherent();
- }
-
- @Override
- public boolean isNodeCoherent() throws TerracottaNotRunningException {
- return store.isNodeCoherent();
- }
-
- @Override
- public void setNodeCoherent(final boolean coherent) throws UnsupportedOperationException, TerracottaNotRunningException {
- store.setNodeCoherent(coherent);
- }
-
- @Override
- public void waitUntilClusterCoherent() throws UnsupportedOperationException, TerracottaNotRunningException, InterruptedException {
- store.waitUntilClusterCoherent();
- }
-
- @Override
- public Object getMBean() {
- return store.getMBean();
- }
-
- @Override
- public void setAttributeExtractors(final Map extractors) {
- store.setAttributeExtractors(extractors);
- }
-
- @Override
- public Results executeQuery(final StoreQuery query) throws SearchException {
- return store.executeQuery(query);
- }
-
- @Override
- public Attribute getSearchAttribute(final String attributeName) {
- return store.getSearchAttribute(attributeName);
- }
-
- @Override
- public Set getSearchAttributes() {
- return store.getSearchAttributes();
- }
-
- @Override
- public Map getAllQuiet(final Collection> keys) {
- Map elements = new HashMap();
- for (Object key : keys) {
- elements.put(key, getQuiet(key));
- }
- return elements;
- }
-
- @Override
- public Map getAll(final Collection> keys) {
- Map elements = new HashMap();
- for (Object key : keys) {
- elements.put(key, get(key));
- }
- return elements;
- }
-
- @Override
- public void recalculateSize(final Object key) {
- store.recalculateSize(key);
- }
-
- /**
- * Accessor to the underlying store
- * @return the underlying store
- */
- public T getUnderlyingStore() {
- return store;
- }
-
- /**
- * Accessor to the {@link CopyStrategyHandler}
- *
- * @return the copy strategy handler
- */
- protected CopyStrategyHandler getCopyStrategyHandler() {
- return copyStrategyHandler;
- }
-}
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/BTMTwoResourceTx1.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/BTMTwoResourceTx1.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/BTMTwoResourceTx1.java (revision 0)
@@ -1,22 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.txns;
-
-
-import bitronix.tm.Configuration;
-import bitronix.tm.TransactionManagerServices;
-
-public class BTMTwoResourceTx1 extends TwoResourceTx1 {
-
- public BTMTwoResourceTx1(String[] args) {
- super(args);
- Configuration config = TransactionManagerServices.getConfiguration();
- config.setServerId("tworesourcetx-1-" + Math.random());
- config.setJournal("null");
- }
-
- public static void main(String[] args) {
- new BTMTwoResourceTx1(args).run();
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/terracotta/ehcache-tc-embedded.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/terracotta/ehcache-tc-embedded.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/resources/terracotta/ehcache-tc-embedded.xml (revision 0)
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- app/logs-%i
-
-
-
-
-
\ No newline at end of file
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/coherence/RestartingL1ExpressClient.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/coherence/RestartingL1ExpressClient.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/ehcache/tests/coherence/RestartingL1ExpressClient.java (revision 0)
@@ -1,111 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.coherence;
-
-import net.sf.ehcache.Cache;
-
-import org.terracotta.toolkit.Toolkit;
-import org.terracotta.toolkit.concurrent.ToolkitBarrier;
-import org.terracotta.ehcache.tests.ClientBase;
-
-import junit.framework.Assert;
-
-public class RestartingL1ExpressClient extends ClientBase {
-
- public static final String PASS_OUTPUT = "Restarting express client PASS output";
- private ToolkitBarrier barrier;
- private boolean afterRestart = false;
- private boolean shouldCrash = false;
-
- public RestartingL1ExpressClient(String[] args) {
- super("test", args);
- for (String arg : args) {
- if (arg.equals(RestartingL1ExpressTest.SHOULD_CRASH)) {
- this.shouldCrash = true;
- }
-
- if (arg.equals(RestartingL1ExpressTest.AFTER_RESTART)) {
- this.afterRestart = true;
- }
- }
- }
-
- // n nodes start in coherent, then setCoherent(false)
- // assert coherent=false in all n nodes
- // n-1 nodes call setCoherent(true)
- // 1 node exits without calling setCoherent(true)
- // n-1 nodes assert coherent
- // 1 node restarts, asserts cache coherent
- @Override
- protected void runTest(Cache cache, Toolkit toolkit) throws Throwable {
- barrier = toolkit.getBarrier("CacheCoherenceExpressClient", RestartingL1ExpressTest.CLIENT_COUNT);
- Assert.assertEquals(true, cache.isClusterCoherent());
- Assert.assertEquals(true, cache.isNodeCoherent());
-
- if (!afterRestart) {
- barrier.await();
- doInitialSteps(cache);
- } else {
- log("Running crashing client AFTER RESTART...");
- // barrier X
- barrier.await();
- // barrier Z
- barrier.await();
- // cache is coherent when it restarts
- Assert.assertEquals(true, cache.isClusterCoherent());
- Assert.assertEquals(true, cache.isNodeCoherent());
- cache.setNodeCoherent(false);
- Assert.assertEquals(false, cache.isClusterCoherent());
- Assert.assertEquals(false, cache.isNodeCoherent());
- cache.setNodeCoherent(true);
- Assert.assertEquals(true, cache.isClusterCoherent());
- Assert.assertEquals(true, cache.isNodeCoherent());
- }
- log(PASS_OUTPUT);
- }
-
- private void doInitialSteps(Cache cache) throws Exception {
- cache.setNodeCoherent(false);
- Assert.assertEquals(false, cache.isNodeCoherent());
- Assert.assertEquals(false, cache.isClusterCoherent());
- barrier.await();
- if (shouldCrash) {
- log("Running crashing client...");
- // let other nodes make cache coherent
- Assert.assertEquals(false, cache.isClusterCoherent());
- Assert.assertEquals(false, cache.isNodeCoherent());
- log("Crashing client finishing without calling calling setNodeCoherent(true)");
- // barrier Y
- barrier.await();
- // exit without calling setNodeCoherent(true)
- } else {
- log("Running normal client...");
- cache.setNodeCoherent(true);
- Assert.assertEquals(true, cache.isNodeCoherent());
- Assert.assertEquals(false, cache.isClusterCoherent());
- log("Normal client before crasher exiting");
- // barrier Y
- barrier.await();
- log("Crashing client has probably exited... waiting for it to come back...");
- // by this time 1 node has exited (or in process of exiting)
- // the call below should return quite fast, as soon as the other node exits
- cache.waitUntilClusterCoherent();
-
- // wait for other node to come back after restart
- // barrier X
- barrier.await();
- log("Crashing client restarted.");
- // other node has restarted now
- Assert.assertEquals(true, cache.isClusterCoherent());
- Assert.assertEquals(true, cache.isNodeCoherent());
- // barrier Z
- barrier.await();
- }
-
- }
-
- private static void log(String msg) {
- System.out.println(msg);
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/management/ManagementServerLoaderTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/management/ManagementServerLoaderTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/test/java/net/sf/ehcache/management/ManagementServerLoaderTest.java (revision 0)
@@ -1,81 +0,0 @@
-package net.sf.ehcache.management;
-
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.ManagementRESTServiceConfiguration;
-import org.junit.Test;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-/**
- * @author Ludovic Orban
- */
-public class ManagementServerLoaderTest {
-
- @Test
- public void testRegistrationLifecycleStandalone() throws Exception {
- boolean managementAvailable = ManagementServerLoader.isManagementAvailable();
- assertThat(managementAvailable, is(true));
-
- CacheManager cacheManager1 = createCacheManager("cm-one", "localhost:1234");
- CacheManager cacheManager2 = createCacheManager("cm-two", "localhost:1234");
-
- try {
- ManagementServerLoader.register(cacheManager1, null, cacheManager1.getConfiguration().getManagementRESTService());
- DummyManagementServerImpl dms = (DummyManagementServerImpl)ManagementServerLoader.MGMT_SVR_BY_BIND.get("localhost:1234").getManagementServer();
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STARTED));
- ManagementServerLoader.register(cacheManager2, null, cacheManager2.getConfiguration().getManagementRESTService());
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STARTED));
-
- ManagementServerLoader.unregister(cacheManager2.getConfiguration()
- .getManagementRESTService()
- .getBind(), cacheManager2);
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STARTED));
- ManagementServerLoader.unregister(cacheManager1.getConfiguration()
- .getManagementRESTService()
- .getBind(), cacheManager1);
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STOPPED));
- } finally {
- cacheManager2.shutdown();
- cacheManager1.shutdown();
- }
- }
-
- @Test
- public void testRegistrationLifecycleClustered() throws Exception {
- boolean managementAvailable = ManagementServerLoader.isManagementAvailable();
- assertThat(managementAvailable, is(true));
-
- CacheManager cacheManager1 = createCacheManager("cm-one", "");
- CacheManager cacheManager2 = createCacheManager("cm-two", "");
-
- try {
- ManagementServerLoader.register(cacheManager1, "uuid1", cacheManager1.getConfiguration().getManagementRESTService());
- ManagementServerLoader.ManagementServerHolder managementServerHolder = ManagementServerLoader.MGMT_SVR_BY_BIND.get("");
- DummyManagementServerImpl dms = (DummyManagementServerImpl)managementServerHolder.getManagementServer();
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STARTED));
-
- ManagementServerLoader.register(cacheManager2, "uuid2", cacheManager2.getConfiguration().getManagementRESTService());
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STARTED));
-
- ManagementServerLoader.unregister("", cacheManager1);
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STARTED));
-
- ManagementServerLoader.unregister("", cacheManager2);
- assertThat(dms.status, is(DummyManagementServerImpl.Status.STOPPED));
- } finally {
- cacheManager2.shutdown();
- cacheManager1.shutdown();
- }
- }
-
- private static net.sf.ehcache.CacheManager createCacheManager(String name, String bind) {
- Configuration cfg = new Configuration().name(name);
- ManagementRESTServiceConfiguration managementRESTServiceConfiguration = new ManagementRESTServiceConfiguration();
- managementRESTServiceConfiguration.setBind(bind);
- cfg.managementRESTService(managementRESTServiceConfiguration);
- return new net.sf.ehcache.CacheManager(cfg);
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/SampledStatistic.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/SampledStatistic.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/SampledStatistic.java (revision 0)
@@ -1,87 +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.List;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import org.terracotta.statistics.ValueStatistic;
-import org.terracotta.statistics.archive.StatisticArchive;
-import org.terracotta.statistics.archive.StatisticSampler;
-import org.terracotta.statistics.archive.Timestamped;
-
-/**
- * The Class SampledStatistic.
- *
- * @param the generic type
- * @author cdennis
- */
-class SampledStatistic {
-
- /** The sampler. */
- private final StatisticSampler sampler;
-
- /** The history. */
- private final StatisticArchive history;
-
- /**
- * Instantiates a new sampled statistic.
- *
- * @param statistic the statistic
- * @param executor the executor
- * @param historySize the history size
- * @param periodNanos the period nanos
- */
- public SampledStatistic(ValueStatistic statistic, ScheduledExecutorService executor, int historySize, long periodNanos) {
- this.history = new StatisticArchive(historySize);
- this.sampler = new StatisticSampler(executor, periodNanos, TimeUnit.NANOSECONDS, statistic, history);
- }
-
- /**
- * Start sampling.
- */
- public void startSampling() {
- sampler.start();
- }
-
- /**
- * Stop sampling.
- */
- public void stopSampling() {
- sampler.stop();
- history.clear();
- }
-
- /**
- * History.
- *
- * @return the list
- */
- public List> history() {
- return history.getArchive();
- }
-
- /**
- * Adjust.
- *
- * @param historySize the history size
- * @param historyNanos the history nanos
- */
- void adjust(int historySize, long historyNanos) {
- history.setCapacity(historySize);
- sampler.setPeriod(historyNanos, TimeUnit.NANOSECONDS);
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/PersistenceConfigurationElement.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/PersistenceConfigurationElement.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/PersistenceConfigurationElement.java (revision 0)
@@ -1,66 +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.generator.model.elements;
-
-import net.sf.ehcache.config.PersistenceConfiguration;
-import net.sf.ehcache.config.generator.model.NodeElement;
-import net.sf.ehcache.config.generator.model.SimpleNodeAttribute;
-import net.sf.ehcache.config.generator.model.SimpleNodeElement;
-
-/**
- * Element representing the {@link net.sf.ehcache.config.PersistenceConfiguration}
- *
- * @author Chris Dennis
- *
- */
-public class PersistenceConfigurationElement extends SimpleNodeElement {
- private final PersistenceConfiguration persistenceConfiguration;
-
- /**
- * Construtor accepting the parent and the {@link net.sf.ehcache.config.PersistenceConfiguration}
- *
- * @param parent
- * @param persistenceConfiguration
- */
- public PersistenceConfigurationElement(ConfigurationElement parent, PersistenceConfiguration persistenceConfiguration) {
- super(parent, "persistence");
- this.persistenceConfiguration = persistenceConfiguration;
- init();
- }
-
- /**
- * Construtor accepting the element and the {@link net.sf.ehcache.config.PersistenceConfiguration}
- *
- * @param element
- * @param persistenceConfiguration
- */
- public PersistenceConfigurationElement(NodeElement element, PersistenceConfiguration persistenceConfiguration) {
- super(element, "persistence");
- this.persistenceConfiguration = persistenceConfiguration;
- init();
- }
-
- private void init() {
- if (persistenceConfiguration == null) {
- return;
- }
- addAttribute(new SimpleNodeAttribute("strategy", persistenceConfiguration.getStrategy()));
- addAttribute(new SimpleNodeAttribute("synchronousWrites", persistenceConfiguration.getSynchronousWrites()).optional(true)
- .defaultValue(PersistenceConfiguration.DEFAULT_SYNCHRONOUS_WRITES));
- }
-
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache/src/test/resources/serializedforms/SerializedReadCommittedClusteredSoftLockSerializationTest.testBasic.ser
===================================================================
diff -u -N -r11014 -r11048
Binary files differ
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BlockingCacheTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BlockingCacheTest.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BlockingCacheTest.java (revision 0)
@@ -1,135 +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.constructs.blocking.BlockingCache;
-
-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.io.Serializable;
-
-import junit.framework.Assert;
-
-/**
- * @author Alex Snaps
- */
-public class BlockingCacheTest extends AbstractCacheTestBase {
-
- public BlockingCacheTest(TestConfig testConfig) {
- super("blocking-cache.xml", testConfig, App.class, App.class, App.class);
- }
-
- public static class App extends ClientBase {
- private static final String KEY_1 = "funkyKey";
- private static final Serializable VALUE_1 = "A really cool value";
- private static final String KEY_2 = "otherFunkyKey";
- private static final Serializable VALUE_2 = "Even cooler value";
- private static final String KEY_3 = "theUeberFunkyKey";
- private static final Serializable VALUE_3 = "can't get any cooler value";
- private final ToolkitBarrier barrier;
-
- public App(String[] args) {
- super("test1", args);
- this.barrier = getClusteringToolkit().getBarrier("test-barrier", getParticipantCount());
- }
-
- public static void main(String[] args) {
- new App(args).run();
- }
-
- @Override
- protected void runTest(Cache testcache, Toolkit clusteringToolkit) throws Throwable {
- final int index = barrier.await();
-
- Ehcache cache = cacheManager.getCache("test1");
- Assert.assertNotNull("There should be a cache test from that manager!", cache);
- BlockingCache blockingCache = new BlockingCache(cache);
- cacheManager.replaceCacheWithDecoratedCache(cache, blockingCache);
- cache = cacheManager.getEhcache("test1");
-
- if (index == 0) {
- // Node 0 blocks all other read to the key
- Assert.assertNull("Key " + KEY_1 + " should not be present in the cache yet", cache.get(KEY_1));
- cache.put(new Element(KEY_2, VALUE_2));
- }
-
- barrier.await();
-
- if (index != 0) {
- // This call should block, until node 0 puts en element for KEY in the cache
- Element element = cache.get(KEY_1);
- Assert.assertNotNull("Node 0 should have put key " + KEY_1 + " in the cache", element);
- Assert.assertEquals("Value for key " + KEY_1 + " should be " + VALUE_1, VALUE_1, element.getValue());
- } else {
- Thread.sleep(2000); // Thinking about the meaning of life for a while
- cache.put(new Element(KEY_1, VALUE_1));
- }
- Element element = cache.get(KEY_2);
- Assert.assertNotNull(element);
- Assert.assertEquals("Value for key " + KEY_2 + " should be " + VALUE_2, VALUE_2, element.getValue());
-
- barrier.await();
-
- blockingCache.setTimeoutMillis(3000);
- if (index == 0) {
- // Should block all other get to the same key
- cache.get(KEY_3);
- }
-
- barrier.await();
-
- switch (index) {
- case 2:
- Thread.sleep(2000);
- Assert.assertNotNull(cache.get(KEY_3));
- break;
- case 1:
- try {
- cache.get(KEY_3);
- Assert.fail();
- } catch (CacheException e) {
- // We failed aquiring the lock
- }
- break;
- case 0:
- Thread.sleep(3500);
- cache.put(new Element(KEY_3, VALUE_3));
- break;
- }
-
- barrier.await();
-
- // This tests inline eviction (EHC-420)
- Thread.sleep(22000);
-
- switch (index) {
- case 0:
- Assert.assertNull(cache.get(KEY_3));
- break;
- }
-
- barrier.await();
- blockingCache.setTimeoutMillis(10000);
- switch (index) {
- case 0:
- Thread.sleep(1500);
- cache.put(new Element(KEY_3, VALUE_3));
- break;
- default:
- Assert.assertNotNull(cache.get(KEY_3));
- Assert.assertEquals(VALUE_3, cache.get(KEY_3).getValue());
- }
- }
-
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/BaseEmitterBean.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/BaseEmitterBean.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/BaseEmitterBean.java (revision 0)
@@ -1,168 +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.management.impl;
-
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.atomic.AtomicLong;
-
-import javax.management.ListenerNotFoundException;
-import javax.management.MBeanNotificationInfo;
-import javax.management.NotCompliantMBeanException;
-import javax.management.Notification;
-import javax.management.NotificationBroadcasterSupport;
-import javax.management.NotificationEmitter;
-import javax.management.NotificationFilter;
-import javax.management.NotificationListener;
-import javax.management.StandardMBean;
-
-/**
- * @author gkeim
- *
- */
-public abstract class BaseEmitterBean extends StandardMBean implements NotificationEmitter {
- /**
- * emitter
- */
- protected final Emitter emitter = new Emitter();
-
- /**
- * sequenceNumber
- */
- protected final AtomicLong sequenceNumber = new AtomicLong();
-
-
- private final List notificationListeners = new CopyOnWriteArrayList();
-
- /**
- * BaseEmitterBean
- *
- * @param
- * @param mbeanInterface
- * @throws NotCompliantMBeanException
- */
- protected BaseEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException {
- super(mbeanInterface);
- }
-
- /**
- * sendNotification
- *
- * @param eventType
- */
- public void sendNotification(String eventType) {
- sendNotification(eventType, null, null);
- }
-
- /**
- * sendNotification
- *
- * @param eventType
- * @param data
- */
- public void sendNotification(String eventType, Object data) {
- sendNotification(eventType, data, null);
- }
-
- /**
- * sendNotification
- *
- * @param eventType
- * @param data
- * @param msg
- */
- public void sendNotification(String eventType, Object data, String msg) {
- Notification notif = new Notification(eventType, this, sequenceNumber.incrementAndGet(), System.currentTimeMillis(), msg);
- if (data != null) {
- notif.setUserData(data);
- }
- emitter.sendNotification(notif);
- }
-
- /**
- * Dispose of this SampledCacheManager and clean up held resources
- */
- public final void dispose() {
- doDispose();
- removeAllNotificationListeners();
- }
-
- /**
- * Dispose callback of subclasses
- */
- protected abstract void doDispose();
-
- /**
- * @author gkeim
- */
- private class Emitter extends NotificationBroadcasterSupport {
- /**
- * @see javax.management.NotificationBroadcasterSupport#getNotificationInfo()
- */
- @Override
- public MBeanNotificationInfo[] getNotificationInfo() {
- return BaseEmitterBean.this.getNotificationInfo();
- }
- }
-
- /**
- * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
- public void addNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) {
- emitter.addNotificationListener(notif, filter, callBack);
- notificationListeners.add(notif);
- }
-
- /**
- * remove all added notification listeners
- */
- private void removeAllNotificationListeners() {
- for (NotificationListener listener : notificationListeners) {
- try {
- emitter.removeNotificationListener(listener);
- } catch (ListenerNotFoundException e) {
- // ignore
- }
- }
- notificationListeners.clear();
- }
-
- /**
- * @see javax.management.NotificationBroadcaster#getNotificationInfo()
- */
- public abstract MBeanNotificationInfo[] getNotificationInfo();
-
-
- /**
- * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener)
- */
- public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
- emitter.removeNotificationListener(listener);
- notificationListeners.remove(listener);
- }
-
- /**
- * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener,
- * javax.management.NotificationFilter, java.lang.Object)
- */
- public void removeNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack)
- throws ListenerNotFoundException {
- emitter.removeNotificationListener(notif, filter, callBack);
- notificationListeners.remove(notif);
- }
-}
Index: rctags/ehcache-2.10.7.0.58/ehcache-scheduled-refresh/checkstyle/checkstyle.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-scheduled-refresh/checkstyle/checkstyle.xml (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-scheduled-refresh/checkstyle/checkstyle.xml (revision 0)
@@ -1,240 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/byteman/LocalTxTestDebug.btm
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/byteman/LocalTxTestDebug.btm (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/system-tests/src/test/resources/byteman/LocalTxTestDebug.btm (revision 0)
@@ -1,77 +0,0 @@
-
-
-RULE trace ServerMap gets
-CLASS ServerMap
-METHOD doGet
-AT EXIT
-#IF NOT $getType.name().equals("UNSAFE")
-IF false
-DO traceln(" ____ ServerMap.doGet key.hashCode(): \"" + $key.hashCode() + "\", \"" + $getType + "\", \"" + $quiet + " -> " + $!);
-ENDRULE
-
-RULE trace ServerMap puts
-CLASS ServerMap
-METHOD doLogicalPut
-AT ENTRY
-IF false
-DO traceln(" _____ ServerMap.doLogicalPut - key.hashCode(): \"" + $key.hashCode() + "\", mutateType: \"" + $type + "\", value: \"" + $value);
-ENDRULE
-
-
-RULE trace ServerMap removes
-CLASS ServerMap
-METHOD doLogicalRemove
-AT ENTRY
-IF false
-DO traceln(" _____ ServerMap.doLogicalRemove - key.hashCode(): \"" + $key.hashCode() + "\", mutateType: \"" + $type);
-ENDRULE
-
-RULE trace clusteredStore doPut
-CLASS ClusteredStore
-METHOD doPut
-AT EXIT
-IF false
-DO traceln(" _____ ClusteredStore.doPut - pkey.hashCode(): \"" + $portableKey.hashCode() + "\", return: \"" + $!);
-ENDRULE
-
-RULE trace clusteredStore replace
-CLASS ClusteredStore
-METHOD replace(Element,Element,ElementValueComparator)
-AT EXIT
-IF false
-DO traceln(" _____ ClusteredStore.replace old: "+$old+" element: "+$element+" return: \"" + $!);
-ENDRULE
-
-RULE trace CustomLifespanSerializedEntry isExpired
-CLASS CustomLifespanSerializedEntry
-METHOD isExpired
-AT EXIT
-IF false
-DO traceln(" _____ CustomLifespanSerializedEntry isExpired atTime: " +$atTime+ " maxTTISeconds: "+$maxTTISeconds+" maxTTLSeconds: "+$maxTTLSeconds+" lastAccessedTime: "+$0.lastAccessedTime+" createTime: "+$0.createTime+" return: " + $!);
-ENDRULE
-
-RULE trace ServerMap createSerializedEntry
-CLASS ServerMap
-METHOD createSerializedEntry
-AT ENTRY
-IF false
-DO traceln(" _____XXX ServerMap createSerializedEntry createTime: "+$createTimeInSecs+" now: " + $0.timeSource.now());
-ENDRULE
-
-RULE trace DefaultElementValueComparator
-CLASS DefaultElementValueComparator
-METHOD equals(Element, Element)
-AT ENTRY
-IF false
-DO traceln(" _____XXX DefaultElementValueComparator: e1: " + $e1 + ", e2: " + $e2);
-ENDRULE
-
-
-RULE trace EhcacheTxnsClusteredStateFacadeImpl clear
-CLASS EhcacheTxnsClusteredStateFacadeImpl
-METHOD clearSoftLock
-AT ENTRY
-IF false
-DO traceln(" _____XXX clearSoftLock: softLockId: " + $softLockId);
-ENDRULE
-
Index: rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/chm/SelectableConcurrentHashMap.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/chm/SelectableConcurrentHashMap.java (revision 11014)
+++ rctags/ehcache-2.10.7.0.58/ehcache-core/src/main/java/net/sf/ehcache/store/chm/SelectableConcurrentHashMap.java (revision 0)
@@ -1,1259 +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.chm;
-
-import java.util.AbstractCollection;
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.NoSuchElementException;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import net.sf.ehcache.CacheOperationOutcomes.EvictionOutcome;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.event.RegisteredEventListeners;
-import net.sf.ehcache.pool.PoolAccessor;
-import org.terracotta.statistics.observer.OperationObserver;
-
-import static net.sf.ehcache.statistics.StatisticBuilder.operation;
-
-/**
- * SelectableConcurrentHashMap subclasses a repackaged version of ConcurrentHashMap
- * ito allow efficient random sampling of the map values.
- *
- * The random sampling technique involves randomly selecting a map Segment, and then
- * selecting a number of random entry chains from that segment.
- *
- * @author Chris Dennis
- */
-@SuppressWarnings("ForLoopReplaceableByForEach")
-public class SelectableConcurrentHashMap {
-
- /**
- * The default initial capacity for this table,
- * used when not otherwise specified in a constructor.
- */
- static final int DEFAULT_INITIAL_CAPACITY = 16;
-
- /**
- * The default load factor for this table, used when not
- * otherwise specified in a constructor.
- */
- static final float DEFAULT_LOAD_FACTOR = 0.75f;
-
- /**
- * The maximum capacity, used if a higher value is implicitly
- * specified by either of the constructors with arguments. MUST
- * be a power of two <= 1<<30 to ensure that entries are indexable
- * using ints.
- */
- private static final int MAXIMUM_CAPACITY = 1 << 30;
-
- /**
- * The maximum number of segments to allow; used to bound
- * constructor arguments.
- */
- private static final int MAX_SEGMENTS = 1 << 16; // slightly conservative
-
- /**
- * Number of unsynchronized retries in size and containsValue
- * methods before resorting to locking. This is used to avoid
- * unbounded retries if tables undergo continuous modification
- * which would make it impossible to obtain an accurate result.
- */
- private static final int RETRIES_BEFORE_LOCK = 2;
-
- /**
- * Mask value for indexing into segments. The upper bits of a
- * key's hash code are used to choose the segment.
- */
- private final int segmentMask;
-
- /**
- * Shift value for indexing within segments.
- */
- private final int segmentShift;
-
- /**
- * The segments, each of which is a specialized hash table
- */
- private final Segment[] segments;
-
- private final Random rndm = new Random();
- private final PoolAccessor poolAccessor;
- private volatile long maxSize;
- private final RegisteredEventListeners cacheEventNotificationService;
-
- private Set keySet;
- private Set> entrySet;
- private Collection values;
-
- private final OperationObserver evictionObserver = operation(EvictionOutcome.class).named("eviction").of(this).build();
-
- public SelectableConcurrentHashMap(PoolAccessor poolAccessor, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService) {
- this(poolAccessor, DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, concurrency, maximumSize, cacheEventNotificationService);
- }
-
- public SelectableConcurrentHashMap(PoolAccessor poolAccessor, int initialCapacity, float loadFactor, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService) {
- if (!(loadFactor > 0) || initialCapacity < 0 || concurrency <= 0)
- throw new IllegalArgumentException();
-
- if (concurrency > MAX_SEGMENTS)
- concurrency = MAX_SEGMENTS;
-
- // Find power-of-two sizes best matching arguments
- int sshift = 0;
- int ssize = 1;
- while (ssize < concurrency) {
- ++sshift;
- ssize <<= 1;
- }
- segmentShift = 32 - sshift;
- segmentMask = ssize - 1;
- this.segments = new Segment[ssize];
-
- if (initialCapacity > MAXIMUM_CAPACITY)
- initialCapacity = MAXIMUM_CAPACITY;
- int c = initialCapacity / ssize;
- if (c * ssize < initialCapacity)
- ++c;
- int cap = 1;
- while (cap < c)
- cap <<= 1;
-
- for (int i = 0; i < this.segments.length; ++i)
- this.segments[i] = createSegment(cap, loadFactor);
-
- this.poolAccessor = poolAccessor;
- this.maxSize = maximumSize;
- this.cacheEventNotificationService = cacheEventNotificationService;
- }
-
- public void setMaxSize(final long maxSize) {
- this.maxSize = maxSize;
- }
-
- public Element[] getRandomValues(final int size, Object keyHint) {
- ArrayList sampled = new ArrayList(size * 2);
-
- // pick a random starting point in the map
- int randomHash = rndm.nextInt();
-
- final int segmentStart;
- if (keyHint == null) {
- segmentStart = (randomHash >>> segmentShift) & segmentMask;
- } else {
- segmentStart = (hash(keyHint.hashCode()) >>> segmentShift) & segmentMask;
- }
-
- int segmentIndex = segmentStart;
- do {
- final HashEntry[] table = segments[segmentIndex].table;
- final int tableStart = randomHash & (table.length - 1);
- int tableIndex = tableStart;
- do {
- for (HashEntry e = table[tableIndex]; e != null; e = e.next) {
- Element value = e.value;
- if (value != null) {
- sampled.add(value);
- }
- }
-
- if (sampled.size() >= size) {
- return sampled.toArray(new Element[sampled.size()]);
- }
-
- //move to next table slot
- tableIndex = (tableIndex + 1) & (table.length - 1);
- } while (tableIndex != tableStart);
-
- //move to next segment
- segmentIndex = (segmentIndex + 1) & segmentMask;
- } while (segmentIndex != segmentStart);
-
- return sampled.toArray(new Element[sampled.size()]);
- }
-
- /**
- * Return an object of the kind which will be stored when
- * the element is going to be inserted
- * @param e the element
- * @return an object looking-alike the stored one
- */
- public Object storedObject(Element e) {
- return new HashEntry(null, 0, null, e, 0);
- }
-
- /**
- * Returns the number of key-value mappings in this map without locking anything.
- * This may not give the exact element count as locking is avoided.
- * If the map contains more than Integer.MAX_VALUE elements, returns
- * Integer.MAX_VALUE .
- *
- * @return the number of key-value mappings in this map
- */
- public int quickSize() {
- final Segment[] segments = this.segments;
- long sum = 0;
- for (Segment seg : segments) {
- sum += seg.count;
- }
-
- if (sum > Integer.MAX_VALUE) {
- return Integer.MAX_VALUE;
- } else {
- return (int)sum;
- }
- }
-
- public boolean isEmpty() {
- final Segment[] segments = this.segments;
- /*
- * We keep track of per-segment modCounts to avoid ABA
- * problems in which an element in one segment was added and
- * in another removed during traversal, in which case the
- * table was never actually empty at any point. Note the
- * similar use of modCounts in the size() and containsValue()
- * methods, which are the only other methods also susceptible
- * to ABA problems.
- */
- int[] mc = new int[segments.length];
- int mcsum = 0;
- for (int i = 0; i < segments.length; ++i) {
- if (segments[i].count != 0)
- return false;
- else
- mcsum += mc[i] = segments[i].modCount;
- }
- // If mcsum happens to be zero, then we know we got a snapshot
- // before any modifications at all were made. This is
- // probably common enough to bother tracking.
- if (mcsum != 0) {
- for (int i = 0; i < segments.length; ++i) {
- if (segments[i].count != 0 ||
- mc[i] != segments[i].modCount)
- return false;
- }
- }
- return true;
- }
-
- public int size() {
- final Segment[] segments = this.segments;
-
- for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
- int[] mc = new int[segments.length];
- long check = 0;
- long sum = 0;
- int mcsum = 0;
- for (int i = 0; i < segments.length; ++i) {
- sum += segments[i].count;
- mcsum += mc[i] = segments[i].modCount;
- }
- if (mcsum != 0) {
- for (int i = 0; i < segments.length; ++i) {
- check += segments[i].count;
- if (mc[i] != segments[i].modCount) {
- check = -1; // force retry
- break;
- }
- }
- }
- if (check == sum) {
- if (sum > Integer.MAX_VALUE) {
- return Integer.MAX_VALUE;
- } else {
- return (int)sum;
- }
- }
- }
-
- long sum = 0;
- for (int i = 0; i < segments.length; ++i) {
- segments[i].readLock().lock();
- }
- try {
- for (int i = 0; i < segments.length; ++i) {
- sum += segments[i].count;
- }
- } finally {
- for (int i = 0; i < segments.length; ++i) {
- segments[i].readLock().unlock();
- }
- }
-
- if (sum > Integer.MAX_VALUE) {
- return Integer.MAX_VALUE;
- } else {
- return (int)sum;
- }
- }
-
- public ReentrantReadWriteLock lockFor(Object key) {
- int hash = hash(key.hashCode());
- return segmentFor(hash);
- }
-
- public ReentrantReadWriteLock[] locks() {
- return segments;
- }
-
- public Element get(Object key) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).get(key, hash);
- }
-
- public boolean containsKey(Object key) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).containsKey(key, hash);
- }
-
- public boolean containsValue(Object value) {
- if (value == null)
- throw new NullPointerException();
-
- // See explanation of modCount use above
-
- final Segment[] segments = this.segments;
- int[] mc = new int[segments.length];
-
- // Try a few times without locking
- for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
- int sum = 0;
- int mcsum = 0;
- for (int i = 0; i < segments.length; ++i) {
- int c = segments[i].count;
- mcsum += mc[i] = segments[i].modCount;
- if (segments[i].containsValue(value))
- return true;
- }
- boolean cleanSweep = true;
- if (mcsum != 0) {
- for (int i = 0; i < segments.length; ++i) {
- int c = segments[i].count;
- if (mc[i] != segments[i].modCount) {
- cleanSweep = false;
- break;
- }
- }
- }
- if (cleanSweep)
- return false;
- }
-
- // Resort to locking all segments
- for (int i = 0; i < segments.length; ++i)
- segments[i].readLock().lock();
- try {
- for (int i = 0; i < segments.length; ++i) {
- if (segments[i].containsValue(value)) {
- return true;
- }
- }
- } finally {
- for (int i = 0; i < segments.length; ++i)
- segments[i].readLock().unlock();
- }
- return false;
- }
-
- public Element put(Object key, Element element, long sizeOf) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).put(key, hash, element, sizeOf, false, true);
- }
-
- public Element putIfAbsent(Object key, Element element, long sizeOf) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).put(key, hash, element, sizeOf, true, true);
- }
-
- public Element remove(Object key) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).remove(key, hash, null);
- }
-
- public boolean remove(Object key, Object value) {
- int hash = hash(key.hashCode());
- if (value == null)
- return false;
- return segmentFor(hash).remove(key, hash, value) != null;
- }
-
- public void clear() {
- for (int i = 0; i < segments.length; ++i)
- segments[i].clear();
- }
-
- public Set keySet() {
- Set ks = keySet;
- return (ks != null) ? ks : (keySet = new KeySet());
- }
-
- public Collection values() {
- Collection vs = values;
- return (vs != null) ? vs : (values = new Values());
- }
-
- public Set> entrySet() {
- Set> es = entrySet;
- return (es != null) ? es : (entrySet = new EntrySet());
- }
-
- protected Segment createSegment(int initialCapacity, float lf) {
- return new Segment(initialCapacity, lf);
- }
-
- public boolean evict() {
- return getRandomSegment().evict();
- }
-
- private Segment getRandomSegment() {
- int randomHash = rndm.nextInt();
- return segments[((randomHash >>> segmentShift) & segmentMask)];
- }
-
- public void recalculateSize(Object key) {
- int hash = hash(key.hashCode());
- segmentFor(hash).recalculateSize(key, hash);
- }
-
- /**
- * Returns the segment that should be used for key with given hash
- * @param hash the hash code for the key
- * @return the segment
- */
- protected final Segment segmentFor(int hash) {
- return segments[(hash >>> segmentShift) & segmentMask];
- }
-
- protected final List segments() {
- return Collections.unmodifiableList(Arrays.asList(segments));
- }
-
- public class Segment extends ReentrantReadWriteLock {
-
- private static final int MAX_EVICTION = 5;
-
- /**
- * The number of elements in this segment's region.
- */
- protected volatile int count;
-
- /**
- * Number of updates that alter the size of the table. This is
- * used during bulk-read methods to make sure they see a
- * consistent snapshot: If modCounts change during a traversal
- * of segments computing size or checking containsValue, then
- * we might have an inconsistent view of state so (usually)
- * must retry.
- */
- int modCount;
-
- /**
- * The table is rehashed when its size exceeds this threshold.
- * (The value of this field is always (int)(capacity *
- * loadFactor) .)
- */
- int threshold;
-
- /**
- * The per-segment table.
- */
- protected volatile HashEntry[] table;
-
- /**
- * The load factor for the hash table. Even though this value
- * is same for all segments, it is replicated to avoid needing
- * links to outer object.
- * @serial
- */
- final float loadFactor;
-
- private Iterator evictionIterator;
-
- protected Segment(int initialCapacity, float lf) {
- loadFactor = lf;
- setTable(new HashEntry[initialCapacity]);
- }
-
- protected void preRemove(HashEntry e) {
-
- }
-
- protected void postInstall(Object key, Element value) {
-
- }
-
- /**
- * Sets table to new HashEntry array.
- * Call only while holding lock or in constructor.
- */
- void setTable(HashEntry[] newTable) {
- threshold = (int)(newTable.length * loadFactor);
- table = newTable;
- }
-
- /**
- * Returns properly casted first entry of bin for given hash.
- */
- protected HashEntry getFirst(int hash) {
- HashEntry[] tab = table;
- return tab[hash & (tab.length - 1)];
- }
-
- private HashEntry removeAndGetFirst(HashEntry e, HashEntry first) {
- preRemove(e);
- // All entries following removed node can stay
- // in list, but all preceding ones need to be
- // cloned.
- HashEntry newFirst = e.next;
- for (HashEntry p = first; p != e; p = p.next)
- newFirst = relinkHashEntry(p, newFirst);
- return newFirst;
- }
-
- protected HashEntry createHashEntry(Object key, int hash, HashEntry next, Element value, long sizeOf) {
- return new HashEntry(key, hash, next, value, sizeOf);
- }
-
- protected HashEntry relinkHashEntry(HashEntry e, HashEntry next) {
- return new HashEntry(e.key, e.hash, next, e.value, e.sizeOf);
- }
-
- protected void clear() {
- final WriteLock writeLock = writeLock();
- writeLock.lock();
- try {
- if (count != 0) {
- HashEntry[] tab = table;
- for (int i = 0; i < tab.length ; i++)
- tab[i] = null;
- ++modCount;
- count = 0; // write-volatile
- }
- evictionIterator = null;
- } finally {
- writeLock.unlock();
- }
- }
-
- Element remove(Object key, int hash, Object value) {
- final WriteLock writeLock = writeLock();
- writeLock.lock();
- try {
- int c = count - 1;
- HashEntry[] tab = table;
- int index = hash & (tab.length - 1);
- HashEntry first = tab[index];
- HashEntry e = first;
- while (e != null && (e.hash != hash || !key.equals(e.key)))
- e = e.next;
-
- Element oldValue = null;
- if (e != null) {
- Element v = e.value;
- if (value == null || value.equals(v)) {
- oldValue = v;
- ++modCount;
- tab[index] = removeAndGetFirst(e, first);
- count = c; // write-volatile
- if (cacheEventNotificationService != null) {
- cacheEventNotificationService.notifyElementRemovedOrdered(oldValue);
- }
- poolAccessor.delete(e.sizeOf);
- if(evictionIterator != null && ((SegmentIterator)evictionIterator).nextEntry == e) {
- evictionIterator.next();
- }
- }
- }
- return oldValue;
- } finally {
- writeLock.unlock();
- }
- }
-
- public void recalculateSize(Object key, int hash) {
- Element value = null;
- long oldSize = 0;
- final ReadLock readLock = readLock();
- readLock.lock();
- try {
- HashEntry[] tab = table;
- int index = hash & (tab.length - 1);
- HashEntry first = tab[index];
- HashEntry e = first;
- while (e != null && (e.hash != hash || !key.equals(e.key))) {
- e = e.next;
- }
- if (e != null) {
- key = e.key;
- value = e.value;
- oldSize = e.sizeOf;
- }
- } finally {
- readLock.unlock();
- }
- if (value != null) {
- long delta = poolAccessor.replace(oldSize, key, value, storedObject(value), true);
- final WriteLock writeLock = writeLock();
- writeLock.lock();
- try {
- HashEntry e = getFirst(hash);
- while (e != null && key != e.key) {
- e = e.next;
- }
-
- if (e != null && e.value == value && oldSize == e.sizeOf) {
- e.sizeOf = oldSize + delta;
- } else {
- poolAccessor.delete(delta);
- }
- } finally {
- writeLock.unlock();
- }
- }
- }
-
- protected Element put(Object key, int hash, Element value, long sizeOf, boolean onlyIfAbsent, boolean fire) {
- Element[] evicted = new Element[MAX_EVICTION];
- final WriteLock writeLock = writeLock();
- writeLock.lock();
- try {
- int c = count;
- if (c++ > threshold) // ensure capacity
- rehash();
- HashEntry[] tab = table;
- int index = hash & (tab.length - 1);
- HashEntry first = tab[index];
- HashEntry e = first;
- while (e != null && (e.hash != hash || !key.equals(e.key)))
- e = e.next;
-
- Element oldValue;
- if (e != null) {
- oldValue = e.value;
- if (!onlyIfAbsent) {
- poolAccessor.delete(e.sizeOf);
- e.value = value;
- e.sizeOf = sizeOf;
- if (cacheEventNotificationService != null) {
- cacheEventNotificationService.notifyElementUpdatedOrdered(oldValue, value);
- }
- if (fire) {
- postInstall(key, value);
- }
- }
- } else {
- oldValue = null;
- ++modCount;
- tab[index] = createHashEntry(key, hash, first, value, sizeOf);
- count = c; // write-volatile
- if (cacheEventNotificationService != null) {
- cacheEventNotificationService.notifyElementPutOrdered(value);
- }
- if (fire) {
- postInstall(key, value);
- }
- }
-
- if((onlyIfAbsent && oldValue != null || !onlyIfAbsent)) {
- if (SelectableConcurrentHashMap.this.maxSize > 0) {
- int runs = Math.min(MAX_EVICTION, SelectableConcurrentHashMap.this.quickSize() - (int) SelectableConcurrentHashMap.this.maxSize);
- while (runs-- > 0) {
- evictionObserver.begin();
- Element evict = nextExpiredOrToEvict(value);
- if (evict != null) {
- Element removed;
- while ((removed = remove(evict.getKey(), hash(evict.getKey().hashCode()), null)) == null) {
- evict = nextExpiredOrToEvict(value);
- if (evict == null) {
- break;
- }
- }
- evicted[runs] = removed;
- }
- evictionObserver.end(EvictionOutcome.SUCCESS);
- }
- }
- }
- return oldValue;
- } finally {
- writeLock.unlock();
- for (Element element : evicted) {
- notifyEvictionOrExpiry(element);
- }
- }
- }
-
- private void notifyEvictionOrExpiry(final Element element) {
- if(element != null && cacheEventNotificationService != null) {
- if (element.isExpired()) {
- cacheEventNotificationService.notifyElementExpiry(element, false);
- } else {
- cacheEventNotificationService.notifyElementEvicted(element, false);
- }
- }
- }
-
- Element get(final Object key, final int hash) {
- final ReadLock readLock = readLock();
- readLock.lock();
- try {
- if (count != 0) { // read-volatile
- HashEntry e = getFirst(hash);
- while (e != null) {
- if (e.hash == hash && key.equals(e.key)) {
- e.accessed = true;
- return e.value;
- }
- e = e.next;
- }
- }
- return null;
- } finally {
- readLock.unlock();
- }
- }
-
- boolean containsKey(final Object key, final int hash) {
- final ReadLock readLock = readLock();
- readLock.lock();
- try {
- if (count != 0) { // read-volatile
- HashEntry e = getFirst(hash);
- while (e != null) {
- if (e.hash == hash && key.equals(e.key))
- return true;
- e = e.next;
- }
- }
- return false;
- } finally {
- readLock.unlock();
- }
- }
-
- boolean containsValue(Object value) {
- final ReadLock readLock = readLock();
- readLock.lock();
- try {
- if (count != 0) { // read-volatile
- HashEntry[] tab = table;
- int len = tab.length;
- for (int i = 0 ; i < len; i++) {
- for (HashEntry e = tab[i]; e != null; e = e.next) {
- Element v = e.value;
- if (value.equals(v))
- return true;
- }
- }
- }
- return false;
- } finally {
- readLock.unlock();
- }
- }
-
- private Element nextExpiredOrToEvict(final Element justAdded) {
-
- Element lastUnpinned = null;
- int i = 0;
-
- while (i++ < count) {
- if (evictionIterator == null || !evictionIterator.hasNext()) {
- evictionIterator = iterator();
- }
- final HashEntry next = evictionIterator.next();
- if (!next.accessed || next.value.isExpired()) {
- return next.value;
- } else {
- if (next.value != justAdded) {
- lastUnpinned = next.value;
- }
- next.accessed = false;
- }
- }
-
- return lastUnpinned;
- }
-
- protected Iterator iterator() {
- return new SegmentIterator(this);
- }
-
- boolean evict() {
- Element remove = null;
- final WriteLock writeLock = writeLock();
- writeLock.lock();
- try {
- Element evict = nextExpiredOrToEvict(null);
- if (evict != null) {
- if (cacheEventNotificationService != null) {
- evictionObserver.begin();
- remove = remove(evict.getKey(), hash(evict.getKey().hashCode()), null);
- evictionObserver.end(EvictionOutcome.SUCCESS);
- } else {
- remove = remove(evict.getKey(), hash(evict.getKey().hashCode()), null);
- }
- }
- } finally {
- writeLock.unlock();
- }
- notifyEvictionOrExpiry(remove);
- return remove != null;
- }
-
- void rehash() {
- HashEntry[] oldTable = table;
- int oldCapacity = oldTable.length;
- if (oldCapacity >= MAXIMUM_CAPACITY)
- return;
-
- /*
- * Reclassify nodes in each list to new Map. Because we are
- * using power-of-two expansion, the elements from each bin
- * must either stay at same index, or move with a power of two
- * offset. We eliminate unnecessary node creation by catching
- * cases where old nodes can be reused because their next
- * fields won't change. Statistically, at the default
- * threshold, only about one-sixth of them need cloning when
- * a table doubles. The nodes they replace will be garbage
- * collectable as soon as they are no longer referenced by any
- * reader thread that may be in the midst of traversing table
- * right now.
- */
-
- HashEntry[] newTable = new HashEntry[oldCapacity << 1];
- threshold = (int)(newTable.length * loadFactor);
- int sizeMask = newTable.length - 1;
- for (int i = 0; i < oldCapacity ; i++) {
- // We need to guarantee that any existing reads of old Map can
- // proceed. So we cannot yet null out each bin.
- HashEntry e = oldTable[i];
-
- if (e != null) {
- HashEntry next = e.next;
- int idx = e.hash & sizeMask;
-
- // Single node on list
- if (next == null)
- newTable[idx] = e;
-
- else {
- // Reuse trailing consecutive sequence at same slot
- HashEntry lastRun = e;
- int lastIdx = idx;
- for (HashEntry last = next;
- last != null;
- last = last.next) {
- int k = last.hash & sizeMask;
- if (k != lastIdx) {
- lastIdx = k;
- lastRun = last;
- }
- }
- newTable[lastIdx] = lastRun;
-
- // Clone all remaining nodes
- for (HashEntry p = e; p != lastRun; p = p.next) {
- int k = p.hash & sizeMask;
- HashEntry n = newTable[k];
- newTable[k] = relinkHashEntry(p, n);
- }
- }
- }
- }
- table = newTable;
- if (evictionIterator != null) {
- evictionIterator = iterator();
- }
- }
-
- Iterator getEvictionIterator() {
- return evictionIterator;
- }
- }
-
- public static class HashEntry {
- public final Object key;
- public final int hash;
- public final HashEntry next;
-
- public volatile Element value;
-
- public volatile long sizeOf;
- public volatile boolean accessed = true;
-
- protected HashEntry(Object key, int hash, HashEntry next, Element value, long sizeOf) {
- this.key = key;
- this.hash = hash;
- this.next = next;
- this.value = value;
- this.sizeOf = sizeOf;
- }
-
- }
-
- static class SegmentIterator implements Iterator {
-
- int nextTableIndex;
- HashEntry[] currentTable;
- HashEntry nextEntry;
- private final Segment seg;
-
- private SegmentIterator(final Segment memoryStoreSegment) {
- nextTableIndex = -1;
- this.seg = memoryStoreSegment;
- advance();
- }
-
- public boolean hasNext() {
- return nextEntry != null;
- }
-
- public HashEntry next() {
- if (nextEntry == null)
- return null;
- HashEntry lastReturned = nextEntry;
- advance();
- return lastReturned;
- }
-
- public void remove() {
- throw new UnsupportedOperationException("remove is not supported");
- }
-
- final void advance() {
- if (nextEntry != null && (nextEntry = nextEntry.next) != null)
- return;
- while (nextTableIndex >= 0) {
- if ( (nextEntry = currentTable[nextTableIndex--]) != null)
- return;
- }
- if (seg.count != 0) {
- currentTable = seg.table;
- for (int j = currentTable.length - 1; j >= 0; --j) {
- if ( (nextEntry = currentTable[j]) != null) {
- nextTableIndex = j - 1;
- return;
- }
- }
- }
- }
- }
-
- final class KeySet extends AbstractSet