();
- extraJars.add(TestBaseUtil.jarFor(UserTransactionManager.class));
- extraJars.add(TestBaseUtil.jarFor(UserTransactionService.class));
- extraJars.add(TestBaseUtil.jarFor(AbstractUserTransactionService.class));
- extraJars.add(TestBaseUtil.jarFor(Atomikos.class));
- return extraJars;
- }
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/clustered-events-nonstop-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/clustered-events-nonstop-test.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/clustered-events-nonstop-test.xml (revision 0)
@@ -1,51 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/ManagementRESTServiceConfiguration.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/ManagementRESTServiceConfiguration.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/ManagementRESTServiceConfiguration.java (revision 0)
@@ -1,303 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.config;
-
-import net.sf.ehcache.statistics.StatisticsGateway;
-import net.sf.ehcache.util.counter.sampled.SampledCounterConfig;
-import net.sf.ehcache.util.counter.sampled.SampledRateCounterConfig;
-
-/**
- * Configuration class of management REST services.
- *
- * @author Ludovic Orban
- */
-public class ManagementRESTServiceConfiguration {
-
- /**
- * Default bind value.
- */
- public static final String DEFAULT_BIND = "0.0.0.0:9888";
-
- /**
- * Synthetic bind value used when no server must be bound.
- */
- public static final String NO_BIND = "";
-
- /**
- * Synthetic security service location used when it should be auto-discovered.
- */
- public static final String AUTO_LOCATION = "";
-
- /**
- * Default timeout for the connection to the configured security service
- */
- public static final int DEFAULT_SECURITY_SVC_TIMEOUT = 5 * 1000;
-
- private volatile boolean enabled = false;
- private volatile String securityServiceLocation;
- private volatile boolean sslEnabled;
- private volatile boolean needClientAuth;
- private volatile int securityServiceTimeout = DEFAULT_SECURITY_SVC_TIMEOUT;
- private volatile String bind = DEFAULT_BIND;
-
- private volatile int sampleHistorySize = StatisticsGateway.DEFAULT_HISTORY_SIZE;
- private volatile int sampleIntervalSeconds = StatisticsGateway.DEFAULT_INTERVAL_SECS;
- private volatile int sampleSearchIntervalSeconds = StatisticsGateway.DEFAULT_SEARCH_INTERVAL_SECS;
-
- /**
- * Check if the REST services should be enabled or not.
- * @return true if REST services should be enabled.
- */
- public boolean isEnabled() {
- return enabled;
- }
-
- /**
- * Set that the REST services should be enabled or disabled.
- * @param enabled true if the REST services should be enabled.
- */
- public void setEnabled(boolean enabled) {
- this.enabled = enabled;
- }
-
- /**
- * Returns the security service location required for trusted identity assertion to the embedded REST management
- * service. This feature is only available with an enterprise license.
- *
- * If this value is set, then this service will require secure dialog with the TMS or other 3rd party REST client
- * implementations. The service furnished by the enterprise version of the TMC is located is provided at /api/assertIdentity.
- *
- *
- * @return a string representing the URL of the security service.
- */
- public String getSecurityServiceLocation() {
- return securityServiceLocation;
- }
-
- /**
- * Sets the security service location required for trusted identity assertion to the embedded REST management
- * service. This feature is only available with an enterprise license.
- *
- * If this value is set, then this service will require secure dialog with the TMS or other 3rd party REST client
- * implementations. The service furnished by the enterprise version of the TMC is located is provided at /api/assertIdentity.
- *
- * @param securityServiceURL a string representing the URL of the security service.
- */
- public void setSecurityServiceLocation(String securityServiceURL) {
- this.securityServiceLocation = securityServiceURL;
- }
-
- /**
- * Returns the connection/read timeout value for the security service in milliseconds.
- *
- * @return security service timeout
- */
- public int getSecurityServiceTimeout() {
- return securityServiceTimeout;
- }
-
- /**
- * Sets the connection/read timeout value for the security service in milliseconds.
- *
- * @param securityServiceTimeout milliseconds to timeout
- */
- public void setSecurityServiceTimeout(int securityServiceTimeout) {
- this.securityServiceTimeout = securityServiceTimeout;
- }
-
- /**
- * Get the host:port pair to which the REST server should be bound.
- * Format is: [IP address|host name]:[port number]
- * @return the host:port pair to which the REST server should be bound.
- */
- public String getBind() {
- return bind;
- }
-
- /**
- * Get the host part of the host:port pair to which the REST server should be bound.
- * @return the host part of the host:port pair to which the REST server should be bound.
- */
- public String getHost() {
- if (bind == null) {
- return null;
- }
- return bind.split("\\:")[0];
- }
-
- /**
- * Get the port part of the host:port pair to which the REST server should be bound.
- * @return the port part of the host:port pair to which the REST server should be bound.
- */
- public int getPort() {
- if (bind == null) {
- return -1;
- }
- String[] split = bind.split("\\:");
- if (split.length != 2) {
- return -1;
- }
- return Integer.parseInt(split[1]);
- }
-
- /**
- * Indicates whether or not the embedded agent should enabled ssl.
- *
- * @return true if ssl should be enabled, false if not.
- */
- public boolean isSslEnabled() {
- return sslEnabled;
- }
-
- /**
- * Set ssl indicator for this embedded agent.
- *
- * @param sslEnabled boolean to indicate ssl status.
- */
- public void setSslEnabled(boolean sslEnabled) {
- this.sslEnabled = sslEnabled;
- }
-
- /**
- * Indicates whether or not the embedded agent should require ssl client certificate authorization. This
- * configuration setting is only relevant if ssl is enabled.
- *
- * @see #isSslEnabled()
- *
- * @return true if ssl client certificate authorization should be required, false if not.
- */
- public boolean isNeedClientAuth() {
- return needClientAuth;
- }
-
- /**
- * Set ssl client certificate authorization required setting. This configuration setting is only relevant if ssl
- * is enabled.
- *
- * @see #setSslEnabled(boolean)
- *
- * @param needClientAuth
- */
- public void setNeedClientAuth(boolean needClientAuth) {
- this.needClientAuth = needClientAuth;
- }
-
- /**
- * Set the host:port pair to which the REST server should be bound.
- * @param bind host:port pair to which the REST server should be bound.
- */
- public void setBind(String bind) {
- this.bind = bind;
- }
-
- /**
- * Returns the sample history size to be applied to the {@link SampledCounterConfig} for sampled statistics
- *
- * @return the sample history size
- */
- public int getSampleHistorySize() {
- return sampleHistorySize;
- }
-
- /**
- * Sets the sample history size to be applied to the {@link SampledCounterConfig} for sampled statistics
- *
- * @param sampleHistorySize to set
- */
- public void setSampleHistorySize(final int sampleHistorySize) {
- this.sampleHistorySize = sampleHistorySize;
- }
-
- /**
- * Returns the sample interval in seconds to be applied to the {@link SampledCounterConfig} for sampled statistics
- *
- * @return the sample interval in seconds
- */
- public int getSampleIntervalSeconds() {
- return sampleIntervalSeconds;
- }
-
- /**
- * Sets the sample interval in seconds to be applied to the {@link SampledCounterConfig} for sampled statistics
- *
- * @param sampleIntervalSeconds to set
- */
- public void setSampleIntervalSeconds(final int sampleIntervalSeconds) {
- this.sampleIntervalSeconds = sampleIntervalSeconds;
- }
-
- /**
- * Returns the sample search interval in seconds to be applied to the {@link SampledRateCounterConfig} for sampled statistics
- *
- * @return the sample search interval in seconds
- */
- public int getSampleSearchIntervalSeconds() {
- return sampleSearchIntervalSeconds;
- }
-
- /**
- * Sets the sample search interval in seconds to be applied to the {@link SampledCounterConfig} for sampled statistics
- *
- * @param sampleSearchInterval to set
- */
- public void setSampleSearchIntervalSeconds(final int sampleSearchInterval) {
- this.sampleSearchIntervalSeconds = sampleSearchInterval;
- }
-
- /**
- * A factory method for {@link SampledCounterConfig} based on the global settings defined on this object
- *
- * @see #getSampleIntervalSeconds()
- * @see #getSampleHistorySize()
- *
- * @return a {@code SampledCounterConfig}
- */
- public SampledCounterConfig makeSampledCounterConfig() {
- return new SampledCounterConfig(getSampleIntervalSeconds(), getSampleHistorySize(), true, 0L);
- }
-
- /**
- * A factory method for {@link SampledCounterConfig} based on the global settings defined on this object
- *
- * @see #getSampleIntervalSeconds()
- * @see #getSampleHistorySize()
- *
- * @return a {@code SampledCounterConfig}
- */
- public SampledRateCounterConfig makeSampledGetRateCounterConfig() {
- return new SampledRateCounterConfig(getSampleIntervalSeconds(), getSampleHistorySize(), true);
- }
-
- /**
- * A factory method for {@link SampledCounterConfig} based on the global settings defined on this object
- *
- * @see #getSampleSearchIntervalSeconds()
- * @see #getSampleHistorySize()
- *
- * @return a {@code SampledCounterConfig}
- */
- public SampledRateCounterConfig makeSampledSearchRateCounterConfig() {
- return new SampledRateCounterConfig(getSampleSearchIntervalSeconds(), getSampleHistorySize(), true);
- }
-
- @Override
- public String toString() {
- return "ManagementRESTServiceConfiguration [enabled=" + enabled + ", securityServiceLocation=" + securityServiceLocation
- + ", sslEnabled=" + sslEnabled + ", needClientAuth=" + needClientAuth + ", securityServiceTimeout="
- + securityServiceTimeout + ", bind=" + bind + ", sampleHistorySize=" + sampleHistorySize + ", sampleIntervalSeconds="
- + sampleIntervalSeconds + ", sampleSearchIntervalSeconds=" + sampleSearchIntervalSeconds + "]";
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/CacheTransactionHelper.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/CacheTransactionHelper.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/CacheTransactionHelper.java (revision 0)
@@ -1,128 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.util;
-
-import java.lang.reflect.InvocationTargetException;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.TransactionController;
-
-/**
- * A collection of utility methods helping controlling transactions for managed operations which may require them.
- *
- * @author Ludovic Orban
- */
-public class CacheTransactionHelper {
-
- private static final int XA_STATUS_NO_TRANSACTION = 6;
-
- /**
- * Begin a transaction on the current thread if the cache is configured as transactional,
- * otherwise this method does nothing.
- *
- * @param cache the cache to begin a transaction for
- * @throws CacheException if anything wrong happens
- */
- public static void beginTransactionIfNeeded(Ehcache cache) throws CacheException {
- try {
- switch (cache.getCacheConfiguration().getTransactionalMode()) {
- case LOCAL:
- TransactionController ctrl = cache.getCacheManager().getTransactionController();
- ctrl.begin();
- break;
-
- case XA:
- case XA_STRICT:
- Object tm = ((net.sf.ehcache.Cache) cache).getTransactionManagerLookup().getTransactionManager();
- tm.getClass().getMethod("begin").invoke(tm);
- break;
-
- case OFF:
- default:
- break;
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new CacheException("error beginning transaction:" + e);
- }
- }
-
- /**
- * Commit a transaction previously begun on the current thread if the cache is configured as
- * transactional, otherwise this method does nothing.
- *
- * @param cache the cache to commit a transaction for
- * @throws CacheException if anything wrong happens
- */
- public static void commitTransactionIfNeeded(Ehcache cache) throws CacheException {
- try {
- switch (cache.getCacheConfiguration().getTransactionalMode()) {
- case LOCAL:
- TransactionController ctrl = cache.getCacheManager().getTransactionController();
- ctrl.commit();
- break;
-
- case XA:
- case XA_STRICT:
- Object tm = ((net.sf.ehcache.Cache) cache).getTransactionManagerLookup().getTransactionManager();
- tm.getClass().getMethod("commit").invoke(tm);
- break;
-
- case OFF:
- default:
- break;
- }
- } catch (Exception e) {
- Throwable t = e;
- if (t instanceof InvocationTargetException) {
- t = ((InvocationTargetException)e).getCause();
- }
- throw new CacheException("error committing transaction: " + t);
- }
- }
-
- /**
- * Check if a transaction has begun on the current thread if the cache is configured as
- * transactional, otherwise always return false.
- * @param cache the cache to check if a transaction started for
- * @return true if the cache is transactional and a transaction started, false otherwise
- * @throws CacheException if anything wrong happens
- */
- public static boolean isTransactionStarted(Ehcache cache) throws CacheException {
- try {
- switch (cache.getCacheConfiguration().getTransactionalMode()) {
- case LOCAL:
- TransactionController ctrl = cache.getCacheManager().getTransactionController();
- return ctrl.getCurrentTransactionContext() != null;
-
- case XA:
- case XA_STRICT:
- Object tm = ((net.sf.ehcache.Cache) cache).getTransactionManagerLookup().getTransactionManager();
- return ((Integer) tm.getClass().getMethod("getStatus").invoke(tm)) != XA_STATUS_NO_TRANSACTION;
-
- case OFF:
- default:
- return false;
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new CacheException("error checking if transaction started: " + e);
- }
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/org/terracotta/test/categories/IntegrationTests.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/org/terracotta/test/categories/IntegrationTests.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/org/terracotta/test/categories/IntegrationTests.java (revision 0)
@@ -1,7 +0,0 @@
-package org.terracotta.test.categories;
-
-/**
- * @author Alex Snaps
- */
-public enum IntegrationTests {
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/StopWatch.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/StopWatch.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/StopWatch.java (revision 0)
@@ -1,165 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache;
-
-
-import java.util.concurrent.TimeUnit;
-
-import net.sf.ehcache.util.PropertyUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A timer service used to check performance of tests.
- *
- * To enable this to work for different machines the following is done:
- *
- * SimpleLog is used for logging with a known logging level controlled by simplelog.properties
- * which is copied to the test classpath. This removes logging as a source of differences.
- * Messages are sent to stderr which also makes it easy to see messages on remote continuous integration
- * machines.
- * A speedAdjustmentFactor is used to equalize machines. It is supplied as a the System Property
- * 'net.sf.ehcache.speedAdjustmentFactor=n', where n is the number of times the machine is slower
- * than the reference machine e.g. 1.1. This factor is then used to adjust "elapsedTime"
- * as returned by this class. Elapsed Time is therefore not true time, but notional time equalized with the reference
- * machine. If you get performance tests failing add this property.
- *
- *
- * @author Greg Luck
- * @version $Id: StopWatch.java 10789 2018-04-26 02:08:13Z adahanne $
- * A stop watch that can be useful for instrumenting for performance
- */
-public class StopWatch {
-
- private static final Logger LOG = LoggerFactory.getLogger(StopWatch.class.getName());
-
-
- private static final String SUFFIX = "ms";
-
-
- /**
- * An attempt to adjust performance tests to different machines.
- */
- private static float speedAdjustmentFactor = 1;
-
-
- /**
- * Used for performance benchmarking
- */
- private long timeStamp = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
-
-
- /**
- * Get the speed adjustment factor
- */
- public static float getSpeedAdjustmentFactor() {
- return speedAdjustmentFactor;
- }
-
-
- static {
-
- String speedAdjustmentFactorString =
- PropertyUtil.extractAndLogProperty("net.sf.ehcache.speedAdjustmentFactor", System.getProperties());
-
- if (speedAdjustmentFactorString != null) {
- try {
- speedAdjustmentFactor = Float.parseFloat(speedAdjustmentFactorString);
- } catch (NumberFormatException e) {
- LOG.debug("Consider setting system property 'net.sf.ehcache.speedAdjustmentFactor=n' " +
- "where n is the number of times your machine is slower than the reference machine, " +
- "which is currently a dual G5 PowerMac. e.g. 1.2, which then enables elasped time " +
- "measurement to be adjusted accordingly.");
- }
- LOG.debug("Using speedAjustmentFactor of " + speedAdjustmentFactor);
-
- } else {
- LOG.debug("Consider setting system property 'net.sf.ehcache.speedAdjustmentFactor=n' " +
- "where n is the number of times your machine is slower than the reference machine, " +
- "which is currently a dual G5 PowerMac. e.g. 1.2, which then enables elasped time " +
- "measurement to be adjusted accordingly.");
- }
-
- StopWatch stopWatch = new StopWatch();
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- //
- }
- LOG.debug("100 measures as " + stopWatch.getElapsedTime());
-
-
- }
-
-// static {
-//
-// float referenceTime = 2050;
-// CacheManager singletonManager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-big.xml");
-//
-// String[] names = singletonManager.getCacheNames();
-// for (int i = 0; i < names.length; i++) {
-// String name = names[i];
-// Ehcache cache = singletonManager.getCache(name);
-// for (int j = 0; i < 100; i++) {
-// cache.put(new Element(Integer.valueOf(j), "value"));
-// }
-// }
-// long start = System.currentTimeMillis();
-// for (int repeats = 0; repeats < 5000; repeats++) {
-// for (int i = 0; i < names.length; i++) {
-// String name = names[i];
-// Ehcache cache = singletonManager.getCache(name);
-// for (int j = 0; i < 100; i++) {
-// Element element = cache.get(name + j);
-// if ((element == null)) {
-// cache.put(new Element(Integer.valueOf(j), "value"));
-// }
-// }
-// }
-// }
-// long elapsedTime = System.currentTimeMillis() - start;
-//
-// LOG.error("It took this machine: " + elapsedTime + " to perform a time trial compared with the reference time of "
-// + referenceTime + "ms");
-//
-// speedAdjustmentFactor = elapsedTime / referenceTime;
-//
-// LOG.error("Elapsed stopwatch times will be adjusted divided by " + speedAdjustmentFactor);
-// }
-
-
- /**
- * Gets the time elapsed between now and for the first time, the creation
- * time of the class, and after that, between each call to this method
- *
- * Note this method returns notional time elapsed. See class description
- */
- public long getElapsedTime() {
- long now = TimeUnit.NANOSECONDS.toMillis(System.nanoTime());
- long elapsed = (long) ((now - timeStamp) / getSpeedAdjustmentFactor());
- timeStamp = now;
- return elapsed;
- }
-
- /**
- * @return formatted elapsed Time
- */
- public String getElapsedTimeString() {
- return String.valueOf(getElapsedTime()) + SUFFIX;
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/constructs/refreshahead/ThreadedWorkQueue.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/constructs/refreshahead/ThreadedWorkQueue.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/constructs/refreshahead/ThreadedWorkQueue.java (revision 0)
@@ -1,216 +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.refreshahead;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * This class implements a work queue of pooled objects. You can offer a
- * stream of objects to the backing poool of threads and it will consume them
- * and hand them to the BatchWorker as a collection to be processed (batched).
- *
- *
- * Essentially, it uses BatchWorker as Callable/Future with a collection argument.
- *
- * @author cschanck
- *
- * @param
- */
-public class ThreadedWorkQueue {
-
- private static final int MINUTES_OF_THE_IDLE_LIFE = 5;
-
- /**
- * Callback class, think of it as a Runnable with an argument that is
- * a {@link Collection}.
- *
- * @author cschanck
- *
- * @param
- */
- public static interface BatchWorker {
-
- /**
- * Process a batch of work.
- *
- * @param collection
- */
- public void process(Collection extends WW> collection);
- }
-
- private final LinkedBlockingQueue queue;
- private final ExecutorService threadPool;
- private volatile boolean isAlive;
- private final AtomicInteger offerCounter = new AtomicInteger();
- private final AtomicInteger droppedCounter = new AtomicInteger();
- private final AtomicInteger processedCounter = new AtomicInteger();
- private final BatchWorker dispatcher;
- private final int batchSize;
-
- /**
- * Create a work queue where work is dispatched through the given dispatcher, which the specified number
- * of threads.
- *
- * @param dispatcher Thread safe dispatcher to use to dispatch work
- * @param numberOfThreads Number of parallel threads used process work from this queue
- * @param factory {@link ThreadFactory} used to create the threads
- * @param maximumQueueSize maximum backlog of work items that can be queued before items get dropped
- * @param batchSize number of items, at a maximum, to send to a dispatcher at a time.
- */
- public ThreadedWorkQueue(BatchWorker dispatcher, int numberOfThreads, ThreadFactory factory, int maximumQueueSize, int batchSize) {
- threadPool = new ThreadPoolExecutor(numberOfThreads,
- numberOfThreads,
- MINUTES_OF_THE_IDLE_LIFE,
- TimeUnit.MINUTES,
- new LinkedBlockingQueue(),
- factory);
- this.batchSize = batchSize;
- this.dispatcher = dispatcher;
- this.isAlive = true;
- queue = new LinkedBlockingQueue(maximumQueueSize);
- for (int i = 0; i < numberOfThreads; i++) {
- threadPool.submit(new Runnable() {
-
- @Override
- public void run() {
- for (; isAlive();) {
- try {
- pullFromQueueAndDispatch();
- } catch (Throwable t) {
- // eat it. if it was an interrupted, we are going to bail out in a second anyway
- }
- }
- }
- });
- }
- }
-
- /**
- * Offer a work unit to queue. Might push prior work units off of the work queue,
- * dropped forever.
- *
- * @param workUnit
- */
- public void offer(W workUnit) {
- offerCounter.incrementAndGet();
- while (!queue.offer(workUnit)) {
- if (queue.poll() != null) {
- droppedCounter.incrementAndGet();
- }
- }
- }
-
- /**
- * Is this work queue still accepting work.
- *
- * @return true if still alive
- */
- public boolean isAlive() {
- return isAlive;
- }
-
- /**
- * Get the current backlog count. An approximation, by necessity.
- *
- * @return count of items yet to be processed.
- */
- public long getBacklogCount() {
- return (offerCounter.get() - (processedCounter.get() + droppedCounter.get()));
- }
-
- /**
- * Gets offer counter. Cumulative tripped
- *
- * @return the offer counter
- */
- public int getOfferedCount() {
- return offerCounter.get();
- }
-
- /**
- * Gets dropped counter.
- *
- * @return the dropped counter
- */
- public int getDroppedCount() {
- return droppedCounter.get();
- }
-
- /**
- * Gets processed count.
- *
- * @return the processed count
- */
- public int getProcessedCount() {
- return processedCounter.get();
- }
-
- /**
- * get the dispatcher being used for this queue.
- *
- * @return dispatcher
- */
- public BatchWorker getDispatcher() {
- return dispatcher;
- }
-
- /**
- * Get the batch size
- *
- * @return batch size
- */
- public int getBatchSize() {
- return batchSize;
- }
-
- /**
- * Shutdown this queue. Propagates an interrupt to currently executing {@link BatchWorker} threads.
- */
- public void shutdown() {
- isAlive = false;
- threadPool.shutdownNow();
- queue.clear();
- }
-
- /**
- * Actually do the work.
- *
- * @throws InterruptedException
- */
- private void pullFromQueueAndDispatch() throws InterruptedException {
- Collection batch = new ArrayList(getBatchSize());
- int currentCount = 0;
- for (W r = queue.take(); r != null; r = queue.poll()) {
- batch.add(r);
- if (++currentCount >= getBatchSize()) {
- break;
- }
- }
- // work to do and alive to do it
- if (currentCount > 0 && isAlive()) {
- processedCounter.addAndGet(batch.size());
- getDispatcher().process(batch);
- }
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/writebehind/WriteBehindQueue.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/writebehind/WriteBehindQueue.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/writebehind/WriteBehindQueue.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.writer.writebehind;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.writer.writebehind.operations.SingleOperation;
-
-/**
- * An implementation of write behind with a queue that is kept in non durable local heap.
- *
- * @author Geert Bevin
- * @version $Id: WriteBehindQueue.java 5793 2012-06-13 23:53:16Z twu $
- */
-class WriteBehindQueue extends AbstractWriteBehindQueue {
-
- private List waiting = new ArrayList();
-
- /**
- * Construct a simple list backed write behind queue.
- *
- * @param config
- */
- WriteBehindQueue(CacheConfiguration config) {
- super(config);
- }
-
- @Override
- protected List quarantineItems() {
- List quarantined = waiting;
- waiting = new ArrayList();
- return quarantined;
- }
-
- @Override
- protected void addItem(SingleOperation operation) {
- waiting.add(operation);
- }
-
- @Override
- public long getQueueSize() {
- return waiting.size();
- }
-
- @Override
- protected void reinsertUnprocessedItems(List operations) {
- List newQueue = new ArrayList(operations);
- newQueue.addAll(waiting);
- waiting = newQueue;
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeClient.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeClient.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeClient.java (revision 0)
@@ -1,190 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.txns;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup;
-import net.sf.ehcache.transaction.manager.TransactionManagerLookup;
-
-import org.terracotta.toolkit.Toolkit;
-
-import javax.transaction.Transaction;
-import javax.transaction.TransactionManager;
-
-/**
- * NOTE: Looks like Atomikos does not support suspend/resume.
- *
- *
- */
-public class SuspendResumeClient extends AbstractTxClient {
-
- public SuspendResumeClient(String[] args) {
- super(args);
- }
-
-
-
- @Override
- protected void runTest(Cache cache, Toolkit toolkit) throws Throwable {
- final TransactionManagerLookup lookup = new DefaultTransactionManagerLookup();
- final TransactionManager txnManager = lookup.getTransactionManager();
- int commitCount = 0;
- int rollbackCount = 0;
- System.out.println(txnManager);
- try {
- txnManager.begin();
- cache.put(new Element("key1", "value1"));
-
- Transaction tx = txnManager.suspend();
-
- txnManager.resume(tx);
-
- Element element = cache.get("key1");
-
- if(!element.getValue().equals("value1")) {
- throw new AssertionError("put should be visible in same thread");
- }
- System.out.println("key1:" + element.getValue());
- System.out.println("size1: " + cache.getSize());
- txnManager.commit();
- commitCount++;
- } catch (Exception e) {
- e.printStackTrace();
- txnManager.rollback();
- rollbackCount++;
- }
-
- try {
- txnManager.begin();
- cache.put(new Element("key1", "value2"));
-
-
- Element element = cache.get("key1");
- System.out.println("key1:" + element.getValue());
- if(!element.getValue().equals("value2")) {
- throw new AssertionError("put should be visible in same thread");
- }
- System.out.println("size1: " + cache.getSize());
- throw new Exception();
- } catch (AssertionError e) {
- throw new AssertionError(e);
- } catch (Exception e) {
- txnManager.rollback();
- rollbackCount++;
- }
-
- try {
- txnManager.begin();
-
- Element element = cache.get("key1");
- System.out.println("key1:" + element.getValue());
- if(!element.getValue().equals("value1")) {
- throw new AssertionError("should be old value");
- }
- System.out.println("size1: " + cache.getSize());
-
- txnManager.commit();
- commitCount++;
- } catch (AssertionError e) {
- throw new AssertionError(e);
- } catch (Exception e) {
- txnManager.rollback();
- rollbackCount++;
- }
-
- if(commitCount != 2) {
- throw new AssertionError("expected 2 commits got: " + commitCount);
- }
-
- if(rollbackCount != 1) {
- throw new AssertionError("expected 1 rollback got: " + rollbackCount);
- }
-
-
- txnManager.begin();
-
- cache.put(new Element("1", "one"));
-
- Transaction tx1 = txnManager.suspend();
-
- txnManager.begin();
-
- cache.put(new Element("2", "two"));
-
- txnManager.commit();
-
- txnManager.resume(tx1);
-
- if (cache.get("2").getValue().equals("two")) {
- cache.put(new Element("1-2", "one-two"));
- }
- txnManager.commit();
-
-
-
- //check
- txnManager.begin();
-
- Element element = cache.get("1-2");
-
- if(element == null) {
- throw new AssertionError("should contain key 1-2");
- }
-
- txnManager.commit();
-
- //cleanup
- txnManager.begin();
-
- cache.remove("1");
- cache.remove("2");
- cache.remove("1-2");
-
- txnManager.commit();
-
-
- // example 2
-
- txnManager.begin();
-
- cache.put(new Element("1", "one"));
-
- tx1 = txnManager.suspend();
-
- txnManager.begin();
- cache.put(new Element("2", "two"));
-
- txnManager.rollback();
-
- txnManager.resume(tx1);
-
- if (cache.get("2") != null && "two".equals(cache.get("2").getValue())) {
- cache.put(new Element("1-2", "one-two"));
- }
-
- txnManager.commit();
-
- //validate
-
- txnManager.begin();
-
- Element elementTwo = cache.get("2");
- if(elementTwo != null) {
- throw new AssertionError("shouldn't exist!");
- }
-
- Element elementOneTwo = cache.get("1-2");
- if(elementOneTwo != null) {
- throw new AssertionError("shouldn't exist!");
- }
-
- txnManager.commit();
-
- }
-
- public static void main(String[] args) {
- new SuspendResumeClient(args).run();
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/SampledCounterImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/SampledCounterImpl.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/SampledCounterImpl.java (revision 0)
@@ -1,148 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.util.counter.sampled;
-
-import java.util.TimerTask;
-
-import net.sf.ehcache.util.CircularLossyQueue;
-import net.sf.ehcache.util.counter.CounterImpl;
-
-/**
- * An implementation of {@link SampledCounter}
- *
- * @author Abhishek Sanoujam
- * @since 1.7
- *
- */
-public class SampledCounterImpl extends CounterImpl implements SampledCounter {
- private static final int MILLIS_PER_SEC = 1000;
-
- /**
- * The history of this counter
- */
- protected final CircularLossyQueue history;
-
- /**
- * Should the counter reset on each sample?
- */
- protected final boolean resetOnSample;
- private final TimerTask samplerTask;
- private final long intervalMillis;
-
- /**
- * todo GL how many threads is this creating?
- * Constructor accepting a {@link SampledCounterConfig}
- *
- * @param config
- */
- public SampledCounterImpl(SampledCounterConfig config) {
- this(config.getIntervalSecs(), config.getHistorySize(), config.isResetOnSample(), config.getInitialValue(), true);
- }
-
- /**
- * Constructor accepting raw config values.
- *
- * @param intervalInSeconds sampling interval in seconds
- * @param historySize size of history sample
- * @param resetOnSample true to reset value on sample
- * @param initValue initial value
- * @param sampleNow true to record smaple immediately
- */
- public SampledCounterImpl(long intervalInSeconds, int historySize, boolean resetOnSample, long initValue, boolean sampleNow) {
- super(initValue);
-
- this.intervalMillis = intervalInSeconds * MILLIS_PER_SEC;
- this.history = new CircularLossyQueue(historySize);
- this.resetOnSample = resetOnSample;
-
- this.samplerTask = new TimerTask() {
- @Override
- public void run() {
- recordSample();
- }
- };
-
- if (sampleNow) {
- recordSample();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public TimeStampedCounterValue getMostRecentSample() {
- return this.history.peek();
- }
-
- /**
- * {@inheritDoc}
- */
- public TimeStampedCounterValue[] getAllSampleValues() {
- return this.history.toArray(new TimeStampedCounterValue[this.history.depth()]);
- }
-
- /**
- * {@inheritDoc}
- */
- public void shutdown() {
- if (samplerTask != null) {
- samplerTask.cancel();
- }
- }
-
- /**
- * Returns the timer task for this sampled counter
- *
- * @return the timer task for this sampled counter
- */
- public TimerTask getTimerTask() {
- return this.samplerTask;
- }
-
- /**
- * Returns the sampling thread interval in millis
- *
- * @return the sampling thread interval in millis
- */
- public long getIntervalMillis() {
- return intervalMillis;
- }
-
- /**
- * {@inheritDoc}
- */
- void recordSample() {
- final long sample;
- if (resetOnSample) {
- sample = getAndReset();
- } else {
- sample = getValue();
- }
-
- final long now = System.currentTimeMillis();
- TimeStampedCounterValue timedSample = new TimeStampedCounterValue(now, sample);
-
- history.push(timedSample);
- }
-
- /**
- * {@inheritDoc}
- */
- public long getAndReset() {
- return getAndSet(0L);
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/ClockMemoryStoreTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/ClockMemoryStoreTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/ClockMemoryStoreTest.java (revision 0)
@@ -1,75 +0,0 @@
-package net.sf.ehcache;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-import java.util.Random;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-/**
- * @author Alex Snaps
- */
-public class ClockMemoryStoreTest extends MemoryStoreTester {
-
- private static final int ENTRIES = 40 * 1000 * 1000;
-
- /**
- * setup test
- */
- @Override
- @Before
- public void setUp() throws Exception {
- super.setUp();
- createMemoryOnlyStore(MemoryStoreEvictionPolicy.CLOCK);
- }
-
- @Test
- @Ignore
- public void testPerfStuff() throws Exception {
-
- Thread[] threads = new Thread[10];
-
- for (int i = 0, threadsLength = threads.length; i < threadsLength; i++) {
- final int node = i;
- threads[i] = new Thread(null, new Runnable() {
- final AtomicInteger value = new AtomicInteger(node );
- final Random r = new Random();
- public void run() {
- int key;
- while ((key = value.getAndIncrement()) < ENTRIES) {
- if (key % 2 == 0) {
- cache.put(new Element(key, "value" + r.nextLong()));
- } else {
- cache.get(r.nextInt(ENTRIES));
- }
- }
- }
- }, "Pounding #" + i);
- threads[i].start();
- }
-
- final long start = System.nanoTime();
- for (Thread thread : threads) {
- thread.join();
- }
-
- System.out.println(TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start));
- System.out.println(cache.getStatistics().getLocalHeapSize());
- }
-
- @Test
- public void testNoReadsButStillEvicts() {
- createMemoryOnlyStore(MemoryStoreEvictionPolicy.CLOCK, 150);
- for(int i = 0; i < 1000; i++) {
- cache.put(new Element(i, i));
- }
- assertThat(cache.getStatistics().getLocalHeapSize(), is(150L));
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/CacheEventListenerAdapter.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/CacheEventListenerAdapter.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/CacheEventListenerAdapter.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.event;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-
-/**
- * An adapter to simplify cache event listeners that do not need all events defined on the CacheEventListener interface.
- *
- * @author Ludovic Orban
- */
-public class CacheEventListenerAdapter implements CacheEventListener {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException {
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementPut(Ehcache cache, Element element) throws CacheException {
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException {
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementExpired(Ehcache cache, Element element) {
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyElementEvicted(Ehcache cache, Element element) {
- }
-
- /**
- * {@inheritDoc}
- */
- public void notifyRemoveAll(Ehcache cache) {
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- }
-}
Index: rctags/ehcache-2.10.8.1.63/distribution/events/src/main/java/org/hibernate/tutorial/EventManager.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/distribution/events/src/main/java/org/hibernate/tutorial/EventManager.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/distribution/events/src/main/java/org/hibernate/tutorial/EventManager.java (revision 0)
@@ -1,48 +0,0 @@
-package org.hibernate.tutorial;
-
-import org.hibernate.Session;
-import org.hibernate.tutorial.domain.Event;
-import org.hibernate.tutorial.util.HibernateUtil;
-
-import java.util.Date;
-import java.util.List;
-
-public class EventManager {
- @SuppressWarnings("rawtypes")
- public static void main(String[] args) {
- EventManager mgr = new EventManager();
-
- if (args.length == 0 || args[0].equals("store")) {
- mgr.createAndStoreEvent("My Event", new Date());
- } else if (args[0].equals("list")) {
- List events = mgr.listEvents();
- for (int i = 0; i < events.size(); i++) {
- Event theEvent = (Event) events.get(i);
- System.out.println("Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate());
- }
- }
-
- HibernateUtil.getSessionFactory().close();
- }
-
- private void createAndStoreEvent(String title, Date theDate) {
- Session session = HibernateUtil.getSessionFactory().getCurrentSession();
- session.beginTransaction();
-
- Event theEvent = new Event();
- theEvent.setTitle(title);
- theEvent.setDate(theDate);
- session.save(theEvent);
-
- session.getTransaction().commit();
- }
-
- @SuppressWarnings("rawtypes")
- private List listEvents() {
- Session session = HibernateUtil.getSessionFactory().getCurrentSession();
- session.beginTransaction();
- List result = session.createQuery("from Event").list();
- session.getTransaction().commit();
- return result;
- }
-}
Index: rctags/ehcache-2.10.8.1.63/distribution/colorcache/src/assemble/bin/start-developer-console.bat
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/distribution/colorcache/src/assemble/bin/start-developer-console.bat (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/distribution/colorcache/src/assemble/bin/start-developer-console.bat (revision 0)
@@ -1,15 +0,0 @@
-@echo off
-
-rem All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
-
-setlocal
-
-cd "%~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%
-popd
-start "terracotta" "%tc_install_dir%\bin\dev-console.bat"
-
-endlocal
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/store/SimpleVersionTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/store/SimpleVersionTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/store/SimpleVersionTest.java (revision 0)
@@ -1,58 +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.toolkit.Toolkit;
-import org.terracotta.toolkit.concurrent.ToolkitBarrier;
-import org.terracotta.ehcache.tests.AbstractCacheTestBase;
-import org.terracotta.ehcache.tests.ClientBase;
-
-import com.tc.test.config.model.TestConfig;
-
-import java.util.concurrent.BrokenBarrierException;
-
-import junit.framework.Assert;
-
-public class SimpleVersionTest extends AbstractCacheTestBase {
-
- private static final int NODE_COUNT = 2;
-
- public SimpleVersionTest(TestConfig testConfig) {
- super("simple-version-test.xml", 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", NODE_COUNT);
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable {
- final int index = barrier.await();
-
- testVersion(index, cacheManager.getCache("serialized"));
- }
-
- private void testVersion(final int index, Cache cache) throws InterruptedException, BrokenBarrierException {
- if (index == 0) {
- Element e1 = new Element("key", "value");
- e1.setVersion(12345);
-
- cache.put(e1);
- }
-
- barrier.await();
-
- Assert.assertEquals(12345, cache.get("key").getVersion());
- }
-
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/distribution/MulticastKeepaliveHeartbeatReceiver.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/distribution/MulticastKeepaliveHeartbeatReceiver.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/distribution/MulticastKeepaliveHeartbeatReceiver.java (revision 0)
@@ -1,244 +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 java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.InetAddress;
-import java.net.MulticastSocket;
-import java.rmi.RemoteException;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.util.NamedThreadFactory;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Receives heartbeats from any {@link MulticastKeepaliveHeartbeatSender}s out there.
- *
- * Our own multicast heartbeats are ignored.
- *
- * @author Greg Luck
- * @version $Id: MulticastKeepaliveHeartbeatReceiver.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public final class MulticastKeepaliveHeartbeatReceiver {
-
- private static final Logger LOG = LoggerFactory.getLogger(MulticastKeepaliveHeartbeatReceiver.class.getName());
-
- private ExecutorService processingThreadPool;
- private Set rmiUrlsProcessingQueue = Collections.synchronizedSet(new HashSet());
- private final InetAddress groupMulticastAddress;
- private final Integer groupMulticastPort;
- private MulticastReceiverThread receiverThread;
- private MulticastSocket socket;
- private volatile boolean stopped;
- private final MulticastRMICacheManagerPeerProvider peerProvider;
- private InetAddress hostAddress;
-
- /**
- * Constructor.
- *
- * @param peerProvider
- * @param multicastAddress
- * @param multicastPort
- * @param hostAddress
- */
- public MulticastKeepaliveHeartbeatReceiver(
- MulticastRMICacheManagerPeerProvider peerProvider, InetAddress multicastAddress, Integer multicastPort,
- InetAddress hostAddress) {
- this.peerProvider = peerProvider;
- this.groupMulticastAddress = multicastAddress;
- this.groupMulticastPort = multicastPort;
- this.hostAddress = hostAddress;
- }
-
-
- /**
- * Start.
- *
- * @throws IOException
- */
- final void init() throws IOException {
- socket = new MulticastSocket(groupMulticastPort.intValue());
- if (hostAddress != null) {
- socket.setInterface(hostAddress);
- }
- socket.joinGroup(groupMulticastAddress);
- receiverThread = new MulticastReceiverThread();
- receiverThread.start();
- processingThreadPool = Executors.newCachedThreadPool(new NamedThreadFactory("Multicast keep-alive Heartbeat Receiver"));
- }
-
- /**
- * Shutdown the heartbeat.
- */
- public final void dispose() {
- LOG.debug("dispose called");
- processingThreadPool.shutdownNow();
- stopped = true;
- receiverThread.interrupt();
- }
-
- /**
- * A multicast receiver which continously receives heartbeats.
- */
- private final class MulticastReceiverThread extends Thread {
-
- /**
- * Constructor
- */
- public MulticastReceiverThread() {
- super("Multicast Heartbeat Receiver Thread");
- setDaemon(true);
- }
-
- @Override
- public final void run() {
- byte[] buf = new byte[PayloadUtil.MTU];
- try {
- while (!stopped) {
- DatagramPacket packet = new DatagramPacket(buf, buf.length);
- try {
- socket.receive(packet);
- byte[] payload = packet.getData();
- processPayload(payload);
-
-
- } catch (IOException e) {
- if (!stopped) {
- LOG.error("Error receiving heartbeat. " + e.getMessage() +
- ". Initial cause was " + e.getMessage(), e);
- }
- }
- }
- } catch (Throwable t) {
- LOG.error("Multicast receiver thread caught throwable. Cause was " + t.getMessage() + ". Continuing...");
- }
- }
-
- private void processPayload(byte[] compressedPayload) {
- byte[] payload = PayloadUtil.ungzip(compressedPayload);
- String rmiUrls = new String(payload);
- if (self(rmiUrls)) {
- return;
- }
- rmiUrls = rmiUrls.trim();
- LOG.debug("rmiUrls received {}", rmiUrls);
- processRmiUrls(rmiUrls);
- }
-
- /**
- * This method forks a new executor to process the received heartbeat in a thread pool.
- * That way each remote cache manager cannot interfere with others.
- *
- * In the worst case, we have as many concurrent threads as remote cache managers.
- *
- * @param rmiUrls
- */
- private void processRmiUrls(final String rmiUrls) {
- if (rmiUrlsProcessingQueue.contains(rmiUrls)) {
-
- LOG.debug("We are already processing these rmiUrls. Another heartbeat came before we finished: {}", rmiUrls);
- return;
- }
-
- if (processingThreadPool == null) {
- return;
- }
-
- processingThreadPool.execute(new Runnable() {
- public void run() {
- try {
- // Add the rmiUrls we are processing.
- rmiUrlsProcessingQueue.add(rmiUrls);
- for (StringTokenizer stringTokenizer = new StringTokenizer(rmiUrls,
- PayloadUtil.URL_DELIMITER); stringTokenizer.hasMoreTokens();) {
- if (stopped) {
- return;
- }
- String rmiUrl = stringTokenizer.nextToken();
- registerNotification(rmiUrl);
- if (!peerProvider.peerUrls.containsKey(rmiUrl)) {
- LOG.debug("Aborting processing of rmiUrls since failed to add rmiUrl: {}", rmiUrl);
- return;
- }
- }
- } finally {
- // Remove the rmiUrls we just processed
- rmiUrlsProcessingQueue.remove(rmiUrls);
- }
- }
- });
- }
-
-
- /**
- * @param rmiUrls
- * @return true if our own hostname and listener port are found in the list. This then means we have
- * caught our onw multicast, and should be ignored.
- */
- private boolean self(String rmiUrls) {
- CacheManager cacheManager = peerProvider.getCacheManager();
- CacheManagerPeerListener cacheManagerPeerListener = cacheManager.getCachePeerListener("RMI");
- if (cacheManagerPeerListener == null) {
- return false;
- }
- List boundCachePeers = cacheManagerPeerListener.getBoundCachePeers();
- if (boundCachePeers == null || boundCachePeers.size() == 0) {
- return false;
- }
- CachePeer peer = (CachePeer) boundCachePeers.get(0);
- try {
- String cacheManagerUrlBase = peer.getUrlBase();
- int baseUrlMatch = rmiUrls.indexOf(cacheManagerUrlBase);
- return baseUrlMatch != -1;
- } catch (RemoteException e) {
- LOG.error("Error geting url base", e);
- return false;
- }
- }
-
- private void registerNotification(String rmiUrl) {
- peerProvider.registerPeer(rmiUrl);
- }
-
-
- /**
- * {@inheritDoc}
- */
- @Override
- public final void interrupt() {
- try {
- socket.leaveGroup(groupMulticastAddress);
- } catch (IOException e) {
- LOG.error("Error leaving group");
- }
- socket.close();
- super.interrupt();
- }
- }
-
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/NotificationScope.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/NotificationScope.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/NotificationScope.java (revision 0)
@@ -1,63 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.event;
-
-/**
- * This enumeration defines valid values for event listener notification scope.
- * By default an event listener will be open to listening for events created
- * on all nodes (ALL). You may also specify to receive only LOCAL events or only
- * REMOTE events.
- *
- * @author Geert Bevin
- * @since 2.0
- */
-public enum NotificationScope {
- /**
- * Receive only events generated by this CacheManager
- */
- LOCAL(true, false),
-
- /**
- * Receive only events generated by another CacheManager
- */
- REMOTE(false, true),
-
- /**
- * Receive all events
- */
- ALL(true, true);
-
-
- private final boolean deliverLocal;
- private final boolean deliverRemote;
-
- private NotificationScope(boolean deliverLocal, boolean deliverRemote) {
- this.deliverLocal = deliverLocal;
- this.deliverRemote = deliverRemote;
- }
-
- /**
- * Determine whether an event should be delivered under this notification scope.
- *
- * @param isRemote Whether the event is local or remote
- * @return True if the event should be delivered to a listener with this notification scope
- */
- public boolean shouldDeliver(boolean isRemote) {
- return (isRemote && deliverRemote) || (!isRemote && deliverLocal);
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/util/ProductInfoTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/util/ProductInfoTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/util/ProductInfoTest.java (revision 0)
@@ -1,41 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.util;
-
-import static org.junit.Assert.assertEquals;
-
-import org.junit.Test;
-
-/**
- * @author hhuynh
- */
-public class ProductInfoTest {
-
- @Test
- public void testBuildInfo() {
- ProductInfo pi = new ProductInfo("/productinfotest-version.properties");
- assertEquals("Ehcache Core", pi.getName());
- assertEquals("1.7.0-SNAPSHOT", pi.getVersion());
- assertEquals("2009-09-18 02:15:49", pi.getBuildTime());
- assertEquals("1078", pi.getBuildRevision());
- assertEquals("1.6.0_16", pi.getBuildJdk());
-
- assertEquals(
- "Ehcache Core version 1.7.0-SNAPSHOT was built on 2009-09-18 02:15:49, at revision 1078, with jdk 1.6.0_16",
- pi.toString());
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/servermaplocalcache/DebugUtil.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/servermaplocalcache/DebugUtil.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/servermaplocalcache/DebugUtil.java (revision 0)
@@ -1,19 +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.Date;
-
-public abstract class DebugUtil {
-
- public static final boolean DEBUG = false;
-
- public static void debug(String msg) {
- if (DEBUG) {
- System.out.println(new Date() + " [" + Thread.currentThread().getName() + "]: " + msg);
- }
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/CacheConfigChangeNotificationMsg.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/CacheConfigChangeNotificationMsg.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/CacheConfigChangeNotificationMsg.java (revision 0)
@@ -1,37 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.store;
-
-import java.io.Serializable;
-
-public class CacheConfigChangeNotificationMsg implements Serializable {
- private final String fullyQualifiedEhcacheName;
- private final String toolkitConfigName;
- private final Serializable newValue;
-
- public CacheConfigChangeNotificationMsg(String fullyQualifiedCacheName, String configName, Serializable newValue) {
- this.fullyQualifiedEhcacheName = fullyQualifiedCacheName;
- this.toolkitConfigName = configName;
- this.newValue = newValue;
- }
-
- public String getToolkitConfigName() {
- return toolkitConfigName;
- }
-
- public Serializable getNewValue() {
- return newValue;
- }
-
- public String getFullyQualifiedEhcacheName() {
- return fullyQualifiedEhcacheName;
- }
-
- @Override
- public String toString() {
- return "CacheConfigChangeNotificationMsg [fullyQualifiedEhcacheName=" + fullyQualifiedEhcacheName
- + ", toolkitConfigName=" + toolkitConfigName + ", newValue=" + newValue + "]";
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/hibernate-config/tc-config.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/hibernate-config/tc-config.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/hibernate-config/tc-config.xml (revision 0)
@@ -1,22 +0,0 @@
-
-
-
-
- terracotta/clients-logs
-
-
-
-
- terracotta/server-logs
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/ConfigurationFactoryTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/ConfigurationFactoryTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/ConfigurationFactoryTest.java (revision 0)
@@ -1,1678 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package net.sf.ehcache.config;
-
-import static org.hamcrest.CoreMatchers.equalTo;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URL;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import java.util.regex.Matcher;
-
-import junit.framework.Assert;
-import net.sf.ehcache.AbstractCacheTest;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.bootstrap.BootstrapCacheLoader;
-import net.sf.ehcache.config.PersistenceConfiguration.Strategy;
-import net.sf.ehcache.config.TerracottaConfiguration.Consistency;
-import net.sf.ehcache.distribution.CacheManagerPeerListener;
-import net.sf.ehcache.distribution.CacheManagerPeerProvider;
-import net.sf.ehcache.distribution.MulticastRMICacheManagerPeerProvider;
-import net.sf.ehcache.distribution.RMIAsynchronousCacheReplicator;
-import net.sf.ehcache.distribution.RMIBootstrapCacheLoader;
-import net.sf.ehcache.distribution.RMICacheManagerPeerListener;
-import net.sf.ehcache.distribution.RMICacheReplicatorFactory;
-import net.sf.ehcache.event.CacheEventListener;
-import net.sf.ehcache.event.CacheManagerEventListener;
-import net.sf.ehcache.event.CountingCacheEventListener;
-import net.sf.ehcache.event.CountingCacheManagerEventListener;
-import net.sf.ehcache.event.NotificationScope;
-import net.sf.ehcache.exceptionhandler.CacheExceptionHandler;
-import net.sf.ehcache.exceptionhandler.CountingExceptionHandler;
-import net.sf.ehcache.store.DefaultElementValueComparator;
-import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
-import net.sf.ehcache.store.compound.ReadWriteSerializationCopyStrategy;
-import net.sf.ehcache.writer.TestCacheWriter;
-
-import org.hamcrest.core.IsNull;
-import org.junit.Before;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Tests for Store Configuration
- *
- * Make sure ant compile has been executed before running these tests, as they rely on the test ehcache.xml being
- * in the classpath.
- *
- * @author Greg Luck
- * @version $Id: ConfigurationFactoryTest.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class ConfigurationFactoryTest extends AbstractCacheTest {
- private static final int CACHES_IN_TEST_EHCACHE = 15;
-
- private static final Logger LOG = LoggerFactory.getLogger(ConfigurationFactoryTest.class.getName());
-
-
- /**
- * setup test
- */
- @Override
- @Before
- public void setUp() throws Exception {
- super.setUp();
- manager.removeAllCaches();
- }
-
- /**
- * Tests that the loader successfully loads from ehcache.xml.
- * ehcache.xml should be found in the classpath. In our ant configuration
- * this should be from build/test-classes/ehcache.xml
- *
- *
- */
- @Test
- public void testLoadConfigurationFromClasspath() throws Exception {
-
- Configuration configuration = ConfigurationFactory.parseConfiguration();
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- //Check core attributes
- assertEquals(null, configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check disk store
- assertEquals(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
-
-
- //Check CacheManagerPeerProvider
- Map peerProviders = configurationHelper.createCachePeerProviders();
- CacheManagerPeerProvider peerProvider = peerProviders.get("RMI");
-
-
- //Check TTL
- assertTrue(peerProvider instanceof MulticastRMICacheManagerPeerProvider);
- assertEquals(Integer.valueOf(0), ((MulticastRMICacheManagerPeerProvider) peerProvider).getHeartBeatSender().getTimeToLive());
-
- //Check CacheManagerEventListener
- assertEquals(null, configurationHelper.createCacheManagerEventListener(null));
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(5, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(10, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, defaultCache.getCacheConfiguration().isOverflowToDisk());
-
- //Check caches
- assertEquals(CACHES_IN_TEST_EHCACHE, configurationHelper.createCaches().size());
-
- /*
-
- */
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(360, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(1000, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, sampleCache1.getCacheConfiguration().isOverflowToDisk());
- assertEquals(1000, sampleCache1.getCacheConfiguration().getMaxElementsOnDisk());
-
- /** A cache which overflows to disk. The disk store is persistent
- between cache and VM restarts. The disk expiry thread interval is set to 10 minutes, overriding
- the default of 2 minutes.
- */
- Ehcache persistentLongExpiryIntervalCache = configurationHelper.createCacheFromName("persistentLongExpiryIntervalCache");
- assertEquals("persistentLongExpiryIntervalCache", persistentLongExpiryIntervalCache.getName());
- assertEquals(false, persistentLongExpiryIntervalCache.getCacheConfiguration().isEternal());
- assertEquals(300, persistentLongExpiryIntervalCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(600, persistentLongExpiryIntervalCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, persistentLongExpiryIntervalCache.getCacheConfiguration().isOverflowToDisk());
- assertEquals(true, persistentLongExpiryIntervalCache.getCacheConfiguration().isDiskPersistent());
- assertEquals(600, persistentLongExpiryIntervalCache.getCacheConfiguration().getDiskExpiryThreadIntervalSeconds());
-
- /*
-
-
-
- CacheExtension cache
- */
- Ehcache exceptionHandlingCache = configurationHelper.createCacheFromName("exceptionHandlingCache");
- assertEquals("exceptionHandlingCache", exceptionHandlingCache.getName());
- assertTrue(exceptionHandlingCache.getCacheExceptionHandler() != null);
- assertTrue(exceptionHandlingCache.getCacheExceptionHandler() instanceof CountingExceptionHandler);
- assertTrue(exceptionHandlingCache.getCacheExceptionHandler() instanceof CacheExceptionHandler);
- }
-
-
- /**
- * Tests that the loader successfully loads from ehcache.xml
- * given as a {@link File}
- *
- *
- */
- @Test
- public void testLoadConfigurationFromFile() throws Exception {
-
- File file = new File(SRC_CONFIG_DIR + "ehcache.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(null, configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check disk store
- assertEquals(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
-
- //Check CacheManagerPeerProvider
- Map peerProviders = configurationHelper.createCachePeerProviders();
- CacheManagerPeerProvider peerProvider = peerProviders.get("RMI");
-
-
- //Check TTL
- assertTrue(peerProvider instanceof MulticastRMICacheManagerPeerProvider);
- assertEquals(Integer.valueOf(1), ((MulticastRMICacheManagerPeerProvider) peerProvider).getHeartBeatSender().getTimeToLive());
-
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(120, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(120, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(Strategy.LOCALTEMPSWAP, defaultCache.getCacheConfiguration().getPersistenceConfiguration().getStrategy());
- assertEquals(10000, defaultCache.getCacheConfiguration().getMaxElementsInMemory());
- assertEquals(10000000, defaultCache.getCacheConfiguration().getMaxElementsOnDisk());
-
- //Check caches
- assertEquals(6, configurationHelper.createCaches().size());
-
- //check config
- CacheConfiguration sampleCache1Config = configuration.getCacheConfigurations().get("sampleCache1");
- assertEquals("sampleCache1", sampleCache1Config.getName());
- assertEquals(false, sampleCache1Config.isEternal());
- assertEquals(300, sampleCache1Config.getTimeToIdleSeconds());
- assertEquals(600, sampleCache1Config.getTimeToLiveSeconds());
- assertEquals(Strategy.LOCALTEMPSWAP, sampleCache1Config.getPersistenceConfiguration().getStrategy());
- assertEquals(20, sampleCache1Config.getDiskSpoolBufferSizeMB());
-
- //
- //Check created cache
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(300, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(1000, sampleCache1.getCacheConfiguration().getMaxElementsOnDisk());
- assertEquals(600, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(Strategy.LOCALTEMPSWAP, sampleCache1Config.getPersistenceConfiguration().getStrategy());
- }
-
- /**
- * Can we read from a UTF8 encoded file which uses Japanese characters
- */
- @Test
- public void testLoadUTF8ConfigurationFromFile() throws Exception {
- CacheManager cacheManager = new CacheManager(TEST_CONFIG_DIR + "ehcacheUTF8.xml");
- try{
- assertThat(cacheManager.getName(), equalTo("バーチャル"));
- assertThat(cacheManager.getCache("バーチャル クリストファー さんは書きました:"), IsNull.notNullValue());
- assertThat(cacheManager.getConfiguration().getCacheConfigurations().size(), is(1));
- } finally {
- cacheManager.shutdown();
- }
- }
-
-
- /**
- * Tests that the loader successfully loads from ehcache-1.1.xml
- * given as a {@link File}. This is a backward compatibility test.
- *
- *
- */
- @Test
- public void testLoadConfigurationFromEhcache11File() throws Exception {
-
- File file = new File(TEST_CONFIG_DIR + "ehcache-1_1.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(null, configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check disk path
- assertEquals(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(5, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(10, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, defaultCache.getCacheConfiguration().isOverflowToDisk());
- assertEquals(10, defaultCache.getCacheConfiguration().getMaxElementsInMemory());
- assertEquals(0, defaultCache.getCacheConfiguration().getMaxElementsOnDisk());
-
- //Check caches
- assertEquals(8, configurationHelper.createCaches().size());
-
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(360, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(1000, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, sampleCache1.getCacheConfiguration().isOverflowToDisk());
- }
-
- /**
- * Tests that the CacheManagerEventListener is null when
- * no CacheManagerEventListener class is specified.
- */
- @Test
- public void testLoadConfigurationFromFileNoCacheManagerListenerDefault() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-nolisteners.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- //Check CacheManagerEventListener
- CacheManagerEventListener listener = configurationHelper.createCacheManagerEventListener(null);
- assertEquals(null, listener);
-
- //Check caches. Configuration should have completed
- assertEquals(10, configurationHelper.createCaches().size());
- }
-
- /**
- * Tests that the CacheManagerEventListener class is set as the CacheManagerEventListener
- * when the class is unloadable.
- */
- @Test
- public void testLoadConfigurationFromFileUnloadableCacheManagerListenerDefault() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-unloadablecachemanagerlistenerclass.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- //Check CacheManagerEventListener
- CacheManagerEventListener listener = null;
- try {
- listener = configurationHelper.createCacheManagerEventListener(null);
- fail();
- } catch (CacheException e) {
- //expected
- }
- }
-
- /**
- * Positive and negative Tests for setting a list of CacheEventListeners in the configuration
- */
- @Test
- public void testLoadConfigurationFromFileCountingCacheListener() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-countinglisteners.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- //Check CacheManagerEventListener
- Class actualClass = configurationHelper.createCacheManagerEventListener(null).getClass();
- assertEquals(CountingCacheManagerEventListener.class, actualClass);
-
- //Check caches. Configuration should have completed
- assertEquals(10, configurationHelper.createCaches().size());
-
- //Should have null and counting
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- Set registeredListeners = sampleCache1.getCacheEventNotificationService().getCacheEventListeners();
- assertEquals(2, registeredListeners.size());
-
- //Should have null and counting
- Ehcache sampleCache2 = configurationHelper.createCacheFromName("sampleCache2");
- registeredListeners = sampleCache2.getCacheEventNotificationService().getCacheEventListeners();
- assertEquals(1, registeredListeners.size());
-
- //Should have null and counting
- Ehcache sampleCache3 = configurationHelper.createCacheFromName("sampleCache3");
- registeredListeners = sampleCache3.getCacheEventNotificationService().getCacheEventListeners();
- assertEquals(1, registeredListeners.size());
-
- //Should have none. None set.
- Ehcache footerPageCache = configurationHelper.createCacheFromName("FooterPageCache");
- registeredListeners = footerPageCache.getCacheEventNotificationService().getCacheEventListeners();
- assertEquals(0, registeredListeners.size());
-
- //Should have one. null listener set.
- Ehcache persistentLongExpiryIntervalCache = configurationHelper.createCacheFromName("persistentLongExpiryIntervalCache");
- registeredListeners = persistentLongExpiryIntervalCache.getCacheEventNotificationService()
- .getCacheEventListeners();
- assertEquals(1, registeredListeners.size());
- }
-
- /**
- * Tests for Distributed Cache config
- */
- @Test
- public void testLoadConfigurationFromFileDistribution() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "distribution/ehcache-distributed.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- //Check CacheManagerPeerProvider
- Map peerProviders = configurationHelper.createCachePeerProviders();
- CacheManagerPeerProvider peerProvider = peerProviders.get("RMI");
-
-
- //Check TTL
- assertTrue(peerProvider instanceof MulticastRMICacheManagerPeerProvider);
- assertEquals(Integer.valueOf(0), ((MulticastRMICacheManagerPeerProvider) peerProvider).getHeartBeatSender().getTimeToLive());
-
-
- //check CacheManagerPeerListener
- Map peerListeners = configurationHelper.createCachePeerListeners();
-
- //should be one in this config
- for (CacheManagerPeerListener peerListener : peerListeners.values()) {
- assertTrue(peerListener instanceof RMICacheManagerPeerListener);
- }
-
- //Check caches. Configuration should have completed
- assertEquals(5, configurationHelper.createCaches().size());
-
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- Set listeners = sampleCache1.getCacheEventNotificationService().getCacheEventListeners();
- assertEquals(2, listeners.size());
- for (Iterator iterator = listeners.iterator(); iterator.hasNext();) {
- CacheEventListener cacheEventListener = (CacheEventListener) iterator.next();
- assertTrue(cacheEventListener instanceof RMIAsynchronousCacheReplicator || cacheEventListener
- instanceof CountingCacheEventListener);
- }
-
- BootstrapCacheLoader bootstrapCacheLoader = sampleCache1.getBootstrapCacheLoader();
- assertNotNull(bootstrapCacheLoader);
- assertEquals(RMIBootstrapCacheLoader.class, bootstrapCacheLoader.getClass());
- assertEquals(true, bootstrapCacheLoader.isAsynchronous());
- assertEquals(5000000, ((RMIBootstrapCacheLoader) bootstrapCacheLoader).getMaximumChunkSizeBytes());
-
- }
-
- /**
- * The following should give defaults of true and 5000000
- *
- */
- @Test
- public void testLoadConfigurationFromFileNoBootstrapPropertiesSet() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "distribution/ehcache-distributed.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
- Ehcache sampleCache3 = configurationHelper.createCacheFromName("sampleCache3");
-
- BootstrapCacheLoader bootstrapCacheLoader = ((Cache) sampleCache3).getBootstrapCacheLoader();
- assertEquals(true, bootstrapCacheLoader.isAsynchronous());
- assertEquals(5000000, ((RMIBootstrapCacheLoader) bootstrapCacheLoader).getMaximumChunkSizeBytes());
- }
-
- /**
- * The following should give defaults of true and 5000000
- *
- */
- @Test
- public void testLoadConfigurationFromFileWithSpecificPropertiesSet() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "distribution/ehcache-distributed.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
- Ehcache sampleCache4 = configurationHelper.createCacheFromName("sampleCache4");
-
- BootstrapCacheLoader bootstrapCacheLoader = ((Cache) sampleCache4).getBootstrapCacheLoader();
- assertEquals(false, bootstrapCacheLoader.isAsynchronous());
- assertEquals(10000, ((RMIBootstrapCacheLoader) bootstrapCacheLoader).getMaximumChunkSizeBytes());
- }
-
- /**
- * Tests that the loader successfully loads from ehcache-nodefault.xml
- * given as a {@link File}
- *
- *
- */
- @Test
- public void testLoadConfigurationFromFileNoDefault() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-nodefault.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(null, configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check disk path
- assertEquals(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
-
- //Check default cache
- try {
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- Assert.assertNull(defaultCache);
- } catch (CacheException e) {
- fail("Calling create default cache when no default cache config specified should return null and not fail");
- }
-
- //Check caches
- assertEquals(4, configurationHelper.createCaches().size());
-
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- Ehcache sampleCache4 = configurationHelper.createCacheFromName("sampleCache4");
- assertEquals("net.sf.ehcache.transaction.manager.DefaultTransactionManagerLookup",
- configuration.getTransactionManagerLookupConfiguration().getFullyQualifiedClassPath());
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(300, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(600, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, sampleCache1.getCacheConfiguration().isOverflowToDisk());
- assertEquals(CacheConfiguration.TransactionalMode.OFF, sampleCache1.getCacheConfiguration().getTransactionalMode());
- assertEquals(false, sampleCache1.getCacheConfiguration().isXaStrictTransactional());
- assertEquals("sampleCache4", sampleCache4.getName());
- assertEquals(CacheConfiguration.TransactionalMode.XA_STRICT, sampleCache4.getCacheConfiguration().getTransactionalMode());
- assertEquals(true, sampleCache4.getCacheConfiguration().isXaStrictTransactional());
- }
-
- /**
- * Tests that the loader successfully loads from ehcache-nodefault.xml
- * given as a {@link File}
- *
- * /**
- * Tests that the loader successfully loads from ehcache-nodefault.xml
- * given as a {@link File}
- *
- *
- */
- @Test
- public void testDefaultValues() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-nodefault.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- Ehcache sampleCacheNoOptionalAttributes = configurationHelper.createCacheFromName("sampleCacheNoOptionalAttributes");
- assertEquals("sampleCacheNoOptionalAttributes", sampleCacheNoOptionalAttributes.getName());
- assertEquals(1000, sampleCacheNoOptionalAttributes.getCacheConfiguration().getMaxElementsInMemory());
- assertEquals(true, sampleCacheNoOptionalAttributes.getCacheConfiguration().isEternal());
- assertEquals(false, sampleCacheNoOptionalAttributes.getCacheConfiguration().isOverflowToDisk());
- assertEquals(0, sampleCacheNoOptionalAttributes.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(0, sampleCacheNoOptionalAttributes.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(false, sampleCacheNoOptionalAttributes.getCacheConfiguration().isDiskPersistent());
- assertEquals(120, sampleCacheNoOptionalAttributes.getCacheConfiguration().getDiskExpiryThreadIntervalSeconds());
- assertEquals(1, sampleCacheNoOptionalAttributes.getCacheConfiguration().getDiskAccessStripes());
- }
-
-
- /**
- * Tests that the loader successfully loads from ehcache-nodisk.xml
- * given as a {@link File}
- *
- *
- */
- @Test
- public void testLoadConfigurationFromFileNoDisk() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-nodisk.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(null, configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check disk path
- assertEquals(null, configurationHelper.getDiskStorePath());
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(5L, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(10, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(false, defaultCache.getCacheConfiguration().isOverflowToDisk());
-
- //Check caches
- assertEquals(2, configurationHelper.createCaches().size());
-
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(360, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(1000, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(false, sampleCache1.getCacheConfiguration().isOverflowToDisk());
- }
-
- /**
- * Tests the default values for optional attributes
- *
- *
- *
- *
- * No disk store path specified as disk store not being used
- * />
- */
- @Test
- public void testOptionalAttributeDefaultValues() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-nodisk.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(null, configurationHelper.getDiskStorePath());
-
-
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(360, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(1000, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(false, sampleCache1.getCacheConfiguration().isOverflowToDisk());
- }
-
- /**
- * Regression test for bug 1432074 - NullPointer on RMICacheManagerPeerProviderFactory
- * If manual peer provider configuration is selected then an info message should be
- * logged if there is no list.
- */
- @Test
- public void testEmptyPeerListManualDistributedConfiguration() {
- Configuration config = ConfigurationFactory.parseConfiguration(
- new File(TEST_CONFIG_DIR + "distribution/ehcache-manual-distributed3.xml")).name("new-name");
- CacheManager cacheManager = new CacheManager(config);
- assertEquals(0, cacheManager.getCacheManagerPeerProvider("RMI")
- .listRemoteCachePeers(cacheManager.getCache("sampleCache1")).size());
- cacheManager.shutdown();
-
- }
-
-
- /**
- * Tests that the loader successfully loads from ehcache.xml
- * given as an {@link URL}.
- *
- * is found first
- *
- *
- */
- @Test
- public void testLoadConfigurationFromURL() throws Exception {
- URL url = getClass().getResource("/ehcache.xml");
- testDefaultConfiguration(url);
- }
-
- /**
- * Exposes a bug where the default configuration could not be loaded from a Jar URL
- * (a common scenario when ehcache is deployed, and always used for failsafe config).
- *
- * @throws Exception When the test fails.
- */
- @Test
- public void testLoadConfigurationFromJarURL() throws Exception {
-
- // first, create the jar
- File tempJar = createTempConfigJar();
-
- // convert it to a URL
- URL tempUrl = tempJar.toURI().toURL();
-
- // create a jar url that points to the configuration file
- String entry = "jar:" + tempUrl + "!/ehcache.xml";
-
- // create a URL object from the string, going through the URI class so it's encoded
- URL entryUrl = new URI(entry).toURL();
-
- testDefaultConfiguration(entryUrl);
- }
-
- /**
- * Given a URL, parse the configuration and test that the config read corresponds
- * to that which exists in the ehcache.xml file.
- *
- * @param url The URL to load.
- */
- private void testDefaultConfiguration(URL url) {
- Configuration configuration = ConfigurationFactory.parseConfiguration(url);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- //Check disk path missing in test ehcache.xml"/>
- assertEquals(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(5L, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(10, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, defaultCache.getCacheConfiguration().isOverflowToDisk());
-
- //Check caches
- assertEquals(CACHES_IN_TEST_EHCACHE, configurationHelper.createCaches().size());
-
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(360, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(1000, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(true, sampleCache1.getCacheConfiguration().isOverflowToDisk());
- }
-
- /**
- * Creates a jar file that contains only ehcache.xml (a supplied configuration file).
- *
- * @return The jar file created with the configuration file as its only entry.
- * @throws IOException If the jar could not be created.
- */
- private File createTempConfigJar() throws IOException, FileNotFoundException {
- File tempJar = File.createTempFile("config_", ".jar");
- tempJar.deleteOnExit();
-
- // write the default config to the jar
- JarOutputStream jos = null;
- try {
- jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(tempJar)));
-
- jos.putNextEntry(new JarEntry("ehcache.xml"));
-
- InputStream defaultCfg = null;
- try {
- defaultCfg = new BufferedInputStream(getClass().getResource("/ehcache.xml").openStream());
- byte[] buf = new byte[1024];
- int read = 0;
- while ((read = defaultCfg.read(buf)) > 0) {
- jos.write(buf, 0, read);
- }
- } finally {
- try {
- if (defaultCfg != null) {
- defaultCfg.close();
- }
- } catch (IOException ioEx) {
- // swallow this exception
- }
- }
-
- } finally {
- try {
- if (jos != null) {
- jos.closeEntry();
-
- jos.flush();
- jos.close();
- }
- } catch (IOException ioEx) {
- // swallow this exception
- }
- }
-
- return tempJar;
- }
-
- /**
- * Tests that the loader successfully loads from ehcache.xml
- * given as a {@link InputStream}
- *
- *
- */
- @Test
- public void testLoadConfigurationFromInputStream() throws Exception {
- InputStream fis = new FileInputStream(new File(SRC_CONFIG_DIR + "ehcache.xml").getAbsolutePath());
- ConfigurationHelper configurationHelper;
- try {
- Configuration configuration = ConfigurationFactory.parseConfiguration(fis);
- configurationHelper = new ConfigurationHelper(manager, configuration);
- } finally {
- fis.close();
- }
-
- assertEquals(null, configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check disk path
- assertEquals(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(120, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(120, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(Strategy.LOCALTEMPSWAP, defaultCache.getCacheConfiguration().getPersistenceConfiguration().getStrategy());
-
- //Check caches
- assertEquals(6, configurationHelper.createCaches().size());
-
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("sampleCache1");
- assertEquals("sampleCache1", sampleCache1.getName());
- assertEquals(false, sampleCache1.getCacheConfiguration().isEternal());
- assertEquals(300, sampleCache1.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(600, sampleCache1.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(Strategy.LOCALTEMPSWAP, sampleCache1.getCacheConfiguration().getPersistenceConfiguration().getStrategy());
- }
-
- /**
- * Tests that the loader successfully loads from ehcache-failsafe.xml
- * found in the classpath.
- * ehcache.xml should be found in the classpath. In our ant configuration
- * this should be from build/classes/ehcache-failsafe.xml
- *
- * We delete ehcache.xml from build/test-classes/ first, as failsafe only
- * kicks in when ehcache.xml is not in the classpath.
- *
- *
- */
- @Test
- public void testLoadConfigurationFromFailsafe() throws Exception {
- try {
- File file = new File(AbstractCacheTest.TEST_CLASSES_DIR + "ehcache.xml");
- file.renameTo(new File(AbstractCacheTest.TEST_CLASSES_DIR + "hideehcache.xml"));
- Configuration configuration = ConfigurationFactory.parseConfiguration();
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(null, configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check disk path
- assertEquals(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(120, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(120, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(Strategy.LOCALTEMPSWAP, defaultCache.getCacheConfiguration().getPersistenceConfiguration().getStrategy());
-
- //Check caches
- assertEquals(0, configurationHelper.createCaches().size());
- } finally {
- //Put ehcache.xml back
- File hiddenFile = new File(AbstractCacheTest.TEST_CLASSES_DIR + "hideehcache.xml");
- hiddenFile.renameTo(new File(AbstractCacheTest.TEST_CLASSES_DIR + "ehcache.xml"));
- }
-
- }
-
- /**
- * Make sure that the empty Configuration constructor remains public for those wishing to create CacheManagers
- * purely programmatically.
- */
- @Test
- public void testCreateEmptyConfiguration() {
- Configuration configuration = new Configuration();
- }
-
-
- /**
- * Tests that you cannot use the name default for a cache.
- */
- @Test
- public void testLoadConfigurationFromInvalidXMLFileWithDefaultCacheNameUsed() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-withdefaultset.xml");
- try {
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- } catch (CacheException e) {
- assertTrue(e.getMessage().contains("The Default Cache has already been configured"));
- }
-
- }
-
-
- /**
- * Tests replacement in the config file.
- */
- @Test
- public void testLoadConfigurationWithReplacement() throws Exception {
- System.setProperty("multicastGroupPort", "4446");
- System.setProperty("serverAndPort", "server.com:9510");
- File file = new File(TEST_CONFIG_DIR + "ehcache-replacement.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
-
- //Check disk path
- assertNotSame(System.getProperty("java.io.tmpdir"), configurationHelper.getDiskStorePath());
- assertTrue(configuration.getCacheManagerPeerProviderFactoryConfiguration().get(0)
- .getProperties().indexOf("multicastGroupPort=4446") != -1);
-
-
- }
-
-
- /**
- * Fun with replaceAll which clobbers \\ by default!
- */
- @Test
- public void testPathExpansionAndReplacement() throws Exception {
-
- String configuration = "This is my ${basedir}.";
- String trimmedToken = "basedir";
- String property = "D:\\sonatype\\workspace\\nexus-aggregator\\nexus\\nexus-app";
- LOG.info("Property: " + property);
- LOG.info("configuration is: " + configuration);
- String propertyWithQuotesProtected = Matcher.quoteReplacement(property);
- configuration = configuration.replaceAll("\\$\\{" + trimmedToken + "\\}", propertyWithQuotesProtected);
- assertTrue(configuration.contains(property));
- LOG.info("configuration is: " + configuration);
-
-
- }
-
-
- /**
- * Tests the property token extraction logic
- */
- @Test
- public void testMatchPropertyTokensProperlyFormed() {
- String example = "";
- Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example);
- assertEquals(1, propertyTokens.size());
- String firstPropertyToken = (String) (propertyTokens.toArray())[0];
- assertEquals("${multicastAddress}", firstPropertyToken);
- }
-
- /**
- * Tests the property token extraction logic
- */
- @Test
- public void testMatchPropertyTokensProperlyFormedUrl() {
- String example = "";
- Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example);
- assertEquals(1, propertyTokens.size());
- String firstPropertyToken = (String) (propertyTokens.toArray())[0];
- assertEquals("${serverAndPort}", firstPropertyToken);
- }
-
-
- /**
- * Tests the property token extraction logic
- */
- @Test
- public void testMatchPropertyTokensProperlyFormedTwo() {
- String example = "";
- Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example);
- assertEquals(1, propertyTokens.size());
- String firstPropertyToken = (String) (propertyTokens.toArray())[0];
- assertEquals("${multicastAddress}", firstPropertyToken);
- }
-
-
- /**
- * Tests the property token extraction logic
- */
- @Test
- public void testMatchPropertyTokensProperlyFormedTwoUnique() {
- String example = "";
- Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example);
- assertEquals(2, propertyTokens.size());
- }
-
- /**
- * If you leave off the } then no match.
- */
- @Test
- public void testMatchPropertyTokensNotClosed() {
- String example = "";
- Set propertyTokens = ConfigurationFactory.extractPropertyTokens(example);
- assertEquals(0, propertyTokens.size());
- }
-
- @Test
- public void testCopyConfiguration() {
- File file = new File(TEST_CONFIG_DIR + "ehcache-copy.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- Ehcache copyOnReadCache = configurationHelper.createCacheFromName("copyOnReadCache");
- assertTrue(copyOnReadCache.getCacheConfiguration().isCopyOnRead());
- assertFalse(copyOnReadCache.getCacheConfiguration().isCopyOnWrite());
- assertNotNull(copyOnReadCache.getCacheConfiguration().getCopyStrategy());
- assertTrue(copyOnReadCache.getCacheConfiguration().getCopyStrategy() instanceof ReadWriteSerializationCopyStrategy);
-
- Ehcache copyOnWriteCache = configurationHelper.createCacheFromName("copyOnWriteCache");
- assertFalse(copyOnWriteCache.getCacheConfiguration().isCopyOnRead());
- assertTrue(copyOnWriteCache.getCacheConfiguration().isCopyOnWrite());
- assertNotNull(copyOnWriteCache.getCacheConfiguration().getCopyStrategy());
- assertTrue(copyOnWriteCache.getCacheConfiguration().getCopyStrategy() instanceof ReadWriteSerializationCopyStrategy);
-
- Ehcache copyCache = configurationHelper.createCacheFromName("copyCache");
- assertTrue(copyCache.getCacheConfiguration().isCopyOnRead());
- assertTrue(copyCache.getCacheConfiguration().isCopyOnWrite());
- assertNotNull(copyCache.getCacheConfiguration().getCopyStrategy());
- assertTrue(copyCache.getCacheConfiguration().getCopyStrategy() instanceof FakeCopyStrategy);
-
- try {
- Configuration config = ConfigurationFactory.parseConfiguration(new File(TEST_CONFIG_DIR + "ehcache-copy.xml")).name("new-cm");
- new CacheManager(config);
- fail("This should have thrown an Exception");
- } catch (Exception e) {
- if (!(e instanceof InvalidConfigurationException)) {
- e.printStackTrace();
- fail("Expected InvalidConfigurationException, but got " + e.getClass().getSimpleName() + ", msg: " + e.getMessage());
- }
- }
-
- file = new File(TEST_CONFIG_DIR + "ehcache-copy-tc.xml");
- configuration = ConfigurationFactory.parseConfiguration(file).name("new-cm");
- configurationHelper = new ConfigurationHelper(manager, configuration);
-
- Ehcache nonCopyCache = configurationHelper.createCacheFromName("nonCopyOnReadCacheTcTrue");
- assertFalse(nonCopyCache.getCacheConfiguration().isCopyOnRead());
- assertTrue(nonCopyCache.getCacheConfiguration().getTerracottaConfiguration().isCopyOnRead());
-
- Ehcache nonCopyCacheTc = configurationHelper.createCacheFromName("copyOnReadCacheTcFalse");
- assertTrue(nonCopyCacheTc.getCacheConfiguration().isCopyOnRead());
- assertFalse(nonCopyCacheTc.getCacheConfiguration().getTerracottaConfiguration().isCopyOnRead());
-
- Ehcache copyOnReadCacheTc = configurationHelper.createCacheFromName("copyOnReadCacheTc");
- assertTrue(copyOnReadCacheTc.getCacheConfiguration().isCopyOnRead());
- assertTrue(copyOnReadCacheTc.getCacheConfiguration().getTerracottaConfiguration().isCopyOnRead());
- }
-
- @Test
- public void testElementValueComparatorConfiguration() {
- File file = new File(TEST_CONFIG_DIR + "ehcache-comparator.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- ClassLoader loader = getClass().getClassLoader();
-
- Ehcache cache = configurationHelper.createCacheFromName("cache");
- assertTrue(cache.getCacheConfiguration().getElementValueComparatorConfiguration().createElementComparatorInstance(cache.getCacheConfiguration(), loader)
- instanceof DefaultElementValueComparator);
-
- Ehcache cache2 = configurationHelper.createCacheFromName("cache2");
- assertTrue(cache2.getCacheConfiguration().getElementValueComparatorConfiguration().createElementComparatorInstance(cache.getCacheConfiguration(), loader)
- .getClass().equals(FakeElementValueComparator.class));
- }
-
- /**
- * Test named cachemanager, terracotta config, clustered caches
- */
- @Test
- public void testTerracottaConfiguration() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-terracotta.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals("tc", configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
- assertEquals(false, configurationHelper.getConfigurationBean().getTerracottaConfiguration().isWanEnabledTSA());
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(5, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(10, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(false, defaultCache.getCacheConfiguration().isOverflowToDisk());
- assertEquals(10, defaultCache.getCacheConfiguration().getMaxElementsInMemory());
- assertEquals(0, defaultCache.getCacheConfiguration().getMaxElementsOnDisk());
- assertEquals(true, defaultCache.getCacheConfiguration().isTerracottaClustered());
- assertEquals(true, defaultCache.getCacheConfiguration().getTerracottaConfiguration().getCoherentReads());
-
- //Check caches
- assertEquals(15, configurationHelper.createCaches().size());
-
- //
- //
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("clustered-1");
- assertEquals("clustered-1", sampleCache1.getName());
- assertEquals(true, sampleCache1.getCacheConfiguration().isTerracottaClustered());
-
- //
- //
- //
- Ehcache sampleCache2 = configurationHelper.createCacheFromName("clustered-2");
- assertEquals("clustered-2", sampleCache2.getName());
- assertEquals(false, sampleCache2.getCacheConfiguration().isTerracottaClustered());
-
- //
- //
- Ehcache sampleCache3 = configurationHelper.createCacheFromName("clustered-3");
- assertEquals("clustered-3", sampleCache3.getName());
- assertEquals(true, sampleCache3.getCacheConfiguration().isTerracottaClustered());
-
- //
- //
- //
- Ehcache sampleCache5 = configurationHelper.createCacheFromName("clustered-5");
- assertEquals("clustered-5", sampleCache5.getName());
- assertEquals(true, sampleCache5.getCacheConfiguration().isTerracottaClustered());
- assertEquals(false,
- sampleCache5.getCacheConfiguration().getTerracottaConfiguration().getCoherentReads());
-
- //
- //
- //
- Ehcache sampleCache6 = configurationHelper.createCacheFromName("clustered-6");
- assertEquals("clustered-6", sampleCache6.getName());
- assertEquals(true, sampleCache6.getCacheConfiguration().isTerracottaClustered());
- assertEquals(false,
- sampleCache6.getCacheConfiguration().getTerracottaConfiguration().getOrphanEviction());
-
- //
- //
- //
- Ehcache sampleCache7 = configurationHelper.createCacheFromName("clustered-7");
- assertEquals("clustered-7", sampleCache7.getName());
- assertEquals(true, sampleCache7.getCacheConfiguration().isTerracottaClustered());
- assertEquals(42,
- sampleCache7.getCacheConfiguration().getTerracottaConfiguration().getOrphanEvictionPeriod());
-
- //
- //
- //
- Ehcache sampleCache8 = configurationHelper.createCacheFromName("clustered-8");
- assertEquals("clustered-8", sampleCache8.getName());
- assertEquals(true, sampleCache8.getCacheConfiguration().isTerracottaClustered());
- assertEquals(true,
- sampleCache8.getCacheConfiguration().getTerracottaConfiguration().getLocalKeyCache());
-
- //
- //
- //
- Ehcache sampleCache9 = configurationHelper.createCacheFromName("clustered-9");
- assertEquals("clustered-9", sampleCache9.getName());
- assertEquals(true, sampleCache9.getCacheConfiguration().isTerracottaClustered());
- assertEquals(42,
- sampleCache9.getCacheConfiguration().getTerracottaConfiguration().getLocalKeyCacheSize());
-
- // assert default value is true always
- assertEquals(true, TerracottaConfiguration.DEFAULT_CACHE_COHERENT);
-
- Ehcache sampleCache10 = configurationHelper.createCacheFromName("clustered-10");
- assertEquals("clustered-10", sampleCache10.getName());
- assertEquals(true, sampleCache10.getCacheConfiguration().isTerracottaClustered());
- final boolean expectedDefault = TerracottaConfiguration.DEFAULT_CONSISTENCY_TYPE == Consistency.STRONG? true: false;
- assertEquals(expectedDefault,
- sampleCache10.getCacheConfiguration().getTerracottaConfiguration().isCoherent());
-
- Ehcache sampleCache11 = configurationHelper.createCacheFromName("clustered-11");
- assertEquals("clustered-11", sampleCache11.getName());
- assertEquals(true, sampleCache11.getCacheConfiguration().isTerracottaClustered());
- assertEquals(false,
- sampleCache11.getCacheConfiguration().getTerracottaConfiguration().isCoherent());
-
- Ehcache sampleCache12 = configurationHelper.createCacheFromName("clustered-12");
- assertEquals("clustered-12", sampleCache12.getName());
- assertEquals(true, sampleCache12.getCacheConfiguration().isTerracottaClustered());
- assertEquals(true,
- sampleCache12.getCacheConfiguration().getTerracottaConfiguration().isCoherent());
-
- // assert default value is false always
- assertEquals(false, TerracottaConfiguration.DEFAULT_SYNCHRONOUS_WRITES);
-
- Ehcache sampleCache13 = configurationHelper.createCacheFromName("clustered-13");
- assertEquals("clustered-13", sampleCache13.getName());
- assertEquals(true, sampleCache13.getCacheConfiguration().isTerracottaClustered());
- assertEquals(false,
- sampleCache13.getCacheConfiguration().getTerracottaConfiguration().isSynchronousWrites());
-
- Ehcache sampleCache14 = configurationHelper.createCacheFromName("clustered-14");
- assertEquals("clustered-14", sampleCache14.getName());
- assertEquals(true, sampleCache14.getCacheConfiguration().isTerracottaClustered());
- assertEquals(false,
- sampleCache14.getCacheConfiguration().getTerracottaConfiguration().isSynchronousWrites());
-
- Ehcache sampleCache15 = configurationHelper.createCacheFromName("clustered-15");
- assertEquals("clustered-15", sampleCache15.getName());
- assertEquals(true, sampleCache15.getCacheConfiguration().isTerracottaClustered());
- assertEquals(true,
- sampleCache15.getCacheConfiguration().getTerracottaConfiguration().isSynchronousWrites());
-
- //
- // localhost:9510
- //
- TerracottaClientConfiguration tcConfig = configuration.getTerracottaConfiguration();
- assertNotNull(tcConfig);
- assertEquals("localhost:9510", tcConfig.getUrl());
- }
-
-
- /**
- * Test tc-config embedded in ehcache.xml
- */
- @Test
- public void testTerracottaEmbeddedConfig() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-tc-embedded.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals("tc", configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
-
- //Check default cache
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertEquals(false, defaultCache.getCacheConfiguration().isEternal());
- assertEquals(5, defaultCache.getCacheConfiguration().getTimeToIdleSeconds());
- assertEquals(10, defaultCache.getCacheConfiguration().getTimeToLiveSeconds());
- assertEquals(false, defaultCache.getCacheConfiguration().isOverflowToDisk());
- assertEquals(10, defaultCache.getCacheConfiguration().getMaxElementsInMemory());
- assertEquals(0, defaultCache.getCacheConfiguration().getMaxElementsOnDisk());
- assertEquals(true, defaultCache.getCacheConfiguration().isTerracottaClustered());
-
- //Check caches
- assertEquals(1, configurationHelper.createCaches().size());
-
- //
- //
- //
- Ehcache sampleCache1 = configurationHelper.createCacheFromName("clustered-1");
- assertEquals("clustered-1", sampleCache1.getName());
- assertEquals(true, sampleCache1.getCacheConfiguration().isTerracottaClustered());
-
- //
- // ...
- //
- TerracottaClientConfiguration tcConfig = configuration.getTerracottaConfiguration();
- assertNotNull(tcConfig);
- assertEquals(null, tcConfig.getUrl());
- String embeddedConfig = tcConfig.getEmbeddedConfig();
- assertEquals(" " +
- " " +
- " " +
- " app/logs-%i ",
- removeLotsOfWhitespace(tcConfig.getEmbeddedConfig()));
- }
-
- @Test
- public void testTerracottaEmbeddedXsdConfig() {
- File file = new File(TEST_CONFIG_DIR
- + "terracotta/ehcache-tc-embedded-xsd.xml");
- Configuration configuration = ConfigurationFactory
- .parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(
- manager, configuration);
-
- assertEquals("tc", configurationHelper.getConfigurationBean().getName());
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper
- .getConfigurationBean().getMonitoring());
-
- //
- // ...
- //
- TerracottaClientConfiguration tcConfig = configuration
- .getTerracottaConfiguration();
- assertNotNull(tcConfig);
- assertEquals(null, tcConfig.getUrl());
- String embeddedConfig = tcConfig.getEmbeddedConfig();
- assertEquals(
- " "
- + " "
- + " "
- + " app/logs-%i ",
- removeLotsOfWhitespace(tcConfig.getEmbeddedConfig()));
- }
-
- /**
- * Test invalid combination of overflow to disk and terracotta ehcache.xml
- */
- @Test
- public void testTerracottaInvalidConfig1() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-terracotta-invalid1.xml");
- try {
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- fail("expecting exception to be thrown");
- } catch (CacheException e) {
- assertTrue(e.getMessage().contains("overflowToDisk isn't supported for a clustered Terracotta cache"));
- }
- }
-
- /**
- * Test invalid combination of disk persistent and terracotta ehcache.xml
- */
- @Test
- public void testTerracottaInvalidConfig2() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-terracotta-invalid2.xml");
- try {
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- fail("expecting exception to be thrown");
- } catch (CacheException e) {
- assertTrue(e.getMessage().contains("diskPersistent isn't supported for a clustered Terracotta cache"));
- }
- }
-
- /**
- * Test valid combination of replicated and terracotta ehcache.xml
- */
- @Test
- public void testTerracottaConfigRMIReplication() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-terracotta-rmi.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- List configs = configuration.getCacheConfigurations().get("clustered").getCacheEventListenerConfigurations();
- assertEquals(1, configs.size());
- assertEquals(((CacheConfiguration.CacheEventListenerFactoryConfiguration) configs.get(0)).getFullyQualifiedClassPath(),
- RMICacheReplicatorFactory.class.getName());
- }
-
- /**
- * Test valid combination of replicated and terracotta ehcache.xml
- */
- @Test
- public void testTerracottaConfigJGroupsReplication() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-terracotta-jgroups.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- List configs = configuration.getCacheConfigurations().get("clustered").getCacheEventListenerConfigurations();
- assertEquals(1, configs.size());
- assertEquals(((CacheConfiguration.CacheEventListenerFactoryConfiguration) configs.get(0)).getFullyQualifiedClassPath(),
- "net.sf.ehcache.distribution.JGroupsCacheReplicatorFactory");
- }
-
- /**
- * Test valid combination of replicated and terracotta ehcache.xml
- */
- @Test
- public void testTerracottaInvalidConfig5() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-terracotta-jms.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- List configs = configuration.getCacheConfigurations().get("clustered").getCacheEventListenerConfigurations();
- assertEquals(1, configs.size());
- assertEquals(((CacheConfiguration.CacheEventListenerFactoryConfiguration) configs.get(0)).getFullyQualifiedClassPath(),
- "net.sf.ehcache.distribution.JMSCacheReplicatorFactory");
- }
-
- private String removeLotsOfWhitespace(String str) {
- return str.replace("\t", "").replace("\r", "").replace("\n", "").replaceAll("\\s+", " ");
- }
-
- @Test
- public void testMonitoringOn() {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-on.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(Configuration.Monitoring.ON, configurationHelper.getConfigurationBean().getMonitoring());
- }
-
- @Test
- public void testMonitoringOff() {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-off.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(Configuration.Monitoring.OFF, configurationHelper.getConfigurationBean().getMonitoring());
- }
-
- @Test
- public void testMonitoringAutodetect() {
- File file = new File(TEST_CONFIG_DIR + "ehcache-monitoring-autodetect.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- assertEquals(Configuration.Monitoring.AUTODETECT, configurationHelper.getConfigurationBean().getMonitoring());
- }
-
- /**
- * Test cache writer config
- */
- @Test
- public void testWriterConfig() {
- File file = new File(TEST_CONFIG_DIR + "ehcache-writer.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- ConfigurationHelper configurationHelper = new ConfigurationHelper(manager, configuration);
-
- CacheWriterConfiguration defaultCacheWriterConfig = new CacheWriterConfiguration();
-
- CacheConfiguration configDefault = configurationHelper.getConfigurationBean().getDefaultCacheConfiguration();
- assertEquals(false, configDefault.isEternal());
- assertEquals(5, configDefault.getTimeToIdleSeconds());
- assertEquals(10, configDefault.getTimeToLiveSeconds());
- assertEquals(false, configDefault.isOverflowToDisk());
- assertEquals(10, configDefault.getMaxElementsInMemory());
- assertNotNull(configDefault.getCacheWriterConfiguration());
- assertEquals(defaultCacheWriterConfig.getWriteMode(), configDefault.getCacheWriterConfiguration().getWriteMode());
- assertEquals(defaultCacheWriterConfig.getCacheWriterFactoryConfiguration(), configDefault.getCacheWriterConfiguration()
- .getCacheWriterFactoryConfiguration());
- assertEquals(defaultCacheWriterConfig.getNotifyListenersOnException(), configDefault.getCacheWriterConfiguration()
- .getNotifyListenersOnException());
- assertEquals(defaultCacheWriterConfig.getMaxWriteDelay(), configDefault.getCacheWriterConfiguration().getMaxWriteDelay());
- assertEquals(defaultCacheWriterConfig.getRateLimitPerSecond(), configDefault.getCacheWriterConfiguration().getRateLimitPerSecond());
- assertEquals(defaultCacheWriterConfig.getWriteCoalescing(), configDefault.getCacheWriterConfiguration().getWriteCoalescing());
- assertEquals(defaultCacheWriterConfig.getWriteBatching(), configDefault.getCacheWriterConfiguration().getWriteBatching());
- assertEquals(defaultCacheWriterConfig.getWriteBatchSize(), configDefault.getCacheWriterConfiguration().getWriteBatchSize());
- assertEquals(defaultCacheWriterConfig.getRetryAttempts(), configDefault.getCacheWriterConfiguration().getRetryAttempts());
- assertEquals(defaultCacheWriterConfig.getRetryAttemptDelaySeconds(), configDefault.getCacheWriterConfiguration()
- .getRetryAttemptDelaySeconds());
-
- Ehcache defaultCache = configurationHelper.createDefaultCache();
- assertEquals("default", defaultCache.getName());
- assertNotNull(defaultCache.getCacheConfiguration().getCacheWriterConfiguration());
-
- Map configs = configurationHelper.getConfigurationBean().getCacheConfigurations();
- CacheConfiguration config1 = configs.get("writeThroughCache1");
- assertNotNull(config1.getCacheWriterConfiguration());
- assertEquals(defaultCacheWriterConfig.getWriteMode(), config1.getCacheWriterConfiguration().getWriteMode());
- assertEquals(defaultCacheWriterConfig.getCacheWriterFactoryConfiguration(), config1.getCacheWriterConfiguration()
- .getCacheWriterFactoryConfiguration());
- assertEquals(defaultCacheWriterConfig.getNotifyListenersOnException(), config1.getCacheWriterConfiguration()
- .getNotifyListenersOnException());
- assertEquals(defaultCacheWriterConfig.getMaxWriteDelay(), config1.getCacheWriterConfiguration().getMaxWriteDelay());
- assertEquals(defaultCacheWriterConfig.getRateLimitPerSecond(), config1.getCacheWriterConfiguration().getRateLimitPerSecond());
- assertEquals(defaultCacheWriterConfig.getWriteCoalescing(), config1.getCacheWriterConfiguration().getWriteCoalescing());
- assertEquals(defaultCacheWriterConfig.getWriteBatching(), config1.getCacheWriterConfiguration().getWriteBatching());
- assertEquals(defaultCacheWriterConfig.getWriteBatchSize(), config1.getCacheWriterConfiguration().getWriteBatchSize());
- assertEquals(defaultCacheWriterConfig.getRetryAttempts(), config1.getCacheWriterConfiguration().getRetryAttempts());
- assertEquals(defaultCacheWriterConfig.getRetryAttemptDelaySeconds(), config1.getCacheWriterConfiguration().getRetryAttemptDelaySeconds());
-
- CacheConfiguration config2 = configs.get("writeThroughCache2");
- assertNotNull(config2.getCacheWriterConfiguration());
- assertEquals(defaultCacheWriterConfig.getWriteMode(), config2.getCacheWriterConfiguration().getWriteMode());
- assertEquals(defaultCacheWriterConfig.getCacheWriterFactoryConfiguration(), config2.getCacheWriterConfiguration()
- .getCacheWriterFactoryConfiguration());
- assertEquals(defaultCacheWriterConfig.getNotifyListenersOnException(), config2.getCacheWriterConfiguration()
- .getNotifyListenersOnException());
- assertEquals(defaultCacheWriterConfig.getMaxWriteDelay(), config2.getCacheWriterConfiguration().getMaxWriteDelay());
- assertEquals(defaultCacheWriterConfig.getRateLimitPerSecond(), config2.getCacheWriterConfiguration().getRateLimitPerSecond());
- assertEquals(defaultCacheWriterConfig.getWriteCoalescing(), config2.getCacheWriterConfiguration().getWriteCoalescing());
- assertEquals(defaultCacheWriterConfig.getWriteBatching(), config2.getCacheWriterConfiguration().getWriteBatching());
- assertEquals(defaultCacheWriterConfig.getWriteBatchSize(), config2.getCacheWriterConfiguration().getWriteBatchSize());
- assertEquals(defaultCacheWriterConfig.getRetryAttempts(), config2.getCacheWriterConfiguration().getRetryAttempts());
- assertEquals(defaultCacheWriterConfig.getRetryAttemptDelaySeconds(), config2.getCacheWriterConfiguration().getRetryAttemptDelaySeconds());
-
- CacheConfiguration config3 = configs.get("writeThroughCache3");
- assertNotNull(config3.getCacheWriterConfiguration());
- assertEquals(CacheWriterConfiguration.WriteMode.WRITE_THROUGH, config3.getCacheWriterConfiguration().getWriteMode());
- assertEquals(defaultCacheWriterConfig.getCacheWriterFactoryConfiguration(), config3.getCacheWriterConfiguration()
- .getCacheWriterFactoryConfiguration());
- assertEquals(true, config3.getCacheWriterConfiguration().getNotifyListenersOnException());
- assertEquals(30, config3.getCacheWriterConfiguration().getMaxWriteDelay());
- assertEquals(10, config3.getCacheWriterConfiguration().getRateLimitPerSecond());
- assertEquals(true, config3.getCacheWriterConfiguration().getWriteCoalescing());
- assertEquals(true, config3.getCacheWriterConfiguration().getWriteBatching());
- assertEquals(8, config3.getCacheWriterConfiguration().getWriteBatchSize());
- assertEquals(20, config3.getCacheWriterConfiguration().getRetryAttempts());
- assertEquals(60, config3.getCacheWriterConfiguration().getRetryAttemptDelaySeconds());
-
- CacheConfiguration config4 = configs.get("writeThroughCache4");
- assertNotNull(config4.getCacheWriterConfiguration());
- assertEquals(CacheWriterConfiguration.WriteMode.WRITE_THROUGH, config4.getCacheWriterConfiguration().getWriteMode());
- assertEquals("net.sf.ehcache.writer.TestCacheWriterFactory", config4.getCacheWriterConfiguration().getCacheWriterFactoryConfiguration()
- .getFullyQualifiedClassPath());
- assertEquals(null, config4.getCacheWriterConfiguration().getCacheWriterFactoryConfiguration().getProperties());
- assertEquals(null, config4.getCacheWriterConfiguration().getCacheWriterFactoryConfiguration().getPropertySeparator());
- assertEquals(false, config4.getCacheWriterConfiguration().getNotifyListenersOnException());
- assertEquals(0, config4.getCacheWriterConfiguration().getMaxWriteDelay());
- assertEquals(0, config4.getCacheWriterConfiguration().getRateLimitPerSecond());
- assertEquals(false, config4.getCacheWriterConfiguration().getWriteCoalescing());
- assertEquals(false, config4.getCacheWriterConfiguration().getWriteBatching());
- assertEquals(1, config4.getCacheWriterConfiguration().getWriteBatchSize());
- assertEquals(0, config4.getCacheWriterConfiguration().getRetryAttempts());
- assertEquals(0, config4.getCacheWriterConfiguration().getRetryAttemptDelaySeconds());
-
- CacheConfiguration config5 = configs.get("writeBehindCache5");
- assertNotNull(config5.getCacheWriterConfiguration());
- assertEquals(CacheWriterConfiguration.WriteMode.WRITE_BEHIND, config5.getCacheWriterConfiguration().getWriteMode());
- assertEquals("net.sf.ehcache.writer.TestCacheWriterFactory", config5.getCacheWriterConfiguration().getCacheWriterFactoryConfiguration()
- .getFullyQualifiedClassPath());
- assertEquals("just.some.property=test; another.property=test2", config5.getCacheWriterConfiguration().getCacheWriterFactoryConfiguration()
- .getProperties());
- assertEquals(";", config5.getCacheWriterConfiguration().getCacheWriterFactoryConfiguration().getPropertySeparator());
- assertEquals(true, config5.getCacheWriterConfiguration().getNotifyListenersOnException());
- assertEquals(8, config5.getCacheWriterConfiguration().getMaxWriteDelay());
- assertEquals(5, config5.getCacheWriterConfiguration().getRateLimitPerSecond());
- assertEquals(true, config5.getCacheWriterConfiguration().getWriteCoalescing());
- assertEquals(false, config5.getCacheWriterConfiguration().getWriteBatching());
- assertEquals(1, config5.getCacheWriterConfiguration().getWriteBatchSize());
- assertEquals(2, config5.getCacheWriterConfiguration().getRetryAttempts());
- assertEquals(2, config5.getCacheWriterConfiguration().getRetryAttemptDelaySeconds());
- Ehcache cache5 = configurationHelper.createCacheFromName("writeBehindCache5");
- Properties properties5 = ((TestCacheWriter) cache5.getRegisteredCacheWriter()).getProperties();
- assertEquals(2, properties5.size());
- assertEquals("test", properties5.getProperty("just.some.property"));
- assertEquals("test2", properties5.getProperty("another.property"));
- }
-
-
- private void helpTestListenFor(Configuration configuration, String cacheName, NotificationScope expectedScope) {
- CacheConfiguration cache = configuration.getCacheConfigurations().get(cacheName);
- List listenerConfigs = cache.getCacheEventListenerConfigurations();
- assertEquals(1, listenerConfigs.size());
-
- CacheConfiguration.CacheEventListenerFactoryConfiguration listenerFactoryConfig = listenerConfigs.get(0);
- assertEquals(expectedScope, listenerFactoryConfig.getListenFor());
- }
-
- @Test
- public void testListenForAttributeParsing() {
- File file = new File(TEST_CONFIG_DIR + "ehcache-listener-scope.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
-
- helpTestListenFor(configuration, "listenDefault", NotificationScope.ALL);
- helpTestListenFor(configuration, "listenAll", NotificationScope.ALL);
- helpTestListenFor(configuration, "listenLocal", NotificationScope.LOCAL);
- helpTestListenFor(configuration, "listenRemote", NotificationScope.REMOTE);
- }
-
-
- @Test
- public void testCacheConfigurationWithNoName() {
-
- //Don't set cache name
- CacheConfiguration cacheConfigurationTest3Cache = new CacheConfiguration().maxElementsInMemory(10)
- .eternal(true).memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LRU).overflowToDisk(false);
-
- try {
- Cache cache = new Cache(cacheConfigurationTest3Cache);
- } catch (InvalidConfigurationException e) {
- //expected
- }
-
- }
-
- @Test
- public void testValidStoreConfigElements() throws Exception {
- File file = new File(TEST_CONFIG_DIR + "ehcache-store.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
-
- CacheConfiguration cacheConfiguration = configuration.getCacheConfigurations().get("offheap1");
- assertEquals(16777216, cacheConfiguration.getMaxMemoryOffHeapInBytes());
- assertEquals(true, cacheConfiguration.isOverflowToOffHeap());
-
- cacheConfiguration = configuration.getCacheConfigurations().get("offheap2");
- assertEquals(2147483648L, cacheConfiguration.getMaxMemoryOffHeapInBytes());
- assertEquals(false, cacheConfiguration.isOverflowToOffHeap());
-
- assertEquals(2164260864L, configuration.getTotalConfiguredOffheap());
- }
-
- @Test
- public void testTerracottaConfigurationForWAN() {
- File file = new File(TEST_CONFIG_DIR + "terracotta/ehcache-terracotta-wan.xml");
- Configuration configuration = ConfigurationFactory.parseConfiguration(file);
- assertEquals(true, configuration.getTerracottaConfiguration().isWanEnabledTSA());
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/DiskStorePathManagerTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/DiskStorePathManagerTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/DiskStorePathManagerTest.java (revision 0)
@@ -1,124 +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 static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.lang.reflect.Field;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Assume;
-import org.junit.Test;
-
-public class DiskStorePathManagerTest {
- private DiskStorePathManager dspm1;
- private DiskStorePathManager dspm2;
-
- @After
- public void tearDown() {
- if (dspm2 != null) {
- dspm2.releaseLock();
- }
- if (dspm1 != null) {
- dspm1.releaseLock();
- }
- }
-
- @Test
- public void testDefault() throws Exception {
- dspm1 = new DiskStorePathManager();
- dspm1.getFile("foo");
- assertFalse(dspm1.isAutoCreated());
- assertTrue(dspm1.isDefault());
-
- dspm2 = new DiskStorePathManager();
- dspm2.getFile("foo");
- assertTrue(dspm2.isAutoCreated());
- assertFalse(dspm2.isDefault());
-
- Assert.assertFalse(getDiskStorePath(dspm1).equals(getDiskStorePath(dspm2)));
- }
-
- @Test
- public void testCollisionSameThread() throws Exception {
- String diskStorePath = getTempDir("testCollisionSameThread") + "/a/b/c";
-
- dspm1 = new DiskStorePathManager(diskStorePath);
- dspm1.getFile("foo");
- assertFalse(dspm1.isAutoCreated());
- assertFalse(dspm1.isDefault());
-
- dspm2 = new DiskStorePathManager(diskStorePath);
- dspm2.getFile("foo");
- assertTrue(dspm2.isAutoCreated());
- assertFalse(dspm2.isDefault());
-
- Assert.assertFalse(getDiskStorePath(dspm1).equals(getDiskStorePath(dspm2)));
- }
-
- @Test
- public void testCollisionDifferentThread() throws Exception {
- final String diskStorePath = getTempDir("testCollisionDifferentThread");
- dspm1 = new DiskStorePathManager(diskStorePath);
- dspm1.getFile("foo");
- Thread newThread = new Thread() {
- @Override
- public void run() {
- dspm2 = new DiskStorePathManager(diskStorePath);
- dspm2.getFile("foo");
- }
- };
- newThread.start();
- newThread.join(10 * 1000L);
-
- Assert.assertFalse(getDiskStorePath(dspm1).equals(getDiskStorePath(dspm2)));
- }
-
- @Test(expected = CacheException.class)
- public void testIllegalPath() {
- Assume.assumeTrue(System.getProperty("os.name").contains("Windows"));
- String diskStorePath = getTempDir("testIllegalPath") + "/com1";
- dspm1 = new DiskStorePathManager(diskStorePath);
- dspm1.getFile("foo");
- }
-
- private String getTempDir(String dirname) {
- String base = System.getProperty("basedir") != null ? System.getProperty("basedir") : ".";
- File target = new File(base, "target");
- File tempBase = new File(target, DiskStorePathManagerTest.class.getSimpleName());
- File tempDir = new File(tempBase, dirname);
- tempDir.mkdirs();
- Assert.assertTrue(tempDir.isDirectory());
- return tempDir.getAbsolutePath();
- }
-
- public static File getDiskStorePath(DiskStorePathManager manager) throws Exception {
- Field pathField = DiskStorePathManager.class.getDeclaredField("path");
- pathField.setAccessible(true);
-
- Object pathObject = pathField.get(manager);
-
- Field diskStorePathField = pathObject.getClass().getDeclaredField("diskStorePath");
- diskStorePathField.setAccessible(true);
-
- return (File) diskStorePathField.get(pathObject);
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/transaction/AbstractSoftLockManager.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/transaction/AbstractSoftLockManager.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/transaction/AbstractSoftLockManager.java (revision 0)
@@ -1,166 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.transaction;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentMap;
-
-import net.sf.ehcache.Element;
-import net.sf.ehcache.store.Store;
-import net.sf.ehcache.transaction.local.LocalTransactionContext;
-
-/**
- * An abstract map backed soft lock manager.
- *
- * @author Chris Dennis
- */
-public abstract class AbstractSoftLockManager implements SoftLockManager {
-
- private final String cacheName;
- private final SoftLockFactory lockFactory;
-
- /**
- * Create an abstract soft lock manager for the given cache name and soft lock factory.
- *
- * @param cacheName name of the cache
- * @param lockFactory factory of managed locks
- */
- public AbstractSoftLockManager(String cacheName, SoftLockFactory lockFactory) {
- this.cacheName = cacheName;
- this.lockFactory = lockFactory;
- }
-
- /**
- * Return the map of all soft locks.
- *
- * @return the map of all locks
- */
- protected abstract ConcurrentMap getAllLocks();
-
- /**
- * Return the map of all locks that are for new keys.
- *
- * @return the map of all new key locks
- */
- protected abstract ConcurrentMap getNewKeyLocks();
-
- /**
- * {@inheritDoc}
- */
- public SoftLockID createSoftLockID(TransactionID transactionID, Object key, Element newElement, Element oldElement) {
- if (newElement != null && newElement.getObjectValue() instanceof SoftLockID) {
- throw new AssertionError("newElement must not contain a soft lock ID");
- }
- if (oldElement != null && oldElement.getObjectValue() instanceof SoftLockID) {
- throw new AssertionError("oldElement must not contain a soft lock ID");
- }
-
- SoftLockID lockId = new SoftLockID(transactionID, key, newElement, oldElement);
-
- if (getAllLocks().containsKey(lockId)) {
- return lockId;
- } else {
- SoftLock lock = lockFactory.newSoftLock(this, key);
-
- if (getAllLocks().putIfAbsent(lockId, lock) != null) {
- throw new AssertionError();
- } else {
- if (oldElement == null) {
- getNewKeyLocks().put(lockId, Boolean.TRUE);
- }
- return lockId;
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public SoftLock findSoftLockById(SoftLockID softLockId) {
- return getAllLocks().get(softLockId);
- }
-
- /**
- * {@inheritDoc}
- */
- public Set getKeysInvisibleInContext(LocalTransactionContext currentTransactionContext, Store underlyingStore) {
- Set invisibleKeys = new HashSet();
-
- // all new keys added into the store are invisible
- invisibleKeys.addAll(getNewKeys());
-
- List currentTransactionContextSoftLocks = currentTransactionContext.getSoftLocksForCache(cacheName);
- for (SoftLock softLock : currentTransactionContextSoftLocks) {
- Element e = underlyingStore.getQuiet(softLock.getKey());
- if (e.getObjectValue() instanceof SoftLockID) {
- SoftLockID softLockId = (SoftLockID) e.getObjectValue();
- if (softLock.getElement(currentTransactionContext.getTransactionId(), softLockId) == null) {
- // if the soft lock's element is null in the current transaction then the key is invisible
- invisibleKeys.add(softLock.getKey());
- } else {
- // if the soft lock's element is not null in the current transaction then the key is visible
- invisibleKeys.remove(softLock.getKey());
- }
- }
- }
-
- return invisibleKeys;
- }
-
- /**
- * {@inheritDoc}
- */
- public Set collectAllSoftLocksForTransactionID(TransactionID transactionID) {
- Set result = new HashSet();
-
- for (Entry entry : getAllLocks().entrySet()) {
- if (entry.getKey().getTransactionID().equals(transactionID)) {
- result.add(entry.getValue());
- }
- }
-
- return result;
- }
-
- /**
- * {@inheritDoc}
- */
- public void clearSoftLock(SoftLock softLock) {
-
- for (Map.Entry entry : getAllLocks().entrySet()) {
- if (entry.getValue() == softLock) {
- getAllLocks().remove(entry.getKey());
- getNewKeyLocks().remove(entry.getKey());
- break;
- }
- }
- }
-
- private Set getNewKeys() {
- Set result = new HashSet();
-
- for (SoftLockID softLock : getNewKeyLocks().keySet()) {
- result.add(softLock.getKey());
- }
-
- return result;
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/distribution/RMIDistributedCacheIT.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/distribution/RMIDistributedCacheIT.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/distribution/RMIDistributedCacheIT.java (revision 0)
@@ -1,173 +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.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.util.RetryAssert;
-
-import org.hamcrest.collection.IsEmptyCollection;
-import org.junit.After;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.junit.Before;
-import org.junit.Test;
-
-import java.rmi.Naming;
-import java.util.Date;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-/**
- * Note these tests need a live network interface running in multicast mode to work
- *
- * @author Greg Luck
- * @version $Id: RMIDistributedCacheIT.java 8870 2014-04-03 20:27:43Z cdennis $
- */
-public class RMIDistributedCacheIT extends AbstractRMITest {
-
-
- /**
- * manager
- */
- protected CacheManager manager;
-
- /**
- * the cache we wish to test
- */
- private Ehcache sampleCache1;
-
-
- private final String hostName = "localhost";
-
- private final Integer port = Integer.valueOf(5010);
- private final Integer remoteObjectPort = Integer.valueOf(0);
- private Element element;
- private CachePeer cache1Peer;
- private CachePeer cache2Peer;
-
- /**
- * {@inheritDoc}
- *
- * @throws Exception
- */
- @Before
- public void setUp() throws Exception {
- manager = new CacheManager(createRMICacheManagerConfiguration()
- .cache(createAsynchronousCache().name("asynchronousCache"))
- .cache(createAsynchronousCacheViaInvalidate().name("asynchronousCacheViaInvalidate"))
- .name("RMIDistributedCacheTest"));
- sampleCache1 = manager.getCache("asynchronousCache");
- sampleCache1.removeAll();
- element = new Element("key", new Date());
- sampleCache1.put(element);
- CacheManagerPeerListener cacheManagerPeerListener =
- new RMICacheManagerPeerListener(hostName, port, remoteObjectPort, manager, Integer.valueOf(2000));
- cacheManagerPeerListener.init();
- cache1Peer = (CachePeer) Naming.lookup(createNamingUrl() + "asynchronousCache");
- cache2Peer = (CachePeer) Naming.lookup(createNamingUrl() + "asynchronousCacheViaInvalidate");
-
- }
-
- /**
- * Shutdown the cache
- */
- @After
- public void tearDown() throws InterruptedException {
-
- Thread.sleep(10);
- manager.shutdown();
- int i = 0;
-
- RetryAssert.assertBy(30, TimeUnit.SECONDS, new Callable>() {
- public Set call() throws Exception {
- return getActiveReplicationThreads();
- }
- }, IsEmptyCollection.empty());
- }
-
- /**
- * Getting an RMI Server going is a big deal
- */
- @Test
- public void testCreation() throws Exception {
- assertNotNull(cache1Peer);
- assertNotNull(cache2Peer);
- }
-
- /**
- * The use of one-time registry creation and Naming.rebind should mean we can create as many listeneres as we like.
- * They will simply replace the ones that were there.
- */
- @Test
- public void testMultipleCreationOfRMIServers() throws Exception {
- RMICacheManagerPeerListener[] listeners = new RMICacheManagerPeerListener[100];
- for (int i = 0; i < 100; i++) {
- listeners[i] = new RMICacheManagerPeerListener(hostName, port, remoteObjectPort, manager, Integer.valueOf(2000));
- }
- cache1Peer = (CachePeer) Naming.lookup(createNamingUrl() + "asynchronousCache");
- assertNotNull(cache1Peer);
-
- for (int i = 0; i < 100; i++) {
- listeners[i].dispose();
- }
- }
-
-
- /**
- * Same as the above with remoteObjectPort the same.
- */
- @Test
- public void testMultipleCreationOfRMIServersWithSpecificRemoteObjectPort() throws Exception {
- RMICacheManagerPeerListener[] listeners = new RMICacheManagerPeerListener[100];
- for (int i = 0; i < 100; i++) {
- listeners[i] = new RMICacheManagerPeerListener(hostName, port, Integer.valueOf(45000), manager, Integer.valueOf(2000));
- }
- cache1Peer = (CachePeer) Naming.lookup(createNamingUrl() + "asynchronousCache");
- assertNotNull(cache1Peer);
- cache1Peer.put(new Element(1, 4));
-
- for (int i = 0; i < 100; i++) {
- listeners[i].dispose();
- }
- }
-
-
- private String createNamingUrl() {
- return "//" + hostName + ":" + port + "/";
- }
-
- /**
- * Attempts to get the cache name
- *
- * @throws java.net.MalformedURLException
- * @throws java.rmi.NotBoundException
- * @throws java.rmi.RemoteException
- */
- @Test
- public void testGetName() throws Exception {
- String lookupCacheName = cache1Peer.getName();
- assertEquals("asynchronousCache", lookupCacheName);
- lookupCacheName = cache2Peer.getName();
- assertEquals("asynchronousCacheViaInvalidate", lookupCacheName);
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/search/CopyOnRWSearchTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/search/CopyOnRWSearchTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/search/CopyOnRWSearchTest.java (revision 0)
@@ -1,360 +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 net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.SearchAttribute;
-import net.sf.ehcache.config.Searchable;
-import net.sf.ehcache.search.Person.Gender;
-import net.sf.ehcache.search.attribute.DynamicAttributesExtractor;
-import net.sf.ehcache.search.impl.GroupedResultImpl;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-@RunWith(Parameterized.class)
-public class CopyOnRWSearchTest {
-
- private final boolean copyOnRead;
- private final boolean copyOnWrite;
-
- @Parameters(name = "copyOnRead:{0}, copyOnWrite:{1}")
- public static Collection data() {
- Object[][] data = new Object[][] { { true, false }, { false, true }, { true, true } };
- return Arrays.asList(data);
- }
-
- public CopyOnRWSearchTest(boolean copyOnRead, boolean copyOnWrite) {
- this.copyOnRead = copyOnRead;
- this.copyOnWrite = copyOnWrite;
- }
-
- private CacheConfiguration getBaseCacheConfiguration() {
- return new CacheConfiguration("copy-search", 0).copyOnRead(copyOnRead).copyOnWrite(copyOnWrite);
- }
-
- @Test
- public void testExpressionAttributeExtractorCache() throws Exception {
- CacheConfiguration config = getBaseCacheConfiguration();
- config.searchable(new Searchable().
- searchAttribute(new SearchAttribute().name("age").expression("value.getAge()")).
- searchAttribute(new SearchAttribute().name("gender").expression("value.getGender()")).
- searchAttribute(new SearchAttribute().name("name").expression("value.getName()")));
- testCacheWithConfiguration(config);
- }
-
- @Test
- public void testCustomAttributeExtractorCache() throws Exception {
- CacheConfiguration config = getBaseCacheConfiguration();
- config.searchable(new Searchable().
- searchAttribute(new SearchAttribute().name("age").className("net.sf.ehcache.search.TestAttributeExtractor")).
- searchAttribute(new SearchAttribute().name("gender").expression("value.getGender()")).
- searchAttribute(new SearchAttribute().name("name").expression("value.getName()")));
- testCacheWithConfiguration(config);
- }
-
- @Test
- public void testBeanAttributeExtractorCache() throws Exception {
- CacheConfiguration config = getBaseCacheConfiguration();
- config.searchable(new Searchable().
- searchAttribute(new SearchAttribute().name("age")).
- searchAttribute(new SearchAttribute().name("gender")).
- searchAttribute(new SearchAttribute().name("name")));
- testCacheWithConfiguration(config);
- }
-
- @Test
- public void testBeanAttributeExtractorWithTypeCache() throws Exception {
- CacheConfiguration config = getBaseCacheConfiguration();
- config.searchable(new Searchable().
- searchAttribute(new SearchAttribute().name("age").type("int")).
- searchAttribute(new SearchAttribute().name("gender").type(Gender.class.getName())).
- searchAttribute(new SearchAttribute().name("name").type("String")));
- testCacheWithConfiguration(config);
- }
-
- @Test
- public void testDynamicAttributeExtractorCache() throws Exception {
- CacheConfiguration config = getBaseCacheConfiguration();
- Searchable searchable = new Searchable();
- searchable.allowDynamicIndexing(true);
- config.searchable(searchable);
- config.setDynamicAttributesExtractor(new DynamicAttributesExtractor() {
- @Override
- public Map attributesFor(Element element) {
- Map map = new HashMap();
- map.put("age", ((Person)element.getObjectValue()).getAge());
- map.put("gender", ((Person)element.getObjectValue()).getGender());
- map.put("name", ((Person)element.getObjectValue()).getName());
- return map;
- }
- });
- testCacheWithConfiguration(config);
- }
-
- private void testCacheWithConfiguration(CacheConfiguration config) throws Exception {
- CacheManager cacheManager = new CacheManager();
- try {
- Ehcache cache = new Cache(config);
- cacheManager.addCache(cache);
-
- assertTrue(cache.isSearchable());
-
- //This data should appear in the search results
- SearchTestUtil.populateData(cache);
-
- basicQueries(cache);
-
- valueQuery(cache);
- } finally {
- cacheManager.shutdown();
- }
- }
-
- private void valueQuery(Ehcache cache) {
- Query query = cache.createQuery();
- query.includeValues();
- query.addCriteria(cache.getSearchAttribute("gender").eq(Gender.FEMALE));
- query.end();
-
- Results results = query.execute();
- assertThat(results.all().get(0).getValue(), instanceOf(Person.class));
- }
-
- private void basicQueries(Ehcache cache) {
- Query query;
- Attribute age = cache.getSearchAttribute("age");
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(age.ne(35));
- query.end();
- verify(query, 2, 4);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").lt(30));
- query.end();
- query.execute();
- verify(query, 2);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").le(30));
- query.end();
- query.execute();
- verify(query, 2, 4);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").in(new HashSet(Arrays.asList(23, 35))));
- query.end();
- query.execute();
- verify(query, 1, 2, 3);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").gt(30));
- query.end();
- query.execute();
- verify(query, 1, 3);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").between(23, 35, true, false));
- query.end();
- query.execute();
- verify(query, 2, 4);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").ge(30));
- query.end();
- query.execute();
- verify(query, 1, 3, 4);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").eq(35).or(cache.getSearchAttribute("gender").eq(Gender.FEMALE)));
- query.end();
- verify(query, 1, 2, 3);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").eq(35).and(cache.getSearchAttribute("gender").eq(Gender.MALE)));
- query.end();
- verify(query, 1, 3);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("age").eq(35).and(cache.getSearchAttribute("gender").eq(Gender.FEMALE)));
- query.end();
- verify(query);
-
- query = cache.createQuery();
- query.includeKeys();
- query.addCriteria(cache.getSearchAttribute("gender").eq(Gender.MALE).not());
- query.end();
- verify(query, 2);
-
- try {
- cache.getSearchAttribute("DOES_NOT_EXIST_PLEASE_DO_NOT_CREATE_ME");
- fail();
- } catch (CacheException ce) {
- // expected
- }
- }
-
- private void verify(Query query, Integer... expectedKeys) {
- Results results = query.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 testBasicGroupBy() throws Exception {
- CacheConfiguration config = getBaseCacheConfiguration();
- config.searchable(new Searchable().
- searchAttribute(new SearchAttribute().name("age")).
- searchAttribute(new SearchAttribute().name("gender")).
- searchAttribute(new SearchAttribute().name("name")).
- searchAttribute(new SearchAttribute().name("department")));
- CacheManager cacheManager = new CacheManager();
-
- try {
- Ehcache cache = new Cache(config);
- cacheManager.addCache(cache);
- assertTrue(cache.isSearchable());
-
- int numOfDepts = 10;
- int numOfMalesPerDept = 100;
- int numOfFemalesPerDept = 100;
-
- for (int i = 0; i < numOfDepts; i++) {
- for (int j = 0; j < numOfMalesPerDept; j++) {
- cache.put(new Element("male" + i + "-" + j, new Person("male" + j, j, Gender.MALE, "department" + i)));
- }
-
- for (int j = 0; j < numOfFemalesPerDept; j++) {
- cache.put(new Element("female" + i + "-" + j, new Person("female" + j, j, Gender.FEMALE, "department" + i)));
- }
- }
-
-
- Query query;
- Results results;
-
- query = cache.createQuery();
- query.includeAttribute(cache.getSearchAttribute("department"));
- query.includeAttribute(cache.getSearchAttribute("gender"));
- query.includeAggregator(cache.getSearchAttribute("age").sum());
- query.includeAggregator(cache.getSearchAttribute("age").min());
- query.includeAggregator(cache.getSearchAttribute("age").max());
- query.addGroupBy(cache.getSearchAttribute("department"));
- query.addOrderBy(cache.getSearchAttribute("department"), Direction.DESCENDING);
- query.addOrderBy(cache.getSearchAttribute("gender"), Direction.ASCENDING);
- query.addGroupBy(cache.getSearchAttribute("gender"));
- query.end();
-
- results = query.execute();
-
- assertEquals(numOfDepts * 2, results.size());
-
- int i = 1;
- for (Iterator iter = results.all().iterator(); iter.hasNext();) {
- Result maleResult = iter.next();
-
- System.out.println("XXXXXXXXX: " + maleResult);
- assertTrue(maleResult instanceof GroupedResultImpl);
- assertEquals("department" + (numOfDepts - i), maleResult.getAttribute(cache.getSearchAttribute("department")));
- assertEquals(Gender.MALE, maleResult.getAttribute(cache.getSearchAttribute("gender")));
-
- Map groupByValues = ((GroupedResultImpl) maleResult).getGroupByValues();
- assertEquals(2, groupByValues.size());
- assertEquals("department" + (numOfDepts - i), groupByValues.get("department"));
- assertEquals(Gender.MALE, groupByValues.get("gender"));
-
- List aggregateResults = maleResult.getAggregatorResults();
- assertEquals(3, aggregateResults.size());
- assertEquals(numOfMalesPerDept * (numOfMalesPerDept - 1) / 2, ((Long) aggregateResults.get(0)).intValue());
- assertEquals(0, ((Integer) aggregateResults.get(1)).intValue());
- assertEquals(numOfMalesPerDept - 1, ((Integer) aggregateResults.get(2)).intValue());
-
- Result femaleResult = iter.next();
- System.out.println("XXXXXXXXX: " + femaleResult);
-
- assertEquals("department" + (numOfDepts - i), femaleResult.getAttribute(cache.getSearchAttribute("department")));
- assertEquals(Gender.FEMALE, femaleResult.getAttribute(cache.getSearchAttribute("gender")));
-
- assertTrue(femaleResult instanceof GroupedResultImpl);
- groupByValues = ((GroupedResultImpl) femaleResult).getGroupByValues();
- assertEquals(2, groupByValues.size());
- assertEquals("department" + (numOfDepts - i), groupByValues.get("department"));
- assertEquals(Gender.FEMALE, groupByValues.get("gender"));
-
- aggregateResults = femaleResult.getAggregatorResults();
- assertEquals(3, aggregateResults.size());
- assertEquals(numOfFemalesPerDept * (numOfFemalesPerDept - 1) / 2, ((Long) aggregateResults.get(0)).intValue());
- assertEquals(0, ((Integer) aggregateResults.get(1)).intValue());
- assertEquals(numOfFemalesPerDept - 1, ((Integer) aggregateResults.get(2)).intValue());
-
- i++;
- }
- } finally {
- cacheManager.shutdown();
- }
-
-
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/search/aggregator/Average.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/search/aggregator/Average.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/search/aggregator/Average.java (revision 0)
@@ -1,244 +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.aggregator;
-
-import net.sf.ehcache.search.Attribute;
-
-/**
- * Compute the average (arithmetic mean) as a double
- *
- * @author teck
- */
-public class Average implements AggregatorInstance {
-
- private final Attribute> attribute;
-
- private Engine engine;
-
- /**
- * @param attribute
- */
- public Average(Attribute> attribute) {
- this.attribute = attribute;
- }
-
- /**
- * {@inheritDoc}
- */
- public Average createClone() {
- return new Average(attribute);
- }
-
- /**
- * {@inheritDoc}
- *
- * NOTE: Null values are ignored and not included in the computation
- */
- public void accept(Object input) throws AggregatorException {
- if (input == null) {
- return;
- }
-
- if (input instanceof Number) {
- if (engine == null) {
- engine = Engine.create((Number) input);
- } else {
- engine.accept((Number) input);
- }
- } else {
- throw new AggregatorException("Non-number type encountered: " + input.getClass());
- }
- }
-
- /**
- * {@inheritDoc}
- *
- * NOTE: null is returned if there was no input supplied to this function
- */
- public Number aggregateResult() {
- if (engine == null) {
- return null;
- } else {
- return engine.result();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Attribute getAttribute() {
- return attribute;
- }
-
- /**
- * Abstract super-class for all average calculating engines.
- */
- abstract static class Engine {
-
- /**
- * Create a type specific engine using the given initial value.
- *
- * @param value initial value
- * @return type specific engine
- */
- static Engine create(Number value) {
- if (value instanceof Float) {
- return new FloatEngine(value.floatValue());
- } else if (value instanceof Double) {
- return new DoubleEngine(value.doubleValue());
- } else if (value instanceof Long) {
- return new LongEngine(value.longValue());
- } else {
- return new IntegerEngine(value.intValue());
- }
- }
-
- /**
- * Update the engine with the given value.
- *
- * @param input data value
- */
- abstract void accept(Number input) throws AggregatorException;
-
- /**
- * Get the (current) result of this engine.
- *
- * @return engine result
- */
- abstract Number result();
-
- /**
- * An int based averaging engine.
- */
- static class IntegerEngine extends Engine {
-
- private int count;
- private long sum;
-
- /**
- * Creates a new instance starting with an initial value
- *
- * @param value initial value
- */
- IntegerEngine(int value) {
- this.count = 1;
- this.sum = value;
- }
-
- @Override
- void accept(Number input) throws AggregatorException {
- count++;
- sum += input.intValue();
- }
-
- @Override
- Number result() {
- return Float.valueOf(((float) sum) / count);
- }
- }
-
- /**
- * A long based averaging engine.
- */
- static class LongEngine extends Engine {
-
- private int count;
- private long sum;
-
- /**
- * Creates a new instance starting with an initial value
- *
- * @param value initial value
- */
- LongEngine(long value) {
- this.count = 1;
- this.sum = value;
- }
-
- @Override
- void accept(Number input) throws AggregatorException {
- count++;
- sum += input.longValue();
- }
-
- @Override
- Number result() {
- return Double.valueOf(((double) sum) / count);
- }
- }
-
- /**
- * A float based averaging engine.
- */
- static class FloatEngine extends Engine {
-
- private int count;
- private float sum;
-
- /**
- * Creates a new instance starting with an initial value
- *
- * @param value initial value
- */
- FloatEngine(float value) {
- this.count = 1;
- this.sum = value;
- }
-
- @Override
- void accept(Number input) throws AggregatorException {
- count++;
- sum += input.floatValue();
- }
-
- @Override
- Number result() {
- return Float.valueOf(sum / count);
- }
- }
-
- /**
- * A double based averaging engine.
- */
- static class DoubleEngine extends Engine {
-
- private int count;
- private double sum;
-
- /**
- * Creates a new instance starting with an initial value
- *
- * @param value initial value
- */
- DoubleEngine(double value) {
- this.count = 1;
- this.sum = value;
- }
-
- @Override
- void accept(Number input) throws AggregatorException {
- count++;
- sum += input.doubleValue();
- }
-
- @Override
- Number result() {
- return Double.valueOf(sum / count);
- }
- }
- }
-}
Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/wan/IllegalConfigurationException.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/wan/IllegalConfigurationException.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/wan/IllegalConfigurationException.java (revision 0)
@@ -1,23 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.modules.ehcache.wan;
-
-public class IllegalConfigurationException extends RuntimeException {
-
- public IllegalConfigurationException() {
- }
-
- public IllegalConfigurationException(final String message) {
- super(message);
- }
-
- public IllegalConfigurationException(final String message, final Throwable cause) {
- super(message, cause);
- }
-
- public IllegalConfigurationException(final Throwable cause) {
- super(cause);
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/generator/RememberingVisitor.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/generator/RememberingVisitor.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/generator/RememberingVisitor.java (revision 0)
@@ -1,62 +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.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import net.sf.ehcache.config.generator.model.AbstractDepthFirstVisitor;
-import net.sf.ehcache.config.generator.model.NodeAttribute;
-import net.sf.ehcache.config.generator.model.NodeElement;
-
-public class RememberingVisitor extends AbstractDepthFirstVisitor {
- private final Set visitedElements = new HashSet();
- private final ConcurrentMap> visitedAttributes = new ConcurrentHashMap>();
-
- public Set getVisitedElements() {
- return visitedElements;
- }
-
- public ConcurrentMap> getVisitedAttributes() {
- return visitedAttributes;
- }
-
- @Override
- protected void visitElement(NodeElement element) {
- visitedElements.add(element);
- }
-
- @Override
- protected void visitAttributes(NodeElement element, List attributes) {
- getVisitedAttributesForElement(element).addAll(attributes);
- }
-
- private Set getVisitedAttributesForElement(NodeElement element) {
- Set set = visitedAttributes.get(element);
- if (set == null) {
- set = new HashSet();
- Set prev = visitedAttributes.putIfAbsent(element, set);
- if (prev != null) {
- set = prev;
- }
- }
- return set;
- }
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/NodeElementVisitor.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/NodeElementVisitor.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/NodeElementVisitor.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.config.generator.model;
-
-/**
- * Interface for visiting a {@link NodeElement}
- *
- * @author Abhishek Sanoujam
- *
- */
-public interface NodeElementVisitor {
-
- /**
- * Visit the element
- *
- * @param element
- * the element to be visited
- */
- void visit(NodeElement element);
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/ClientArrayValues2.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/ClientArrayValues2.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/ClientArrayValues2.java (revision 0)
@@ -1,30 +0,0 @@
-package org.terracotta.ehcache.tests;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.Element;
-
-import org.terracotta.toolkit.Toolkit;
-
-public class ClientArrayValues2 extends ClientBase {
-
- public ClientArrayValues2(String[] args) {
- super("test", args);
- }
-
- public static void main(String[] args) {
- new ClientArrayValues2(args).run();
- }
-
- @Override
- protected void runTest(Cache cache, Toolkit toolkit) throws Throwable {
- Element elem = cache.get("key");
- if(elem == null) {
- throw new AssertionError("No element!");
- }
- String[] value = (String[])elem.getValue();
- if(value.length != 3 || !value[0].equals("a") || !value[1].equals("b") || !value[2].equals("c")) {
- throw new AssertionError("Didn't get String[] { \"a\", \"b\", \"c\"");
- }
-
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/terracotta/ehcache-terracotta-offheap.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/terracotta/ehcache-terracotta-offheap.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/terracotta/ehcache-terracotta-offheap.xml (revision 0)
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/src/main/java/net/sf/ehcache/management/service/impl/DfltSamplerRepositoryServiceV2.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/src/main/java/net/sf/ehcache/management/service/impl/DfltSamplerRepositoryServiceV2.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/src/main/java/net/sf/ehcache/management/service/impl/DfltSamplerRepositoryServiceV2.java (revision 0)
@@ -1,1159 +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.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.CopyOnWriteArraySet;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.ClusteredInstanceFactoryAccessor;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.CacheConfigurationListener;
-import net.sf.ehcache.config.ManagementRESTServiceConfiguration;
-import net.sf.ehcache.event.CacheManagerEventListener;
-import net.sf.ehcache.management.resource.CacheConfigEntityV2;
-import net.sf.ehcache.management.resource.CacheEntityV2;
-import net.sf.ehcache.management.resource.CacheManagerConfigEntityV2;
-import net.sf.ehcache.management.resource.CacheManagerEntityV2;
-import net.sf.ehcache.management.resource.CacheStatisticSampleEntityV2;
-import net.sf.ehcache.management.resource.QueryResultsEntityV2;
-import net.sf.ehcache.management.sampled.CacheManagerSampler;
-import net.sf.ehcache.management.sampled.CacheManagerSamplerImpl;
-import net.sf.ehcache.management.sampled.CacheSampler;
-import net.sf.ehcache.management.sampled.CacheSamplerImpl;
-import net.sf.ehcache.management.service.CacheManagerServiceV2;
-import net.sf.ehcache.management.service.CacheServiceV2;
-import net.sf.ehcache.management.service.EntityResourceFactoryV2;
-import net.sf.ehcache.management.service.SamplerRepositoryServiceV2;
-import net.sf.ehcache.terracotta.ClusteredInstanceFactory;
-
-import org.terracotta.management.ServiceExecutionException;
-import org.terracotta.management.ServiceLocator;
-import org.terracotta.management.resource.AgentEntityV2;
-import org.terracotta.management.resource.AgentMetadataEntityV2;
-import org.terracotta.management.resource.Representable;
-import org.terracotta.management.resource.ResponseEntityV2;
-import org.terracotta.management.resource.events.EventEntityV2;
-import org.terracotta.management.resource.exceptions.ExceptionUtils;
-import org.terracotta.management.resource.services.AgentServiceV2;
-import org.terracotta.management.resource.services.LicenseService;
-import org.terracotta.management.resource.services.Utils;
-import org.terracotta.management.resource.services.events.EventServiceV2;
-
-/**
- * A controller class registering new {@link CacheManager}.
- *
- * An {@link EntityResourceFactoryV2} implementation that interacts with the native Ehcache API.
- *
- * A {@link CacheServiceV2} implementation that interacts with the native Ehcache API to manipulate {@link Cache}
- * objects.
- *
- * @author brandony
- */
-public class DfltSamplerRepositoryServiceV2 implements SamplerRepositoryServiceV2,
- EntityResourceFactoryV2, CacheManagerServiceV2, CacheServiceV2, AgentServiceV2,
- EventServiceV2 {
-
- public static final String AGENCY = "Ehcache";
-
- final Set listeners = new CopyOnWriteArraySet();
-
- /**
- * Guarded By cacheManagerSamplerRepoLock
- */
- private final Map cacheManagerSamplerRepo = new HashMap();
-
- private final ReadWriteLock cacheManagerSamplerRepoLock = new ReentrantReadWriteLock();
- protected final ManagementRESTServiceConfiguration configuration;
-
- private final Map configurationChangeListenerMap = new HashMap();
-
- private final RemoteAgentEndpointImpl remoteAgentEndpoint;
-
- public DfltSamplerRepositoryServiceV2(ManagementRESTServiceConfiguration configuration,
- RemoteAgentEndpointImpl remoteAgentEndpoint) {
- this.configuration = configuration;
- this.remoteAgentEndpoint = remoteAgentEndpoint;
- }
-
- private static void enableNonStopFor(SamplerRepoEntry samplerRepoEntry, boolean enable) {
- ClusteredInstanceFactory clusteredInstanceFactory = ClusteredInstanceFactoryAccessor.getClusteredInstanceFactory(samplerRepoEntry.cacheManager);
- if (clusteredInstanceFactory != null) {
- clusteredInstanceFactory.enableNonStopForCurrentThread(enable);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void dispose() {
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void register(CacheManager cacheManager) {
- String name = cacheManager.getName();
-
- cacheManagerSamplerRepoLock.writeLock().lock();
- try {
- if (!cacheManagerSamplerRepo.containsKey(name)) {
- SamplerRepoEntry entry = new SamplerRepoEntry(cacheManager);
- cacheManager.setCacheManagerEventListener(entry);
- cacheManagerSamplerRepo.put(name, entry);
- }
- } finally {
- cacheManagerSamplerRepoLock.writeLock().unlock();
- }
-
- Collection> cacheEntities = new ArrayList>();
- String[] cacheNames = cacheManager.getCacheNames();
- for (String cacheName : cacheNames) {
- Map cacheAttributes = new HashMap();
- cacheAttributes.put("version", this.getClass().getPackage().getImplementationVersion());
- cacheAttributes.put("agentId", Representable.EMBEDDED_AGENT_ID);
- cacheAttributes.put("name", cacheName);
- Collection createCacheEntities = createCacheEntities(
- Collections.singleton(name), Collections.singleton(cacheName), null).getEntities();
- if (createCacheEntities != null && !createCacheEntities.isEmpty()) {
- cacheAttributes.put("attributes", createCacheEntities.iterator().next().getAttributes());
- }
- cacheEntities.add(cacheAttributes);
- }
-
- EventEntityV2 eventEntityV2 = new EventEntityV2();
- ResponseEntityV2 responseEntity = createCacheManagerEntities(Collections.singleton(name), null);
- CacheManagerEntityV2 cacheManagerEntity = responseEntity.getEntities().iterator().next();
- eventEntityV2.setAgentId(Representable.EMBEDDED_AGENT_ID);
- eventEntityV2.setType("EHCACHE.CACHEMANAGER.ADDED");
- eventEntityV2.getRootRepresentables().put("attributes", cacheManagerEntity.getAttributes());
- eventEntityV2.getRootRepresentables().put("caches", cacheEntities);
- eventEntityV2.getRootRepresentables().put("cacheManagerName", name);
- cacheManager.sendManagementEvent(eventEntityV2, eventEntityV2.getType());
- for (EventListener eventListener : listeners) {
- eventListener.onEvent(eventEntityV2);
- }
-
- PropertyChangeListener pcl = new ConfigurationPropertyChangeListener(cacheManager);
- cacheManager.getConfiguration().addPropertyChangeListener(pcl);
- configurationChangeListenerMap.put(cacheManager.getName(), pcl);
- }
-
- class ConfigurationPropertyChangeListener implements PropertyChangeListener {
- private CacheManager cacheManager;
-
- ConfigurationPropertyChangeListener(CacheManager cacheManager) {
- this.cacheManager = cacheManager;
-
- }
- @Override
- public void propertyChange(PropertyChangeEvent pce) {
- String propName = pce.getPropertyName();
-
- if (propName.equals("maxBytesLocalHeap")) {
- Map attrs = new HashMap();
-
- attrs.put("MaxBytesLocalHeap", pce.getNewValue());
- attrs.put("MaxBytesLocalHeapAsString", cacheManager.getConfiguration().getMaxBytesLocalHeapAsString());
-
- sendCacheManagerEvent(attrs, cacheManager);
- } else if (propName.equals("maxBytesLocalDisk")) {
- Map attrs = new HashMap();
-
- attrs.put("MaxBytesLocalDisk", pce.getNewValue());
- attrs.put("MaxBytesLocalDiskAsString", cacheManager.getConfiguration().getMaxBytesLocalDiskAsString());
-
- sendCacheManagerEvent(attrs, cacheManager);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void unregister(CacheManager cacheManager) {
- cacheManagerSamplerRepoLock.writeLock().lock();
-
- try {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.remove(cacheManager.getName());
- entry.destroy();
- } finally {
- cacheManagerSamplerRepoLock.writeLock().unlock();
- }
- EventEntityV2 eventEntityV2 = new EventEntityV2();
- eventEntityV2.setAgentId(Representable.EMBEDDED_AGENT_ID);
- eventEntityV2.getRootRepresentables().put("cacheManagerName", cacheManager.getName());
- eventEntityV2.getRootRepresentables().put("ClusterUUID", cacheManager.getClusterUUID());
- eventEntityV2.setType("EHCACHE.CACHEMANAGER.REMOVED");
- cacheManager.sendManagementEvent(eventEntityV2, eventEntityV2.getType());
- for (EventListener eventListener : listeners) {
- eventListener.onEvent(eventEntityV2);
- }
-
- String cacheManagerName = cacheManager.getName();
- cacheManager.getConfiguration().removePropertyChangeListener(configurationChangeListenerMap.get(cacheManagerName));
- configurationChangeListenerMap.remove(cacheManagerName);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean hasRegistered() {
- cacheManagerSamplerRepoLock.readLock().lock();
-
- try {
- return !cacheManagerSamplerRepo.isEmpty();
- } finally {
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public ResponseEntityV2 createCacheManagerEntities(Set cacheManagerNames,
- Set attributes) {
- ResponseEntityV2 responseEntityV2 = new ResponseEntityV2();
-
- String requestClusterUUID = remoteAgentEndpoint.getRequestClusterUUID();
- CacheManagerEntityBuilderV2 builder = null;
- Collection entities;
- cacheManagerSamplerRepoLock.readLock().lock();
-
- try {
- if (cacheManagerNames == null) {
- for (SamplerRepoEntry entry : cacheManagerSamplerRepo.values()) {
- if (!entry.isConnectedToCluster(requestClusterUUID)) {
- continue;
- }
- builder = builder == null ? CacheManagerEntityBuilderV2.createWith(entry.getCacheManagerSampler()) : builder
- .add(entry.getCacheManagerSampler());
- }
- } else {
- for (String cmName : cacheManagerNames) {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName);
- if (entry != null && entry.isConnectedToCluster(requestClusterUUID)) {
- builder = builder == null ? CacheManagerEntityBuilderV2.createWith(entry.getCacheManagerSampler()) : builder
- .add(entry.getCacheManagerSampler());
- }
- }
- }
- if (builder == null) {
- entities = new HashSet(0);
- } else {
- entities = attributes == null ? builder.build() : builder.add(attributes).build();
- }
- } finally {
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
-
- responseEntityV2.getEntities().addAll(entities);
- return responseEntityV2;
- }
-
- @Override
- public ResponseEntityV2 createCacheManagerConfigEntities(Set cacheManagerNames) {
- ResponseEntityV2 responseEntityV2 = new ResponseEntityV2();
-
- CacheManagerConfigurationEntityBuilderV2 builder = null;
- Collection entities;
- String requestClusterUUID = remoteAgentEndpoint.getRequestClusterUUID();
-
- cacheManagerSamplerRepoLock.readLock().lock();
-
- try {
- if (cacheManagerNames == null) {
- for (SamplerRepoEntry entry : cacheManagerSamplerRepo.values()) {
- if (!entry.isConnectedToCluster(requestClusterUUID)) {
- continue;
- }
- builder = builder == null ? CacheManagerConfigurationEntityBuilderV2
- .createWith(entry.getCacheManagerSampler()) : builder.add(entry.getCacheManagerSampler());
- }
- } else {
- for (String cmName : cacheManagerNames) {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName);
-
- if (entry != null && entry.isConnectedToCluster(requestClusterUUID)) {
- builder = builder == null ? CacheManagerConfigurationEntityBuilderV2
- .createWith(entry.getCacheManagerSampler()) : builder.add(entry.getCacheManagerSampler());
- }
- }
- }
- if (builder == null) {
- entities = new HashSet(0);
- } else {
- entities = builder.build();
- }
- } finally {
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
-
- responseEntityV2.getEntities().addAll(entities);
- return responseEntityV2;
- }
-
- @Override
- public ResponseEntityV2 createCacheEntities(Set cacheManagerNames,
- Set cacheNames,
- Set attributes) {
- ResponseEntityV2 responseEntityV2 = new ResponseEntityV2();
- CacheEntityBuilderV2 builder = null;
- Collection entities;
- String requestClusterUUID = remoteAgentEndpoint.getRequestClusterUUID();
-
- cacheManagerSamplerRepoLock.readLock().lock();
-
- List disabledSamplerRepoEntries = new ArrayList();
-
- try {
- if (cacheManagerNames == null) {
- for (Map.Entry entry : cacheManagerSamplerRepo.entrySet()) {
- if (!entry.getValue().isConnectedToCluster(requestClusterUUID)) {
- continue;
- }
- enableNonStopFor(entry.getValue(), false);
- disabledSamplerRepoEntries.add(entry.getValue());
- for (CacheSampler sampler : entry.getValue().getComprehensiveCacheSamplers(cacheNames)) {
- builder = builder == null ? CacheEntityBuilderV2.createWith(sampler, entry.getKey()) : builder
- .add(sampler, entry.getKey());
- }
- }
- } else {
- for (String cmName : cacheManagerNames) {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName);
- if (entry != null && entry.isConnectedToCluster(requestClusterUUID)) {
- enableNonStopFor(entry, false);
- disabledSamplerRepoEntries.add(entry);
- for (CacheSampler sampler : entry.getComprehensiveCacheSamplers(cacheNames)) {
- builder = builder == null ? CacheEntityBuilderV2.createWith(sampler, cmName) : builder.add(sampler, cmName);
- }
- }
- }
- }
- if (builder == null) {
- entities = new HashSet(0);
- } else {
- entities = attributes == null ? builder.build() : builder.add(attributes).build();
- }
- } finally {
- for (SamplerRepoEntry samplerRepoEntry : disabledSamplerRepoEntries) {
- enableNonStopFor(samplerRepoEntry, true);
- }
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
-
- responseEntityV2.getEntities().addAll(entities);
- return responseEntityV2;
- }
-
- @Override
- public ResponseEntityV2 createCacheConfigEntities(Set cacheManagerNames,
- Set cacheNames) {
- CacheConfigurationEntityBuilderV2 builder = null;
- Collection entities;
- ResponseEntityV2 responseEntityV2 = new ResponseEntityV2();
- String requestClusterUUID = remoteAgentEndpoint.getRequestClusterUUID();
-
- cacheManagerSamplerRepoLock.readLock().lock();
-
- try {
- if (cacheManagerNames == null) {
- for (Map.Entry entry : cacheManagerSamplerRepo.entrySet()) {
- for (CacheSampler sampler : entry.getValue().getComprehensiveCacheSamplers(cacheNames)) {
- if (!entry.getValue().isConnectedToCluster(requestClusterUUID)) {
- continue;
- }
- builder = builder == null ? CacheConfigurationEntityBuilderV2
- .createWith(entry.getValue().getCacheManagerSampler(), sampler.getCacheName()) : builder
- .add(entry.getValue().getCacheManagerSampler(), sampler.getCacheName());
- }
- }
- } else {
- for (String cmName : cacheManagerNames) {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName);
- if (entry != null && entry.isConnectedToCluster(requestClusterUUID)) {
- for (CacheSampler sampler : entry.getComprehensiveCacheSamplers(cacheNames)) {
- builder = builder == null ? CacheConfigurationEntityBuilderV2
- .createWith(entry.getCacheManagerSampler(), sampler.getCacheName()) : builder
- .add(entry.getCacheManagerSampler(), sampler.getCacheName());
- }
- }
- }
- }
- if (builder == null) {
- entities = new HashSet(0);
- } else {
- entities = builder.build();
- }
- } finally {
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
-
- responseEntityV2.getEntities().addAll(entities);
- return responseEntityV2;
- }
-
- @Override
- public ResponseEntityV2 createCacheStatisticSampleEntity(Set cacheManagerNames,
- Set cacheNames,
- Set sampleNames) {
- CacheStatisticSampleEntityBuilderV2 builder = CacheStatisticSampleEntityBuilderV2.createWith(sampleNames);
- ResponseEntityV2 responseEntityV2 = new ResponseEntityV2();
- String requestClusterUUID = remoteAgentEndpoint.getRequestClusterUUID();
-
- cacheManagerSamplerRepoLock.readLock().lock();
-
- List disabledSamplerRepoEntries = new ArrayList();
-
- try {
- if (cacheManagerNames == null) {
- for (Map.Entry entry : cacheManagerSamplerRepo.entrySet()) {
- if (!entry.getValue().isConnectedToCluster(requestClusterUUID)) {
- continue;
- }
- enableNonStopFor(entry.getValue(), false);
- disabledSamplerRepoEntries.add(entry.getValue());
- for (CacheSampler sampler : entry.getValue().getComprehensiveCacheSamplers(cacheNames)) {
- builder.add(sampler, entry.getKey());
- }
- }
- } else {
- for (String cmName : cacheManagerNames) {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cmName);
- if (entry != null && entry.isConnectedToCluster(requestClusterUUID)) {
- enableNonStopFor(entry, false);
- disabledSamplerRepoEntries.add(entry);
- for (CacheSampler sampler : entry.getComprehensiveCacheSamplers(cacheNames)) {
- builder.add(sampler, cmName);
- }
- }
- }
- }
-
- responseEntityV2.getEntities().addAll(builder.build());
- return responseEntityV2;
- } finally {
- for (SamplerRepoEntry samplerRepoEntry : disabledSamplerRepoEntries) {
- enableNonStopFor(samplerRepoEntry, true);
- }
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
- }
-
- @Override
- public void createOrUpdateCache(String cacheManagerName, String cacheName, CacheEntityV2 resource)
- throws ServiceExecutionException {
- cacheManagerSamplerRepoLock.readLock().lock();
-
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cacheManagerName);
- try {
- enableNonStopFor(entry, false);
- if (entry != null) {
- entry.updateCache(cacheName, resource);
- } else {
- throw new ServiceExecutionException("CacheManager not found !");
- }
- } finally {
- enableNonStopFor(entry, true);
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
-
- }
-
- @Override
- public void clearCache(String cacheManagerName, String cacheName) {
- cacheManagerSamplerRepoLock.readLock().lock();
-
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cacheManagerName);
- try {
- enableNonStopFor(entry, false);
- if (entry != null) {
- entry.clearCache(cacheName);
- }
- } finally {
- enableNonStopFor(entry, true);
- cacheManagerSamplerRepoLock.readLock().unlock();
- }
- }
-
- @Override
- public void updateCacheManager(String cacheManagerName,
- CacheManagerEntityV2 resource) throws ServiceExecutionException {
- cacheManagerSamplerRepoLock.writeLock().lock();
-
- try {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cacheManagerName);
- if (entry != null) {
- CacheManagerSampler cms = entry.getCacheManagerSampler();
- checkForInvalidAttributes(cacheManagerName, resource);
-
- Object mbldsAttr = resource.getAttributes().get(SamplerRepoEntry.MAX_BYTES_LOCAL_DISK_STRING);
- if (mbldsAttr != null) {
- cms.setMaxBytesLocalDiskAsString(mbldsAttr.toString());
- }
-
- Object mblhsAttr = resource.getAttributes().get(SamplerRepoEntry.MAX_BYTES_LOCAL_HEAP_STRING);
- if (mblhsAttr != null) {
- cms.setMaxBytesLocalHeapAsString(mblhsAttr.toString());
- }
-
- Object enabledAttr = resource.getAttributes().get(SamplerRepoEntry.ENABLED_ATTR);
- if (enabledAttr != null) {
- cms.setEnabled(Boolean.valueOf(enabledAttr.toString()));
- }
- } else {
- throw new ServiceExecutionException("CacheManager not found !");
- }
- } finally {
- cacheManagerSamplerRepoLock.writeLock().unlock();
- }
- }
-
- @Override
- public ResponseEntityV2 executeQuery(String cacheManagerName, String queryString) throws ServiceExecutionException {
- cacheManagerSamplerRepoLock.writeLock().lock();
- ResponseEntityV2 responseEntityV2 = new ResponseEntityV2();
-
- try {
- SamplerRepoEntry entry = cacheManagerSamplerRepo.get(cacheManagerName);
- if (entry != null) {
- try {
- enableNonStopFor(entry, false);
- CacheManagerSampler cms = entry.getCacheManagerSampler();
-
- responseEntityV2.getEntities().addAll(
- buildQueryResultsEntity(cacheManagerName, cms.executeQuery(queryString)));
- return responseEntityV2;
- } catch (Exception e) {
- Throwable t = ExceptionUtils.getRootCause(e);
- throw new ServiceExecutionException(t.getMessage());
- } finally {
- enableNonStopFor(entry, true);
- }
- } else {
- throw new ServiceExecutionException("CacheManager not found !");
- }
- } finally {
- cacheManagerSamplerRepoLock.writeLock().unlock();
- }
- }
-
- private Collection buildQueryResultsEntity(String cacheManagerName, Object[][] data) {
- QueryResultsEntityV2 qre = new QueryResultsEntityV2();
-
- qre.setAgentId(AgentEntityV2.EMBEDDED_AGENT_ID);
- qre.setName(cacheManagerName);
- qre.setData(data);
-
- return Collections.singleton(qre);
- }
-
- private void checkForInvalidAttributes(String cacheManagerName, CacheManagerEntityV2 resource) throws ServiceExecutionException {
- boolean invalidAttributesFound = false;
- StringBuilder errorMessage = new StringBuilder("You are not allowed to update those attributes : ");
- if(resource.getName() != null && !resource.getName().equals(cacheManagerName)) {
- errorMessage.append("name ");
- invalidAttributesFound = true;
- }
- for(Map.Entry attribute : resource.getAttributes().entrySet()) {
- String key = attribute.getKey();
- if(!key.equals(SamplerRepoEntry.MAX_BYTES_LOCAL_DISK_STRING) &&
- !key.equals(SamplerRepoEntry.MAX_BYTES_LOCAL_HEAP_STRING) &&
- !key.equals(SamplerRepoEntry.ENABLED_ATTR)) {
- errorMessage.append(key).append(" ");
- invalidAttributesFound = true;
- }
- }
- if (invalidAttributesFound) {
- errorMessage.append(". Only ")
- .append(SamplerRepoEntry.MAX_BYTES_LOCAL_DISK_STRING)
- .append(", ")
- .append(SamplerRepoEntry.MAX_BYTES_LOCAL_HEAP_STRING)
- .append(" and ")
- .append(SamplerRepoEntry.ENABLED_ATTR)
- .append(" can be updated for a CacheManager.");
- throw new ServiceExecutionException(errorMessage.toString());
- }
- }
-
- private static void checkForInvalidAttributes(String cacheName, CacheEntityV2 resource) throws ServiceExecutionException {
- boolean invalidAttributesFound = false;
- StringBuilder errorMessage = new StringBuilder("You are not allowed to update those attributes : ");
- if(resource.getName() != null && !resource.getName().equals(cacheName)) {
- errorMessage.append("name ");
- invalidAttributesFound = true;
- }
- Set validAttributes = new HashSet();
- validAttributes.add(SamplerRepoEntry.ENABLED_ATTR);
- validAttributes.add(SamplerRepoEntry.BULK_LOAD_ENABLED);
- validAttributes.add(SamplerRepoEntry.MAX_ELEMENTS_ON_DISK);
- validAttributes.add(SamplerRepoEntry.LOGGING_ENABLED);
- validAttributes.add(SamplerRepoEntry.MAX_BYTES_LOCAL_DISK_STRING);
- validAttributes.add(SamplerRepoEntry.MAX_BYTES_LOCAL_HEAP_STRING);
- validAttributes.add(SamplerRepoEntry.MAX_ENTRIES_LOCAL_HEAP);
- validAttributes.add(SamplerRepoEntry.MAX_ENTRIES_IN_CACHE);
- validAttributes.add(SamplerRepoEntry.TIME_TO_IDLE_SECONDS);
- validAttributes.add(SamplerRepoEntry.TIME_TO_LIVE_SEC);
-
- for(Map.Entry attribute : resource.getAttributes().entrySet()) {
- String key = attribute.getKey();
- if(!validAttributes.contains(key) ) {
- errorMessage.append(key).append(" ");
- invalidAttributesFound = true;
- }
- }
- if (invalidAttributesFound) {
- errorMessage.append(". Only ");
- for (String validAttribute : validAttributes) {
- errorMessage.append(validAttribute).append(" ");
- }
- errorMessage.append("can be updated for a Cache.");
- throw new ServiceExecutionException(errorMessage.toString());
- }
- }
-
- @Override
- public ResponseEntityV2 getAgents(Set ids) throws ServiceExecutionException {
- ResponseEntityV2 agentEntityCollectionV2 = new ResponseEntityV2();
-
- if (ids.isEmpty()) {
- agentEntityCollectionV2.getEntities().add(buildAgentEntity());
- return agentEntityCollectionV2;
- }
-
- for (String id : ids) {
- if (!id.equals(AgentEntityV2.EMBEDDED_AGENT_ID)) {
- throw new ServiceExecutionException("Unknown agent ID : " + id);
- }
- agentEntityCollectionV2.getEntities().add(buildAgentEntity());
- }
-
- return agentEntityCollectionV2;
- }
-
- private AgentEntityV2 buildAgentEntity() {
- AgentEntityV2 e = new AgentEntityV2();
- e.setAgentId(AgentEntityV2.EMBEDDED_AGENT_ID);
- e.setAgencyOf(AGENCY);
-
- StringBuilder sb = new StringBuilder();
- for (String cmName : cacheManagerSamplerRepo.keySet()) {
- sb.append(cmName).append(",");
- }
- if (sb.indexOf(",") > -1) {
- sb.deleteCharAt(sb.length() - 1);
- }
-
- e.getRootRepresentables().put("cacheManagerNames", sb.toString());
- return e;
- }
-
- @Override
- public ResponseEntityV2 getAgentsMetadata(Set ids) throws ServiceExecutionException {
- ResponseEntityV2 agentEntityCollectionV2 = new ResponseEntityV2();
-
- if (ids.isEmpty()) {
- agentEntityCollectionV2.getEntities().addAll(Collections.singleton(buildAgentMetadata()));
- return agentEntityCollectionV2;
- }
-
- Collection result = new ArrayList();
-
- for (String id : ids) {
- if (!id.equals(AgentEntityV2.EMBEDDED_AGENT_ID)) {
- throw new ServiceExecutionException("Unknown agent ID : " + id);
- }
- result.add(buildAgentMetadata());
- }
- agentEntityCollectionV2.getEntities().addAll(result);
- return agentEntityCollectionV2;
- }
-
- private AgentMetadataEntityV2 buildAgentMetadata() {
- AgentMetadataEntityV2 ame = new AgentMetadataEntityV2();
-
- ame.setAgentId(AgentEntityV2.EMBEDDED_AGENT_ID);
- ame.setAgencyOf(AGENCY);
- ame.setProductVersion(this.getClass().getPackage().getImplementationVersion());
- ame.setAvailable(true);
-
- if (isTsaBridged()) {
- ame.setSecured(isTsaSecured());
- ame.setSslEnabled(isTsaSecured());
- ame.setNeedClientAuth(false);
- } else {
- ame.setSecured(Utils.trimToNull(configuration.getSecurityServiceLocation()) != null);
- ame.setSslEnabled(Utils.trimToNull(configuration.getSecurityServiceLocation()) != null);
- ame.setNeedClientAuth(configuration.isNeedClientAuth());
- }
-
- ame.setLicensed(ServiceLocator.locate(LicenseService.class).isLicensed());
- ame.setSampleHistorySize(configuration.getSampleHistorySize());
- ame.setSampleIntervalSeconds(configuration.getSampleIntervalSeconds());
- ame.setEnabled(configuration.isEnabled());
-
- return ame;
- }
-
- protected boolean isTsaBridged() {
- return remoteAgentEndpoint.isTsaBridged();
- }
-
- protected boolean isTsaSecured() {
- return false;
- }
-
- /**
- * The repository entry class that is also a {@link CacheManagerEventListener}.
- */
- private final class SamplerRepoEntry implements CacheManagerEventListener {
- private final static String ENABLED_ATTR = "Enabled";
-
- private final static String BULK_LOAD_ENABLED = "NodeBulkLoadEnabled";
-
- private final static String MAX_ELEMENTS_ON_DISK = "MaxElementsOnDisk";
-
- private final static String MAX_BYTES_LOCAL_DISK = "MaxBytesLocalDisk";
-
- private final static String MAX_BYTES_LOCAL_DISK_STRING = "MaxBytesLocalDiskAsString";
-
- private final static String MAX_BYTES_LOCAL_HEAP = "MaxBytesLocalHeap";
-
- private final static String MAX_BYTES_LOCAL_HEAP_STRING = "MaxBytesLocalHeapAsString";
-
- private final static String LOGGING_ENABLED = "LoggingEnabled";
-
- private final static String TIME_TO_IDLE_SECONDS = "TimeToIdleSeconds";
-
- private final static String TIME_TO_LIVE_SEC = "TimeToLiveSeconds";
-
- private final static String MAX_ENTRIES_LOCAL_HEAP = "MaxEntriesLocalHeap";
-
- private final static String MAX_ENTRIES_IN_CACHE = "MaxEntriesInCache";
-
- private CacheManager cacheManager;
-
- private CacheManagerSampler cacheManagerSampler;
-
- /**
- * Guarded by cacheSamplerMapLock
- */
- private Map cacheSamplersByName;
-
- private volatile Status status = Status.STATUS_UNINITIALISED;
-
- private final ReadWriteLock cacheSamplerMapLock = new ReentrantReadWriteLock();
-
- private final Map propertyChangeListeners = new ConcurrentHashMap();
- private final Map samplerCacheConfigurationListeners = new ConcurrentHashMap();
-
- public SamplerRepoEntry(CacheManager cacheManager) {
- if (cacheManager == null) {
- throw new IllegalArgumentException("cacheManager == null");
- }
-
- this.cacheManagerSampler = new CacheManagerSamplerImpl(cacheManager);
- this.cacheManager = cacheManager;
-
- String[] cNames = cacheManager.getCacheNames();
- this.cacheSamplersByName = new HashMap(cNames.length);
-
- for (String cName : cNames) {
- Ehcache ehcache = cacheManager.getEhcache(cName);
- cacheSamplersByName.put(cName, new CacheSamplerImpl(ehcache));
- PropertyChangeListenerImplementation propertyChangeListener = new PropertyChangeListenerImplementation(ehcache);
- SamplerCacheConfigurationListener samplerCacheConfigurationListener = new SamplerCacheConfigurationListener(ehcache);
- propertyChangeListeners.put(cName, propertyChangeListener);
- samplerCacheConfigurationListeners.put(cName, samplerCacheConfigurationListener);
- ehcache.addPropertyChangeListener(propertyChangeListener);
- ehcache.getCacheConfiguration().addConfigurationListener(samplerCacheConfigurationListener);
- }
- }
-
- public boolean isConnectedToCluster(String uuid) {
- return uuid == null // local requests
- || cacheManager.getClusterUUID().equals("") // unclustered cache managers
- || cacheManager.getClusterUUID().equals(uuid);
- }
-
- public CacheManagerSampler getCacheManagerSampler() {
- return cacheManagerSampler;
- }
-
- public Collection getComprehensiveCacheSamplers(Set cacheSamplerNames) {
- Collection samplers = new HashSet();
-
- cacheSamplerMapLock.readLock().lock();
- try {
- if (cacheSamplerNames == null) {
- for (CacheSampler cs : cacheSamplersByName.values()) {
- samplers.add(cs);
- }
- } else {
- for (String cName : cacheSamplerNames) {
- CacheSampler cs = cacheSamplersByName.get(cName);
- if (cs != null) {
- samplers.add(cs);
- }
- }
- }
- } finally {
- cacheSamplerMapLock.readLock().unlock();
- }
-
- return samplers;
- }
-
- public void clearCache(String cacheSamplerName) {
- cacheSamplerMapLock.writeLock().lock();
-
- CacheSampler cs;
- try {
- cs = cacheSamplersByName.get(cacheSamplerName);
- if (cs != null) {
- cs.removeAll();
- }
- } finally {
- cacheSamplerMapLock.writeLock().unlock();
- }
- }
-
- public void updateCache(String cacheSamplerName, CacheEntityV2 cacheResource)
- throws ServiceExecutionException {
- cacheSamplerMapLock.writeLock().lock();
-
- CacheSampler cs;
- try {
- cs = cacheSamplersByName.get(cacheSamplerName);
-
- if (cs != null) {
- try {
- checkForInvalidAttributes(cacheSamplerName, cacheResource);
-
- Boolean enabledAttr = (Boolean) cacheResource.getAttributes().get(ENABLED_ATTR);
- if (enabledAttr != null) {
- cs.setEnabled(enabledAttr);
- }
-
- Boolean enabledBlkLoad = (Boolean) cacheResource.getAttributes().get(BULK_LOAD_ENABLED);
- if (enabledBlkLoad != null) {
- cs.setNodeBulkLoadEnabled(enabledBlkLoad);
- }
-
- Integer maxElementsOnDiskAttr = (Integer) cacheResource.getAttributes().get(MAX_ELEMENTS_ON_DISK);
- if (maxElementsOnDiskAttr != null) {
- cs.setMaxElementsOnDisk(maxElementsOnDiskAttr);
- }
-
- Boolean loggingEnabledAttr = (Boolean) cacheResource.getAttributes().get(LOGGING_ENABLED);
- if (loggingEnabledAttr != null) {
- cs.setLoggingEnabled(loggingEnabledAttr);
- }
-
- Object mbldsAttr = cacheResource.getAttributes().get(MAX_BYTES_LOCAL_DISK_STRING);
- if (mbldsAttr != null) {
- cs.setMaxBytesLocalDiskAsString(mbldsAttr.toString());
- }
-
- Object mblhsAttr = cacheResource.getAttributes().get(MAX_BYTES_LOCAL_HEAP_STRING);
- if (mblhsAttr != null) {
- cs.setMaxBytesLocalHeapAsString(mblhsAttr.toString());
- }
-
- Integer melhAttr = (Integer) cacheResource.getAttributes().get(MAX_ENTRIES_LOCAL_HEAP);
- if (melhAttr != null) {
- cs.setMaxEntriesLocalHeap(melhAttr);
- }
-
- Integer meicAttr = (Integer) cacheResource.getAttributes().get(MAX_ENTRIES_IN_CACHE);
- if (meicAttr != null) {
- cs.setMaxEntriesInCache(meicAttr);
- }
-
- Object ttiAttr = cacheResource.getAttributes().get(TIME_TO_IDLE_SECONDS);
- if (ttiAttr != null) {
- cs.setTimeToIdleSeconds(Long.parseLong(ttiAttr.toString()));
- }
-
- Object ttlAttr = cacheResource.getAttributes().get(TIME_TO_LIVE_SEC);
- if (ttlAttr != null) {
- cs.setTimeToLiveSeconds(Long.parseLong(ttlAttr.toString()));
- }
- } catch (RuntimeException e) {
- throw new ServiceExecutionException(e);
- }
-
- } else {
- throw new ServiceExecutionException("Cache not found !");
- }
- } finally {
- cacheSamplerMapLock.writeLock().unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void init() throws CacheException {
- status = Status.STATUS_ALIVE;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Status getStatus() {
- return status;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void dispose() throws CacheException {
- cacheSamplerMapLock.writeLock().lock();
-
- try {
- cacheSamplersByName.clear();
- cacheSamplersByName = null;
- } finally {
- cacheSamplerMapLock.writeLock().unlock();
- }
-
- status = Status.STATUS_SHUTDOWN;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void notifyCacheAdded(String cacheName) {
- cacheSamplerMapLock.writeLock().lock();
- try {
- Ehcache ehcache = cacheManager.getEhcache(cacheName);
-
- if (ehcache != null) {
- cacheSamplersByName.put(cacheName, new CacheSamplerImpl(ehcache));
-
- Map cacheAttributes = new HashMap();
- cacheAttributes.put("version", this.getClass().getPackage().getImplementationVersion());
- cacheAttributes.put("name", ehcache.getName());
- cacheAttributes.put("cacheManagerName", cacheManager.getName());
- Collection createCacheEntities = DfltSamplerRepositoryServiceV2.this.createCacheEntities(
- Collections.singleton(cacheManager.getName()), Collections.singleton(ehcache.getName()), null).getEntities();
- if (createCacheEntities != null && !createCacheEntities.isEmpty()) {
- CacheEntityV2 next = createCacheEntities.iterator().next();
- cacheAttributes.put("attributes", next.getAttributes());
- }
-
- final EventEntityV2 evenEntityV2 = new EventEntityV2();
- evenEntityV2.setAgentId(Representable.EMBEDDED_AGENT_ID);
- evenEntityV2.setType("EHCACHE.CACHE.ADDED");
- evenEntityV2.getRootRepresentables().put("cache", cacheAttributes);
- cacheManager.sendManagementEvent(evenEntityV2, evenEntityV2.getType());
- for (EventListener eventListener : listeners) {
- eventListener.onEvent(evenEntityV2);
- }
- PropertyChangeListenerImplementation propertyChangeListener = new PropertyChangeListenerImplementation(ehcache);
- SamplerCacheConfigurationListener samplerCacheConfigurationListener = new SamplerCacheConfigurationListener(ehcache);
- propertyChangeListeners.put(cacheName, propertyChangeListener);
- samplerCacheConfigurationListeners.put(cacheName, samplerCacheConfigurationListener);
- ehcache.addPropertyChangeListener(propertyChangeListener);
- ehcache.getCacheConfiguration().addConfigurationListener(samplerCacheConfigurationListener);
- }
-
- } finally {
- cacheSamplerMapLock.writeLock().unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void notifyCacheRemoved(String cacheName) {
- cacheSamplerMapLock.writeLock().lock();
-
- try {
- propertyChangeListeners.remove(cacheName);
- samplerCacheConfigurationListeners.remove(cacheName);
-
- cacheSamplersByName.remove(cacheName);
-
- Map cacheAttributes = new HashMap();
- cacheAttributes.put("version", this.getClass().getPackage().getImplementationVersion());
- cacheAttributes.put("name", cacheName);
- cacheAttributes.put("cacheManagerName", cacheManager.getName());
-
- EventEntityV2 evenEntityV2 = new EventEntityV2();
- evenEntityV2.setAgentId(Representable.EMBEDDED_AGENT_ID);
- evenEntityV2.setType("EHCACHE.CACHE.REMOVED");
- evenEntityV2.getRootRepresentables().put("cache", cacheAttributes);
- cacheManager.sendManagementEvent(evenEntityV2, evenEntityV2.getType());
- for (EventListener eventListener : listeners) {
- eventListener.onEvent(evenEntityV2);
- }
- } finally {
- cacheSamplerMapLock.writeLock().unlock();
- }
- }
-
- public void destroy() {
- cacheManagerSampler = null;
- cacheManager = null;
- }
- }
-
- class PropertyChangeListenerImplementation implements PropertyChangeListener {
- private final Ehcache cache;
-
- public PropertyChangeListenerImplementation(Ehcache cache) {
- this.cache = cache;
- }
-
- @Override
- public void propertyChange(PropertyChangeEvent evt) {
- String propName = evt.getPropertyName();
- Object propVal = evt.getNewValue();
-
- if ("Disabled".equals(propName)) {
- propName = "Enabled";
- propVal = Boolean.valueOf(((Boolean) propVal) != Boolean.TRUE);
- }
-
- sendCacheEvent(propVal, propName, cache);
- }
- }
-
- class SamplerCacheConfigurationListener implements CacheConfigurationListener {
-
- private final Ehcache cache;
-
- public SamplerCacheConfigurationListener(Ehcache ehcache) {
- this.cache = ehcache;
- }
-
- @Override
- public void timeToIdleChanged(long oldTimeToIdle, long newTimeToIdle) {
- String key = "TimeToIdleSeconds";
- sendCacheEvent(newTimeToIdle, key, cache);
- }
-
- @Override
- public void timeToLiveChanged(long oldTimeToLive, long newTimeToLive) {
- String key = "TimeToLiveSeconds";
- sendCacheEvent(newTimeToLive, key, cache);
- }
-
- @Override
- public void diskCapacityChanged(int oldCapacity, int newCapacity) {
- String key = "MaxEntriesLocalDisk";
- sendCacheEvent(newCapacity, key, cache);
- }
-
- @Override
- public void memoryCapacityChanged(int oldCapacity, int newCapacity) {
- String key = "MaxEntriesLocalHeap";
- sendCacheEvent(newCapacity, key, cache);
- }
-
- @Override
- public void loggingChanged(boolean oldValue, boolean newValue) {
- String key = "LoggingEnabled";
- sendCacheEvent(newValue, key, cache);
- }
-
- @Override
- public void registered(CacheConfiguration config) {
- }
-
- @Override
- public void deregistered(CacheConfiguration config) {
- }
-
- @Override
- public void maxBytesLocalHeapChanged(long oldValue, long newValue) {
- String key = "MaxBytesLocalHeap";
- sendCacheEvent(newValue, key, cache);
- }
-
- @Override
- public void maxBytesLocalDiskChanged(long oldValue, long newValue) {
- String key = "MaxBytesLocalDisk";
- sendCacheEvent(newValue, key, cache);
- }
-
- @Override
- public void maxEntriesInCacheChanged(long oldValue, long newValue) {
- String key = "MaxEntriesInCache";
- sendCacheEvent(newValue, key, cache);
- }
- }
-
- private void sendCacheEvent(Object newValue, String key, Ehcache cache) {
- sendCacheEvent(Collections.singletonMap(key, newValue), cache);
- }
-
- private void sendCacheEvent(Map attributes, Ehcache cache) {
- CacheManager cacheManager = cache.getCacheManager();
- EventEntityV2 evenEntityV2 = new EventEntityV2();
- evenEntityV2.setAgentId(Representable.EMBEDDED_AGENT_ID);
- evenEntityV2.setType("EHCACHE.CACHE.UPDATED");
- evenEntityV2.getRootRepresentables().put("attributes", attributes);
- evenEntityV2.getRootRepresentables().put("cacheManagerName", cacheManager.getName());
- evenEntityV2.getRootRepresentables().put("cacheName", cache.getName());
-
- cacheManager.sendManagementEvent(evenEntityV2, evenEntityV2.getType());
- for (EventListener eventListener : listeners) {
- eventListener.onEvent(evenEntityV2);
- }
- }
-
- private void sendCacheManagerEvent(Map attributes, CacheManager cacheManager) {
- EventEntityV2 evenEntityV2 = new EventEntityV2();
- evenEntityV2.setAgentId(Representable.EMBEDDED_AGENT_ID);
- evenEntityV2.setType("EHCACHE.CACHEMANAGER.UPDATED");
- evenEntityV2.getRootRepresentables().put("attributes", attributes);
- evenEntityV2.getRootRepresentables().put("cacheManagerName", cacheManager.getName());
-
- cacheManager.sendManagementEvent(evenEntityV2, evenEntityV2.getType());
- for (EventListener eventListener : listeners) {
- eventListener.onEvent(evenEntityV2);
- }
- }
-
- @Override
- public void registerEventListener(EventListener listener, boolean localOnly) {
- listeners.add(listener);
- }
-
- @Override
- public void unregisterEventListener(EventListener listener) {
- listeners.remove(listener);
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/ehcache-comparator.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/ehcache-comparator.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/ehcache-comparator.xml (revision 0)
@@ -1,31 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/JvmInformation.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/JvmInformation.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/JvmInformation.java (revision 0)
@@ -1,777 +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;
-
-import java.lang.management.GarbageCollectorMXBean;
-import java.lang.management.ManagementFactory;
-
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-import javax.management.openmbean.CompositeData;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Detects and represents JVM-specific properties that relate to the memory
- * data model for java objects that are useful for size of calculations.
- *
- * @author jhouse
- * @author Chris Dennis
- */
-public enum JvmInformation {
-
- /**
- * Represents Generic 32-bit
- */
- UNKNOWN_32_BIT(null) {
-
- /* default values are for this vm */
-
- @Override
- public String getJvmDescription() {
- return "Unrecognized 32-Bit JVM";
- }
-
- @Override
- public int getPointerSize() {
- return 4;
- }
-
- @Override
- public int getJavaPointerSize() {
- return 4;
- }
-
- @Override
- public int getObjectAlignment() {
- return 8;
- }
-
- @Override
- public int getFieldOffsetAdjustment() {
- return 0;
- }
-
- @Override
- public int getAgentSizeOfAdjustment() {
- return 0;
- }
-
- @Override
- public boolean supportsAgentSizeOf() {
- return true;
- }
-
- @Override
- public boolean supportsUnsafeSizeOf() {
- return true;
- }
-
- @Override
- public boolean supportsReflectionSizeOf() {
- return true;
- }
- },
-
- /**
- * Represents 64-Bit Generic JVM
- */
- UNKNOWN_64_BIT(UNKNOWN_32_BIT) {
-
- @Override
- public int getPointerSize() {
- return 8;
- }
-
- @Override
- public int getJavaPointerSize() {
- return 8;
- }
-
- @Override
- public String getJvmDescription() {
- return "Unrecognized 64-Bit JVM";
- }
- },
-
- /**
- * Represents HotSpot 32-bit
- */
- HOTSPOT_32_BIT(UNKNOWN_32_BIT) {
-
- /* default values are for this vm */
-
- @Override
- public String getJvmDescription() {
- return "32-Bit HotSpot JVM";
- }
- },
-
- /**
- * Represents 32-Bit HotSpot JVM with Concurrent Mark-and-Sweep GC
- */
- HOTSPOT_32_BIT_WITH_CONCURRENT_MARK_AND_SWEEP(UNKNOWN_32_BIT) {
-
- @Override
- public int getMinimumObjectSize() {
- return 16;
- }
-
- @Override
- public String getJvmDescription() {
- return "32-Bit HotSpot JVM with Concurrent Mark-and-Sweep GC";
- }
- },
-
- /**
- * Represents 64-Bit HotSpot JVM
- */
- HOTSPOT_64_BIT(UNKNOWN_64_BIT) {
-
- @Override
- public String getJvmDescription() {
- return "64-Bit HotSpot JVM";
- }
- },
-
- /**
- * Represents 64-Bit HotSpot JVM with Concurrent Mark-and-Sweep GC
- */
- HOTSPOT_64_BIT_WITH_CONCURRENT_MARK_AND_SWEEP(HOTSPOT_64_BIT) {
-
- @Override
- public int getMinimumObjectSize() {
- return 24;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit HotSpot JVM with Concurrent Mark-and-Sweep GC";
- }
- },
-
- /**
- * Represents 64-Bit HotSpot JVM with Compressed OOPs
- */
- HOTSPOT_64_BIT_WITH_COMPRESSED_OOPS(HOTSPOT_64_BIT) {
-
- @Override
- public int getJavaPointerSize() {
- return 4;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit HotSpot JVM with Compressed OOPs";
- }
- },
-
- /**
- * Represents 64-Bit HotSpot JVM with Compressed OOPs and Concurrent Mark-and-Sweep GC
- */
- HOTSPOT_64_BIT_WITH_COMPRESSED_OOPS_AND_CONCURRENT_MARK_AND_SWEEP(HOTSPOT_64_BIT_WITH_COMPRESSED_OOPS) {
-
- @Override
- public int getMinimumObjectSize() {
- return 24;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit HotSpot JVM with Compressed OOPs and Concurrent Mark-and-Sweep GC";
- }
- },
-
- /**
- * Represents OpenJDK 32-bit
- */
- OPENJDK_32_BIT(HOTSPOT_32_BIT) {
-
- @Override
- public String getJvmDescription() {
- return "32-Bit OpenJDK JVM";
- }
- },
-
- /**
- * Represents 32-Bit OpenJDK JVM with Concurrent Mark-and-Sweep GC
- */
- OPENJDK_32_BIT_WITH_CONCURRENT_MARK_AND_SWEEP(HOTSPOT_32_BIT) {
- @Override
- public int getMinimumObjectSize() {
- return 16;
- }
-
- @Override
- public String getJvmDescription() {
- return "32-Bit OpenJDK JVM with Concurrent Mark-and-Sweep GC";
- }
- },
-
- /**
- * Represents 64-Bit OpenJDK JVM
- */
- OPENJDK_64_BIT(HOTSPOT_64_BIT) {
-
- @Override
- public String getJvmDescription() {
- return "64-Bit OpenJDK JVM";
- }
- },
-
- /**
- * Represents 64-Bit OpenJDK JVM with Concurrent Mark-and-Sweep GC
- */
- OPENJDK_64_BIT_WITH_CONCURRENT_MARK_AND_SWEEP(OPENJDK_64_BIT) {
-
- @Override
- public int getMinimumObjectSize() {
- return 24;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit OpenJDK JVM with Concurrent Mark-and-Sweep GC";
- }
- },
-
- /**
- * Represents 64-Bit OpenJDK JVM with Compressed OOPs
- */
- OPENJDK_64_BIT_WITH_COMPRESSED_OOPS(OPENJDK_64_BIT) {
-
- @Override
- public int getJavaPointerSize() {
- return 4;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit OpenJDK JVM with Compressed OOPs";
- }
- },
-
- /**
- * Represents 64-Bit OpenJDK JVM with Compressed OOPs and Concurrent Mark-and-Sweep GC
- */
- OPENJDK_64_BIT_WITH_COMPRESSED_OOPS_AND_CONCURRENT_MARK_AND_SWEEP(OPENJDK_64_BIT_WITH_COMPRESSED_OOPS) {
-
- @Override
- public int getMinimumObjectSize() {
- return 24;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit OpenJDK JVM with Compressed OOPs and Concurrent Mark-and-Sweep GC";
- }
- },
-
- /**
- * Represents 32-Bit JRockit JVM"
- */
- JROCKIT_32_BIT(UNKNOWN_32_BIT) {
-
- @Override
- public int getAgentSizeOfAdjustment() {
- return 8;
- }
-
- @Override
- public int getFieldOffsetAdjustment() {
- return 8;
- }
-
- @Override
- public int getObjectHeaderSize() {
- return 16;
- }
-
- @Override
- public String getJvmDescription() {
- return "32-Bit JRockit JVM";
- }
-
- @Override
- public boolean supportsReflectionSizeOf() {
- return false;
- }
- },
-
- /**
- * Represents 64-Bit JRockit JVM (with no reference compression)
- */
- JROCKIT_64_BIT(JROCKIT_32_BIT) {
-
- @Override
- public int getObjectHeaderSize() {
- return 16;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit JRockit JVM (with no reference compression)";
- }
- },
-
- /**
- * Represents 64-Bit JRockit JVM with 64GB Compressed References
- */
- JROCKIT_64_BIT_WITH_64GB_COMPRESSED_REFS(JROCKIT_32_BIT) {
-
-
- @Override
- public int getObjectAlignment() {
- return 16;
- }
-
- @Override
- public int getAgentSizeOfAdjustment() {
- return 16;
- }
-
- @Override
- public int getFieldOffsetAdjustment() {
- return 16;
- }
-
- @Override
- public int getObjectHeaderSize() {
- return 24;
- }
-
- @Override
- public String getJvmDescription() {
- return "64-Bit JRockit JVM with 64GB Compressed References";
- }
- },
-
- /**
- * Represents IBM 32-bit
- */
- IBM_32_BIT(UNKNOWN_32_BIT) {
-
- @Override
- public String getJvmDescription() {
- return "IBM 32-Bit JVM";
- }
-
- @Override
- public int getObjectHeaderSize() {
- return 16;
- }
-
- @Override
- public boolean supportsReflectionSizeOf() {
- return false;
- }
- },
-
- /**
- * Represents 64-Bit IBM JVM (with no reference compression)
- */
- IBM_64_BIT(UNKNOWN_64_BIT) {
-
- @Override
- public int getObjectHeaderSize() {
- return 24;
- }
-
- @Override
- public boolean supportsReflectionSizeOf() {
- return false;
- }
-
- @Override
- public String getJvmDescription() {
- return "IBM 64-Bit JVM (with no reference compression)";
- }
- },
-
- /**
- * Represents 64-Bit IBM JVM (with reference compression)
- */
- IBM_64_BIT_WITH_COMPRESSED_REFS(IBM_32_BIT) {
-
- @Override
- public int getMinimumObjectSize() {
- return 16;
- }
-
- @Override
- public boolean supportsAgentSizeOf() {
- return false;
- }
-
- @Override
- public int getObjectHeaderSize() {
- return 16;
- }
-
- @Override
- public String getJvmDescription() {
- return "IBM 64-Bit JVM with Compressed References";
- }
- };
-
-
- /**
- * The JvmInformation instance representing the current JVM
- */
- public static final JvmInformation CURRENT_JVM_INFORMATION;
-
- private static final Logger LOGGER = LoggerFactory.getLogger(JvmInformation.class);
-
- private static final long TWENTY_FIVE_GB = 25L * 1024L * 1024L * 1024L;
- private static final long FIFTY_SEVEN_GB = 57L * 1024L * 1024L * 1024L;
-
-
- static {
- CURRENT_JVM_INFORMATION = getJvmInformation();
- LOGGER.info("Detected JVM data model settings of: " + CURRENT_JVM_INFORMATION.getJvmDescription());
- }
-
- private JvmInformation parent;
-
- private JvmInformation(JvmInformation parent) {
- this.parent = parent;
- }
-
- /**
- * Size of a pointer in bytes on this runtime
- */
- public int getPointerSize() {
- return parent.getPointerSize();
- }
-
- /**
- * Size of a java pointer in bytes on this runtime (that differs when compressedOops are being used)
- */
- public int getJavaPointerSize() {
- return parent.getJavaPointerSize();
- }
-
- /**
- * Minimal size an object will occupy on the heap in bytes.
- */
- public int getMinimumObjectSize() {
- return getObjectAlignment();
- }
-
- /**
- * Object alignment / padding in bytes
- */
- public int getObjectAlignment() {
- return parent.getObjectAlignment();
- }
-
- /**
- * The size of an object header in bytes.
- */
- public int getObjectHeaderSize() {
- return getPointerSize() + getJavaPointerSize();
- }
-
- /**
- * The size of the jvm-specific field offset adjustment in bytes.
- */
- public int getFieldOffsetAdjustment() {
- return parent.getFieldOffsetAdjustment();
- }
-
- /**
- * The size of the jvm-specific agent result adjustment in bytes.
- */
- public int getAgentSizeOfAdjustment() {
- return parent.getAgentSizeOfAdjustment();
- }
-
- /**
- * Whether the jvm can support AgentSizeOf implementation.
- */
- public boolean supportsAgentSizeOf() {
- return parent.supportsAgentSizeOf();
- }
-
- /**
- * Whether the jvm can support UnsafeSizeOf implementation.
- */
- public boolean supportsUnsafeSizeOf() {
- return parent.supportsUnsafeSizeOf();
- }
-
- /**
- * Whether the jvm can support ReflectionSizeOf implementation.
- */
- public boolean supportsReflectionSizeOf() {
- return parent.supportsReflectionSizeOf();
- }
-
- /**
- * A human-readable description of the JVM and its relevant enabled options.Os
- */
- public abstract String getJvmDescription();
-
- /**
- * Determine the JvmInformation for the current JVM.
- */
- private static JvmInformation getJvmInformation() {
- JvmInformation jif = null;
-
- jif = detectHotSpot();
-
- if (jif == null) {
- jif = detectOpenJDK();
- }
-
- if (jif == null) {
- jif = detectJRockit();
- }
- if (jif == null) {
- jif = detectIBM();
- }
-
- if (jif == null && is64Bit()) {
- // unknown 64-bit JVMs
- jif = UNKNOWN_64_BIT;
- } else if (jif == null) {
- // unknown 32-bit JVMs
- jif = UNKNOWN_32_BIT;
- }
-
- return jif;
- }
-
- private static JvmInformation detectHotSpot() {
- JvmInformation jif = null;
-
- if (isHotspot()) {
- if (is64Bit()) {
- if (isHotspotCompressedOops() && isHotspotConcurrentMarkSweepGC()) {
- jif = HOTSPOT_64_BIT_WITH_COMPRESSED_OOPS_AND_CONCURRENT_MARK_AND_SWEEP;
- } else if (isHotspotCompressedOops()) {
- jif = HOTSPOT_64_BIT_WITH_COMPRESSED_OOPS;
- } else if (isHotspotConcurrentMarkSweepGC()) {
- jif = HOTSPOT_64_BIT_WITH_CONCURRENT_MARK_AND_SWEEP;
- } else {
- jif = HOTSPOT_64_BIT;
- }
- } else {
- if (isHotspotConcurrentMarkSweepGC()) {
- jif = HOTSPOT_32_BIT_WITH_CONCURRENT_MARK_AND_SWEEP;
- } else {
- jif = HOTSPOT_32_BIT;
- }
- }
- }
-
- return jif;
- }
-
- private static JvmInformation detectOpenJDK() {
- JvmInformation jif = null;
-
- if (isOpenJDK()) {
- if (is64Bit()) {
- if (isHotspotCompressedOops() && isHotspotConcurrentMarkSweepGC()) {
- jif = OPENJDK_64_BIT_WITH_COMPRESSED_OOPS_AND_CONCURRENT_MARK_AND_SWEEP;
- } else if (isHotspotCompressedOops()) {
- jif = OPENJDK_64_BIT_WITH_COMPRESSED_OOPS;
- } else if (isHotspotConcurrentMarkSweepGC()) {
- jif = OPENJDK_64_BIT_WITH_CONCURRENT_MARK_AND_SWEEP;
- } else {
- jif = OPENJDK_64_BIT;
- }
- } else {
- if (isHotspotConcurrentMarkSweepGC()) {
- jif = OPENJDK_32_BIT_WITH_CONCURRENT_MARK_AND_SWEEP;
- } else {
- jif = OPENJDK_32_BIT;
- }
- }
- }
-
- return jif;
- }
-
- private static JvmInformation detectJRockit() {
- JvmInformation jif = null;
-
- if (isJRockit()) {
- if (is64Bit()) {
- if (isJRockit64GBCompression()) {
- jif = JROCKIT_64_BIT_WITH_64GB_COMPRESSED_REFS;
- } else {
- jif = JROCKIT_64_BIT;
- }
- } else {
- jif = JROCKIT_32_BIT;
- }
- }
-
- return jif;
- }
-
- private static JvmInformation detectIBM() {
- JvmInformation jif = null;
-
- if (isIBM()) {
- if (is64Bit()) {
- if (isIBMCompressedRefs()) {
- jif = IBM_64_BIT_WITH_COMPRESSED_REFS;
- } else {
- jif = IBM_64_BIT;
- }
- } else {
- jif = IBM_32_BIT;
- }
- }
-
- return jif;
- }
-
- private static boolean isJRockit64GBCompression() {
- if (getJRockitVmArgs().contains("-XXcompressedRefs:enable=false")) {
- return false;
- }
- if (getJRockitVmArgs().contains("-XXcompressedRefs:size=4GB") ||
- getJRockitVmArgs().contains("-XXcompressedRefs:size=32GB")) {
- return false;
- }
-
- if (getJRockitVmArgs().contains("-XXcompressedRefs:size=64GB")) {
- return true;
- }
- if (Runtime.getRuntime().maxMemory() > TWENTY_FIVE_GB && Runtime.getRuntime().maxMemory() <= FIFTY_SEVEN_GB
- && getJRockitVmArgs().contains("-XXcompressedRefs:enable=true")) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Returns true if VM is JRockit
- * @return true, if JRockit
- */
- public static boolean isJRockit() {
- return System.getProperty("jrockit.version") != null
- || System.getProperty("java.vm.name", "").toLowerCase().indexOf("jrockit") >= 0;
- }
-
- /**
- * Return true if the VM's vendor is Apple
- * @return true, if OS X
- */
- public static boolean isOSX() {
- final String vendor = System.getProperty("java.vm.vendor");
- return vendor != null && vendor.startsWith("Apple");
- }
-
- /**
- * Returns true if VM vendor is Hotspot
- * @return true, if Hotspot
- */
- public static boolean isHotspot() {
- return System.getProperty("java.vm.name", "").toLowerCase().contains("hotspot");
- }
-
- /**
- * Returns true if VM vendor is OpenJDK
- * @return true, if OpenJDK
- */
- public static boolean isOpenJDK() {
- return System.getProperty("java.vm.name", "").toLowerCase().contains("openjdk");
- }
-
- /**
- * Returns true if VM vendor is IBM
- * @return true, if IBM
- */
- public static boolean isIBM() {
- return System.getProperty("java.vm.name", "").contains("IBM") && System.getProperty("java.vm.vendor").contains("IBM");
- }
-
- private static boolean isIBMCompressedRefs() {
- return System.getProperty("com.ibm.oti.vm.bootstrap.library.path", "").contains("compressedrefs");
- }
-
- private static boolean isHotspotCompressedOops() {
- String value = getHotSpotVmOptionValue("UseCompressedOops");
- if (value == null) {
- return false;
- } else {
- return Boolean.valueOf(value);
- }
- }
-
- private static String getHotSpotVmOptionValue(String name) {
- try {
- MBeanServer server = ManagementFactory.getPlatformMBeanServer();
- ObjectName beanName = ObjectName.getInstance("com.sun.management:type=HotSpotDiagnostic");
- Object vmOption = server.invoke(beanName, "getVMOption", new Object[] {name}, new String[] {"java.lang.String"});
- return (String)((CompositeData)vmOption).get("value");
- } catch (Throwable t) {
- return null;
- }
- }
-
- private static String getPlatformMBeanAttribute(String beanName, String attrName) {
- try {
- MBeanServer server = ManagementFactory.getPlatformMBeanServer();
- ObjectName name = ObjectName.getInstance(beanName);
- Object attr = server.getAttribute(name, attrName).toString();
- if (attr != null) {
- return attr.toString();
- }
- return null;
- } catch (Throwable t) {
- return null;
- }
- }
-
- private static String getJRockitVmArgs() {
- return getPlatformMBeanAttribute("oracle.jrockit.management:type=PerfCounters", "java.rt.vmArgs");
- }
-
- private static boolean isHotspotConcurrentMarkSweepGC() {
- for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) {
- if ("ConcurrentMarkSweep".equals(bean.getName())) {
- return true;
- }
- }
- return false;
- }
-
- private static boolean is64Bit() {
- String systemProp;
- systemProp = System.getProperty("com.ibm.vm.bitmode");
- if (systemProp != null) {
- return systemProp.equals("64");
- }
- systemProp = System.getProperty("sun.arch.data.model");
- if (systemProp != null) {
- return systemProp.equals("64");
- }
- systemProp = System.getProperty("java.vm.version");
- if (systemProp != null) {
- return systemProp.contains("_64");
- }
- return false;
- }
-}
Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/net/sf/ehcache/terracotta/StandaloneTerracottaClusteredInstanceFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/net/sf/ehcache/terracotta/StandaloneTerracottaClusteredInstanceFactory.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/net/sf/ehcache/terracotta/StandaloneTerracottaClusteredInstanceFactory.java (revision 0)
@@ -1,16 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package net.sf.ehcache.terracotta;
-
-import net.sf.ehcache.config.TerracottaClientConfiguration;
-
-import org.terracotta.modules.ehcache.store.TerracottaClusteredInstanceFactory;
-
-public class StandaloneTerracottaClusteredInstanceFactory extends TerracottaClusteredInstanceFactory {
-
- public StandaloneTerracottaClusteredInstanceFactory(final TerracottaClientConfiguration terracottaConfig,
- ClassLoader loader) {
- super(terracottaConfig, loader);
- }
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/url-config-cache-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/url-config-cache-test.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/url-config-cache-test.xml (revision 0)
@@ -1,18 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/extension/TestCacheExtensionFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/extension/TestCacheExtensionFactory.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/extension/TestCacheExtensionFactory.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.extension;
-
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.util.PropertyUtil;
-
-import java.util.Properties;
-
-/**
- * @author Greg Luck
- * @version $Id: TestCacheExtensionFactory.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class TestCacheExtensionFactory extends CacheExtensionFactory {
-
- /**
- * @param cache the cache this extension should hold a reference to, and to whose lifecycle it should be bound.
- * @param properties implementation specific properties configured as delimiter separated name value pairs in ehcache.xml
- */
- public CacheExtension createCacheExtension(Ehcache cache, Properties properties) {
- String propertyA = PropertyUtil.extractAndLogProperty("propertyA", properties);
- return new TestCacheExtension(cache, propertyA);
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/DynamicCacheConfigurationValidityTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/DynamicCacheConfigurationValidityTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/DynamicCacheConfigurationValidityTest.java (revision 0)
@@ -1,170 +0,0 @@
-package net.sf.ehcache.config;
-
-import junit.framework.Assert;
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheManager;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * @author Raghvendra Singh
- */
-public class DynamicCacheConfigurationValidityTest {
-
- private CacheManager cacheManager;
- private final String TEST_NAME = "tempCache";
-
- @Before
- public void setup() {
- this.cacheManager = CacheManager.getInstance();
- cacheManager.addCache(new Cache(new CacheConfiguration(TEST_NAME, 0)));
- }
-
- @After
- public void cleanup() {
- this.cacheManager.shutdown();
- }
-
- @Test
- public void testMaxEntriesLocalHeap() {
-
- CacheConfiguration cacheConfiguration;
- try {
- cacheConfiguration = new CacheConfiguration(TEST_NAME, -1);
- Assert.fail("should not be able to create config with negative maxEntriesLocalHeap");
- } catch (IllegalArgumentException e) {
- // expected exception;
- Assert.assertEquals("Illegal value -1 for maxEntriesLocalHeap: has to be larger than or equal to 0", e.getMessage());
- }
-
- Cache cache = cacheManager.getCache(TEST_NAME);
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxEntriesLocalHeap());
- try {
- cache.getCacheConfiguration().setMaxEntriesLocalHeap(-1234L);
- Assert.fail("should not be able to set negative maxEntriesLocalHeap");
- } catch (IllegalArgumentException e) {
- // expected exception;
- Assert.assertEquals("Illegal value -1234 for maxEntriesLocalHeap: has to be larger than or equal to 0", e.getMessage());
- }
-
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxEntriesLocalHeap());
- cache.getCacheConfiguration().setMaxEntriesLocalHeap(1234L);
- Assert.assertEquals(1234, cache.getCacheConfiguration().getMaxEntriesLocalHeap());
-
- cache.getCacheConfiguration().setMaxEntriesLocalHeap(0);
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxEntriesLocalHeap());
- }
-
- @Test
- public void testMaxBytesLocalOffHeap() {
- Cache cache = cacheManager.getCache(TEST_NAME);
-
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxBytesLocalOffHeap());
- try {
- cache.getCacheConfiguration().setMaxBytesLocalOffHeap(-1234L);
- Assert.fail("should not be able to set maxEntriesLocalHeap dynamically");
- } catch (IllegalStateException e) {
- // expected exception;
- Assert.assertEquals(e.getMessage(), "OffHeap can't be set dynamically!");
- }
-
- try {
- cache.getCacheConfiguration().setMaxBytesLocalOffHeap(1234L);
- Assert.fail("should not be able to set maxEntriesLocalHeap dynamically");
- } catch (IllegalStateException e) {
- // expected exception;
- Assert.assertEquals(e.getMessage(), "OffHeap can't be set dynamically!");
- }
-
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxBytesLocalOffHeap());
- }
-
- @Test
- public void testMaxEntriesLocalDisk() {
- Cache cache = cacheManager.getCache(TEST_NAME);
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxEntriesLocalDisk());
- try {
- cache.getCacheConfiguration().setMaxEntriesLocalDisk(-1234L);
- Assert.fail("should not be able to set negative maxEntriesLocalDisk");
- } catch (IllegalArgumentException e) {
- // expected exception;
- Assert.assertEquals("Illegal value -1234 for maxEntriesLocalDisk: has to be larger than or equal to 0", e.getMessage());
- }
-
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxEntriesLocalDisk());
- cache.getCacheConfiguration().setMaxEntriesLocalHeap(1234L);
- Assert.assertEquals(1234, cache.getCacheConfiguration().getMaxEntriesLocalHeap());
-
- cache.getCacheConfiguration().setMaxEntriesLocalHeap(0);
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxEntriesLocalHeap());
- }
-
- @Test
- public void testMaxElementsOnDisk() {
- Cache cache = cacheManager.getCache(TEST_NAME);
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxElementsOnDisk());
- try {
- cache.getCacheConfiguration().setMaxElementsOnDisk(-1234);
- Assert.fail("should not be able to set negative maxElementsOnDisk");
- } catch (IllegalArgumentException e) {
- // expected exception;
- Assert.assertEquals("Illegal value -1234 for maxElementsOnDisk: has to be larger than or equal to 0", e.getMessage());
- }
-
- Assert.assertEquals(0, cache.getCacheConfiguration().getMaxElementsOnDisk());
- cache.getCacheConfiguration().setMaxElementsOnDisk(1234);
- Assert.assertEquals(1234, cache.getCacheConfiguration().getMaxElementsOnDisk());
- }
-
- @Test
- public void testTTL() {
- Cache cache = cacheManager.getCache(TEST_NAME);
- Assert.assertEquals(false, cache.getCacheConfiguration().isEternal());
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToLiveSeconds());
- try {
- cache.getCacheConfiguration().setTimeToLiveSeconds(-1234L);
- Assert.fail("should not be able to set negative TTL");
- } catch (IllegalArgumentException e) {
- // expected exception;
- Assert.assertEquals("Illegal value -1234 for timeToLiveSeconds: has to be larger than or equal to 0", e.getMessage());
- }
-
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToLiveSeconds());
- cache.getCacheConfiguration().setTimeToLiveSeconds(1234L);
- Assert.assertEquals(1234, cache.getCacheConfiguration().getTimeToLiveSeconds());
-
- cache.getCacheConfiguration().setEternal(true);
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToLiveSeconds());
- cache.getCacheConfiguration().setTimeToLiveSeconds(1234L);
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToLiveSeconds());
-
- cache.getCacheConfiguration().setEternal(false);
- cache.getCacheConfiguration().setTimeToLiveSeconds(1234L);
- Assert.assertEquals(1234, cache.getCacheConfiguration().getTimeToLiveSeconds());
- }
-
- @Test
- public void testTTI() {
- Cache cache = cacheManager.getCache(TEST_NAME);
- Assert.assertEquals(false, cache.getCacheConfiguration().isEternal());
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToIdleSeconds());
- try {
- cache.getCacheConfiguration().setTimeToIdleSeconds(-1234L);
- Assert.fail("should not be able to set negative TTI");
- } catch (IllegalArgumentException e) {
- // expected exception;
- Assert.assertEquals("Illegal value -1234 for timeToIdleSeconds: has to be larger than or equal to 0", e.getMessage());
- }
-
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToIdleSeconds());
- cache.getCacheConfiguration().setTimeToIdleSeconds(1234L);
- Assert.assertEquals(1234, cache.getCacheConfiguration().getTimeToIdleSeconds());
-
- cache.getCacheConfiguration().setEternal(true);
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToIdleSeconds());
- cache.getCacheConfiguration().setTimeToIdleSeconds(1234L);
- Assert.assertEquals(0, cache.getCacheConfiguration().getTimeToIdleSeconds());
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/disk/DiskSizeOfEngine.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/disk/DiskSizeOfEngine.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/disk/DiskSizeOfEngine.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.store.disk;
-
-import net.sf.ehcache.pool.Size;
-import net.sf.ehcache.pool.SizeOfEngine;
-
-/**
- * SizeOf engine which calculates exact usage of the disk store.
- *
- * @author Ludovic Orban
- */
-public class DiskSizeOfEngine implements SizeOfEngine {
-
- /**
- * {@inheritDoc}
- */
- public Size sizeOf(Object key, Object value, Object container) {
- if (container != null && !(container instanceof DiskStorageFactory.DiskMarker)) {
- throw new IllegalArgumentException("can only size DiskStorageFactory.DiskMarker");
- }
-
- if (container == null) {
- return new Size(0, true);
- }
-
- DiskStorageFactory.DiskMarker marker = (DiskStorageFactory.DiskMarker) container;
- return new Size(marker.getSize(), true);
- }
-
- /**
- * {@inheritDoc}
- */
- public SizeOfEngine copyWith(int maxDepth, boolean abortWhenMaxDepthExceeded) {
- return new DiskSizeOfEngine();
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EhcacheHibernateMBeanRegistrationImpl.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EhcacheHibernateMBeanRegistrationImpl.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EhcacheHibernateMBeanRegistrationImpl.java (revision 0)
@@ -1,159 +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.lang.management.ManagementFactory;
-import java.util.Properties;
-
-import javax.management.InstanceAlreadyExistsException;
-import javax.management.MBeanServer;
-import javax.management.ObjectName;
-
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheManager;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.event.CacheManagerEventListener;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.Environment;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Implementation of {@link EhcacheHibernateMBeanRegistration}.
- * Also implements {@link CacheManagerEventListener}. Deregisters mbeans when the associated cachemanager is shutdown.
- *
- *
- *
- * @author Abhishek Sanoujam
- *
- */
-public class EhcacheHibernateMBeanRegistrationImpl implements EhcacheHibernateMBeanRegistration, CacheManagerEventListener {
-
- private static final Logger LOG = LoggerFactory.getLogger(EhcacheHibernateMBeanRegistrationImpl.class.getName());
-
- private static final int MAX_MBEAN_REGISTRATION_RETRIES = 50;
- private String cacheManagerClusterUUID;
- private String registeredCacheManagerName;
- private Status status = Status.STATUS_UNINITIALISED;
- private volatile EhcacheHibernate ehcacheHibernate;
- private volatile ObjectName cacheManagerObjectName;
-
- /**
- * {@inheritDoc}
- */
- public synchronized void registerMBeanForCacheManager(final CacheManager manager, final Properties properties) throws Exception {
- String sessionFactoryName = properties.getProperty(Environment.SESSION_FACTORY_NAME);
- String name = null;
- if (sessionFactoryName == null) {
- name = manager.getName();
- } else {
- name = "".equals(sessionFactoryName.trim()) ? manager.getName() : sessionFactoryName;
- }
- registerBean(name, manager);
- }
-
- private void registerBean(String name, CacheManager manager) throws Exception {
- ehcacheHibernate = new EhcacheHibernate(manager);
- int tries = 0;
- boolean success = false;
- Exception exception = null;
- cacheManagerClusterUUID = manager.getClusterUUID();
- do {
- this.registeredCacheManagerName = name;
- if (tries != 0) {
- registeredCacheManagerName += "_" + tries;
- }
- try {
- // register the CacheManager MBean
- MBeanServer mBeanServer = getMBeanServer();
- cacheManagerObjectName = EhcacheHibernateMbeanNames.getCacheManagerObjectName(cacheManagerClusterUUID,
- registeredCacheManagerName);
- mBeanServer.registerMBean(ehcacheHibernate, cacheManagerObjectName);
- success = true;
- break;
- } catch (InstanceAlreadyExistsException e) {
- success = false;
- exception = e;
- }
- tries++;
- } while (tries < MAX_MBEAN_REGISTRATION_RETRIES);
- if (!success) {
- throw new Exception("Cannot register mbean for CacheManager with name" + manager.getName() + " after "
- + MAX_MBEAN_REGISTRATION_RETRIES + " retries. Last tried name=" + registeredCacheManagerName, exception);
- }
- status = status.STATUS_ALIVE;
- }
-
- private MBeanServer getMBeanServer() {
- return ManagementFactory.getPlatformMBeanServer();
- }
-
- /**
- * {@inheritDoc}
- */
- public void enableHibernateStatisticsSupport(SessionFactory sessionFactory) {
- ehcacheHibernate.enableHibernateStatistics(sessionFactory);
- }
-
- /**
- * {@inheritDoc}
- */
- public synchronized void dispose() throws CacheException {
- if (status == Status.STATUS_SHUTDOWN) {
- return;
- }
-
- try {
- getMBeanServer().unregisterMBean(cacheManagerObjectName);
- } catch (Exception e) {
- LOG.warn("Error unregistering object instance " + cacheManagerObjectName + " . Error was " + e.getMessage(), e);
- }
- ehcacheHibernate = null;
- cacheManagerObjectName = null;
- status = Status.STATUS_SHUTDOWN;
- }
-
- /**
- * {@inheritDoc}
- */
- public synchronized Status getStatus() {
- return status;
- }
-
- /**
- * No-op in this case
- */
- public void init() throws CacheException {
- // no-op
- }
-
- /**
- * No-op in this case
- */
- public void notifyCacheAdded(String cacheName) {
- // no-op
- }
-
- /**
- * No-op in this case
- */
- public void notifyCacheRemoved(String cacheName) {
- // no-op
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/Policy.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/Policy.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/Policy.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.store;
-
-import net.sf.ehcache.Element;
-
-/**
- * An eviction policy.
- *
- * The Cache will use a policy at startup. There are three policy implementations provided in ehcache:
- * LRU, LFU and FIFO. However many other policies are possible. That the policy
- * has access to the whole element enables policies based on the key, value, metadata, statistics, or a combination of
- * any of the above.
- *
- * @author Greg Luck
- */
-public interface Policy {
-
- /**
- * @return the name of the Policy. Inbuilt examples are LRU, LFU and FIFO.
- */
- String getName();
-
- /**
- * Finds the best eviction candidate based on the sampled elements. What distinguishes
- * this approach from the classic data structures approach is that an Element contains
- * metadata (e.g. usage statistics) which can be used for making policy decisions,
- * while generic data structures do not. It is expected that implementations will take
- * advantage of that metadata.
- *
- * @param sampledElements this should be a random subset of the population
- * @param justAdded we probably never want to select the element just added.
- * It is provided so that it can be ignored if selected. May be null.
- * @return the selected Element
- */
- Element selectedBasedOnPolicy(Element[] sampledElements, Element justAdded);
-
- /**
- * Compares the desirableness for eviction of two elements
- *
- * @param element1 the element to compare against
- * @param element2 the element to compare
- * @return true if the second element is preferable for eviction to the first element
- * under ths policy
- */
- boolean compare(Element element1, Element element2);
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/ContainerTestSetup.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/ContainerTestSetup.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/ContainerTestSetup.java (revision 0)
@@ -1,105 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.container;
-
-import ch.qos.logback.classic.LoggerContext;
-import ch.qos.logback.core.Layout;
-import net.sf.ehcache.Ehcache;
-
-import org.apache.commons.io.IOUtils;
-import org.junit.Assert;
-import org.slf4j.LoggerFactory;
-import org.slf4j.impl.StaticLoggerBinder;
-import org.terracotta.test.util.TestBaseUtil;
-import org.terracotta.toolkit.Toolkit;
-
-import com.tc.test.server.appserver.StandardAppServerParameters;
-import com.tc.test.server.appserver.deployment.AbstractStandaloneTwoServerDeploymentTest;
-import com.tc.test.server.appserver.deployment.AbstractStandaloneTwoServerDeploymentTest.StandaloneTwoServerTestSetup;
-import com.tc.test.server.appserver.deployment.DeploymentBuilder;
-import com.tc.test.server.appserver.deployment.TempDirectoryUtil;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-
-public class ContainerTestSetup extends StandaloneTwoServerTestSetup {
- protected final String ehcacheConfigTemplate;
-
- public ContainerTestSetup(Class extends AbstractStandaloneTwoServerDeploymentTest> testClass,
- String ehcacheConfigTemplate, String context) {
- super(testClass, context);
- this.ehcacheConfigTemplate = ehcacheConfigTemplate;
- }
-
- @Override
- protected void configureWar(DeploymentBuilder builder) {
- addCommonJars(builder);
- builder.addFileAsResource(getTempEhcacheConfigFile(), "WEB-INF/classes/");
- }
-
- protected void addCommonJars(DeploymentBuilder builder) {
- addEhcacheDependencies(builder);
- addToolkitRuntimeDependencies(builder);
- builder.addDirectoryOrJARContainingClass(Assert.class); // junit
- builder.addDirectoryOrJARContainingClass(LoggerFactory.class); // slf4j-api
- builder.addDirectoryOrJARContainingClass(StaticLoggerBinder.class); // slf4j-log4j
- builder.addDirectoryOrJARContainingClass(LoggerContext.class);
- builder.addDirectoryOrJARContainingClass(Layout.class); // logback
- }
-
- private void addEhcacheDependencies(DeploymentBuilder builder) {
- List jars = TestBaseUtil.getEhcacheDependencies(Ehcache.class);
- for (String jar : jars) {
- builder.addDirectoryOrJAR(jar);
- }
- }
-
- private void addToolkitRuntimeDependencies(DeploymentBuilder builder) {
- List jars = TestBaseUtil.getToolkitRuntimeDependencies(Toolkit.class);
- for (String jar : jars) {
- builder.addDirectoryOrJAR(jar);
- }
- }
-
- private File getTempEhcacheConfigFile() {
- try {
- File ehcacheConfigFile = writeDefaultConfigFile(TempDirectoryUtil.getTempDirectory(this.getClass()),
- getServerManager().getServerTcConfig().getTsaPort());
- System.out.println("Wrote temp config file at: " + ehcacheConfigFile.getAbsolutePath());
- return ehcacheConfigFile;
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- private File writeDefaultConfigFile(File configFileLocation, int port) throws IOException {
- return writeConfigFile(configFileLocation, "ehcache.xml", port);
- }
-
- private File writeConfigFile(File configFileLocation, String fileName, int port) throws IOException {
- InputStream in = null;
- FileOutputStream out = null;
-
- try {
- in = getClass().getClassLoader().getResourceAsStream(ehcacheConfigTemplate);
- File rv = new File(configFileLocation, fileName);
- out = new FileOutputStream(rv);
- String template = IOUtils.toString(in);
- String config = template.replace("PORT", String.valueOf(port));
- out.write(config.getBytes());
- return rv;
- } finally {
- IOUtils.closeQuietly(in);
- IOUtils.closeQuietly(out);
- }
- }
-
- @Override
- protected void configureServerParamers(StandardAppServerParameters params) {
- super.configureServerParamers(params);
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache/src/test/resources/serializedforms/DeleteAsyncOperationSerializationTest.testBasic.ser
===================================================================
diff -u -N -r11322 -r11323
Binary files differ
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/EhCacheClusteredHibernateCacheServlet.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/EhCacheClusteredHibernateCacheServlet.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/EhCacheClusteredHibernateCacheServlet.java (revision 0)
@@ -1,129 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package org.terracotta.ehcache.tests.container.hibernate.nontransactional;
-
-import org.hibernate.stat.QueryStatistics;
-import org.hibernate.stat.SecondLevelCacheStatistics;
-import org.hibernate.stat.Statistics;
-import org.junit.Assert;
-import org.terracotta.ehcache.tests.container.hibernate.BaseClusteredRegionFactoryTestServlet;
-import org.terracotta.ehcache.tests.container.hibernate.domain.Event;
-import org.terracotta.ehcache.tests.container.hibernate.domain.EventManager;
-import org.terracotta.ehcache.tests.container.hibernate.domain.Person;
-import org.terracotta.ehcache.tests.container.hibernate.domain.PhoneNumber;
-
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-import javax.servlet.http.HttpSession;
-
-public class EhCacheClusteredHibernateCacheServlet extends BaseClusteredRegionFactoryTestServlet {
- public EhCacheClusteredHibernateCacheServlet() {
- //
- }
-
- private static final long serialVersionUID = 1L;
-
- @Override
- protected void doServer0(HttpSession httpSession, Map parameters) throws Exception {
- HibernateUtil.dropAndCreateDatabaseSchema();
-
- EventManager mgr = new EventManager(HibernateUtil.getSessionFactory());
- Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
- stats.setStatisticsEnabled(true);
-
- // create 3 persons Steve, Orion, Tim
- Person stevePerson = new Person();
- stevePerson.setFirstname("Steve");
- stevePerson.setLastname("Harris");
- Long steveId = mgr.createAndStorePerson(stevePerson);
- mgr.addEmailToPerson(steveId, "steve@tc.com");
- mgr.addEmailToPerson(steveId, "sharrif@tc.com");
- mgr.addTalismanToPerson(steveId, "rabbit foot");
- mgr.addTalismanToPerson(steveId, "john de conqueroo");
-
- PhoneNumber p1 = new PhoneNumber();
- p1.setNumberType("Office");
- p1.setPhone(111111);
- mgr.addPhoneNumberToPerson(steveId, p1);
-
- PhoneNumber p2 = new PhoneNumber();
- p2.setNumberType("Home");
- p2.setPhone(222222);
- mgr.addPhoneNumberToPerson(steveId, p2);
-
- Person orionPerson = new Person();
- orionPerson.setFirstname("Orion");
- orionPerson.setLastname("Letizi");
- Long orionId = mgr.createAndStorePerson(orionPerson);
- mgr.addEmailToPerson(orionId, "orion@tc.com");
- mgr.addTalismanToPerson(orionId, "voodoo doll");
-
- Long timId = mgr.createAndStorePerson("Tim", "Teck");
- mgr.addEmailToPerson(timId, "teck@tc.com");
- mgr.addTalismanToPerson(timId, "magic decoder ring");
-
- Long engMeetingId = mgr.createAndStoreEvent("Eng Meeting", stevePerson, new Date());
- mgr.addPersonToEvent(steveId, engMeetingId);
- mgr.addPersonToEvent(orionId, engMeetingId);
- mgr.addPersonToEvent(timId, engMeetingId);
-
- Long docMeetingId = mgr.createAndStoreEvent("Doc Meeting", orionPerson, new Date());
- mgr.addPersonToEvent(steveId, docMeetingId);
- mgr.addPersonToEvent(orionId, docMeetingId);
-
- for (Event event : (List) mgr.listEvents()) {
- mgr.listEmailsOfEvent(event.getId());
- }
-
- HibernateUtil.getSessionFactory().close();
-
- System.err.println("Second Level Cache Regions");
- for (String region : stats.getSecondLevelCacheRegionNames()) {
- System.err.println("Region : " + region);
- SecondLevelCacheStatistics l2Stats = stats.getSecondLevelCacheStatistics(region);
- System.err.println("\tCache Miss Count " + l2Stats.getMissCount());
- System.err.println("\tCache Hit Count " + l2Stats.getHitCount());
- System.err.println("\tCache Put Count " + l2Stats.getPutCount());
- }
-
- QueryStatistics queryStats = stats.getQueryStatistics("from Event");
- Assert.assertEquals("Cache Miss Count", 1L, queryStats.getCacheMissCount());
- Assert.assertEquals("Cache Hit Count", 0L, queryStats.getCacheHitCount());
- Assert.assertEquals("Cache Put Count", 1L, queryStats.getCachePutCount());
-
- }
-
- @Override
- @SuppressWarnings("deprecation")
- protected void doServer1(HttpSession httpSession, Map parameters) throws Exception {
- EventManager mgr = new EventManager(HibernateUtil.getSessionFactory());
- Statistics stats = HibernateUtil.getSessionFactory().getStatistics();
- stats.setStatisticsEnabled(true);
-
- for (Event event : (List) mgr.listEvents()) {
- mgr.listEmailsOfEvent(event.getId());
- }
-
- HibernateUtil.getSessionFactory().close();
-
- System.err.println("Second Level Cache Regions");
- for (String region : stats.getSecondLevelCacheRegionNames()) {
- System.err.println("Region : " + region);
- SecondLevelCacheStatistics l2Stats = stats.getSecondLevelCacheStatistics(region);
- Assert.assertEquals("L2 Cache [Region " + region + "] Cache Miss Count", 0L, l2Stats.getMissCount());
-
- System.err.println("\tCache Miss Count " + l2Stats.getMissCount());
- System.err.println("\tCache Hit Count " + l2Stats.getHitCount());
- System.err.println("\tCache Put Count " + l2Stats.getPutCount());
- }
-
- QueryStatistics queryStats = stats.getQueryStatistics("from Event");
- Assert.assertEquals("Cache Miss Count", 0L, queryStats.getCacheMissCount());
- Assert.assertEquals("Cache Hit Count", 1L, queryStats.getCacheHitCount());
- Assert.assertEquals("Cache Put Count", 0L, queryStats.getCachePutCount());
-
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/CopyStrategy.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/CopyStrategy.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/CopyStrategy.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.store.compound;
-
-import java.io.Serializable;
-
-/**
- * @deprecated replaced by {@link net.sf.ehcache.store.compound.ReadWriteCopyStrategy}
- * @author Alex Snaps
- */
-@Deprecated
-public interface CopyStrategy extends Serializable {
- /**
- * Deep copies some object and returns the copy
- * @param value the value to copy
- * @param type
- * @return the copy
- */
- T copy(final T value);
-}
Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/src/main/java/net/sf/ehcache/management/service/impl/ConstrainableEntityBuilderSupport.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/src/main/java/net/sf/ehcache/management/service/impl/ConstrainableEntityBuilderSupport.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/src/main/java/net/sf/ehcache/management/service/impl/ConstrainableEntityBuilderSupport.java (revision 0)
@@ -1,136 +0,0 @@
-/*
- * All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright
- * notice. All rights reserved.
- */
-package net.sf.ehcache.management.service.impl;
-
-import net.sf.ehcache.management.service.AccessorPrefix;
-import net.sf.ehcache.util.counter.Counter;
-import net.sf.ehcache.util.counter.sampled.SampledCounter;
-import org.slf4j.Logger;
-
-import java.lang.reflect.Method;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-/**
-* @author brandony
-*/
-abstract class ConstrainableEntityBuilderSupport {
-
- private static final Set SIZE_ATTRIBUTE_NAMES =
- Collections.unmodifiableSet(new HashSet(Arrays.asList("Size", "SizeSample", "RemoteSizeSample")));
-
- private Set constraints;
-
- abstract Logger getLog();
-
- protected void addConstraints(Set constraints) {
- if (constraints == null) throw new IllegalArgumentException("constraints == null");
-
- if (this.constraints == null) {
- this.constraints = constraints;
- } else {
- this.constraints.addAll(constraints);
- }
- }
-
- protected Set getAttributeConstraints() {
- return constraints;
- }
-
- protected void buildAttributeMapByAttribute(Class> api,
- SAMPLER sampler,
- Map attributeMap,
- Collection attributes,
- String nameAccessor) {
- Set excludedNames = getExcludedAttributeNames(sampler);
-
- for (String attribute : attributes) {
- Method method = null;
- for (AccessorPrefix prefix : AccessorPrefix.values()) {
- try {
- method = api.getMethod(prefix + attribute);
- break;
- } catch (NoSuchMethodException e) {
- //This is not the accessor you were looking for....move along
- }
- }
-
- if (method != null && !nameAccessor.equals(method.getName())) {
- if (excludedNames.contains(attribute)) {
- attributeMap.put(attribute, 0);
- continue;
- }
-
- addAttribute(sampler, attributeMap, attribute, method);
- }
- }
- }
-
- protected void buildAttributeMapByApi(Class> api,
- SAMPLER sampler,
- Map attributeMap,
- Collection attributes,
- String nameAccessor) {
- Set excludedNames = getExcludedAttributeNames(sampler);
-
- for (Method method : api.getMethods()) {
- String name = method.getName();
- String trimmedName = AccessorPrefix.trimPrefix(name);
- if (!nameAccessor.equals(name) && AccessorPrefix.isAccessor(name) && (attributes == null || attributes.contains(
- trimmedName))) {
-
- if (excludedNames.contains(trimmedName)) {
- attributeMap.put(trimmedName, 0);
- continue;
- }
-
- addAttribute(sampler, attributeMap, trimmedName, method);
- }
- }
- }
-
- protected abstract Set getExcludedAttributeNames(SAMPLER sampler);
-
- protected Set getUnsignedIntAttributeNames(SAMPLER sampler) {
- return SIZE_ATTRIBUTE_NAMES;
- }
-
- private void addAttribute(SAMPLER sampler,
- Map attributeMap,
- String attribute,
- Method method) {
- Object value = null;
- try {
- value = method.invoke(sampler);
-
- // stats reflection "helper" code
- if (value instanceof SampledCounter) {
- value = ((SampledCounter)value).getMostRecentSample().getCounterValue();
- } else if (value instanceof Counter) {
- value = ((Counter)value).getValue();
- }
-
- if (getUnsignedIntAttributeNames(sampler).contains(attribute) && value instanceof Number) {
- value = coerceUnsignedIntToLong(((Number)value).intValue());
- }
- } catch (Exception e) {
- value = null;
- String msg = String.format("Failed to invoke method %s while constructing entity.", method.getName());
- getLog().warn(msg);
- getLog().debug(msg, e);
- } finally {
- attributeMap.put(attribute, value);
- }
- }
-
- private static long coerceUnsignedIntToLong(int value) {
- return value < 0 ? ((long)Integer.MAX_VALUE) + (value - Integer.MIN_VALUE + 1) : value;
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/hibernate-config/shutdowntest/hibernate.cfg.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/hibernate-config/shutdowntest/hibernate.cfg.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/hibernate-config/shutdowntest/hibernate.cfg.xml (revision 0)
@@ -1,52 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
- org.apache.derby.jdbc.ClientDriver
-
-
- jdbc:derby://localhost:__PORT__/MyDbTest;create=true
-
-
- user1
- user1
-
-
- 1
-
-
-
- org.hibernate.dialect.DerbyDialect
-
-
-
- thread
-
- true
- true
- true
- net.sf.ehcache.hibernate.EhCacheRegionFactory
- /ehcache-config.xml
-
- true
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriterFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriterFactory.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriterFactory.java (revision 0)
@@ -1,45 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.writer;
-
-import net.sf.ehcache.Ehcache;
-
-import java.util.Properties;
-
-/**
- * An abstract factory for creating cache writers. Implementers should provide their own
- * concrete factory extending this factory.
- *
- * Note that Ehcache API also allows the CacheWriter to be set programmatically.
- *
- * @author Greg Luck
- * @author Geert Bevin
- * @version $Id: CacheWriterFactory.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public abstract class CacheWriterFactory {
-
- /**
- * Creates a CacheWriter using the Ehcache configuration mechanism at the time the associated cache is created.
- *
- * @param cache a reference to the owning cache
- * @param properties configuration properties that will be ignored by Ehcache, but may be useful for specifying
- * the underlying resource. e.g. dataSourceName could be specified and then looked up in JNDI.
- *
- * @return a constructed CacheWriter
- */
- public abstract CacheWriter createCacheWriter(Ehcache cache, Properties properties);
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/hibernate-config/domain/Event.hbm.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/hibernate-config/domain/Event.hbm.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/hibernate-config/domain/Event.hbm.xml (revision 0)
@@ -1,26 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/distribution/src/main/assembly/root/licenses/THIRD-PARTY-LICENSES.txt
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/distribution/src/main/assembly/root/licenses/THIRD-PARTY-LICENSES.txt (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/distribution/src/main/assembly/root/licenses/THIRD-PARTY-LICENSES.txt (revision 0)
@@ -1,622 +0,0 @@
-Acknowledgements & Disclosures
-
-Terracotta gratefully acknowledges the open-source software community's
-contributions to the development of our products.� In accordance with
-requirements established by the operative license agreements entered
-into by Terracotta and certain third-party software vendors, Terracotta
-discloses the items listed below.
-
-In addition, please note that any customer that purchases and installs
-Terracotta software accepts, and agrees to comply with, the license
-agreements cited herein.� Terracotta does not charge any customer for
-the use of any third-party software product(s).
-
-Disclosures:
-
-(1) Terracotta's software uses unmodified portions of ANTLR's source
-code and uses its output.
-
-(2) Terracotta incorporates ObjectWeb's ASM into its software, and
-recites the following terms, pursuant to the governing BSD license.
-(Note that herein, "copyright holder" and "contributor" refers to
-ObjectWeb, and "software" refers to the ASM product.)
-
-Copyright (c) 2005, ObjectWeb (ASM).� All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-(1) Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-
-(2)�Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
-
-(3)�Neither the name of ObjectWeb (ASM) nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
-IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
-TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-(4)�Terracotta incorporates AspectWerkz into its software.
-�Because Terracotta does not modify Aspectwerkz and redistribute the
-modifications, most of the substantive terms of the governing Lesser
-GNU Public License (LGPL) are inapplicable, pursuant to the express
-terms of the Aspectwerkz licensing documentation, which is available
-online at http://aspectwerkz.codehaus.org/license.html and excerpted in
-relevant part, below:� AspectWerkz is Free Software. The LGPL license
-is sufficiently flexible to allow the use of AspectWerkz in both open
-source and commercial projects. Using AspectWerkz (by importing
-AspectWerkz's public interfaces in your Java code), and extending
-AspectWerkz (by subclassing) is considered by the authors of
-AspectWerkz to be dynamic linking. Hence our interpretation of the LGPL
-is that the use of the unmodified AspectWerkz source does not affect
-the license of your application code. The use of the unmodified
-AspectWerkz binary of course never affects the license of your
-application or distribution. If you modify AspectWerkz and redistribute
-your modifications, the LGPL applies.
-
-(5)�Terracotta incorporates eleven components into its software
-(Apache Commons CLI; Apache Commons Collections; Apache Commons IO,
-Apache Commons Lang; Apache Commons Logging; Apache Jakarta Regexp;
-Apache Log4j; Apache Xalan-Java; Apache XMLBeans 2.0.0; TrueZIP;
-Google Collections; and Jetty) that are licensed under the Apache
-License 2.0, which sets forth the following requirements:
-
-Copyright 2005 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.
-
-Apache Xerces is licensed under the Apache License 1.1, which sets
-forth the following requirements:
-
-Copyright (c) 1999 The Apache Software Foundation.� All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-1. Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-
-2. Redistributions in binary form must reproduce the above copyright
-notice, this list of conditions and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
-
-3. The end-user documentation included with the redistribution, if any,
-must include the following acknowledgment: "This product includes
-software developed by the Apache Software Foundation
-(http://www.apache.org/)." Alternately, this acknowledgment may appear
-in the software itself, if and wherever such third-party
-acknowledgments normally appear.
-
-4. The names "Xerces" and "Apache Software Foundation" must not be used
-to endorse or promote products derived from this software without prior
-written permission. For written permission, please contact
-apache@apache.org.
-
-5. Products derived from this software may not be called "Apache", nor
-may "Apache" appear in their name, without prior written permission of
-the Apache Software Foundation.
-
-THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR �IMPLIED
-WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
-IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE
-LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
-BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
-WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-This software consists of voluntary contributions made by many
-individuals on behalf of the Apache Software Foundation and was
-originally based on software copyright (c) 1999, International Business
-Machines, Inc., http://www.ibm.com.� For more information on the Apache
-Software Foundation, please see .
-
-(6)�Terracotta incorporates the GNU Trove library into its
-software. �The source code for GNU Trove is licensed under the Lesser
-GNU Public License (LGPL), a copy of which is available for public
-download at http://www.gnu.org/copyleft/lesser.html.� Because
-Terracotta does not modify the source code for GNU Trove, most of the
-substantive requirements of the LGPL are inapplicable.� As required by
-the LGPL, Terracotta recites the following:
-
-Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
-
-This library is free software; you can redistribute it and/or modify it
-under the terms of the GNU Lesser General Public License as published
-by the Free Software Foundation; either version 2.1 of the License, or
-(at your option) any later version.
-
-This library is distributed in the hope that it will be useful, but
-WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.� See the GNU
-General Public License for more details.
-
-Two classes (HashFunctions and PrimeFinder) included in Trove are
-licensed under the following terms:
-
-Copyright (c) 1999 CERN - European Organization for Nuclear Research.
-
-Permission to use, copy, modify, distribute and sell this software and
-its documentation for any purpose is hereby granted without fee,
-provided that the above copyright notice appear in all copies and that
-both that copyright notice and this permission notice appear in
-supporting documentation. CERN makes no representations about the
-suitability of this software for any purpose. It is provided "as is"
-without expressed or implied warranty.
-
-(7)�Terracotta incorporates Sun Microsystems' JAXP into its
-software. �Pursuant to the terms of the governing W3C license,
-Terracotta recites the following terms:
-
-W3C� SOFTWARE NOTICE AND LICENSE
-
-Copyright � 1994-2002 World Wide Web Consortium, (Massachusetts
-Institute of Technology, Institut National de Recherche en Informatique
-et en Automatique, Keio University). All Rights Reserved.
-
-http://www.w3.org/Consortium/Legal/
-
-This W3C work (including software, documents, or other related items)
-is being provided by the copyright holders under the following license.
-By obtaining, using and/or copying this work, you (the licensee) agree
-that you have read, understood, and will comply with the following
-terms and conditions:
-
-Permission to use, copy, modify, and distribute this software and its
-documentation, with or without modification, for any purpose and
-without fee or royalty is hereby granted, provided that you include the
-following on ALL copies of the software and documentation or portions
-thereof, including modifications, that you make:
-
-1.The full text of this NOTICE in a location viewable to users of the
-redistributed or derivative work.
-
-2.Any pre-existing intellectual property disclaimers, notices, or terms
-and conditions. If none exist, a short notice of the following form
-(hypertext is preferred, text is permitted) should be used within the
-body of any redistributed or derivative code: "Copyright � [2005] World
-Wide Web Consortium, (Massachusetts Institute of Technology, Institut
-National de Recherche en Informatique et en Automatique, Keio
-University). All Rights Reserved. http://www.w3.org/Consortium/Legal/"
-
-3.Notice of any changes or modifications to the W3C files, including
-the date changes were made. (We recommend you provide URIs to the
-location from which the code is derived.)
-
-THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT
-HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED,
-INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS
-FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR
-DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS,
-TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR
-ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF
-ANY USE OF THE SOFTWARE OR DOCUMENTATION.
-
-The name and trademarks of copyright holders may NOT be used in
-advertising or publicity pertaining to the software without specific,
-written prior permission. Title to copyright in this software and any
-associated documentation will at all times remain with copyright
-holders.
-
-The following software may be included in this product: Xalan 2.x. Use
-of any of this software is governed by the terms of the Apache License,
-version 2.0 (January 2004), as set forth above in this Documentation
-(See section (4), supra, and accompanying text).
-
-The following software may be included in this product: BCEL 5.x. Use
-of any of this software is governed by the terms of the license below:
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met: Redistribution of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-Redistribution in binary form must reproduce the above copyright
-notice, this list of conditions and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
-All advertising materials mentioning features or use of this software
-must display the following acknowledgment: This product includes
-software developed by the Java Apache Project for use in the Apache
-JServ servlet engine project (http://java.apache.org/).
-
-The names "Apache JServ", "Apache JServ Servlet Engine" and "Java
-Apache Project" must not be used to endorse or promote products derived
-from this software without prior written permission. Products derived
-from this software may not be called "Apache JServ" nor may "Apache"
-nor "Apache JServ" appear in their names without prior written
-permission of the Java Apache Project. Redistribution of any form
-whatsoever must retain the following acknowledgment: This product
-includes software developed by the Java Apache Project for use in the
-Apache JServ servlet engine project (http://java.apache.org/).
-
-THIS SOFTWARE IS PROVIDED BY THE JAVA APACHE PROJECT "AS IS" AND ANY
-EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JAVA APACHE PROJECT OR
-ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-The following software may be included in this product: RegExp v1.x.
-Use of any of this software is governed by the terms of the license
-below:
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met: Redistribution of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-Redistribution in binary form must reproduce the above copyright
-notice, this list of conditions and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
-All advertising materials mentioning features or use of this software
-must display the following acknowledgment: This product includes
-software developed by the Java Apache Project for use in the Apache
-JServ servlet engine project (http://java.apache.org/).
-
-The names "Apache JServ", "Apache JServ Servlet Engine" and "Java
-Apache Project" must not be used to endorse or promote products derived
-from this software without prior written permission. Products derived
-from this software may not be called "Apache JServ" nor may "Apache"
-nor "Apache JServ" appear in their names without prior written
-permission of the Java Apache Project. Redistribution of any form
-whatsoever must retain the following acknowledgment: This product
-includes software developed by the Java Apache Project for use in the
-Apache JServ servlet engine project (http://java.apache.org/).
-
-THIS SOFTWARE IS PROVIDED BY THE JAVA APACHE PROJECT "AS IS" AND ANY
-EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JAVA APACHE PROJECT OR
-ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-The following software may be included in this product: Jcup. Use of
-any of this software is governed by the terms of the license below:
-
-CUP Parser Generator Copyright Notice, License, and Disclaimer
-
-Copyright 1996-1999 by Scott Hudson, Frank Flannery, C. Scott Ananian
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both the copyright notice and this permission notice and warranty
-disclaimer appear in supporting documentation, and that the names of
-the authors or their employers not be used in advertising or publicity
-pertaining to distribution of the software without specific, written
-prior permission.
-
-The authors and their employers disclaim all warranties with regard to
-this software, including all implied warranties of merchantability and
-fitness. In no event shall the authors or their employers be liable for
-any special, indirect or consequential damages or any damages
-whatsoever resulting from loss of use, data or profits, whether in an
-action of contract, negligence or other tortious action, arising out of
-or in connection with the use or performance of this software.
-
-The following software may be included in this product: Jlex. Use of
-any of this software is governed by the terms of the license below:
-
-JLEX COPYRIGHT NOTICE, LICENSE AND DISCLAIMER.
-
-Copyright 1996-2003 by Elliot Joel Berk and C. Scott Ananian
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both the copyright notice and this permission notice and warranty
-disclaimer appear in supporting documentation, and that the name of the
-authors or their employers not be used in advertising or publicity
-pertaining to distribution of the software without specific, written
-prior permission.
-
-The authors and their employers disclaim all warranties with regard to
-this software, including all implied warranties of merchantability and
-fitness. In no event shall the authors or their employers be liable for
-any special, indirect or consequential damages or any damages
-whatsoever resulting from loss of use, data or profits, whether in an
-action of contract, negligence or other tortious action, arising out of
-or in connection with the use or performance of this software.
-
-Java is a trademark of Sun Microsystems, Inc. References to the Java
-programming language in relation to JLex are not meant to imply that
-Sun endorses this product.
-
-The following software may be included in this product: Xerces v2.6.x.
-Use of any of this software is governed by the terms of the license
-below:
-
-Copyright 1996-2003 by Elliot Joel Berk and C. Scott Ananian
-
-Permission to use, copy, modify, and distribute this software and its
-documentation for any purpose and without fee is hereby granted,
-provided that the above copyright notice appear in all copies and that
-both the copyright notice and this permission notice and warranty
-disclaimer appear in supporting documentation, and that the name of the
-authors or their employers not be used in advertising or publicity
-pertaining to distribution of the software without specific, written
-prior permission.
-
-The authors and their employers disclaim all warranties with regard to
-this software, including all implied warranties of merchantability and
-fitness. In no event shall the authors or their employers be liable for
-any special, indirect or consequential damages or any damages
-whatsoever resulting from loss of use, data or profits, whether in an
-action of contract, negligence or other tortious action, arising out of
-or in connection with the use or performance of this software.
-
-Java is a trademark of Sun Microsystems, Inc. References to the Java
-programming language in relation to JLex are not meant to imply that
-Sun endorses this product.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met: Redistribution of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-Redistribution in binary form must reproduce the above copyright
-notice, this list of conditions and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
-All advertising materials mentioning features or use of this software
-must display the following acknowledgment: This product includes
-software developed by the Java Apache Project for use in the Apache
-JServ servlet engine project (http://java.apache.org/).
-
-The names "Apache JServ", "Apache JServ Servlet Engine" and "Java
-Apache Project" must not be used to endorse or promote products derived
-from this software without prior written permission. Products derived
-from this software may not be called "Apache JServ" nor may "Apache"
-nor "Apache JServ" appear in their names without prior written
-permission of the Java Apache Project. Redistribution of any form
-whatsoever must retain the following acknowledgment: This product
-includes software developed by the Java Apache Project for use in the
-Apache JServ servlet engine project (http://java.apache.org/).
-
-THIS SOFTWARE IS PROVIDED BY THE JAVA APACHE PROJECT "AS IS" AND ANY
-EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JAVA APACHE PROJECT OR
-ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-Terracotta also incorporates Sun Microsystems' JAXP / SAX and JAXP /
-DOM into its software.� Pursuant to the terms of the APIs' governing
-license, Terracotta recites the following:
-
-Copyright Sun Microsystems, Inc. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
-- Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
-
-- Redistribution in binary form must reproduce the above copyright
-notice, this list of conditions and the following disclaimer in the
-documentation and/or other materials provided with the distribution.
-
-Neither the name of Sun Microsystems, Inc. or the names of contributors
-may be used to endorse or promote products derived from this software
-without specific prior written permission.
-
-This software is provided "AS IS," without a warranty of any kind. ALL
-EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
-INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
-ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
-AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE OR ITS
-DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY
-LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
-CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND
-REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR
-INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-You acknowledge that Software is not designed, licensed or intended for
-use in the design, construction, operation or maintenance of any
-nuclear facility.
-
-(8) Terracotta incorporates Doug Lea's utilities into its software.
-Portions of the CopyOnWriteArrayList and ConcurrentReaderHashMap
-classes are adapted from Sun Microsystems' JDK source code.� Sun
-Microsystems retains all copyright in the classes, which are subject to
-the conditions set forth in the license agreement between Doug Lea and
-Sun Microsystems, which is online at
-http://gee.cs.oswego.edu/dl/classes/EDU/oswego/cs/dl/util/sun-u.c.
-license.pdf and excerpted, in relevant part, as follows:
-
-"Java Software Technologies" means
-
-classes/java/util/ArrayList.java, and
-classes/java/util/HashMap.java.
-
-The Java Software Technologies are copyright � 1994-2000 Sun
-Microsystems, Inc.� All rights reserved.
-
-Sun hereby grants Doug Lea a non-excusive, worldwide, non-transferrable
-license to use, reproduce, create derivative works of, and distribute
-the Java Software and derivative works thereof in source and binary
-forms as part of a larger work, and to sublicense the right to use,
-reproduce and distribute the Java Software and Doug Lea's derivative
-works as the part of larger works through multiple tiers of
-sublicensees provided that the following conditions are met:
-
-(a)�Neither the name of or trademarks of Sun may be used to endorse
-or promote products including or derived from the Java Software
-Technology without specific prior written permission; and
-
-(b)�Redistributions of source or binary code must contain the above
-copyright notice, this notice and the following disclaimers:
-
-This software is provided "AS IS," without a warranty of any kind.� ALL
-EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
-INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED.� SUN
-MICROSYSTEMS, INC. AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY
-DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
-DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES.� IN NO EVENT WILL SUN
-MICROSYSTEMS, INC. OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE,
-PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
-INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE
-THEORY OF LIABILITY, ARISING OUT OF THE USE OR INABILITY TO USE
-SOFTWARE, EVEN IF SUN MICROSYSTEMS, INC. HAS BEEN ADVISED OF THE
-POSSIBILITY OF SUCH DAMAGES.
-
-You acknowledge that Software is not designed, licensed or intended for
-us in the design, construction, operation or maintenance of any nuclear
-facility.
-
-(9) Terracotta incorporates Base64, a Java class
-freely-available in the public domain, into its software.
-
-(10) Terracotta software contains, and Terracotta redistributes to its end
-users in binary format only, the SIGAR library, made available under exclusive
-license to Terracotta, from Hyperic, Inc. ("Hyperic"). The SIGAR library is
-not licensed under the Terracotta Public License, but rather, the following
-terms and conditions. You may use the SIGAR library but may not modify it or
-redistribute it to any third-party. You may not remove any trademarks, trade
-names, service marks, logos, slogans or URLs of Hyperic that appear in the
-SIGAR library. In addition, you may not adapt, alter, recast, transform,
-translate or create derivative works from the SIGAR library; distribute,
-sublicense, lease, rent, sell, loan or otherwise transfer the SIGAR library
-to any third party; or reverse engineer, decompile, or disassemble the SIGAR
-library. THE SIGAR LIBRARY IS PROVIDED "AS IS" WITHOUT ANY WARRANTY WHATSOEVER.
-HYPERIC AND TERRACOTTA DISCLAIM ANY AND ALL WARRANTIES, EXPRESS, IMPLIED OR
-STATUTORY REGARDING THE SOFTWARE, SERVICES AND ANY OTHER MATERIALS, INCLUDING
-ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
-NON-INFRINGEMENT. HYPERIC DOES NOT WARRANT THAT THE SIGAR LIBRARY WILL BE
-PROVIDED ERROR-FREE OR WILL OPERATE WITHOUT INTERRUPTION. HYPERIC MAKES NO, AND
-HEREBY DISCLAIMS ANY, WARRANTY OR REPRESENTATION TO ANY PERSON OR ENTITY WITH
-RESPECT TO THE SIGAR LIBRARY. TO THE EXTENT THAT A WARRANTY CANNOT BE
-DISCLAIMED AS A MATTER OF APPLICABLE LAW, THE SCOPE AND DURATION OF SUCH WILL BE
-THE MINIMUM REQUIRED UNDER SUCH LAW. NEITHER HYPERIC NOR TERRACOTTA WILL BE
-LIABLE FOR ANY CONSEQUENTIAL, INDIRECT, EXEMPLARY, SPECIAL OR INCIDENTAL DAMAGES,
-WHETHER FOR BREACH OF CONTRACT OR TORT OR UNDER ANY OTHER LEGAL THEORY, INCLUDING
-BUT NOT LIMITED TO, DAMAGES FOR ANY LOST DATA AND LOST PROFITS, BUSINESS
-INTERRUPTION OR LOSS OF BUSINESS INFORMATION, ARISING FROM OR RELATING TO THIS
-AGREEMENT, EVEN IF SUCH PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES,
-REGARDLESS OF THE CAUSE OF ACTION.
-
-(11) Certain components of Terracotta's software use the Oracle Berkeley DB; in
-accordance with the Open Source License for Oracle Berkeley DB Java Edition listed
-below, the source code for those components and the DB software are available for
-free at:
-
- *
- * Copyright (c) 2002-2008 Oracle. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Redistributions in any form must be accompanied by information on
- * how to obtain complete source code for the DB software and any
- * accompanying software that uses the DB software. The source code
- * must either be included in the distribution or be available for no
- * more than the cost of distribution plus a nominal fee, and must be
- * freely redistributable under reasonable conditions. For an
- * executable file, complete source code means the source code for all
- * modules it contains. It does not include source code for modules or
- * files that typically accompany the major components of the operating
- * system on which the executable file runs.
- *
- * THIS SOFTWARE IS PROVIDED BY ORACLE ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
- * NON-INFRINGEMENT, ARE DISCLAIMED. IN NO EVENT SHALL ORACLE BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
- * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
- * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
- * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-/***
- * ASM: a very small and fast Java bytecode manipulation framework
- * Copyright (c) 2000-2005 INRIA, France Telecom
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the copyright holders nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-(12) Certain components of Terracotta's software use a collection of Concurrent
-and Highly Scalable Utilities, which are in the public domain, as
-detailed on the following web page: http://creativecommons.org/licenses/publicdomain
-
-(13) Certain components of Terracotta's software use javabi-sizeof, the use of
-which is governed by the BSD license, the terms of which are available online
-at http://www.opensource.org/licenses/bsd-license.php
-
-(14) Some components of Ehcache use SLF4J libraries which are licensed under the MIT License
-http://www.slf4j.org/license.html
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshJdbcTxJobStoreFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshJdbcTxJobStoreFactory.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshJdbcTxJobStoreFactory.java (revision 0)
@@ -1,47 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package net.sf.ehcache.constructs.scheduledrefresh;
-
-import java.util.Properties;
-
-import net.sf.ehcache.Ehcache;
-
-import org.quartz.impl.StdSchedulerFactory;
-
-/**
- * An example factory for creating Jdbc TX quartz job stores. Relies on proper
- * configuration elements being set in the config via the ehcache.xml config.
- * Or, a subclass of this class could easily define them from other sources.
- *
- * @author cschanck
- */
-public class ScheduledRefreshJdbcTxJobStoreFactory implements ScheduledRefreshJobStorePropertiesFactory {
-
- /**
- * Return the necessary job store properties to initialize a JDBC job store
- * in Quartz.
- */
- @Override
- public Properties jobStoreProperties(Ehcache underlyingCache, ScheduledRefreshConfiguration config) {
- // get the exces properties -- should have everything you need for JDBC
- Properties p = new Properties(config.getExcessProperties());
- // enforce the JDBC job store class
- p.put(StdSchedulerFactory.PROP_SCHED_INSTANCE_ID, StdSchedulerFactory.AUTO_GENERATE_INSTANCE_ID);
- p.put(StdSchedulerFactory.PROP_JOB_STORE_CLASS, org.quartz.impl.jdbcjobstore.JobStoreTX.class.getName());
- return p;
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/PoolCacheManagerTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/PoolCacheManagerTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/PoolCacheManagerTest.java (revision 0)
@@ -1,152 +0,0 @@
-package net.sf.ehcache;
-
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.Configuration;
-import net.sf.ehcache.config.MemoryUnit;
-import net.sf.ehcache.pool.sizeof.AgentSizeOf;
-import net.sf.ehcache.pool.sizeof.ReflectionSizeOf;
-import net.sf.ehcache.pool.sizeof.SizeOf;
-import net.sf.ehcache.pool.sizeof.UnsafeSizeOf;
-import net.sf.ehcache.store.Store;
-
-import org.hamcrest.Matchers;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.mockito.internal.matchers.EqualsWithDelta;
-import org.terracotta.test.categories.CheckShorts;
-
-import java.lang.reflect.Field;
-import java.util.concurrent.atomic.AtomicLong;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-/**
- * @author Alex Snaps
- */
-@Category(CheckShorts.class)
-public class PoolCacheManagerTest {
-
- private static long deepSizeOf(SizeOf sizeOf, Object... obj) {
- return sizeOf.deepSizeOf(1000, true, obj).getCalculated();
- }
-
-
- @Before
- public void setup() {
- getSizeOfEngine().sizeOf("");
- System.err.println("Testing for a " + System.getProperty("java.version") + " JDK on a "
- + System.getProperty("sun.arch.data.model") + "bit VM");
- }
-
- @Ignore
- @Test
- public void testOnHeapConsumption() throws Exception {
- SizeOf sizeOf = getSizeOfEngine();
- CacheManager cacheManager = new CacheManager(new Configuration().maxBytesLocalHeap(40, MemoryUnit.MEGABYTES));
- cacheManager.addCache(new Cache(new CacheConfiguration("one", 0).overflowToDisk(false)));
- cacheManager.addCache(new Cache(new CacheConfiguration("double", 0).overflowToDisk(false)));
-
- Cache oneSize = cacheManager.getCache("one");
- Cache doubleSize = cacheManager.getCache("double");
-
- Element test = new Element("test", new Pair("0", new Object()));
- oneSize.put(test);
- doubleSize.put(test);
- deepSizeOf(sizeOf, test);
- oneSize.remove(test.getKey());
- int size = 60000;
- for (int i = 0; i < size; i++) {
-// oneSize.put(new Element(i, new Pair(new Object(), new Object())));
-// doubleSize.put(new Element(i, new Pair(new Object(), new Object[] {new Object(), new Object()})));
-// doubleSize.put(new Element(i + size, new Pair(new Object(), new Object[] {new Object(), new Object()})));
- doubleSize.put(new Element(new Object(), new Object()));
-// doubleSize.put(new Element(i, i + "" + i));
- }
- doubleSize.removeAll();
-
- long usedBefore = measureMemoryUse();
-
- for (int i = 0; i < size; i++) {
-// oneSize.put(new Element(i, new Pair(new Object(), new Object())));
-// doubleSize.put(new Element(i, new Pair(new Object(), new Object[] {new Object(), new Object()})));
-// doubleSize.put(new Element(i + size, new Pair(new Object(), new Object[] {new Object(), new Object()})));
- oneSize.put(new Element(new Object(), new Object()));
-// doubleSize.put(new Element(i, i + "" + i));
- }
-
- long mem = 0;
- for (Object key : oneSize.getKeys()) {
- Element element = oneSize.get(key);
- mem += deepSizeOf(sizeOf, element);
- }
- for (Object key : doubleSize.getKeys()) {
- Element element = doubleSize.get(key);
- mem += deepSizeOf(sizeOf, element);
- }
-
- assertThat(MemoryUnit.MEGABYTES.toBytes(40) - mem >= 0, is(true));
- long consumes = measureMemoryUse() - usedBefore;
- assertThat(consumes +" bytes are actually being used, while we believe " + mem + " are",
- mem / (double)consumes, Matchers.closeTo(1d, 0.025d));
- }
-
- private long getInMemorySizeInBytes(final Cache oneSize) throws Exception {
- Field store = Cache.class.getDeclaredField("compoundStore");
- store.setAccessible(true);
- return ((Store) store.get(oneSize)).getInMemorySizeInBytes();
- }
-
- protected long measureMemoryUse() throws InterruptedException {
- System.gc();
- Thread.sleep(2000);
- System.gc();
- return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
- }
-
- private static final class Pair {
- private static final AtomicLong counter = new AtomicLong(Long.MIN_VALUE);
- private final Object one;
- private final Object two;
- private final Object oneHidden;
- private final Object twoHidden;
- private final Object threeHidden;
- private final Object fourHidden;
- private final long instanceNumber;
-
- private Pair(final Object one, final Object two) {
- this.one = one;
- this.two = two;
- instanceNumber = counter.getAndIncrement();
- if(instanceNumber % 4 == 1) {
- oneHidden = new Object();
- twoHidden = new Object();
- threeHidden = new Object();
- fourHidden = new Object();
- } else {
- oneHidden = null;
- twoHidden = null;
- threeHidden = null;
- fourHidden = null;
- }
- }
- }
-
- private static SizeOf getSizeOfEngine() {
- try {
- return new AgentSizeOf();
- } catch (UnsupportedOperationException e) {
- try {
- return new UnsafeSizeOf();
- } catch (UnsupportedOperationException f) {
- try {
- return new ReflectionSizeOf();
- } catch (UnsupportedOperationException g) {
- throw new CacheException("A suitable SizeOf engine could not be loaded: " + e + ", " + f + ", " + g);
- }
- }
- }
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/MemoryStore.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/MemoryStore.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/MemoryStore.java (revision 0)
@@ -1,1152 +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.CacheEntry;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheOperationOutcomes.EvictionOutcome;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.concurrent.CacheLockProvider;
-import net.sf.ehcache.concurrent.ReadWriteLockSync;
-import net.sf.ehcache.concurrent.Sync;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.CacheConfigurationListener;
-import net.sf.ehcache.config.PinningConfiguration;
-import net.sf.ehcache.config.SizeOfPolicyConfiguration;
-import net.sf.ehcache.event.RegisteredEventListeners;
-import net.sf.ehcache.pool.Pool;
-import net.sf.ehcache.pool.PoolAccessor;
-import net.sf.ehcache.pool.PoolParticipant;
-import net.sf.ehcache.pool.Size;
-import net.sf.ehcache.pool.SizeOfEngine;
-import net.sf.ehcache.pool.SizeOfEngineLoader;
-import net.sf.ehcache.pool.impl.UnboundedPool;
-import net.sf.ehcache.search.Attribute;
-import net.sf.ehcache.search.attribute.AttributeExtractor;
-import net.sf.ehcache.search.impl.SearchManager;
-import net.sf.ehcache.store.StoreOperationOutcomes.GetOutcome;
-import net.sf.ehcache.store.StoreOperationOutcomes.PutOutcome;
-import net.sf.ehcache.store.StoreOperationOutcomes.RemoveOutcome;
-import net.sf.ehcache.store.chm.SelectableConcurrentHashMap;
-import net.sf.ehcache.store.disk.StoreUpdateException;
-import net.sf.ehcache.writer.CacheWriterManager;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.terracotta.statistics.OperationStatistic;
-import org.terracotta.statistics.Statistic;
-import org.terracotta.statistics.StatisticsManager;
-import org.terracotta.statistics.derived.EventRateSimpleMovingAverage;
-import org.terracotta.statistics.derived.OperationResultFilter;
-import org.terracotta.statistics.observer.OperationObserver;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.EnumSet;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import static net.sf.ehcache.statistics.StatisticBuilder.operation;
-
-/**
- * A Store implementation suitable for fast, concurrent in memory stores. The policy is determined by that
- * configured in the cache.
- *
- * @author Terracotta
- * @version $Id: MemoryStore.java 10789 2018-04-26 02:08:13Z adahanne $
- */
-public class MemoryStore extends AbstractStore implements CacheConfigurationListener, Store {
-
- /**
- * This is the default from {@link java.util.concurrent.ConcurrentHashMap}. It should never be used, because we size
- * the map to the max size of the store.
- */
- static final float DEFAULT_LOAD_FACTOR = 0.75f;
-
- /**
- * Set optimisation for 100 concurrent threads.
- */
- private static final int CONCURRENCY_LEVEL = 100;
-
- private static final int MAX_EVICTION_RATIO = 5;
-
- private static final Logger LOG = LoggerFactory.getLogger(MemoryStore.class.getName());
-
- private static final CopyStrategyHandler NO_COPY_STRATEGY_HANDLER = new CopyStrategyHandler(false, false, null, null);
-
- /**
- * Eviction outcome observer
- */
- protected final OperationObserver evictionObserver = operation(EvictionOutcome.class).named("eviction").of(this).build();
-
- /**
- * The cache this store is associated with.
- */
- private final Ehcache cache;
-
- /**
- * Map where items are stored by key.
- */
- private final SelectableConcurrentHashMap map;
- private final PoolAccessor poolAccessor;
-
- private final OperationObserver getObserver = operation(GetOutcome.class).named("get").of(this).tag("local-heap").build();
- private final OperationObserver putObserver = operation(PutOutcome.class).named("put").of(this).tag("local-heap").build();
- private final OperationObserver removeObserver = operation(RemoveOutcome.class).named("remove").of(this).tag("local-heap").build();
-
- private final boolean storePinned;
- private final CopyStrategyHandler copyStrategyHandler;
-
- /**
- * The maximum size of the store (0 == no limit)
- */
- private volatile int maximumSize;
-
- /**
- * status.
- */
- private volatile Status status;
-
- /**
- * The eviction policy to use
- */
- private volatile Policy policy;
-
- /**
- * The pool accessor
- */
-
- private volatile CacheLockProvider lockProvider;
-
- /**
- * Constructs things that all MemoryStores have in common.
- *
- * @param cache the cache
- * @param pool the pool tracking the on-heap usage
- * @param searchManager the search manager
- */
- protected MemoryStore(Ehcache cache, Pool pool, BackingFactory factory, final SearchManager searchManager) {
- super(searchManager, cache.getName());
- status = Status.STATUS_UNINITIALISED;
- this.cache = cache;
- this.maximumSize = (int) cache.getCacheConfiguration().getMaxEntriesLocalHeap();
- this.policy = determineEvictionPolicy(cache);
- if (pool instanceof UnboundedPool) {
- this.poolAccessor = pool.createPoolAccessor(null, null);
- } else {
- this.poolAccessor = pool.createPoolAccessor(new Participant(),
- SizeOfPolicyConfiguration.resolveMaxDepth(cache),
- SizeOfPolicyConfiguration.resolveBehavior(cache).equals(SizeOfPolicyConfiguration.MaxDepthExceededBehavior.ABORT));
- }
-
- this.storePinned = determineStorePinned(cache.getCacheConfiguration());
-
- int maximumCapacity = isClockEviction() && !storePinned ? maximumSize : 0;
- RegisteredEventListeners eventListener = cache.getCacheEventNotificationService();
- if (Boolean.getBoolean(MemoryStore.class.getName() + ".presize")) {
- // create the CHM with initialCapacity sufficient to hold maximumSize
- final float loadFactor = maximumSize == 1 ? 1 : DEFAULT_LOAD_FACTOR;
- int initialCapacity = getInitialCapacityForLoadFactor(maximumSize, loadFactor);
- this.map = factory.newBackingMap(poolAccessor, initialCapacity,
- loadFactor, CONCURRENCY_LEVEL, maximumCapacity, eventListener);
- } else {
- this.map = factory.newBackingMap(poolAccessor, CONCURRENCY_LEVEL, maximumCapacity, eventListener);
- }
-
- this.status = Status.STATUS_ALIVE;
-
- if (LOG.isDebugEnabled()) {
- LOG.debug("Initialized " + this.getClass().getName() + " for " + cache.getName());
- }
- copyStrategyHandler = getCopyStrategyHandler(cache);
- }
-
- static CopyStrategyHandler getCopyStrategyHandler(final Ehcache cache) {
- if (cache.getCacheConfiguration().isXaTransactional() || cache.getCacheConfiguration().isXaStrictTransactional()
- || cache.getCacheConfiguration().isLocalTransactional()) {
- return new TxCopyStrategyHandler(cache.getCacheConfiguration().isCopyOnRead(),
- cache.getCacheConfiguration().isCopyOnWrite(), cache.getCacheConfiguration().getCopyStrategy(),
- cache.getCacheConfiguration().getClassLoader());
- } else if (cache.getCacheConfiguration().isCopyOnRead() || cache.getCacheConfiguration().isCopyOnWrite()) {
- return new CopyStrategyHandler(cache.getCacheConfiguration().isCopyOnRead(),
- cache.getCacheConfiguration().isCopyOnWrite(), cache.getCacheConfiguration().getCopyStrategy(),
- cache.getCacheConfiguration().getClassLoader());
- } else {
- return NO_COPY_STRATEGY_HANDLER;
- }
- }
-
- private boolean determineStorePinned(CacheConfiguration cacheConfiguration) {
- PinningConfiguration pinningConfiguration = cacheConfiguration.getPinningConfiguration();
- if (pinningConfiguration == null) {
- return false;
- }
-
- switch (pinningConfiguration.getStore()) {
- case LOCALMEMORY:
- return false;
-
- case INCACHE:
- return !cacheConfiguration.isOverflowToOffHeap() && !cacheConfiguration.isOverflowToDisk();
-
- default:
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Calculates the initialCapacity for a desired maximumSize goal and loadFactor.
- *
- * @param maximumSizeGoal the desired maximum size goal
- * @param loadFactor the load factor
- * @return the calculated initialCapacity. Returns 0 if the parameter maximumSizeGoal is less than or equal
- * to 0
- */
- protected static int getInitialCapacityForLoadFactor(int maximumSizeGoal, float loadFactor) {
- double actualMaximum = Math.ceil(maximumSizeGoal / loadFactor);
- return Math.max(0, actualMaximum >= Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) actualMaximum);
- }
-
- /**
- * A factory method to create a MemoryStore.
- *
- * @param cache the cache
- * @param pool the pool tracking the on-heap usage
- * @return an instance of a NotifyingMemoryStore, configured with the appropriate eviction policy
- */
- public static Store create(final Ehcache cache, Pool pool) {
- CacheConfiguration cacheConfiguration = cache.getCacheConfiguration();
- final BruteForceSearchManager searchManager = new BruteForceSearchManager(cache);
- MemoryStore memoryStore = new MemoryStore(cache, pool, new BasicBackingFactory(), searchManager);
- cacheConfiguration.addConfigurationListener(memoryStore);
- searchManager.setBruteForceSource(createBruteForceSource(memoryStore, cache.getCacheConfiguration()));
- return memoryStore;
- }
-
- /**
- * Factory method to wrap the MemoryStore into a BruteForceSource, accounting for transactional and copy
- * configuration
- *
- * @param memoryStore the underlying store acting as source
- * @param cacheConfiguration the cache configuration
- * @return a BruteForceSource connected to underlying MemoryStore and matching configuration
- */
- protected static BruteForceSource createBruteForceSource(MemoryStore memoryStore, CacheConfiguration cacheConfiguration) {
- BruteForceSource source = new MemoryStoreBruteForceSource(memoryStore, cacheConfiguration.getSearchable());
- CopyStrategyHandler copyStrategyHandler = new CopyStrategyHandler(cacheConfiguration.isCopyOnRead(),
- cacheConfiguration.isCopyOnWrite(),
- cacheConfiguration.getCopyStrategy(), cacheConfiguration.getClassLoader());
- if (cacheConfiguration.getTransactionalMode().isTransactional()) {
- source = new TransactionalBruteForceSource(source, copyStrategyHandler);
- } else if (cacheConfiguration.isCopyOnRead() || cacheConfiguration.isCopyOnWrite()) {
- source = new CopyingBruteForceSource(source, copyStrategyHandler);
- }
- return source;
- }
-
- /**
- * Puts an item in the store. Note that this automatically results in an eviction if the store is full.
- *
- * @param element the element to add
- */
- public boolean put(final Element element) throws CacheException {
- if (element == null) {
- return false;
- }
- if (searchManager != null) {
- searchManager.put(cache.getName(), -1, element, null, attributeExtractors, cache.getCacheConfiguration().getDynamicExtractor());
- }
- putObserver.begin();
- long delta = poolAccessor.add(element.getObjectKey(), element.getObjectValue(), map.storedObject(element), storePinned);
- if (delta > -1) {
- Element old = map.put(element.getObjectKey(), element, delta);
- checkCapacity(element);
- if (old == null) {
- putObserver.end(PutOutcome.ADDED);
- return true;
- } else {
- putObserver.end(PutOutcome.UPDATED);
- return false;
- }
- } else {
- notifyDirectEviction(element);
- putObserver.end(PutOutcome.ADDED);
- return true;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws CacheException {
- if (searchManager != null) {
- searchManager.put(cache.getName(), -1, element, null, attributeExtractors, cache.getCacheConfiguration().getDynamicExtractor());
- }
- long delta = poolAccessor.add(element.getObjectKey(), element.getObjectValue(), map.storedObject(element), storePinned);
- if (delta > -1) {
- final ReentrantReadWriteLock lock = map.lockFor(element.getObjectKey());
- lock.writeLock().lock();
- try {
- Element old = map.put(element.getObjectKey(), element, delta);
- if (writerManager != null) {
- try {
- writerManager.put(element);
- } catch (RuntimeException e) {
- throw new StoreUpdateException(e, old != null);
- }
- }
- checkCapacity(element);
- return old == null;
- } finally {
- lock.writeLock().unlock();
- }
- } else {
- notifyDirectEviction(element);
- return true;
- }
- }
-
- /**
- * Gets an item from the cache.
- *
- * The last access time in {@link net.sf.ehcache.Element} is updated.
- *
- * @param key the key of the Element
- * @return the element, or null if there was no match for the key
- */
- public final Element get(final Object key) {
- getObserver.begin();
- if (key == null) {
- getObserver.end(GetOutcome.MISS);
- return null;
- } else {
- final Element e = map.get(key);
- if (e == null) {
- getObserver.end(GetOutcome.MISS);
- return null;
- } else {
- getObserver.end(GetOutcome.HIT);
- return e;
- }
- }
- }
-
- /**
- * Gets an item from the cache, without updating statistics.
- *
- * @param key the cache key
- * @return the element, or null if there was no match for the key
- */
- public final Element getQuiet(Object key) {
- return map.get(key);
- }
-
- /**
- * Removes an Element from the store.
- *
- * @param key the key of the Element, usually a String
- * @return the Element if one was found, else null
- */
- public Element remove(final Object key) {
- if (key == null) {
- return null;
- }
- removeObserver.begin();
- try {
- return map.remove(key);
- } finally {
- removeObserver.end(RemoveOutcome.SUCCESS);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public final Element removeWithWriter(Object key, CacheWriterManager writerManager) throws CacheException {
- if (key == null) {
- return null;
- }
-
- // remove single item.
- Element element;
- final ReentrantReadWriteLock.WriteLock writeLock = map.lockFor(key).writeLock();
- writeLock.lock();
- try {
- element = map.remove(key);
- if (writerManager != null) {
- writerManager.remove(new CacheEntry(key, element));
- }
- } finally {
- writeLock.unlock();
- }
- if (element == null && LOG.isDebugEnabled()) {
- LOG.debug(cache.getName() + "Cache: Cannot remove entry as key " + key + " was not found");
- }
- return element;
- }
-
- /**
- * Memory stores are never backed up and always return false
- */
- public final boolean bufferFull() {
- return false;
- }
-
- /**
- * Expire all elements.
- *
- * This is a default implementation which does nothing. Expiration on demand is only implemented for disk stores.
- */
- public void expireElements() {
- for (Object key : keySet()) {
- final Element element = expireElement(key);
- if (element != null) {
- cache.getCacheEventNotificationService()
- .notifyElementExpiry(copyStrategyHandler.copyElementForReadIfNeeded(element), false);
- }
- }
- }
-
- /**
- * Evicts the element for the given key, if it exists and is expired
- * @param key the key
- * @return the evicted element, if any. Otherwise null
- */
- protected Element expireElement(final Object key) {
- Element value = get(key);
- return value != null && value.isExpired() && map.remove(key, value) ? value : null;
- }
-
- /**
- * Chooses the Policy from the cache configuration
- * @param cache the cache
- * @return the chosen eviction policy
- */
- static Policy determineEvictionPolicy(Ehcache cache) {
- MemoryStoreEvictionPolicy policySelection = cache.getCacheConfiguration().getMemoryStoreEvictionPolicy();
-
- if (policySelection.equals(MemoryStoreEvictionPolicy.LRU)) {
- return new LruPolicy();
- } else if (policySelection.equals(MemoryStoreEvictionPolicy.FIFO)) {
- return new FifoPolicy();
- } else if (policySelection.equals(MemoryStoreEvictionPolicy.LFU)) {
- return new LfuPolicy();
- } else if (policySelection.equals(MemoryStoreEvictionPolicy.CLOCK)) {
- return null;
- }
-
- throw new IllegalArgumentException(policySelection + " isn't a valid eviction policy");
- }
-
- /**
- * Remove all of the elements from the store.
- */
- public final void removeAll() throws CacheException {
- for (Object key : map.keySet()) {
- remove(key);
- }
- }
-
- /**
- * Prepares for shutdown.
- */
- public synchronized void dispose() {
- if (status.equals(Status.STATUS_SHUTDOWN)) {
- return;
- }
- status = Status.STATUS_SHUTDOWN;
- flush();
- poolAccessor.unlink();
- }
-
- /**
- * Flush to disk only if the cache is diskPersistent.
- */
- public void flush() {
- if (cache.getCacheConfiguration().isClearOnFlush()) {
- removeAll();
- }
- }
-
- /**
- * Gets an Array of the keys for all elements in the memory cache.
- *
- * Does not check for expired entries
- *
- * @return An List
- */
- public final List> getKeys() {
- return new ArrayList(map.keySet());
- }
-
- /**
- * Returns the keySet for this store
- * @return keySet
- */
- protected Set> keySet() {
- return map.keySet();
- }
-
- /**
- * Returns the current store size.
- *
- * @return The size value
- */
- public final int getSize() {
- return map.size();
- }
-
- /**
- * Returns nothing since a disk store isn't clustered
- *
- * @return returns 0
- */
- public final int getTerracottaClusteredSize() {
- return 0;
- }
-
- /**
- * A check to see if a key is in the Store. No check is made to see if the Element is expired.
- *
- * @param key The Element key
- * @return true if found. If this method return false, it means that an Element with the given key is definitely not
- * in the MemoryStore. If it returns true, there is an Element there. An attempt to get it may return null if
- * the Element has expired.
- */
- public final boolean containsKey(final Object key) {
- return map.containsKey(key);
- }
-
- /**
- * Before eviction elements are checked.
- *
- * @param element the element to notify about its expiry
- */
- private void notifyExpiry(final Element element) {
- cache.getCacheEventNotificationService().notifyElementExpiry(copyStrategyHandler.copyElementForReadIfNeeded(element), false);
- }
-
- /**
- * Called when an element is evicted even before it could be installed inside the store
- *
- * @param element the evicted element
- */
- protected void notifyDirectEviction(final Element element) {
- evictionObserver.begin();
- evictionObserver.end(EvictionOutcome.SUCCESS);
- cache.getCacheEventNotificationService().notifyElementEvicted(copyStrategyHandler.copyElementForReadIfNeeded(element), false);
- }
-
- /**
- * An algorithm to tell if the MemoryStore is at or beyond its carrying capacity.
- *
- * @return true if the store is full, false otherwise
- */
- public final boolean isFull() {
- return maximumSize > 0 && map.quickSize() >= maximumSize;
- }
-
- /**
- * Check if adding an element won't provoke an eviction.
- *
- * @param element the element
- * @return true if the element can be added without provoking an eviction.
- */
- public final boolean canPutWithoutEvicting(Element element) {
- if (element == null) {
- return true;
- }
-
- return !isFull() && poolAccessor.canAddWithoutEvicting(element.getObjectKey(), element.getObjectValue(), map.storedObject(element));
- }
-
- /**
- * If the store is over capacity, evict elements until capacity is reached
- *
- * @param elementJustAdded the element added by the action calling this check
- */
- private void checkCapacity(final Element elementJustAdded) {
- if (maximumSize > 0 && !isClockEviction()) {
- int evict = Math.min(map.quickSize() - maximumSize, MAX_EVICTION_RATIO);
- for (int i = 0; i < evict; i++) {
- removeElementChosenByEvictionPolicy(elementJustAdded);
- }
- }
- }
-
- /**
- * Removes the element chosen by the eviction policy
- *
- * @param elementJustAdded it is possible for this to be null
- * @return true if an element was removed, false otherwise.
- */
- private boolean removeElementChosenByEvictionPolicy(final Element elementJustAdded) {
-
- if (policy == null) {
- return map.evict();
- }
-
- Element element = findEvictionCandidate(elementJustAdded);
- if (element == null) {
- LOG.debug("Eviction selection miss. Selected element is null");
- return false;
- }
-
- // If the element is expired, remove
- if (element.isExpired()) {
- remove(element.getObjectKey());
- notifyExpiry(element);
- return true;
- }
-
- if (storePinned) {
- return false;
- }
-
- return evict(element);
- }
-
- /**
- * Find a "relatively" unused element.
- *
- * @param elementJustAdded the element added by the action calling this check
- * @return the element chosen as candidate for eviction
- */
- private Element findEvictionCandidate(final Element elementJustAdded) {
- Object objectKey = elementJustAdded != null ? elementJustAdded.getObjectKey() : null;
- Element[] elements = sampleElements(objectKey);
- // this can return null. Let the cache get bigger by one.
- return policy.selectedBasedOnPolicy(elements, elementJustAdded);
- }
-
- /**
- * Uses random numbers to sample the entire map.
- *
- * This implemenation uses a key array.
- *
- * @param keyHint a key used as a hint indicating where the just added element is
- * @return a random sample of elements
- */
- private Element[] sampleElements(Object keyHint) {
- int size = AbstractPolicy.calculateSampleSize(map.quickSize());
- return map.getRandomValues(size, keyHint);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getInternalContext() {
- if (lockProvider != null) {
- return lockProvider;
- } else {
- lockProvider = new LockProvider();
- return lockProvider;
- }
- }
-
- /**
- * Gets the status of the MemoryStore.
- */
- public final Status getStatus() {
- return status;
- }
-
- /**
- * {@inheritDoc}
- */
- public void timeToIdleChanged(long oldTti, long newTti) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void timeToLiveChanged(long oldTtl, long newTtl) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void diskCapacityChanged(int oldCapacity, int newCapacity) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void loggingChanged(boolean oldValue, boolean newValue) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void memoryCapacityChanged(int oldCapacity, int newCapacity) {
- maximumSize = newCapacity;
- if (isClockEviction() && !storePinned) {
- map.setMaxSize(maximumSize);
- }
- }
-
- private boolean isClockEviction() {
- return policy == null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void registered(CacheConfiguration config) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void deregistered(CacheConfiguration config) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void maxBytesLocalHeapChanged(final long oldValue, final long newValue) {
- this.poolAccessor.setMaxSize(newValue);
- }
-
- /**
- * {@inheritDoc}
- */
- public void maxBytesLocalDiskChanged(final long oldValue, final long newValue) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void maxEntriesInCacheChanged(final long oldValue, final long newValue) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyInMemory(Object key) {
- return containsKey(key);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyOffHeap(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyOnDisk(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public Policy getInMemoryEvictionPolicy() {
- return policy;
- }
-
- /**
- * {@inheritDoc}
- */
- @Statistic(name = "size", tags = "local-heap")
- public int getInMemorySize() {
- return getSize();
- }
-
- /**
- * {@inheritDoc}
- */
- @Statistic(name = "size-in-bytes", tags = "local-heap")
- public long getInMemorySizeInBytes() {
- if (poolAccessor.getSize() < 0) {
- SizeOfEngine defaultSizeOfEngine = SizeOfEngineLoader.newSizeOfEngine(SizeOfPolicyConfiguration.resolveMaxDepth(cache),
- SizeOfPolicyConfiguration.resolveBehavior(cache)
- .equals(SizeOfPolicyConfiguration.MaxDepthExceededBehavior.ABORT),
- true);
- long sizeInBytes = 0;
- for (Object o : map.values()) {
- Element element = (Element) o;
- if (element != null) {
- Size size = defaultSizeOfEngine.sizeOf(element.getObjectKey(), element, map.storedObject(element));
- sizeInBytes += size.getCalculated();
- }
- }
- return sizeInBytes;
- }
- return poolAccessor.getSize();
- }
-
- /**
- * {@inheritDoc}
- */
- public int getOffHeapSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getOffHeapSizeInBytes() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getOnDiskSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getOnDiskSizeInBytes() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean hasAbortedSizeOf() {
- return poolAccessor.hasAbortedSizeOf();
- }
-
- /**
- * {@inheritDoc}
- */
- public void setInMemoryEvictionPolicy(Policy policy) {
- this.policy = policy;
- }
-
- @Override
- public void setAttributeExtractors(Map extractors) {
- super.setAttributeExtractors(extractors);
- Set> attrs = new HashSet>(attributeExtractors.size());
-
- for (String name : extractors.keySet()) {
- attrs.add(new Attribute(name));
- }
- ((BruteForceSearchManager)searchManager).addSearchAttributes(attrs);
- }
-
- /**
- * {@inheritDoc}
- */
- public Element putIfAbsent(Element element) throws NullPointerException {
- if (element == null) {
- return null;
- }
- if (searchManager != null) {
- searchManager.put(cache.getName(), -1, element, null, attributeExtractors, cache.getCacheConfiguration().getDynamicExtractor());
- }
- long delta = poolAccessor.add(element.getObjectKey(), element.getObjectValue(), map.storedObject(element), storePinned);
- if (delta > -1) {
- Element old = map.putIfAbsent(element.getObjectKey(), element, delta);
- if (old == null) {
- checkCapacity(element);
- } else {
- poolAccessor.delete(delta);
- }
- return old;
- } else {
- notifyDirectEviction(element);
- return null;
- }
- }
-
- /**
- * Evicts the element from the store
- * @param element the element to be evicted
- * @return true if succeeded, false otherwise
- */
- protected boolean evict(final Element element) {
- final ReentrantReadWriteLock.WriteLock lock = map.lockFor(element.getObjectKey()).writeLock();
- if (lock.tryLock()) {
- evictionObserver.begin();
- Element remove;
- try {
- remove = remove(element.getObjectKey());
- } finally {
- lock.unlock();
- }
- if (remove != null) {
- evictionObserver.end(EvictionOutcome.SUCCESS);
- cache.getCacheEventNotificationService().notifyElementEvicted(copyStrategyHandler.copyElementForReadIfNeeded(remove), false);
- }
- return remove != null;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException {
- if (element == null || element.getObjectKey() == null) {
- return null;
- }
-
- Object key = element.getObjectKey();
-
- Lock lock = getWriteLock(key);
- lock.lock();
- try {
- Element toRemove = map.get(key);
- if (comparator.equals(element, toRemove)) {
- map.remove(key);
- return toRemove;
- } else {
- return null;
- }
- } finally {
- lock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException,
- IllegalArgumentException {
- if (element == null || element.getObjectKey() == null) {
- return false;
- }
-
- if (searchManager != null) {
- searchManager.put(cache.getName(), -1, element, null, attributeExtractors, cache.getCacheConfiguration().getDynamicExtractor());
- }
- Object key = element.getObjectKey();
-
- long delta = poolAccessor.add(element.getObjectKey(), element.getObjectValue(), map.storedObject(element), storePinned);
- if (delta > -1) {
- Lock lock = getWriteLock(key);
- lock.lock();
- try {
- Element toRemove = map.get(key);
- if (comparator.equals(old, toRemove)) {
- map.put(key, element, delta);
- return true;
- } else {
- poolAccessor.delete(delta);
- return false;
- }
- } finally {
- lock.unlock();
- }
- } else {
- notifyDirectEviction(element);
- return false;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Element replace(Element element) throws NullPointerException {
- if (element == null || element.getObjectKey() == null) {
- return null;
- }
- if (searchManager != null) {
- searchManager.put(cache.getName(), -1, element, null, attributeExtractors, cache.getCacheConfiguration().getDynamicExtractor());
- }
- Object key = element.getObjectKey();
-
- long delta = poolAccessor.add(element.getObjectKey(), element.getObjectValue(), map.storedObject(element), storePinned);
- if (delta > -1) {
- Lock lock = getWriteLock(key);
- lock.lock();
- try {
- Element toRemove = map.get(key);
- if (toRemove != null) {
- map.put(key, element, delta);
- return toRemove;
- } else {
- poolAccessor.delete(delta);
- return null;
- }
- } finally {
- lock.unlock();
- }
- } else {
- notifyDirectEviction(element);
- return null;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getMBean() {
- return null;
- }
-
- private Lock getWriteLock(Object key) {
- return map.lockFor(key).writeLock();
- }
-
- /**
- * Get a collection of the elements in this store
- *
- * @return element collection
- */
- public Collection elementSet() {
- return map.values();
- }
-
- /**
- * LockProvider implementation that uses the segment locks.
- */
- private class LockProvider implements CacheLockProvider {
-
- /**
- * {@inheritDoc}
- */
- public Sync getSyncForKey(Object key) {
- return new ReadWriteLockSync(map.lockFor(key));
- }
- }
-
- private static boolean getAdvancedBooleanConfigProperty(String property, String cacheName, boolean defaultValue) {
- String globalPropertyKey = "net.sf.ehcache.store.config." + property;
- String cachePropertyKey = "net.sf.ehcache.store." + cacheName + ".config." + property;
- return Boolean.parseBoolean(System.getProperty(cachePropertyKey, System.getProperty(globalPropertyKey, Boolean.toString(defaultValue))));
- }
-
- @Override
- public void recalculateSize(Object key) {
- if (key == null) {
- return;
- }
- map.recalculateSize(key);
- }
-
- /**
- * PoolParticipant that is used with the HeapPool.
- */
- private final class Participant implements PoolParticipant {
-
- private final EventRateSimpleMovingAverage hitRate = new EventRateSimpleMovingAverage(1, TimeUnit.SECONDS);
- private final EventRateSimpleMovingAverage missRate = new EventRateSimpleMovingAverage(1, TimeUnit.SECONDS);
-
- private Participant() {
- OperationStatistic getStatistic = StatisticsManager.getOperationStatisticFor(getObserver);
- getStatistic.addDerivedStatistic(new OperationResultFilter(EnumSet.of(GetOutcome.HIT), hitRate));
- getStatistic.addDerivedStatistic(new OperationResultFilter(EnumSet.of(GetOutcome.MISS), missRate));
- }
-
- @Override
- public boolean evict(int count, long size) {
- if (storePinned) {
- return false;
- }
-
- for (int i = 0; i < count; i++) {
- boolean removed = removeElementChosenByEvictionPolicy(null);
- if (!removed) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public float getApproximateHitRate() {
- return hitRate.rate(TimeUnit.SECONDS).floatValue();
- }
-
- @Override
- public float getApproximateMissRate() {
- return missRate.rate(TimeUnit.SECONDS).floatValue();
- }
-
- @Override
- public long getApproximateCountSize() {
- return map.quickSize();
- }
- }
-
- /**
- * Factory interface to create a MemoryStore backing.
- */
- protected interface BackingFactory {
- /**
- * Create a MemoryStore backing map.
- *
- * @param poolAccessor on-heap pool accessor
- * @param initialCapacity initial store capacity
- * @param loadFactor map load factor
- * @param concurrency map concurrency
- * @param maximumCapacity maximum store capacity
- * @param eventListener event listener (or {@code null} for no notifications)
- * @return a backing map
- */
- @Deprecated
- SelectableConcurrentHashMap newBackingMap(PoolAccessor poolAccessor, int initialCapacity,
- float loadFactor, int concurrency, int maximumCapacity, RegisteredEventListeners eventListener);
-
- /**
- * Create a MemoryStore backing map.
- *
- * @param poolAccessor on-heap pool accessor
- * @param concurrency map concurrency
- * @param maximumCapacity maximum store capacity
- * @param eventListener event listener (or {@code null} for no notifications)
- * @return a backing map
- */
- SelectableConcurrentHashMap newBackingMap(PoolAccessor poolAccessor, int concurrency,
- int maximumCapacity, RegisteredEventListeners eventListener);
- }
-
- /**
- * Simple backing map factory.
- */
- static class BasicBackingFactory implements BackingFactory {
-
- @Override
- public SelectableConcurrentHashMap newBackingMap(PoolAccessor poolAccessor, int concurrency,
- int maximumCapacity, RegisteredEventListeners eventListener) {
- return new SelectableConcurrentHashMap(poolAccessor, concurrency, maximumCapacity, eventListener);
- }
-
- @Override
- public SelectableConcurrentHashMap newBackingMap(PoolAccessor poolAccessor, int initialCapacity,
- float loadFactor, int concurrency, int maximumCapacity, RegisteredEventListeners eventListener) {
- return new SelectableConcurrentHashMap(poolAccessor, initialCapacity,
- loadFactor, concurrency, maximumCapacity, eventListener);
- }
- }
-}
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/TerracottaConfigurationElement.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/TerracottaConfigurationElement.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/TerracottaConfigurationElement.java (revision 0)
@@ -1,80 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.config.generator.model.elements;
-
-import net.sf.ehcache.config.TerracottaConfiguration;
-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 TerracottaConfiguration}
- *
- * @author Abhishek Sanoujam
- *
- */
-public class TerracottaConfigurationElement extends SimpleNodeElement {
-
- private final TerracottaConfiguration tcConfiguration;
-
- /**
- * Constructor accepting the parent and the {@link TerracottaConfiguration}
- *
- * @param parent
- * @param tcConfiguration
- */
- public TerracottaConfigurationElement(NodeElement parent, TerracottaConfiguration tcConfiguration) {
- super(parent, "terracotta");
- this.tcConfiguration = tcConfiguration;
- init();
- }
-
- private void init() {
- if (tcConfiguration == null) {
- return;
- }
- if (!TerracottaConfiguration.DEFAULT_NON_STOP_CONFIGURATION.equals(tcConfiguration.getNonstopConfiguration())) {
- this.addChildElement(new NonstopConfigurationElement(this, tcConfiguration.getNonstopConfiguration()));
- }
- addAttribute(new SimpleNodeAttribute("clustered", tcConfiguration.isClustered()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_CLUSTERED));
- addAttribute(new SimpleNodeAttribute("consistency", tcConfiguration.getConsistency().name()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_CONSISTENCY_TYPE.name()));
- addAttribute(new SimpleNodeAttribute("synchronousWrites", tcConfiguration.isSynchronousWrites()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_SYNCHRONOUS_WRITES));
- addAttribute(new SimpleNodeAttribute("copyOnRead", tcConfiguration.isCopyOnRead()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_COPY_ON_READ));
- addAttribute(new SimpleNodeAttribute("localKeyCache", tcConfiguration.getLocalKeyCache()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_LOCAL_KEY_CACHE));
- addAttribute(new SimpleNodeAttribute("localKeyCacheSize", tcConfiguration.getLocalKeyCacheSize()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_LOCAL_KEY_CACHE_SIZE));
- addAttribute(new SimpleNodeAttribute("orphanEviction", tcConfiguration.getOrphanEviction()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_ORPHAN_EVICTION));
- addAttribute(new SimpleNodeAttribute("orphanEvictionPeriod", tcConfiguration.getOrphanEvictionPeriod()).optional(true)
- .defaultValue(TerracottaConfiguration.DEFAULT_ORPHAN_EVICTION_PERIOD));
- addAttribute(new SimpleNodeAttribute("coherentReads", tcConfiguration.getCoherentReads()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_COHERENT_READS));
- addAttribute(new SimpleNodeAttribute("concurrency", tcConfiguration.getConcurrency()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_CONCURRENCY));
- addAttribute(new SimpleNodeAttribute("localCacheEnabled", tcConfiguration.isLocalCacheEnabled()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_LOCAL_CACHE_ENABLED));
- addAttribute(new SimpleNodeAttribute("compressionEnabled", tcConfiguration.isCompressionEnabled()).optional(true).defaultValue(
- TerracottaConfiguration.DEFAULT_COMPRESSION_ENABLED));
-
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/distribution/events/src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/distribution/events/src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/distribution/events/src/main/java/org/hibernate/tutorial/web/EventManagerServlet.java (revision 0)
@@ -1,146 +0,0 @@
-package org.hibernate.tutorial.web;
-
-import java.io.PrintWriter;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.hibernate.Criteria;
-import org.hibernate.tutorial.domain.Event;
-import org.hibernate.tutorial.util.HibernateUtil;
-
-public class EventManagerServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
- SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy");
-
- try {
- // Begin unit of work
- HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
-
- // Write HTML header
- PrintWriter out = response.getWriter();
- out.println("Event Manager ");
-
- // Handle actions
- if ("store".equals(request.getParameter("action"))) {
- String eventTitle = request.getParameter("eventTitle");
- String eventDate = request.getParameter("eventDate");
-
- if ("".equals(eventTitle) || "".equals(eventDate)) {
- out.println("Please enter event title and date. ");
- } else {
- try {
- createAndStoreEvent(eventTitle, dateFormatter.parse(eventDate));
- out.println("Added event. ");
- } catch (ParseException e) {
- out.println("Date format error: " + eventDate + " ");
- }
-
- }
- }
-
- // Print page
- printEventForm(out);
- listEvents(out, dateFormatter);
- printSummary(request, out);
-
- // Write HTML footer
- out.println("");
- out.flush();
- out.close();
- // End unit of work
- HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
- } catch (Exception ex) {
- HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().rollback();
- if (ServletException.class.isInstance(ex)) {
- throw (ServletException) ex;
- } else {
- throw new ServletException(ex);
- }
- }
- }
-
- @Override
- public void destroy() {
- try {
- HibernateUtil.getSessionFactory().close();
- } catch (Throwable t) {
- //
- }
- }
-
- protected void createAndStoreEvent(String title, Date theDate) {
- Event theEvent = new Event();
- theEvent.setTitle(title);
- theEvent.setDate(theDate);
- HibernateUtil.getSessionFactory().getCurrentSession().save(theEvent);
- }
-
- private void printEventForm(PrintWriter out) {
- out.println("Add new event: ");
- out.println("");
- }
-
- @SuppressWarnings("rawtypes")
- private void listEvents(PrintWriter out, SimpleDateFormat dateFormatter) {
- Criteria crit = HibernateUtil.getSessionFactory().getCurrentSession().createCriteria(Event.class);
- crit.setCacheable(true);
- List result = crit.list();
- if (result.size() > 0) {
- out.println("Events in database: ");
- out.println("");
- out.println("");
- out.println("Event title ");
- out.println("Event date ");
- out.println(" ");
- Iterator it = result.iterator();
- while (it.hasNext()) {
- Event event = (Event) it.next();
- out.println("");
- out.println("" + event.getTitle() + " ");
- out.println("" + dateFormatter.format(event.getDate()) + " ");
- out.println(" ");
- }
- out.println("
");
- }
- }
-
- private void printSummary(HttpServletRequest request, PrintWriter out) {
- String server1 = "9081";
- String server2 = "9082";
- String currentServer = request.getRequestURL().indexOf(server1) == -1 ? server2 : server1;
- String otherServer = currentServer == server1 ? server2 : server1;
- String serverColor = currentServer == server1 ? "goldenrod" : "darkseagreen";
- String summaryMsg = "The Events sample demonstrates a standard Hibernate demo configured to use clustered Terracotta Ehcache as the 2nd-level cache.
With the Terracotta Developer Console, you can monitor the cache activity and dynamically change it's eviction configuration; see the Hibernate tab under My application .";
- String rowStart = "
";
- String rowMiddle = " ";
- String rowEnd = " ";
-
- out.println(" ");
- out
- .println("");
- out.println("
");
- out.println(rowStart + "Current server:" + rowMiddle + currentServer + rowEnd);
- out.println(rowStart + "Go to:" + rowMiddle + "Server " + otherServer + " " + rowEnd
- + "
");
- out.println(summaryMsg);
- out.println("
");
- }
-}
\ No newline at end of file
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/net/sf/ehcache/osgi/OddCacheLoaderFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/net/sf/ehcache/osgi/OddCacheLoaderFactory.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/net/sf/ehcache/osgi/OddCacheLoaderFactory.java (revision 0)
@@ -1,18 +0,0 @@
-/*
- * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
- */
-package net.sf.ehcache.osgi;
-
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.loader.CacheLoader;
-import net.sf.ehcache.loader.CacheLoaderFactory;
-
-import java.util.Properties;
-
-public class OddCacheLoaderFactory extends CacheLoaderFactory {
-
- @Override
- public CacheLoader createCacheLoader(Ehcache cache, Properties properties) {
- return new OddCacheLoader();
- }
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicWriteBehindTestClient.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicWriteBehindTestClient.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicWriteBehindTestClient.java (revision 0)
@@ -1,83 +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 net.sf.ehcache.writer.writebehind.WriteBehindManager;
-
-import org.terracotta.ehcache.tests.AbstractWriteBehindClient;
-import org.terracotta.ehcache.tests.WriteBehindCacheWriter;
-import org.terracotta.toolkit.Toolkit;
-
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicLong;
-
-import junit.framework.Assert;
-
-public class BasicWriteBehindTestClient extends AbstractWriteBehindClient {
- private static final int ELEMENT_COUNT = BasicWriteBehindTest.ELEMENT_COUNT;
-
- public BasicWriteBehindTestClient(String[] args) {
- super(args);
- }
-
- @Override
- public long getSleepBetweenWrites() {
- return 100L;
- }
-
- @Override
- public long getSleepBetweenDeletes() {
- return 100L;
- }
-
- public static void main(String[] args) {
- new BasicWriteBehindTestClient(args).run();
- }
-
- @Override
- protected void runTest(final Cache cache, Toolkit toolkit) throws Throwable {
- cache.registerCacheWriter(new WriteBehindCacheWriter(this));
- for (int i = 0; i < ELEMENT_COUNT; i++) {
- cache.putWithWriter(new Element("key" + i % 200, "value" + i)); // 200 different keys, write operation
- if (0 == i % 10) {
- cache.removeWithWriter("key" + i % 200 / 10); // 10 different keys, delete operation
- }
- }
-
- final WriteBehindManager wbManager = ((WriteBehindManager) cache.getWriterManager());
-
- System.out.println("write behind queue size " + wbManager.getQueueSize());
- System.out.println("write behind queue size (stats)" + cache.getStatistics().getWriterQueueLength());
- // can't really do this as it would be racy: Assert.assertEquals(wbManager.getQueueSize(), cache.getStatistics().getWriterQueueLength());
- // let's take a moment and assure we foundthe statistic and stitched it all together.
- Assert.assertFalse(cache.getStatistics().getExtended().writerQueueLength().getClass().getName().contains("NullStatistic"));
- final AtomicLong counter = new AtomicLong();
- final ScheduledExecutorService executor = Executors.newScheduledThreadPool(10);
- executor.scheduleAtFixedRate(new Runnable() {
- @Override
- public void run() {
- long count = counter.incrementAndGet();
- cache.putWithWriter(new Element("key-" + count, "value-" + count));
- System.out.println("executor write behind queue size " + wbManager.getQueueSize() + " counter " + count);
- }
- }, 500L, 1L, TimeUnit.MILLISECONDS);
-
- // done with put now shutdown cache manager
- // this call should wait write behind queue to get empty
- Thread.sleep(TimeUnit.SECONDS.toMillis(1L));
- System.out.println("calling cacheManager shutdown");
- cache.getCacheManager().shutdown();
-
- try {
- wbManager.getQueueSize();
- Assert.fail("should have failed because cacheManager.shutdown is called before");
- } catch (IllegalStateException e) {
- // expected exception
- }
- }
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/overflow-to-disk-cache-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/overflow-to-disk-cache-test.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/overflow-to-disk-cache-test.xml (revision 0)
@@ -1,19 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/strong-writebehind-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/strong-writebehind-test.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/strong-writebehind-test.xml (revision 0)
@@ -1,19 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/transaction/xa/XAThreadPoolTest.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/transaction/xa/XAThreadPoolTest.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/transaction/xa/XAThreadPoolTest.java (revision 0)
@@ -1,70 +0,0 @@
-package net.sf.ehcache.transaction.xa;
-
-import junit.framework.TestCase;
-import net.sf.ehcache.transaction.xa.processor.XAThreadPool;
-
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.atomic.AtomicInteger;
-
-/**
- * @author lorban
- */
-public class XAThreadPoolTest extends TestCase {
-
- public void test() throws Exception {
- final int COUNTER = 5000;
- final int CONCURRENCY = 50;
-
- XAThreadPool xaThreadPool = new XAThreadPool();
-
- XAThreadPool.MultiRunner[] runners = new XAThreadPool.MultiRunner[CONCURRENCY];
- for (int i = 0; i < CONCURRENCY; i++) {
- runners[i] = xaThreadPool.getMultiRunner();
- }
-
- final Map results = new ConcurrentHashMap();
-
- Callable myCallable = new Callable() {
- public Object call() throws Exception {
- String threadName = Thread.currentThread().getName();
-
- AtomicInteger counter = results.get(threadName);
- if (counter == null) {
- counter = new AtomicInteger();
- results.put(threadName, counter);
- }
-
- counter.incrementAndGet();
-
- return null;
- }
- };
-
- // execution
- for (int i = 0; i < COUNTER; i++) {
- for (int j = 0; j < CONCURRENCY; j++) {
- runners[j].execute(myCallable);
- }
- }
-
- // release
- for (int j = 0; j < CONCURRENCY; j++) {
- runners[j].release();
-
- try {
- runners[j].execute(myCallable);
- fail("expected IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
- }
-
- // assertions
- assertEquals(CONCURRENCY, results.size());
- for (Map.Entry entry : results.entrySet()) {
- assertEquals(COUNTER, entry.getValue().get());
- }
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/terracotta/TerracottaUnitTesting.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/terracotta/TerracottaUnitTesting.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/terracotta/TerracottaUnitTesting.java (revision 0)
@@ -1,83 +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.Ehcache;
-import net.sf.ehcache.cluster.CacheCluster;
-import net.sf.ehcache.concurrent.CacheLockProvider;
-import net.sf.ehcache.config.TerracottaClientConfiguration;
-import net.sf.ehcache.store.TerracottaStore;
-import net.sf.ehcache.terracotta.TerracottaClusteredInstanceHelper.TerracottaRuntimeType;
-
-import org.mockito.Mockito;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-
-import java.lang.reflect.Method;
-import java.util.concurrent.Callable;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.when;
-
-/**
- * @author Abhishek Sanoujam
- */
-public class TerracottaUnitTesting {
-
- public static void setupTerracottaTesting(ClusteredInstanceFactory mockFactory) throws Exception {
- setupTerracottaTesting(mockFactory, null, TerracottaRuntimeType.EnterpriseExpress);
- }
-
- public static void setupTerracottaTesting(ClusteredInstanceFactory mockFactory, Runnable onNewClusteredInstanceFactory)
- throws Exception {
- setupTerracottaTesting(mockFactory, onNewClusteredInstanceFactory, TerracottaRuntimeType.EnterpriseExpress);
- }
-
- public static void setupTerracottaTesting(ClusteredInstanceFactory mockFactory, TerracottaRuntimeType terracottaRuntimeType) throws Exception {
- setupTerracottaTesting(mockFactory, null, terracottaRuntimeType);
- }
-
- public static void setupTerracottaTesting(final ClusteredInstanceFactory mockFactory, final Runnable onNewClusteredInstanceFactory,
- TerracottaRuntimeType terracottaRuntimeType)
- throws Exception {
- TerracottaStore terracottaStore = Mockito.mock(TerracottaStore.class);
- CacheCluster mockCacheCluster = Mockito.mock(CacheCluster.class);
- when(mockFactory.createStore((Ehcache) any())).thenReturn(terracottaStore);
- when(mockFactory.getTopology()).thenReturn(mockCacheCluster);
- CacheLockProvider mockCacheLockProvider = Mockito.mock(CacheLockProvider.class);
- when(terracottaStore.getInternalContext()).thenReturn(mockCacheLockProvider);
- when(mockFactory.createNonStopStore((Callable) any(), (Cache) any())).thenReturn(
- terracottaStore);
-
- TerracottaClusteredInstanceHelper mockHelper = Mockito.mock(TerracottaClusteredInstanceHelper.class);
- when(mockHelper.newClusteredInstanceFactory((TerracottaClientConfiguration) any(), null))
- .thenAnswer(new Answer() {
- public ClusteredInstanceFactory answer(InvocationOnMock invocation) throws Throwable {
- if (onNewClusteredInstanceFactory != null) {
- onNewClusteredInstanceFactory.run();
- }
- return mockFactory;
- }
- });
- when(mockHelper.getTerracottaRuntimeTypeOrNull()).thenReturn(terracottaRuntimeType);
-
- Method method = TerracottaClient.class.getDeclaredMethod("setTestMode", TerracottaClusteredInstanceHelper.class);
- method.setAccessible(true);
- method.invoke(null, mockHelper);
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/Primitive.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/Primitive.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/Primitive.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.store;
-
-import java.io.Serializable;
-
-
-/**
- * Test class to investigate class loading issues
- *
- * @author Greg Luck
- * @version $Id: Primitive.java 5594 2012-05-07 16:04:31Z cdennis $
- */
-public class Primitive implements Serializable {
- public int integerPrimitive;
- public long longPrimitive;
- public byte bytePrimitive;
- public char charPrimitive;
- public boolean booleanPrimitive;
-
- /**
- * Indicates whether some other object is "equal to" this one.
- */
- public boolean equals(Object object) {
- return object != null
- && object instanceof Primitive
- && ((Primitive) object).integerPrimitive == integerPrimitive
- && ((Primitive) object).longPrimitive == longPrimitive
- && ((Primitive) object).bytePrimitive == bytePrimitive
- && ((Primitive) object).charPrimitive == charPrimitive
- && ((Primitive) object).booleanPrimitive == booleanPrimitive;
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheMBean.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheMBean.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheMBean.java (revision 0)
@@ -1,83 +0,0 @@
-/**
- * Copyright Terracotta, Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package net.sf.ehcache.management;
-
-import net.sf.ehcache.CacheException;
-
-/**
- * A management bean for a cache
- *
- * @author Greg Luck
- * @version $Id: CacheMBean.java 5594 2012-05-07 16:04:31Z cdennis $
- * @since 1.3
- */
-public interface CacheMBean {
-
-
- /**
- * Removes all cached items.
- *
- * @throws IllegalStateException if the cache is not {@link net.sf.ehcache.Status#STATUS_ALIVE}
- */
- void removeAll() throws IllegalStateException, CacheException;
-
-
- /**
- * Flushes all cache items from memory to the disk store, and from the DiskStore to disk.
- *
- * @throws IllegalStateException if the cache is not {@link net.sf.ehcache.Status#STATUS_ALIVE}
- */
- void flush() throws IllegalStateException, CacheException;
-
-
- /**
- * Gets the status attribute of the Cache.
- *
- * @return The status value from the Status enum class
- */
- String getStatus();
-
-
- /**
- * Gets the cache name.
- */
- String getName();
-
- /**
- * Uses a Terracotta clustered store.
- */
- boolean isTerracottaClustered();
-
- /**
- * Check if the cache may contain elements which the SizeOf engine could not fully size.
- */
- boolean hasAbortedSizeOf();
-
- /**
- *
- * Gets the JMX read-only CacheConfiguration
- */
- CacheConfiguration getCacheConfiguration();
-
-
- /**
- *
- * Gets the JMX cache statistics
- */
- CacheStatistics getStatistics();
-
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/test/java/net/sf/ehcache/constructs/scheduledrefresh/OddCacheLoaderFactory.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/test/java/net/sf/ehcache/constructs/scheduledrefresh/OddCacheLoaderFactory.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/test/java/net/sf/ehcache/constructs/scheduledrefresh/OddCacheLoaderFactory.java (revision 0)
@@ -1,16 +0,0 @@
-package net.sf.ehcache.constructs.scheduledrefresh;
-
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.loader.CacheLoader;
-import net.sf.ehcache.loader.CacheLoaderFactory;
-
-import java.util.Properties;
-
-public class OddCacheLoaderFactory extends CacheLoaderFactory {
-
- @Override
- public CacheLoader createCacheLoader(Ehcache cache, Properties properties) {
- return new OddCacheLoader();
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/tti-cache-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/tti-cache-test.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/tti-cache-test.xml (revision 0)
@@ -1,24 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/disk/DiskStore.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/disk/DiskStore.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/disk/DiskStore.java (revision 0)
@@ -1,1247 +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.disk;
-
-import net.sf.ehcache.Cache;
-import net.sf.ehcache.CacheEntry;
-import net.sf.ehcache.CacheException;
-import net.sf.ehcache.CacheOperationOutcomes.EvictionOutcome;
-import net.sf.ehcache.Ehcache;
-import net.sf.ehcache.Element;
-import net.sf.ehcache.Status;
-import net.sf.ehcache.concurrent.CacheLockProvider;
-import net.sf.ehcache.concurrent.LockType;
-import net.sf.ehcache.concurrent.StripedReadWriteLock;
-import net.sf.ehcache.concurrent.Sync;
-import net.sf.ehcache.config.CacheConfiguration;
-import net.sf.ehcache.config.CacheConfigurationListener;
-import net.sf.ehcache.config.SizeOfPolicyConfiguration;
-import net.sf.ehcache.pool.Pool;
-import net.sf.ehcache.pool.PoolAccessor;
-import net.sf.ehcache.pool.PoolParticipant;
-import net.sf.ehcache.pool.impl.UnboundedPool;
-import net.sf.ehcache.store.AbstractStore;
-import net.sf.ehcache.store.AuthoritativeTier;
-import net.sf.ehcache.store.CacheStore;
-import net.sf.ehcache.store.ElementValueComparator;
-import net.sf.ehcache.store.Policy;
-import net.sf.ehcache.store.Store;
-import net.sf.ehcache.store.StoreOperationOutcomes.GetOutcome;
-import net.sf.ehcache.store.StoreOperationOutcomes.PutOutcome;
-import net.sf.ehcache.store.StoreOperationOutcomes.RemoveOutcome;
-import net.sf.ehcache.store.StripedReadWriteLockProvider;
-import net.sf.ehcache.store.cachingtier.OnHeapCachingTier;
-import net.sf.ehcache.store.disk.DiskStorageFactory.DiskMarker;
-import net.sf.ehcache.store.disk.DiskStorageFactory.DiskSubstitute;
-import net.sf.ehcache.store.disk.DiskStorageFactory.Placeholder;
-import net.sf.ehcache.writer.CacheWriterManager;
-
-import org.terracotta.statistics.OperationStatistic;
-import org.terracotta.statistics.Statistic;
-import org.terracotta.statistics.StatisticsManager;
-import org.terracotta.statistics.derived.EventRateSimpleMovingAverage;
-import org.terracotta.statistics.derived.OperationResultFilter;
-import org.terracotta.statistics.observer.OperationObserver;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.AbstractSet;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import static net.sf.ehcache.statistics.StatisticBuilder.operation;
-
-/**
- * Implements a persistent-to-disk store.
- *
- * All new elements are automatically scheduled for writing to disk.
- *
- * @author Chris Dennis
- * @author Ludovic Orban
- */
-public final class DiskStore extends AbstractStore implements StripedReadWriteLockProvider, AuthoritativeTier {
-
- private static final int FFFFCD7D = 0xffffcd7d;
- private static final int FIFTEEN = 15;
- private static final int TEN = 10;
- private static final int THREE = 3;
- private static final int SIX = 6;
- private static final int FOURTEEN = 14;
- private static final int SIXTEEN = 16;
-
- private static final int RETRIES_BEFORE_LOCK = 2;
- private static final int DEFAULT_INITIAL_CAPACITY = 16;
- private static final int DEFAULT_SEGMENT_COUNT = 64;
- private static final float DEFAULT_LOAD_FACTOR = 0.75f;
-
- private final DiskStorageFactory disk;
- private final Random rndm = new Random();
- private final Segment[] segments;
- private final int segmentShift;
- private final AtomicReference status = new AtomicReference(Status.STATUS_UNINITIALISED);
- private final OperationObserver getObserver = operation(GetOutcome.class).of(this).named("get").tag("local-disk").build();
- private final OperationObserver putObserver = operation(PutOutcome.class).of(this).named("put").tag("local-disk").build();
- private final OperationObserver removeObserver = operation(RemoveOutcome.class).of(this).named("remove").tag("local-disk").build();
- private final OperationObserver evictionObserver = operation(EvictionOutcome.class).named("eviction").of(this).build();
- private final PoolAccessor onHeapPoolAccessor;
- private final PoolAccessor onDiskPoolAccessor;
-
- private volatile CacheLockProvider lockProvider;
- private volatile Set keySet;
-
- private DiskStore(DiskStorageFactory disk, Ehcache cache, Pool onHeapPool, Pool onDiskPool) {
- this.segments = new Segment[DEFAULT_SEGMENT_COUNT];
- this.segmentShift = Integer.numberOfLeadingZeros(segments.length - 1);
-
- EventRateSimpleMovingAverage hitRate = new EventRateSimpleMovingAverage(1, TimeUnit.SECONDS);
- EventRateSimpleMovingAverage missRate = new EventRateSimpleMovingAverage(1, TimeUnit.SECONDS);
- OperationStatistic getStatistic = StatisticsManager.getOperationStatisticFor(getObserver);
- getStatistic.addDerivedStatistic(new OperationResultFilter(EnumSet.of(GetOutcome.HIT), hitRate));
- getStatistic.addDerivedStatistic(new OperationResultFilter(EnumSet.of(GetOutcome.MISS), missRate));
-
- this.onHeapPoolAccessor = onHeapPool.createPoolAccessor(new DiskStoreHeapPoolParticipant(hitRate, missRate),
- SizeOfPolicyConfiguration.resolveMaxDepth(cache),
- SizeOfPolicyConfiguration.resolveBehavior(cache).equals(SizeOfPolicyConfiguration.MaxDepthExceededBehavior.ABORT));
- this.onDiskPoolAccessor = onDiskPool.createPoolAccessor(new DiskStoreDiskPoolParticipant(hitRate, missRate), new DiskSizeOfEngine());
-
- for (int i = 0; i < this.segments.length; ++i) {
- this.segments[i] = new Segment(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR,
- disk, cache.getCacheConfiguration(), onHeapPoolAccessor, onDiskPoolAccessor,
- cache.getCacheEventNotificationService(), evictionObserver);
- }
-
- this.disk = disk;
- this.disk.bind(this);
- this.status.set(Status.STATUS_ALIVE);
- }
-
- /**
- * Creates a persitent-to-disk store for the given cache, using the given disk path.
- *
- * @param cache cache that fronts this store
- * @param onHeapPool pool to track heap usage
- * @param onDiskPool pool to track disk usage
- * @return a fully initialized store
- */
- public static DiskStore create(Ehcache cache, Pool onHeapPool, Pool onDiskPool) {
- if (cache.getCacheManager() == null) {
- throw new CacheException("Can't create diskstore without a cache manager");
- }
- DiskStorageFactory disk = new DiskStorageFactory(cache, cache.getCacheEventNotificationService());
- DiskStore store = new DiskStore(disk, cache, onHeapPool, onDiskPool);
- cache.getCacheConfiguration().addConfigurationListener(new CacheConfigurationListenerAdapter(disk, onDiskPool));
- return store;
- }
-
- /**
- * Creates a persitent-to-disk store for the given cache, using the given disk path.
- * Heap and disk usage are not tracked by the returned store.
- *
- * @param cache cache that fronts this store
- * @return a fully initialized store
- */
- public static DiskStore create(Cache cache) {
- return create(cache, new UnboundedPool(), new UnboundedPool());
- }
-
- /**
- * Create a DiskBackedMemoryStore instance
- * @param cache the cache
- * @param onHeapPool the pool tracking on-heap usage
- * @param onDiskPool the pool tracking on-disk usage
- * @return a DiskBackedMemoryStore instance
- */
- public static Store createCacheStore(Ehcache cache, Pool onHeapPool, Pool onDiskPool) {
- final DiskStore result;
- CacheConfiguration config = cache.getCacheConfiguration();
- if (config.isOverflowToDisk()) {
- result = create(cache, onHeapPool, onDiskPool);
- } else {
- throw new CacheException("DiskBackedMemoryStore can only be used for cache overflowing to disk");
- }
- DiskStore diskStore = result;
-
- final OnHeapCachingTier onHeapCache = OnHeapCachingTier.createOnHeapCache(cache, onHeapPool);
- return new CacheStore(
- onHeapCache,
- diskStore, cache.getCacheConfiguration()
- );
- }
-
- /**
- * {@inheritDoc}
- */
- public StripedReadWriteLock createStripedReadWriteLock() {
- return new DiskStoreStripedReadWriteLock();
- }
-
- @Override
- public Element fault(final Object key, final boolean updateStats) {
- getObserver.begin();
- if (key == null) {
- getObserver.end(GetOutcome.MISS);
- return null;
- } else {
- int hash = hash(key.hashCode());
- Element e = segmentFor(hash).get(key, hash, true);
- if (e == null) {
- getObserver.end(GetOutcome.MISS);
- } else {
- getObserver.end(GetOutcome.HIT);
- }
- return e;
- }
- }
-
-
- @Override
- public boolean putFaulted(final Element element) {
- if (element == null) {
- return false;
- } else {
- putObserver.begin();
- Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- Element oldElement = segmentFor(hash).put(key, hash, element, false, true);
- if (oldElement == null) {
- putObserver.end(PutOutcome.ADDED);
- return true;
- } else {
- putObserver.end(PutOutcome.UPDATED);
- return false;
- }
- }
- }
-
- @Override
- public boolean flush(final Element element) {
- final Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- if (disk.getOnDiskSize() > disk.getDiskCapacity()) {
- // todo this is ugly and only there to please the tests ... again!
- return segmentFor(hash).flush(key, hash, element) && segmentFor(hash).evict(key, hash, null) != null;
- } else {
- return segmentFor(hash).flush(key, hash, element);
- }
- }
-
- /**
- * Verifies if the mapping for a key is marked as faulted
- * @param key the key to check the mapping for
- * @return true if faulted, false otherwise (including no mapping)
- */
- public boolean isFaulted(final Object key) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).isFaulted(hash, key);
- }
-
- /**
- *
- */
- private static final class CacheConfigurationListenerAdapter implements CacheConfigurationListener {
-
- private final DiskStorageFactory disk;
- private final Pool diskPool;
-
- private CacheConfigurationListenerAdapter(DiskStorageFactory disk, Pool diskPool) {
- this.disk = disk;
- this.diskPool = diskPool;
- }
-
- /**
- * {@inheritDoc}
- */
- public void timeToIdleChanged(long oldTimeToIdle, long newTimeToIdle) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void timeToLiveChanged(long oldTimeToLive, long newTimeToLive) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void diskCapacityChanged(int oldCapacity, int newCapacity) {
- disk.setOnDiskCapacity(newCapacity);
- }
-
- /**
- * {@inheritDoc}
- */
- public void memoryCapacityChanged(int oldCapacity, int newCapacity) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void loggingChanged(boolean oldValue, boolean newValue) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void registered(CacheConfiguration config) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void deregistered(CacheConfiguration config) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void maxBytesLocalHeapChanged(final long oldValue, final long newValue) {
- // no-op
- }
-
- /**
- * {@inheritDoc}
- */
- public void maxBytesLocalDiskChanged(final long oldValue, final long newValue) {
- diskPool.setMaxSize(newValue);
- }
-
- /**
- * {@inheritDoc}
- */
- public void maxEntriesInCacheChanged(final long oldValue, final long newValue) {
- // no-op
- }
- }
-
- /**
- * Change the disk capacity, in number of elements
- * @param newCapacity the new max elements on disk
- */
- public void changeDiskCapacity(int newCapacity) {
- disk.setOnDiskCapacity(newCapacity);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean bufferFull() {
- return disk.bufferFull();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyInMemory(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyOffHeap(Object key) {
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKeyOnDisk(Object key) {
- return containsKey(key);
- }
-
- /**
- * {@inheritDoc}
- */
- public void expireElements() {
- disk.expireElements();
- }
-
- /**
- * {@inheritDoc}
- */
- public void flush() throws IOException {
- disk.flush();
- }
-
- /**
- * {@inheritDoc}
- */
- public Policy getInMemoryEvictionPolicy() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public int getInMemorySize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getInMemorySizeInBytes() {
- long size = onHeapPoolAccessor.getSize();
- if (size < 0) {
- return 0;
- } else {
- return size;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public int getOffHeapSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public long getOffHeapSizeInBytes() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- @Statistic(name = "size", tags = "local-disk")
- public int getOnDiskSize() {
- return disk.getOnDiskSize();
- }
-
- /**
- * {@inheritDoc}
- */
- @Statistic(name = "size-in-bytes", tags = "local-disk")
- public long getOnDiskSizeInBytes() {
- long size = onDiskPoolAccessor.getSize();
- if (size < 0) {
- return disk.getOnDiskSizeInBytes();
- } else {
- return size;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public int getTerracottaClusteredSize() {
- return 0;
- }
-
- /**
- * {@inheritDoc}
- */
- public void setInMemoryEvictionPolicy(Policy policy) {
- }
-
- /**
- * Return a reference to the data file backing this store.
- *
- * @return a reference to the data file backing this store.
- */
- public File getDataFile() {
- return disk.getDataFile();
- }
-
- /**
- * Return a reference to the index file for this store.
- *
- * @return a reference to the index file for this store.
- */
- public File getIndexFile() {
- return disk.getIndexFile();
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getMBean() {
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean put(Element element) {
- if (element == null) {
- return false;
- } else {
- putObserver.begin();
- Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- Element oldElement = segmentFor(hash).put(key, hash, element, false, false);
- if (oldElement == null) {
- putObserver.end(PutOutcome.ADDED);
- return true;
- } else {
- putObserver.end(PutOutcome.UPDATED);
- return false;
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean putWithWriter(Element element, CacheWriterManager writerManager) {
- Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- final ReentrantReadWriteLock.WriteLock writeLock = segmentFor(hash).writeLock();
- writeLock.lock();
- try {
- boolean newPut = put(element);
- if (writerManager != null) {
- try {
- writerManager.put(element);
- } catch (RuntimeException e) {
- throw new StoreUpdateException(e, !newPut);
- }
- }
- return newPut;
- } finally {
- writeLock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Element get(Object key) {
- getObserver.begin();
- Element e = getQuiet(key);
- if (e == null) {
- getObserver.end(GetOutcome.MISS);
- return null;
- } else {
- getObserver.end(GetOutcome.HIT);
- return e;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Element getQuiet(Object key) {
- if (key == null) {
- return null;
- } else {
- int hash = hash(key.hashCode());
- return segmentFor(hash).get(key, hash, false);
- }
- }
-
- /**
- * Return the unretrieved (undecoded) value for this key
- *
- * @param key key to lookup
- * @return Element or ElementSubstitute
- */
- public Object unretrievedGet(Object key) {
- if (key == null) {
- return null;
- }
-
- int hash = hash(key.hashCode());
- return segmentFor(hash).unretrievedGet(key, hash);
- }
-
- /**
- * Put the given encoded element directly into the store
- *
- * @param key the key of the element
- * @param encoded the encoded element
- * @return true if the encoded element was installed
- * @throws IllegalArgumentException if the supplied key is already present
- */
- public boolean putRawIfAbsent(Object key, DiskMarker encoded) throws IllegalArgumentException {
- int hash = hash(key.hashCode());
- return segmentFor(hash).putRawIfAbsent(key, hash, encoded);
- }
-
- /**
- * {@inheritDoc}
- */
- public List getKeys() {
- return new ArrayList(keySet());
- }
-
- /**
- * Get a set view of the keys in this store
- *
- * @return a set view of the keys in this store
- */
- public Set keySet() {
- if (keySet != null) {
- return keySet;
- } else {
- keySet = new KeySet();
- return keySet;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Element remove(Object key) {
- if (key == null) {
- return null;
- }
- removeObserver.begin();
- try {
- int hash = hash(key.hashCode());
- return segmentFor(hash).remove(key, hash, null, null);
- } finally {
- removeObserver.end(RemoveOutcome.SUCCESS);
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Element removeWithWriter(Object key, CacheWriterManager writerManager) {
- int hash = hash(key.hashCode());
- final ReentrantReadWriteLock.WriteLock writeLock = segmentFor(hash).writeLock();
- writeLock.lock();
- try {
- Element removed = remove(key);
- if (writerManager != null) {
- writerManager.remove(new CacheEntry(key, removed));
- }
- return removed;
- } finally {
- writeLock.unlock();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void removeAll() {
- for (Segment s : segments) {
- s.clear();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void dispose() {
- if (status.compareAndSet(Status.STATUS_ALIVE, Status.STATUS_SHUTDOWN)) {
- clearFaultedBit();
- disk.unbind();
- onHeapPoolAccessor.unlink();
- onDiskPoolAccessor.unlink();
- }
- }
-
- /**
- * Marks all entries has flushed (i.e. not faulted)
- */
- public void clearFaultedBit() {
- for (Segment segment : segments) {
- segment.clearFaultedBit();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public int getSize() {
- final Segment[] segs = this.segments;
- long size = -1;
- // Try a few times to get accurate count. On failure due to
- // continuous async changes in table, resort to locking.
- for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) {
- size = volatileSize(segs);
- if (size >= 0) {
- break;
- }
- }
- if (size < 0) {
- // Resort to locking all segments
- size = lockedSize(segs);
- }
- if (size > Integer.MAX_VALUE) {
- return Integer.MAX_VALUE;
- } else {
- return (int) size;
- }
- }
-
- private static long volatileSize(Segment[] segs) {
- int[] mc = new int[segs.length];
- long check = 0;
- long sum = 0;
- int mcsum = 0;
- for (int i = 0; i < segs.length; ++i) {
- sum += segs[i].count;
- mc[i] = segs[i].modCount;
- mcsum += mc[i];
- }
- if (mcsum != 0) {
- for (int i = 0; i < segs.length; ++i) {
- check += segs[i].count;
- if (mc[i] != segs[i].modCount) {
- return -1;
- }
- }
- }
- if (check == sum) {
- return sum;
- } else {
- return -1;
- }
- }
-
- private static long lockedSize(Segment[] segs) {
- long size = 0;
- for (Segment seg : segs) {
- seg.readLock().lock();
- }
- for (Segment seg : segs) {
- size += seg.count;
- }
- for (Segment seg : segs) {
- seg.readLock().unlock();
- }
-
- return size;
- }
-
- /**
- * {@inheritDoc}
- */
- public Status getStatus() {
- return status.get();
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean containsKey(Object key) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).containsKey(key, hash);
- }
-
- /**
- * {@inheritDoc}
- */
- public Object getInternalContext() {
- if (lockProvider != null) {
- return lockProvider;
- } else {
- lockProvider = new LockProvider();
- return lockProvider;
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public Element putIfAbsent(Element element) throws NullPointerException {
- Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- return segmentFor(hash).put(key, hash, element, true, false);
- }
-
- /**
- * {@inheritDoc}
- */
- public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException {
- Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- return segmentFor(hash).remove(key, hash, element, comparator);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean replace(Element old, Element element, ElementValueComparator comparator)
- throws NullPointerException, IllegalArgumentException {
- Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- return segmentFor(hash).replace(key, hash, old, element, comparator);
- }
-
- /**
- * {@inheritDoc}
- */
- public Element replace(Element element) throws NullPointerException {
- Object key = element.getObjectKey();
- int hash = hash(key.hashCode());
- return segmentFor(hash).replace(key, hash, element);
- }
-
- /**
- * Atomically switch (CAS) the expect
representation of this element for the
- * fault
representation.
- *
- * A successful switch will return true
, and free the replaced element/element-proxy.
- * A failed switch will return false
and free the element/element-proxy which was not
- * installed.
- *
- * @param key key to which this element (proxy) is mapped
- * @param expect element (proxy) expected
- * @param fault element (proxy) to install
- * @return true
if fault
was installed
- */
- public boolean fault(Object key, Placeholder expect, DiskMarker fault) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).fault(key, hash, expect, fault, status.get() == Status.STATUS_SHUTDOWN);
- }
-
- /**
- * Remove the matching mapping. The evict method does referential comparison
- * of the unretrieved substitute against the argument value.
- *
- * @param key key to match against
- * @param substitute optional value to match against
- * @return true
on a successful remove
- */
- public boolean evict(Object key, DiskSubstitute substitute) {
- return evictElement(key, substitute) != null;
- }
-
- /**
- * Remove the matching mapping. The evict method does referential comparison
- * of the unretrieved substitute against the argument value.
- *
- * @param key key to match against
- * @param substitute optional value to match against
- * @return the evicted element on a successful remove
- */
- public Element evictElement(Object key, DiskSubstitute substitute) {
- int hash = hash(key.hashCode());
- return segmentFor(hash).evict(key, hash, substitute);
- }
-
- /**
- * Select a random sample of elements generated by the supplied factory.
- *
- * @param factory generator of the given type
- * @param sampleSize minimum number of elements to return
- * @param keyHint a key on which we are currently working
- * @return list of sampled elements/element substitute
- */
- public List getRandomSample(ElementSubstituteFilter factory, int sampleSize, Object keyHint) {
- ArrayList sampled = new ArrayList(sampleSize);
-
- // pick a random starting point in the map
- int randomHash = rndm.nextInt();
-
- final int segmentStart;
- if (keyHint == null) {
- segmentStart = (randomHash >>> segmentShift);
- } else {
- segmentStart = (hash(keyHint.hashCode()) >>> segmentShift);
- }
-
- int segmentIndex = segmentStart;
- do {
- segments[segmentIndex].addRandomSample(factory, sampleSize, sampled, randomHash);
- if (sampled.size() >= sampleSize) {
- break;
- }
-
- // move to next segment
- segmentIndex = (segmentIndex + 1) & (segments.length - 1);
- } while (segmentIndex != segmentStart);
-
- return sampled;
- }
-
- private static int hash(int hash) {
- int spread = hash;
- spread += (spread << FIFTEEN ^ FFFFCD7D);
- spread ^= spread >>> TEN;
- spread += (spread << THREE);
- spread ^= spread >>> SIX;
- spread += (spread << 2) + (spread << FOURTEEN);
- return (spread ^ spread >>> SIXTEEN);
- }
-
- private Segment segmentFor(int hash) {
- return segments[hash >>> segmentShift];
- }
-
- /**
- * Key set implementation for the DiskStore
- */
- final class KeySet extends AbstractSet {
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Iterator iterator() {
- return new KeyIterator();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int size() {
- return DiskStore.this.getSize();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean contains(Object o) {
- return DiskStore.this.containsKey(o);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean remove(Object o) {
- return DiskStore.this.remove(o) != null;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void clear() {
- DiskStore.this.removeAll();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public Object[] toArray() {
- Collection c = new ArrayList();
- for (Object object : this) {
- c.add(object);
- }
- return c.toArray();
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public T[] toArray(T[] a) {
- Collection c = new ArrayList();
- for (Object object : this) {
- c.add(object);
- }
- return c.toArray(a);
- }
- }
-
- /**
- * LockProvider implementation that uses the segment locks.
- */
- private class LockProvider implements CacheLockProvider {
-
- /**
- * {@inheritDoc}
- */
- public Sync getSyncForKey(Object key) {
- int hash = key == null ? 0 : hash(key.hashCode());
- return new ReadWriteLockSync(segmentFor(hash));
- }
- }
-
- /**
- * Superclass for all store iterators.
- */
- abstract class HashIterator {
- private int segmentIndex;
- private Iterator currentIterator;
-
- /**
- * Constructs a new HashIterator
- */
- HashIterator() {
- segmentIndex = segments.length;
-
- while (segmentIndex > 0) {
- segmentIndex--;
- currentIterator = segments[segmentIndex].hashIterator();
- if (currentIterator.hasNext()) {
- return;
- }
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean hasNext() {
- if (this.currentIterator == null) {
- return false;
- }
-
- if (this.currentIterator.hasNext()) {
- return true;
- } else {
- while (segmentIndex > 0) {
- segmentIndex--;
- currentIterator = segments[segmentIndex].hashIterator();
- if (currentIterator.hasNext()) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Returns the next hash-entry - called by subclasses
- *
- * @return next HashEntry
- */
- protected HashEntry nextEntry() {
- if (currentIterator == null) {
- return null;
- }
-
- if (currentIterator.hasNext()) {
- return currentIterator.next();
- } else {
- while (segmentIndex > 0) {
- segmentIndex--;
- currentIterator = segments[segmentIndex].hashIterator();
- if (currentIterator.hasNext()) {
- return currentIterator.next();
- }
- }
- }
- return null;
- }
-
- /**
- * {@inheritDoc}
- */
- public void remove() {
- currentIterator.remove();
- }
-
- }
-
- /**
- * Iterator over the store key set.
- */
- private final class KeyIterator extends HashIterator implements Iterator {
- /**
- * {@inheritDoc}
- */
- public Object next() {
- return super.nextEntry().key;
- }
- }
-
- /**
- * Sync implementation that wraps the segment locks
- */
- private static final class ReadWriteLockSync implements Sync {
-
- private final ReentrantReadWriteLock lock;
-
- private ReadWriteLockSync(ReentrantReadWriteLock lock) {
- this.lock = lock;
- }
-
- /**
- * {@inheritDoc}
- */
- public void lock(LockType type) {
- switch (type) {
- case READ:
- lock.readLock().lock();
- break;
- case WRITE:
- lock.writeLock().lock();
- break;
- default:
- throw new IllegalArgumentException("We don't support any other lock type than READ or WRITE!");
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean tryLock(LockType type, long msec) throws InterruptedException {
- switch (type) {
- case READ:
- return lock.readLock().tryLock(msec, TimeUnit.MILLISECONDS);
- case WRITE:
- return lock.writeLock().tryLock(msec, TimeUnit.MILLISECONDS);
- default:
- throw new IllegalArgumentException("We don't support any other lock type than READ or WRITE!");
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public void unlock(LockType type) {
- switch (type) {
- case READ:
- lock.readLock().unlock();
- break;
- case WRITE:
- lock.writeLock().unlock();
- break;
- default:
- throw new IllegalArgumentException("We don't support any other lock type than READ or WRITE!");
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean isHeldByCurrentThread(LockType type) {
- switch (type) {
- case READ:
- throw new UnsupportedOperationException("Querying of read lock is not supported.");
- case WRITE:
- return lock.isWriteLockedByCurrentThread();
- default:
- throw new IllegalArgumentException("We don't support any other lock type than READ or WRITE!");
- }
- }
-
- }
-
- /**
- * StripedReadWriteLock impl.
- */
- private final class DiskStoreStripedReadWriteLock implements StripedReadWriteLock {
-
- private final net.sf.ehcache.concurrent.ReadWriteLockSync[] locks =
- new net.sf.ehcache.concurrent.ReadWriteLockSync[DEFAULT_SEGMENT_COUNT];
-
- private DiskStoreStripedReadWriteLock() {
- for (int i = 0; i < locks.length; i++) {
- locks[i] = new net.sf.ehcache.concurrent.ReadWriteLockSync();
- }
- }
-
- /**
- * {@inheritDoc}
- */
- public ReadWriteLock getLockForKey(final Object key) {
- return getSyncForKey(key).getReadWriteLock();
- }
-
- /**
- * {@inheritDoc}
- */
- public List getAllSyncs() {
- ArrayList syncs =
- new ArrayList(locks.length);
- Collections.addAll(syncs, locks);
- return syncs;
- }
-
- /**
- * {@inheritDoc}
- */
- public net.sf.ehcache.concurrent.ReadWriteLockSync getSyncForKey(final Object key) {
- return locks[indexFor(key)];
- }
-
- private int indexFor(final Object key) {
- return hash(key.hashCode()) >>> segmentShift;
- }
- }
-
- /**
- * PoolParticipant that encapsulate shared logic for both DiskStorePoolParticipant
- */
- private abstract class DiskStorePoolParticipant implements PoolParticipant {
-
- protected final EventRateSimpleMovingAverage hitRate;
- protected final EventRateSimpleMovingAverage missRate;
-
- public DiskStorePoolParticipant(final EventRateSimpleMovingAverage hitRate, final EventRateSimpleMovingAverage missRate) {
- this.hitRate = hitRate;
- this.missRate = missRate;
- }
-
- @Override
- public boolean evict(int count, long size) {
- return disk.evict(count) == count;
- }
-
- @Override
- public float getApproximateHitRate() {
- return hitRate.rate(TimeUnit.SECONDS).floatValue();
- }
-
- @Override
- public float getApproximateMissRate() {
- return missRate.rate(TimeUnit.SECONDS).floatValue();
- }
- }
-
- /**
- * PoolParticipant that is used with the HeapPool. As the DiskStore uses Heap resources
- */
- private class DiskStoreHeapPoolParticipant extends DiskStorePoolParticipant {
-
- public DiskStoreHeapPoolParticipant(final EventRateSimpleMovingAverage hitRate, final EventRateSimpleMovingAverage missRate) {
- super(hitRate, missRate);
- }
-
- @Override
- public long getApproximateCountSize() {
- return getInMemorySize();
- }
- }
-
- /**
- * PoolParticipant that is used with the DiskPool.
- */
- private class DiskStoreDiskPoolParticipant extends DiskStorePoolParticipant {
-
- DiskStoreDiskPoolParticipant(final EventRateSimpleMovingAverage hitRate, final EventRateSimpleMovingAverage missRate) {
- super(hitRate, missRate);
- }
-
- @Override
- public long getApproximateCountSize() {
- return getOnDiskSize();
- }
- }
-}
Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/ElementIdHelper.java
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/ElementIdHelper.java (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/ElementIdHelper.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;
-
-/**
- * Provide access to the package private methods for getting/setting Element id. The id field of an Element is for internal ehcache use only
- * and this class is meant to discourage casual use of the methods from application code
- *
- * @author teck
- */
-public class ElementIdHelper {
-
- /**
- * Is element id set?
- *
- * @param e element to inspect
- * @return true if this element has an id set
- */
- public static boolean hasId(Element e) {
- return e.hasId();
- }
-
- /**
- * Get the element id
- *
- * @param e element to inspect
- * @return element id
- */
- public static long getId(Element e) {
- return e.getId();
- }
-
- /**
- * Set the element id
- *
- * @param e element to adjust
- * @param id
- */
- public static void setId(Element e, long id) {
- e.setId(id);
- }
-
-}
Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/basic-xa-appserver-test.xml
===================================================================
diff -u -N
--- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/basic-xa-appserver-test.xml (revision 11322)
+++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/basic-xa-appserver-test.xml (revision 0)
@@ -1,29 +0,0 @@
-
-
-
-
-