Index: rctags/ehcache-2.10.8.1.63/terracotta/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/pom.xml (revision 0) @@ -1,74 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - - - net.sf.ehcache.internal - ehcache-terracotta-root - ehcache-terracotta-root - pom - - - bootstrap - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - false - - - true - - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - true - - - false - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - false - - - true - - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - true - - - false - - - - - - - deploy-sonatype - - true - - - - Index: rctags/ehcache-2.10.8.1.63/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/pom.xml (revision 0) @@ -1,484 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-parent - 2.25 - - - - ehcache-root - net.sf.ehcache - ehcache-root - pom - 2.10.8.1.63 - - - scm:svn:https://svn.terracotta.org/repo/ehcache/trunk/ehcache - - - - 1.7.25 - 1.0.1 - 2.1.1 - 2.15 - 1.17 - 2.1.13.3 - 0.10.0 - 1.0.2 - 2.2.3 - 9.4.28.v20200408 - 3.5.1-Final - - - - ehcache-core - terracotta - ehcache - management-ehcache-v1 - management-ehcache-v2 - management-ehcache-impl - ehcache-scheduled-refresh - ehcache-search-parser - - - - - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.terracotta.internal - statistics - ${statistics.version} - - - org.terracotta - management-core-resources - ${management-core.version} - - - com.terracotta - clustered-entity-management - ${clustered-entity-management.version} - - - org.eclipse.jetty - jetty-servlet - ${jetty.version} - - - javax.servlet - javax.servlet-api - - - - - - gf-40 - gf.javax.servlet-api - 3.1.0 - - - - - org.terracotta.toolkit - terracotta-toolkit-api-internal - ${terracotta-toolkit-api-internal.version} - provided - - - javax.servlet - javax.servlet-api - 3.1.0 - provided - - - org.hibernate - hibernate-core - ${hibernate-core.version} - provided - - - javax.transaction - jta - 1.1 - provided - - - net.sf.ehcache - sizeof-agent - 1.0.1 - provided - - - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - test - - - org.codehaus.btm - btm - 2.1.3 - test - - - net.sf.hibernate - hibernate - 2.1.8 - test - - - org.hamcrest - hamcrest-core - 1.3 - test - - - org.hamcrest - hamcrest-library - 1.3 - test - - - junit - junit - 4.11 - test - - - dom4j - dom4j - 1.6.1 - test - - - javassist - javassist - 3.4.GA - test - - - org.hibernate - hibernate-ehcache - 3.3.2.GA - test - - - ehcache - net.sf.ehcache - - - - - commons-logging - commons-logging - 1.1.1 - test - - - org.apache.derby - derby - 10.5.3.0_1 - test - - - org.mockito - mockito-core - 1.9.0 - test - - - com.sun.xsom - xsom - 20100725 - test - - - org.beanshell - bsh - 1.3.0 - test - - - org.quartz-scheduler - quartz - ${quartz.version} - - - org.easymock - easymock - 3.0 - test - - - org.powermock - powermock-api-easymock - 1.4.10 - test - - - org.powermock - powermock-module-junit4 - 1.4.10 - test - - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.3.2 - - - - true - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - true - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.8.1 - - - org.apache.maven.plugins - maven-checkstyle-plugin - 3.1.0 - - - org.apache.maven.plugins - maven-dependency-plugin - 2.8 - - - org.codehaus.mojo - build-helper-maven-plugin - 1.7 - - - org.apache.maven.plugins - maven-antrun-plugin - 1.3 - - - org.terracotta - maven-forge-plugin - ${maven-forge-plugin.version} - - -Djava.net.preferIPv4Stack=true - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - org.terracotta.maven.plugins - terracotta-shader - 1.2 - - - - - org.codehaus.gmaven - groovy-maven-plugin - ${groovy-maven-plugin.version} - - - org.codehaus.mojo - rmic-maven-plugin - 1.1 - - - - - - org.terracotta - maven-forge-plugin - - - generateBuildInfoFile - generate-resources - - buildinfo - - - true - ${project.build.outputDirectory} - - - - default-test - test - - test - - - - - - - - - - system-tests - - system-tests - - - - dist - - distribution - - - - - - check-short - - true - true - - - - - org.reflections - reflections-maven - 0.9.9-RC1 - - org.reflections.scanners.TypeAnnotationsScanner - ${project.build.directory}/reflections.xml - true - true - - - - - reflections - - process-test-classes - - - - - org.terracotta - maven-forge-plugin - - true - org.terracotta.test.categories.CheckShorts - - - java.awt.headless - true - - - - - - - - - - deploy-terracotta - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - 1.6.1 - true - - - http://nexus.terracotta.eur.ad.sag - - terracotta-nexus-staging - ${skipDeploy} - - - - - - - org.sonatype.plugins - nexus-staging-maven-plugin - - - - - - - deploy-sonatype - - - sonatype-nexus-staging - http://oss.sonatype.org/service/local/staging/deploy/maven2 - - - sonatype-nexus-snapshots - https://oss.sonatype.org/content/repositories/snapshots - - - - - - - - terracotta-nexus-staging - Terracotta Nexus Staging Repository - ${terracotta-nexus-staging-url} - - - terracotta-os-snapshots - false - Terracotta OS Snapshots Repository - ${terracotta-os-snapshots-url} - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/distribution/colorcache/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/colorcache/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/colorcache/pom.xml (revision 0) @@ -1,182 +0,0 @@ - - 4.0.0 - - org.terracotta.forge - forge-parent - 4.0 - - - net.sf.ehcache.examples - colorcache - 2.10.8.1.63 - colorcache - war - Clustered Ehcache sample with Terracotta - - 2.1.0 - 4.3.8.1.46 - true - true - 9.4.28.v20200408 - - - ${project.name} - - - maven-assembly-plugin - 2.3 - - ${project.name} - - src/assemble/distribution.xml - - gnu - - - - package - - single - - - - - - jetty-maven-plugin - ${jetty.version} - org.eclipse.jetty - - - ${project.name} - - STOP - - - - org.terracotta.maven.plugins - tc-maven-plugin - ${tc-maven-plugin.version} - - - org.terracotta - terracotta - ${terracotta.version} - - - - - - - - net.sf.ehcache - ehcache - ${project.version} - - - org.terracotta - terracotta-toolkit-runtime - ${terracotta.version} - - - gf-40 - gf.javax.servlet-api - 3.1.0 - - - org.slf4j - slf4j-jdk14 - 1.7.25 - - - - - 9081 - - - - jetty-maven-plugin - ${jetty.version} - org.eclipse.jetty - - - - jetty.port - 9081 - - - 9981 - - - - - - - 9082 - - - - jetty-maven-plugin - ${jetty.version} - org.eclipse.jetty - - - - jetty.port - 9082 - - - 9982 - - - - - - - sag-deps - - - sag-deps - true - - - - - - - org.terracotta - maven-forge-plugin - - - com.softwareag.ibit.tools.util - finder - 3.0 - compile - - - - - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/system-tests/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/pom.xml (revision 0) @@ -1,291 +0,0 @@ - - 4.0.0 - - org.terracotta - system-tests-parent - 4.3.8.1.46 - - - net.sf.ehcache.internal - ehcache-terracotta-system-tests - 2.10.8.1.63 - ehcache-terracotta-system-tests - System tests for ehcache-terracotta - - 512m - 1024m - -XX:MaxPermSize=512m - true - true - 10.10.1.1 - 2.2.3 - 1.7.7 - 1.5 - - - - org.terracotta - terracotta - ${terracotta.core.version} - - - gf-40 - gf.javax.servlet-api - - - - - net.sf.ehcache - ehcache - ${project.version} - test - - - net.sf.ehcache - management-ehcache-v1 - ${project.version} - test - - - net.sf.ehcache - management-ehcache-v2 - ${project.version} - test - - - org.slf4j - slf4j-simple - ${slf4j.version} - - - org.terracotta - terracotta-toolkit-runtime - ${terracotta.core.version} - test - - - asm - asm - 3.2 - test - - - org.hibernate - hibernate-core - 3.3.2.GA - test - - - javassist - javassist - 3.8.0.GA - test - - - org.apache.derby - derby - ${derby.version} - test - - - org.apache.derby - derbynet - ${derby.version} - test - - - org.apache.derby - derbyclient - ${derby.version} - test - - - javax.transaction - jta - 1.1 - test - - - org.codehaus.btm - btm - 2.1.3 - test - - - org.apache.geronimo.specs - geronimo-jta_1.0.1B_spec - 1.0.1 - test - - - com.atomikos - transactions-jta - 3.8.0 - test - - - org.mockito - mockito-all - - - - - org.ow2.jotm - jotm-core - 2.1.9 - test - - - org.terracotta.test - container-test-framework - - - org.quartz-scheduler - quartz - ${quartz.version} - - - io.rest-assured - rest-assured - - - io.rest-assured - json-path - - - org.codehaus.groovy - groovy - - - org.codehaus.groovy - groovy-json - - - org.codehaus.groovy - groovy-xml - - - net.sf.ehcache.test - hibernate-ehcache-bundle - ${osgi-test-tool.version} - - - org.terracotta.test - osgi-test-utils - ${osgi-test-tool.version} - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - test-jar - - test-jar - - - - - - org.apache.servicemix.tooling - depends-maven-plugin - 1.2 - - - generate-depends-file - - generate-depends-file - - - - - - - - - include-container-tests - - - appserver - - - - - - org.terracotta - maven-forge-plugin - - - **/container/**/*Test.java - - - - - - - - no-appserver-tests - - - appserver - no-appserver - - - - - - org.terracotta - maven-forge-plugin - - -Xmx768m - -XX:MaxPermSize=128m - - **/*Test.java - - - - - - - - deploy-sonatype - - true - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - jboss - JBoss Repository - https://repository.jboss.org/nexus/content/repositories/public/ - - true - - - false - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/TestCategories.properties =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/TestCategories.properties (revision 11322) +++ rctags/ehcache-2.10.8.1.63/TestCategories.properties (revision 0) @@ -1,328 +0,0 @@ -net.sf.ehcache.AutoVersioningElementTest=production -net.sf.ehcache.CacheClassicLruMemoryStoreTest=production -net.sf.ehcache.CacheCopyOnRwPoolTest=production -net.sf.ehcache.CacheCopyOnRwReplaceRemoveTest=production -net.sf.ehcache.CacheExceptionTest=production -net.sf.ehcache.CacheManagerTest=production -net.sf.ehcache.CachePinningTest=production -net.sf.ehcache.CachePoolPinningTest=production -net.sf.ehcache.CacheTest=production -net.sf.ehcache.ChrisCachePerformanceTest=production -net.sf.ehcache.ClockMemoryStoreTest=production -net.sf.ehcache.DiskStoreTest=production -net.sf.ehcache.DynamicCacheConfigurationTest=production -net.sf.ehcache.ElementTest=production -net.sf.ehcache.ExplicitMaxInMemoryTest=production -net.sf.ehcache.InfiniteCapacityCacheTest=production -net.sf.ehcache.MemoryStoreTester=production -net.sf.ehcache.OverflowCacheTest=production -net.sf.ehcache.PoolCacheManagerTest=production -net.sf.ehcache.RecalculateSizeTest=production -net.sf.ehcache.SameCacheManagerNameTest=production -net.sf.ehcache.StatisticsTest=production -net.sf.ehcache.TerracottaIntegrationTest=production -net.sf.ehcache.XACacheTest=production -net.sf.ehcache.concurrent.ConcurrencyUtilTest=production -net.sf.ehcache.concurrent.ConcurrentCacheMethodsTest=production -net.sf.ehcache.config.CacheConfigConflictTest=production -net.sf.ehcache.config.CacheConfigurationListenerTest=production -net.sf.ehcache.config.CacheConfigurationTest=production -net.sf.ehcache.config.CacheWriterConfigurationTest=production -net.sf.ehcache.config.CoherenceModeConfigTest=production -net.sf.ehcache.config.ConfigurationFactoryTest=production -net.sf.ehcache.config.ConfigurationHelperTest=production -net.sf.ehcache.config.DefaultCacheOptionalTest=production -net.sf.ehcache.config.DynamicCacheConfigurationValidityTest=production -net.sf.ehcache.config.InvalidConfigTest=production -net.sf.ehcache.config.MemoryUnitTest=production -net.sf.ehcache.config.SchemaValidationTest=production -net.sf.ehcache.config.StorageStrategyConfigTest=production -net.sf.ehcache.config.generator.AllConfigurationGeneratedTest=production -net.sf.ehcache.config.generator.ConfigurationGeneratedParsesTest=production -net.sf.ehcache.config.generator.DecoratedCacheConfigTest=production -net.sf.ehcache.config.nonstop.NonStopConfigTest=production -net.sf.ehcache.config.nonstop.NonstopInheritsDefaultConfigTest=production -net.sf.ehcache.constructs.CacheDecoratorFactoryTest=production -net.sf.ehcache.constructs.DecoratorNoNameTest=production -net.sf.ehcache.constructs.DefaultCacheDecoratorFactoryTest=production -net.sf.ehcache.constructs.blocking.BlockingCacheTest=production -net.sf.ehcache.constructs.blocking.SelfPopulatingCacheTest=production -net.sf.ehcache.constructs.blocking.UpdatingSelfPopulatingCacheTest=production -net.sf.ehcache.constructs.locking.ExplicitLockApiTest=production -net.sf.ehcache.constructs.nonstop.BasicNonstopTest=production -net.sf.ehcache.constructs.nonstop.ExecutorServiceTest=production -net.sf.ehcache.constructs.nonstop.NonStopThreadDestroyedTest=production -net.sf.ehcache.constructs.nonstop.NonstopTestUtil=production -net.sf.ehcache.constructs.nonstop.TimeoutOnRejoinTest=production -net.sf.ehcache.distribution.EventMessageTest=production -net.sf.ehcache.distribution.ManualRMIPeerProviderTest=production -net.sf.ehcache.distribution.MulticastRMIPeerProviderTest=production -net.sf.ehcache.distribution.PayloadUtilTest=production -net.sf.ehcache.distribution.RMIBootstrapCacheLoaderTest=production -net.sf.ehcache.distribution.RMICacheManagerPeerListenerTest=production -net.sf.ehcache.distribution.RMICacheManagerPeerTest=production -net.sf.ehcache.distribution.RMICacheReplicatorTest=production -net.sf.ehcache.distribution.RMICacheReplicatorWithLargePayloadTest=production -net.sf.ehcache.distribution.RMIDistributedCacheTest=production -net.sf.ehcache.distribution.ShutdownRMICacheManagerPeerListenerTestImpl=production -net.sf.ehcache.event.BulkOpsEventListenerTest=production -net.sf.ehcache.event.CacheEventListenerTest=production -net.sf.ehcache.event.CacheManagerEventListenerTest=production -net.sf.ehcache.event.EvictionListenerTest=production -net.sf.ehcache.event.ProgrammaticallyCreatedCacheEventListenerTest=production -net.sf.ehcache.event.TestCacheManagerEventListenerFactory=production -net.sf.ehcache.exceptionhandler.CacheExceptionHandlerTest=production -net.sf.ehcache.extension.CacheExtensionTest=production -net.sf.ehcache.extension.TestCacheExtension=production -net.sf.ehcache.extension.TestCacheExtensionFactory=production -net.sf.ehcache.hibernate.EhCacheRegionFactoryTest=production -net.sf.ehcache.hibernate.HibernateAPIUsageTest=production -net.sf.ehcache.hibernate.HibernateCacheTest=production -net.sf.ehcache.hibernate.management.impl.EhcacheStatsImplTest=production -net.sf.ehcache.loader.CacheLoaderTest=production -net.sf.ehcache.loader.CompositeLoaderTest=production -net.sf.ehcache.management.ManagementServiceTest=production -net.sf.ehcache.management.ResourceClassLoaderTest=production -net.sf.ehcache.management.sampled.MBeanRegistrationProviderTest=production -net.sf.ehcache.pool.PoolableStoresTest=production -net.sf.ehcache.pool.TwinCachesTest=production -net.sf.ehcache.pool.sizeof.AgentLoaderRaceTest=production -net.sf.ehcache.pool.sizeof.AgentLoaderSystemPropTest=production -net.sf.ehcache.pool.sizeof.AgentLoaderTest=production -net.sf.ehcache.pool.sizeof.FilteredSizeOfTest=production -net.sf.ehcache.pool.sizeof.ObjectGraphWalkerTest=production -net.sf.ehcache.pool.sizeof.SizeOfTest=production -net.sf.ehcache.pool.sizeof.filter.AnnotationProxyFactoryTest=production -net.sf.ehcache.search.BasicSearchTest=production -net.sf.ehcache.search.QueryExamplesTest=production -net.sf.ehcache.search.SearchTestUtil=production -net.sf.ehcache.search.TestAttributeExtractor=production -net.sf.ehcache.search.TransactionalSearchTest=production -net.sf.ehcache.search.attribute.JavaBeanAttributeExtractorTest=production -net.sf.ehcache.search.attribute.ReflectionAttributeExtractorTest=production -net.sf.ehcache.servermaplocalcache.ServerMapLocalCacheTest=production -net.sf.ehcache.statistics.CacheUsageListenerTest=production -net.sf.ehcache.statistics.DisabledCacheStatisticsTest=production -net.sf.ehcache.statistics.LiveCacheStatisticsTest=production -net.sf.ehcache.store.CacheKeySetTest=production -net.sf.ehcache.store.DiskBackedMemoryStoreTest=production -net.sf.ehcache.store.DiskStoreBootstrapCacheLoaderFactoryTest=production -net.sf.ehcache.store.ElementIdAssigningStoreTest=production -net.sf.ehcache.store.FifoMemoryStoreTest=production -net.sf.ehcache.store.InitialCapacityTest=production -net.sf.ehcache.store.LruClassicMemoryStoreTest=production -net.sf.ehcache.store.LruMemoryStoreTest=production -net.sf.ehcache.store.MemoryOnlyStoreTest=production -net.sf.ehcache.store.MemoryStorePinningTest=production -net.sf.ehcache.store.MemoryStorePoolingTest=production -net.sf.ehcache.store.OffheapStoreInOssTest=production -net.sf.ehcache.store.PoolableMemoryStoreTest=production -net.sf.ehcache.store.XATransactionalStoreTest=production -net.sf.ehcache.store.chm.SelectableConcurrentHashMapTest=production -net.sf.ehcache.store.compound.PartialSerializationCopyStrategyTest=production -net.sf.ehcache.store.compound.TCCLReadWriteSerializationCopyStrategyTest=production -net.sf.ehcache.store.disk.DiskBackMemoryStoreTest=production -net.sf.ehcache.store.disk.DiskStorePoolingTest=production -net.sf.ehcache.store.disk.DiskStoreTest=production -net.sf.ehcache.store.disk.ods.FileAllocationTreeTest=production -net.sf.ehcache.terracotta.BasicRejoinTest=production -net.sf.ehcache.terracotta.BootstrapCacheTest=quarantined -net.sf.ehcache.terracotta.EventReplicationTest=production -net.sf.ehcache.terracotta.KeySnapshotterTest=production -net.sf.ehcache.terracotta.RejoinEventSequenceTest=production -net.sf.ehcache.terracotta.RotatingSnapshotFileTest=production -net.sf.ehcache.terracotta.StorageStrategyInvalidConfigurationTest=production -net.sf.ehcache.terracotta.TerracottaBootstrapCacheLoaderTest=production -net.sf.ehcache.terracotta.TerracottaUnitTesting=production -net.sf.ehcache.terracotta.TerracottaWithLocalOffHeapTest=production -net.sf.ehcache.terracotta.TestRejoinStore=production -net.sf.ehcache.transaction.SoftLockPinningTest=production -net.sf.ehcache.transaction.local.LocalTransactionSizeOfTest=production -net.sf.ehcache.transaction.local.LocalTransactionTest=production -net.sf.ehcache.transaction.xa.TwoPCTest=production -net.sf.ehcache.transaction.xa.XAThreadPoolTest=production -net.sf.ehcache.transaction.xa.XATransactionSizeOfTest=production -net.sf.ehcache.transaction.xa.XATransactionTest=production -net.sf.ehcache.util.LargeCollectionTest=production -net.sf.ehcache.util.MemoryEfficientByteArrayOutputStreamTest=production -net.sf.ehcache.util.MemorySizeParserTest=production -net.sf.ehcache.util.ProductInfoTest=production -net.sf.ehcache.util.SlewClockTest=production -net.sf.ehcache.util.SmokeTests=production -net.sf.ehcache.util.TimestamperTest=production -net.sf.ehcache.util.UpdateCheckerTest=production -net.sf.ehcache.util.WeakIdentityConcurrentMapTest=production -net.sf.ehcache.writer.CacheWriterTest=production -net.sf.ehcache.writer.CoalesceKeysFilterTest=production -net.sf.ehcache.writer.TestCacheWriter=production -net.sf.ehcache.writer.TestCacheWriterException=production -net.sf.ehcache.writer.TestCacheWriterFactory=production -net.sf.ehcache.writer.TestCacheWriterRetries=production -net.sf.ehcache.writer.TestCacheWriterSlow=production -org.terracotta.ehcache.tests.BasicAtomikosXATest=quarantined -org.terracotta.ehcache.tests.BasicBTMXATest=quarantined -org.terracotta.ehcache.tests.BasicStandaloneCacheAndServerTopologyTest=production -org.terracotta.ehcache.tests.BasicStandaloneCacheTest=production -org.terracotta.ehcache.tests.BasicWriteBehindTest=quarantined -org.terracotta.ehcache.tests.CacheBlockingQueueTest=quarantined -org.terracotta.ehcache.tests.CacheConsistencyTest=production -org.terracotta.ehcache.tests.CacheLocksTest=quarantined -org.terracotta.ehcache.tests.CacheWriterBTMXATest=quarantined -org.terracotta.ehcache.tests.ClusterCacheEventsRejoinEnabledTest=quarantined -org.terracotta.ehcache.tests.ClusterEventsRejoinEnabledTest=quarantined -org.terracotta.ehcache.tests.ClusterEventsTest=production -org.terracotta.ehcache.tests.ClusteredCacheRemovalTest=quarantined -org.terracotta.ehcache.tests.CoalescingWriteBehindTest=quarantined -org.terracotta.ehcache.tests.CompressedCacheTest=production -org.terracotta.ehcache.tests.ConcurrencyValueTest=quarantined -org.terracotta.ehcache.tests.CopyOnWriteTest=production -org.terracotta.ehcache.tests.DoubleConfigStandaloneCacheTest=production -org.terracotta.ehcache.tests.EmbeddedConfigNamespaceStandaloneCacheTest=production -org.terracotta.ehcache.tests.EmbeddedConfigStandaloneCacheTest=production -org.terracotta.ehcache.tests.EmbeddedEhcacheJarTest=production -org.terracotta.ehcache.tests.EmbeddedEhcacheJarTestClient=production -org.terracotta.ehcache.tests.ExpiryListenerTest=production -org.terracotta.ehcache.tests.ExplicitlyUnclusteredStandaloneCacheTest=production -org.terracotta.ehcache.tests.ExpressShutdownTest=production -org.terracotta.ehcache.tests.GetKeysSerializedCacheTest=production -org.terracotta.ehcache.tests.HibernateExpressShutdownTest=production -org.terracotta.ehcache.tests.LocalTxTest=production -org.terracotta.ehcache.tests.MemoryStoreEvictionPolicyTest=production -org.terracotta.ehcache.tests.MixedCacheTest=production -org.terracotta.ehcache.tests.NamelessCacheManagerStandaloneCacheTest=production -org.terracotta.ehcache.tests.NoTcConfigStandaloneCacheTest=production -org.terracotta.ehcache.tests.OtherClassLoaderEventTest=production -org.terracotta.ehcache.tests.OtherClassloaderCacheTest=production -org.terracotta.ehcache.tests.OverflowToDiskStandaloneCacheTest=production -org.terracotta.ehcache.tests.SerializationWriteBehindTest=production -org.terracotta.ehcache.tests.SerializedArrayCacheTest=production -org.terracotta.ehcache.tests.SuspendResumeAtomikosXATest=production -org.terracotta.ehcache.tests.SuspendResumeBTMXATest=production -org.terracotta.ehcache.tests.SynchronousWriteBehindTest=production -org.terracotta.ehcache.tests.SystemPropTcConfigTest=production -org.terracotta.ehcache.tests.ThreadLocalTest=production -org.terracotta.ehcache.tests.TwoResourceAtomikosXATest=production -org.terracotta.ehcache.tests.TwoResourceBTMXATest=production -org.terracotta.ehcache.tests.TwoResourceSuspendResumeAtomikosXATest=production -org.terracotta.ehcache.tests.TwoResourceSuspendResumeBTMXATest=production -org.terracotta.ehcache.tests.UrlConfigStandaloneCacheTest=production -org.terracotta.ehcache.tests.XAResourceTest=production -org.terracotta.ehcache.tests.coherence.CacheCoherenceExpressTest=quarantined -org.terracotta.ehcache.tests.coherence.IncoherentNodesTest=quarantined -org.terracotta.ehcache.tests.coherence.RestartingL1ExpressTest=quarantined -org.terracotta.ehcache.tests.container.BasicContainerJTATest=production -org.terracotta.ehcache.tests.container.BasicContainerTest=production -org.terracotta.ehcache.tests.container.BasicJTATestServlet=production -org.terracotta.ehcache.tests.container.BasicTestServlet=production -org.terracotta.ehcache.tests.container.EARContainerTest=production -org.terracotta.ehcache.tests.container.TwoResourceContainerJTATest=production -org.terracotta.ehcache.tests.container.TwoResourceJTATestServlet=production -org.terracotta.ehcache.tests.container.hibernate.BaseClusteredRegionFactoryTest=production -org.terracotta.ehcache.tests.container.hibernate.BaseClusteredRegionFactoryTestServlet=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.EhCacheClusteredHibernateCacheTest=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.EmptySecondLevelCacheEntryTest=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.KeyDeserializationSecondLevelCacheEntryTest=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.KeyDeserializationSecondLevelCacheEntryTestServlet=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.NonEternalSecondLevelCacheTest=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.NonEternalSecondLevelCacheTestServlet=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.NonTransactionalCacheTest=production -org.terracotta.ehcache.tests.container.hibernate.nontransactional.QueryCacheInvalidationTest=production -org.terracotta.ehcache.tests.loader.LoaderTest=production -org.terracotta.ehcache.tests.servermap.BasicServerMapExpressCacheTest=production -org.terracotta.ehcache.tests.servermap.BasicServerMapExpressTestHelper=production -org.terracotta.ehcache.tests.servermap.CacheSizeTest=production -org.terracotta.ehcache.tests.servermap.LockGCNotFlushingEntriesTest=production -org.terracotta.ehcache.tests.servermap.LockGCNotFlushingEntriesTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapCapacityEvictionExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapCapacityEvictionExpressTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapClearExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapClearExpressTestClient1=production -org.terracotta.ehcache.tests.servermap.ServerMapClearExpressTestClient2=production -org.terracotta.ehcache.tests.servermap.ServerMapClearTestHelper=production -org.terracotta.ehcache.tests.servermap.ServerMapElementTTIExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapElementTTIExpressTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapElementTTLExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapElementTTLExpressTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapL1CapacityEvictionExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapL1CapacityEvictionExpressTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapL1CapacityExpirationExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapL1CapacityExpirationExpressTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapL1EvictionOffHeapDestroyExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapL1EvictionOffHeapDestroyExpressTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapL2EvictionReachesL1Test=production -org.terracotta.ehcache.tests.servermap.ServerMapL2EvictionReachesL1TestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapL2EvictionReachesOneL1Test=production -org.terracotta.ehcache.tests.servermap.ServerMapL2EvictionReachesOneL1TestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapLocalSizeTest=production -org.terracotta.ehcache.tests.servermap.ServerMapTTIExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapTTIExpressTestClient=production -org.terracotta.ehcache.tests.servermap.ServerMapTTLExpressTest=production -org.terracotta.ehcache.tests.servermap.ServerMapTTLExpressTestClient=production -org.terracotta.modules.ehcache.LocalVMResourcesTestUtil=production -org.terracotta.modules.ehcache.bulkops.BulkOpsBasicSerializationSanityTest=production -org.terracotta.modules.ehcache.bulkops.BulkOpsExplictLockingTest=production -org.terracotta.modules.ehcache.bulkops.BulkOpsGenericSanityTest=production -org.terracotta.modules.ehcache.bulkops.GetAllCustomMapTest=production -org.terracotta.modules.ehcache.bulkops.GetAllNonLiteralTest=production -org.terracotta.modules.ehcache.bulkops.GetAllTest=production -org.terracotta.modules.ehcache.cluster.CacheClusterTest=production -org.terracotta.modules.ehcache.cluster.ClusterTopologyListenerTest=production -org.terracotta.modules.ehcache.cluster.FailoverDuringPassiveSyncTest=production -org.terracotta.modules.ehcache.cluster.FailoverToOutOfSyncPassivesTest=production -org.terracotta.modules.ehcache.coherence.CacheCoherenceTest=production -org.terracotta.modules.ehcache.coherence.CacheCoherenceTestL1Client=production -org.terracotta.modules.ehcache.coherence.GetSizeTest=production -org.terracotta.modules.ehcache.coherence.NoLocksCreatedEventualTest=production -org.terracotta.modules.ehcache.coherence.NoLocksCreatedTest=production -org.terracotta.modules.ehcache.event.ClusterTopologyTest=production -org.terracotta.modules.ehcache.event.ClusteredEventsAllTest=production -org.terracotta.modules.ehcache.event.ClusteredEventsEvictionExpiryTest=production -org.terracotta.modules.ehcache.event.ClusteredEventsLocalTest=production -org.terracotta.modules.ehcache.event.ClusteredEventsRemoteTest=production -org.terracotta.modules.ehcache.event.ClusteredEventsSerializationTest=production -org.terracotta.modules.ehcache.l1bm.L1BMCacheManagerRecreateTest=production -org.terracotta.modules.ehcache.l1bm.L1BMCacheStatisticsTest=production -org.terracotta.modules.ehcache.l1bm.L1BMDynamicConfigurationTest=production -org.terracotta.modules.ehcache.l1bm.L1BMOnHeapActivePassiveSanityTest=production -org.terracotta.modules.ehcache.l1bm.L1BMOnHeapBasicSanityTestApp=production -org.terracotta.modules.ehcache.l1bm.L1BMOnHeapReadWriteTest=production -org.terracotta.modules.ehcache.l1bm.L1BMOnHeapSanityTest=production -org.terracotta.modules.ehcache.l1bm.L1BMOnHeapWithTTISanityTest=production -org.terracotta.modules.ehcache.l1bm.L1BMOnHeapWithTTLSanityTest=production -org.terracotta.modules.ehcache.l1bm.L1BMUpdateInvalidatedEntryTest=production -org.terracotta.modules.ehcache.store.BasicCacheSyncWriteTest=production -org.terracotta.modules.ehcache.store.BasicCacheTest=production -org.terracotta.modules.ehcache.store.BlockingCacheTest=production -org.terracotta.modules.ehcache.store.CachePinningTest=production -org.terracotta.modules.ehcache.store.ClassicIsInvalidTest=production -org.terracotta.modules.ehcache.store.ConcurrentCacheMethodsTest=production -org.terracotta.modules.ehcache.store.CopyOnReadTest=production -org.terracotta.modules.ehcache.store.DCV2ConfigurationChangePropagationTest=production -org.terracotta.modules.ehcache.store.DynamicCacheConfigurationTest=production -org.terracotta.modules.ehcache.store.EvictionListenerTest=production -org.terracotta.modules.ehcache.store.ExpirationListenerTest=production -org.terracotta.modules.ehcache.store.GetKeysSerializedCacheTest=production -org.terracotta.modules.ehcache.store.InlineExpirationTest=production -org.terracotta.modules.ehcache.store.LocalBufferedMapTest=production -org.terracotta.modules.ehcache.store.LocalReadsGetKeysTest=production -org.terracotta.modules.ehcache.store.NoCacheWithMaxBytesLocalDiskTest=production -org.terracotta.modules.ehcache.store.PinnedCacheTest=production -org.terracotta.modules.ehcache.store.PrimitiveClassTest=production -org.terracotta.modules.ehcache.store.ProgrammaticCacheTest=production -org.terracotta.modules.ehcache.store.ProgrammaticConfigTest=production -org.terracotta.modules.ehcache.store.SampledStatisticTimerTest=production -org.terracotta.modules.ehcache.store.SerializedCacheCopyOnReadTest=production -org.terracotta.modules.ehcache.store.SerializedCacheTest=production -org.terracotta.modules.ehcache.store.ServerMapBasicCacheTest=production -org.terracotta.modules.ehcache.store.SimpleVersionTest=production -org.terracotta.modules.ehcache.store.StorageStrategyNotSupportedTest=production -org.terracotta.modules.ehcache.store.TTICacheTest=production -org.terracotta.modules.ehcache.store.TTLCacheTest=production -org.terracotta.modules.ehcache.store.TotalCapacityTest=production -org.terracotta.modules.ehcache.store.backend.BulkLoadInternalKeyRepresentationExposedTest=production -org.terracotta.modules.ehcache.writebehind.AsyncWriteBehindTest=production -org.terracotta.modules.ehcache.writebehind.BasicWriteBehindTest=production -org.terracotta.modules.ehcache.writebehind.CacheSeparationWriteBehindTest=production -org.terracotta.modules.ehcache.writebehind.CoalescingWriteBehindTest=production -org.terracotta.modules.ehcache.writebehind.RemovingCacheWriteBehindTest=production -org.terracotta.modules.ehcache.writebehind.SerializationWriteBehindTest=production Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/pom.xml (revision 0) @@ -1,136 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - management-ehcache-impl-parent - 2.10.8.1.63 - .. - - - management-ehcache-impl-v2 - management-ehcache-impl-v2 - A product library integrating with ehcache to construct the relevant management resource entities V1 - - - - net.sf.ehcache - management-ehcache-v2 - ${project.version} - - - net.sf.ehcache - management-ehcache-common - ${project.version} - - - org.terracotta - management-core-resources - ${management-core.version} - test-jar - test - - - net.sf.ehcache.internal - ehcache-core - ${project.version} - provided - - - net.sf.ehcache.internal - ehcache-terracotta-bootstrap - ${project.version} - provided - - - org.terracotta.toolkit - terracotta-toolkit-api - 2.5 - provided - - - org.terracotta.toolkit - terracotta-toolkit-api-internal - provided - - - gf-40 - gf.javax.servlet-api - - - org.easymock - easymock - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.mockito - mockito-core - test - - - org.powermock - powermock-api-easymock - test - - - org.powermock - powermock-module-junit4 - test - - - org.hamcrest - hamcrest-all - 1.3 - test - - - commons-io - commons-io - 2.6 - test - - - net.sf.ehcache.internal - ehcache-core - test-jar - ${project.version} - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/distribution/events/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/events/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/events/pom.xml (revision 0) @@ -1,298 +0,0 @@ - - 4.0.0 - - org.terracotta.forge - forge-parent - 4.0 - - - net.sf.ehcache.examples - events - 2.10.8.1.63 - events - war - Clustered Ehcache Terracotta as second level cache for Hibernate - - 2.1.0 - 4.3.8.1.46 - 1.1.116 - 9.4.28.v20200408 - 1.1 - true - true - - - - org.slf4j - slf4j-api - 1.7.25 - - - ch.qos.logback - logback-classic - 1.2.3 - - - javassist - javassist - 3.8.0.GA - - - h2 - ${h2.version} - com.h2database - - - net.sf.ehcache - ehcache - ${project.version} - - - org.terracotta - terracotta-toolkit-runtime - ${terracotta.version} - - - commons-logging - commons-logging - 1.1 - compile - - - logkit - logkit - - - avalon-framework - avalon-framework - - - javax.servlet - servlet-api - - - - - gf-40 - gf.javax.servlet-api - 3.1.0 - - - org.hibernate - hibernate-core - 3.3.1.GA - - - org.slf4j - slf4j-api - - - javax.transaction - jta - - - - - gf-3122 - gf.javax.transaction - 1.1 - - - - ${project.name} - - - maven-assembly-plugin - 2.3 - - ${project.name} - - src/assemble/distribution.xml - - gnu - - - - package - - single - - - - - - jetty-maven-plugin - ${jetty.version} - org.eclipse.jetty - - - ${project.name} - - STOP - - - - hibernate3-maven-plugin - 2.1 - org.codehaus.mojo - - - target/classes/hibernate3hbm2ddl.properties - target/classes/hibernate.cfg.xml - true - true - schema.sql - - - - - com.h2database - h2 - ${h2.version} - - - - - org.terracotta.maven.plugins - tc-maven-plugin - ${tc-maven-plugin.version} - - - org.terracotta - terracotta - ${terracotta.version} - - - - - - - - start-h2 - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - org.h2.tools.Server - - -tcp - -tcpAllowOthers - - - - - - - - stop-h2 - - - - org.codehaus.mojo - exec-maven-plugin - ${exec-maven-plugin.version} - - org.h2.tools.Server - - -tcpShutdown - tcp://localhost:9092 - - - - - - - - 9081 - - - - jetty-maven-plugin - ${jetty.version} - org.eclipse.jetty - - - - jetty.port - 9081 - - - 9981 - - - - - - - 9082 - - - - jetty-maven-plugin - ${jetty.version} - org.eclipse.jetty - - - - jetty.port - 9082 - - - 9982 - - - - - - - sag-deps - - - sag-deps - true - - - - - - - org.terracotta - maven-forge-plugin - - - com.softwareag.ibit.tools.util - finder - 3.0 - compile - - - - - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/pom.xml (revision 0) @@ -1,43 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - .. - - - management-ehcache-impl-parent - management-ehcache-impl-parent - pom - - - management-ehcache-impl-v1 - management-ehcache-impl-v2 - management-ehcache-common - ehcache-rest-agent - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-core/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/pom.xml (revision 0) @@ -1,536 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - - - net.sf.ehcache.internal - ehcache-core - jar - - ehcache-core - Internal ehcache-core module. This artifact is not meant to be used directly - - - Ehcache - UTF-8 - UTF-8 - 5 - src/test/java - src/test/resources - ehcache - false - - -Xmx64m - - - - - - org.slf4j - slf4j-api - - - org.terracotta.internal - statistics - - - - - javax.servlet - javax.servlet-api - - - org.hibernate - hibernate-core - - - javax.transaction - jta - - - net.sf.ehcache - sizeof-agent - - - - - org.slf4j - slf4j-jdk14 - - - org.codehaus.btm - btm - - - net.sf.hibernate - hibernate - - - org.hamcrest - hamcrest-core - - - org.hamcrest - hamcrest-library - - - junit - junit - - - dom4j - dom4j - - - javassist - javassist - - - org.hibernate - hibernate-ehcache - - - - commons-logging - commons-logging - - - org.apache.derby - derby - - - org.mockito - mockito-core - - - com.sun.xsom - xsom - - - org.beanshell - bsh - - - - - - - src/main/resources - true - - - ${project.build.directory}/generated-resources - false - - - ${basedir}/${testDir} - - - ${basedir}/src/main/config/jcache - - - ${basedir}/${testResources} - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - test-jar - - test-jar - - - - - - org.terracotta - maven-forge-plugin - - - build-info - generate-resources - - buildinfo - - - ${basedir}/.. - - - - - - - - - org.terracotta - maven-forge-plugin - - pertest - ${tests.supplemental.args} ${tests.max.heap.size} - false - false - true - plain - false - - true - ${net.sf.ehcache.speedAdjustmentFactor} - ${project.build.directory} - true - - - net.sf.ehcache:sizeof-agent - - - - - - default-test - - - **/*$* - **/*PerfTest.java - **/*PerfTest*.java - **/Abstract*Test.java - - - - - integration-test-execution - integration-test - - test - - - ${checkshort} - false - - **/*$* - - - **/IT*.java - **/*IT.java - **/*ITCase.java - - ${tests.supplemental.args} -Xms512m -Xmx512m - - - - - - - org.apache.maven.plugins - maven-checkstyle-plugin - - - verify - - checkstyle - - - - - ${basedir}/checkstyle/checkstyle.xml - ${basedir}/checkstyle/suppressions.xml - ${basedir}/checkstyle/ClassHeader.txt - ${skipCheckstyle} - false - false - false - false - false - false - true - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - generate-resources - copy-agent-jar-to-resources - - copy-dependencies - - - * - sizeof-agent - ${project.build.directory}/generated-resources/net/sf/ehcache/pool/sizeof/ - true - true - - - - - - org.codehaus.mojo - rmic-maven-plugin - - - rmi-compilation - compile - - rmic - - - - **/RMICachePeer.class - - ${project.build.outputDirectory} - - - - - - - - - - skip-ehcache-core-deploy - - true - - - - staging - - - - org.apache.maven.plugins - maven-gpg-plugin - - - sign-artifacts - deploy - - sign - - - - - - - - - perfTests - - - - org.terracotta - maven-forge-plugin - - - - default-test - - ${tests.supplemental.args} -Xmx512m - - **/*PerfTest.java - **/*PerfTest*.java - - - **/*$* - **/Abstract*Test.java - - - - - - - - - - - buildnumber-git - - - - org.codehaus.mojo - buildnumber-maven-plugin - 1.0-beta-3 - - - generate-resources - - create - - - - - false - false - {0,date,yyyy-MM-dd_HH-mm}_{1} - - timestamp - ${user.name} - - - - - - - - - - no-interruptible-io-solaris - - - java.vendor - Sun Microsystems Inc. - - - - -XX:-UseVMInterruptibleIO - - - - enable-system-gc-jrockit - - - java.vm.name - Oracle JRockit(R) - - - - -XXfullSystemGC -Xverbose:systemgc - - - - ibmj9 - - - java.vm.name - IBM J9 VM - - - - -Xenableexplicitgc - -Xmx256m - - - - - - test-nonstopcache - - - - org.terracotta - maven-forge-plugin - - - **/nonstop/*Test.java - - - **/*$* - - - - java.awt.headless - true - - - - - - - - - - - fast - - true - - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - false - - - true - - - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - true - - - false - - - - - - jboss-releases - http://repository.jboss.org/nexus/content/groups/public-jboss - - true - - - false - - - - - - Java.net Maven 2 - http://download.java.net/maven/2 - - true - - - false - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - false - - - true - - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - true - - - false - - - - - - Index: rctags/ehcache-2.10.8.1.63/third-party.txt =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/third-party.txt (revision 11322) +++ rctags/ehcache-2.10.8.1.63/third-party.txt (revision 0) @@ -1,5 +0,0 @@ -This project depends on repackaged GlassFish libraries. -They can be identified by their groupId starting with gf-*. - -The source code for these libraries can be found at https://svn.java.net/svn/glassfish~svn/. -Otherwise contact to get the source code for these libraries. \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/management-ehcache-v2/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-v2/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-v2/pom.xml (revision 0) @@ -1,72 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - .. - - - management-ehcache-v2 - management-ehcache-v2 - A library defining the ehcache management resource services and resource entities, version 2 - - - - org.terracotta - management-common-resources-v2 - ${management-core.version} - - - - - junit - junit - test - - - org.easymock - easymock - test - - - net.sf.ehcache.internal - ehcache-core - test-jar - ${project.version} - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/pom.xml (revision 0) @@ -1,113 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - management-ehcache-impl-parent - 2.10.8.1.63 - .. - - - management-ehcache-impl-v1 - management-ehcache-impl-v1 - A product library integrating with ehcache to construct the relevant management resource entities V1 - - - - net.sf.ehcache - management-ehcache-v1 - ${project.version} - - - net.sf.ehcache - management-ehcache-common - ${project.version} - - - org.terracotta - management-core-resources - ${management-core.version} - test-jar - test - - - net.sf.ehcache.internal - ehcache-core - ${project.version} - provided - - - gf-40 - gf.javax.servlet-api - - - org.easymock - easymock - test - - - org.eclipse.jetty - jetty-servlet - test - - - org.mockito - mockito-core - test - - - org.powermock - powermock-api-easymock - test - - - org.powermock - powermock-module-junit4 - test - - - org.hamcrest - hamcrest-all - 1.3 - test - - - net.sf.ehcache.internal - ehcache-core - test-jar - ${project.version} - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-search-parser/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-search-parser/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-search-parser/pom.xml (revision 0) @@ -1,53 +0,0 @@ - - - 4.0.0 - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - .. - - - net.sf.ehcache.internal - ehcache-search-parser - ehcache-search-parser - A parser for Big Memory Structured Query Language. - - - - - org.codehaus.mojo - javacc-maven-plugin - 2.6 - - - javacc - - javacc - - - - - - - - - - net.sf.ehcache.internal - ehcache-core - ${project.version} - - - junit - junit - test - - - net.sf.ehcache.internal - ehcache-core - test-jar - ${project.version} - test - - - Index: rctags/ehcache-2.10.8.1.63/README.txt =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/README.txt (revision 11322) +++ rctags/ehcache-2.10.8.1.63/README.txt (revision 0) @@ -1,18 +0,0 @@ -1. To compile: - %> mvn install -DskipTests - -Note: the final Ehcache jar is found under ehcache/target - - -2. To build Ehcache distribution kit: - - %> cd distribution - - %> mvn package (build without an embedded Terracotta kit, lean and mean Ehcache kit) - - %> mvn package -Dtc-kit-url=http://url/to/teracotta.tar.gz (built with Terracotta kit, offical distribution kit) - -3. To deploy Maven central repo (via Sonatype) - - %> mvn clean deploy -P sign-artifacts,deploy-sonatype -DskipTests - \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/distribution/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/pom.xml (revision 0) @@ -1,298 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - - - ehcache-kit - pom - ehcache-kit - - project to build distribution kit - - - colorcache - events - - - - ehcache - ${productName}-${project.version} - ${kitFolder}-distribution - ${project.build.directory}/${kitFolder} - ${project.build.directory}/tmp/terracotta - - - - - net.sf.ehcache - ehcache - ${project.version} - provided - - - org.slf4j - slf4j-api - provided - - - org.slf4j - slf4j-jdk14 - provided - - - - - - includeJavadoc - - - !skipJavadoc - - - - - net.sf.ehcache - ehcache - ${project.version} - javadoc - provided - - - - - - - - - com.github.goldin - copy-maven-plugin - 0.2.3.8 - - false - - - - {{ new File( project.build.directory, "${kitFolder}" ).isDirectory() }} - ${root.dir} - - **/** - - true - true - - - - ${root.dir} - ${basedir}/src/main/assembly/root - true - true - - - - ${root.dir} - ${basedir}/../ehcache-core/src/main/config - true - - - - ${root.dir}/src - - - net.sf.ehcache - ehcache - sources - - - true - - - - false - ${root.dir}/javadoc - - - net.sf.ehcache - ehcache - javadoc - - - true - - - - {{ new File(project.properties['terracotta.kit.path']).isDirectory() }} - ${root.dir}/samples - - - net.sf.ehcache.examples - events - ${project.version} - distribution - tar.gz - - - net.sf.ehcache.examples - colorcache - ${project.version} - distribution - tar.gz - - - true - - - - {{ new File(project.properties['terracotta.kit.path']).isDirectory() }} - ${root.dir}/terracotta - ${terracotta.kit.path} - - **/ehcache/** - **/quartz/** - **/sessions/** - - true - - - {{ new File(project.properties['terracotta.kit.path']).isDirectory() }} - ${root.dir}/samples - ${terracotta.kit.path}/ehcache/samples - true - - - {{ new File(project.properties['terracotta.kit.path']).isDirectory() }} - ${root.dir}/samples/colorcache/bin - ${basedir}/src/main/assembly - - relative-paths.* - - - - {{ new File(project.properties['terracotta.kit.path']).isDirectory() }} - ${root.dir}/samples/events/bin - ${basedir}/src/main/assembly - - relative-paths.* - - - - - - - package-with-no-tc - package - - copy - - - - - - - org.terracotta - maven-forge-plugin - - - package-lib - package - - copy-dependencies - - - ${root.dir}/lib - false - - net.sf.ehcache:ehcache:${project.version} - org.slf4j:slf4j-api:${slf4j.version} - org.slf4j:slf4j-jdk14:${slf4j.version} - - - - - - - org.codehaus.gmaven - groovy-maven-plugin - - - create-tarball - package - - execute - - - - def srcdir = new File(project.basedir, "target/${kitFolder}") - def destFile = new File(project.basedir, "target/${tarballName}.tar.gz") - ant.tar(destfile: "${destFile}", longfile: "gnu", compression: "gzip") { - tarfileset(dir: "${srcdir}", prefix: "${kitFolder}", excludes: "**/bin/**,**/lib/**,**/*.sh,**/*.bat") - tarfileset(dir: "${srcdir}", prefix: "${kitFolder}", includes: "**/bin/**,**/lib/**,**/*.sh,**/*.bat", filemode: "755") - } - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.5 - - - attach-distribution - package - - attach-artifact - - - - - ${project.build.directory}/${tarballName}.tar.gz - tar.gz - distribution - - - - - - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - evgenyg.artifactoryonline.com - http://evgenyg.artifactoryonline.com/evgenyg/repo/ - - true - - - false - - - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/pom.xml (revision 0) @@ -1,46 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - .. - - - ehcache-scheduled-refresh - net.sf.ehcache.internal - ehcache-scheduled-refresh - Ehcache functionality for Scheduled Refresh; uses the Quartz Job Scheduler - - - - net.sf.ehcache.internal - ehcache-core - ${project.version} - - - org.quartz-scheduler - quartz - provided - - - org.slf4j - slf4j-jdk14 - provided - - - junit - junit - test - - - net.sf.ehcache.internal - ehcache-core - test-jar - ${project.version} - test - - - Index: rctags/ehcache-2.10.8.1.63/management-ehcache-v1/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-v1/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-v1/pom.xml (revision 0) @@ -1,72 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - .. - - - management-ehcache-v1 - management-ehcache-v1 - A library defining the ehcache management resource services and resource entities, version 1 - - - - org.terracotta - management-common-resources-v1 - ${management-core.version} - - - - - junit - junit - test - - - org.easymock - easymock - test - - - net.sf.ehcache.internal - ehcache-core - test-jar - ${project.version} - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/ehcache/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache/pom.xml (revision 0) @@ -1,414 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - ehcache-root - 2.10.8.1.63 - .. - - - ehcache - jar - ehcache - Ehcache is an open source, standards-based cache used to boost performance, - offload the database and simplify scalability. Ehcache is robust, proven and full-featured and - this has made it the most widely-used Java-based cache. - - - - The Apache Software License, Version 2.0 - src/assemble/EHCACHE-CORE-LICENSE.txt - - - http://ehcache.org - - - - ${project.artifactId}-${project.version}-distribution - ${project.build.directory}/${kit.name} - ${project.build.directory}/tmp/terracotta - 2.1.1 - false - true - - - - - - net.sf.ehcache.internal - ehcache-terracotta-bootstrap - ${project.version} - - - net.sf.ehcache.internal - ehcache-rest-agent - ${project.version} - - - net.sf.ehcache.internal - ehcache-core - ${project.version} - - - net.sf.ehcache.internal - ehcache-scheduled-refresh - ${project.version} - - - net.sf.ehcache.internal - ehcache-search-parser - ${project.version} - - - junit - junit - test - - - org.terracotta - product-upgradability-testing-utils - 0.9.2 - test - - - org.codehaus.btm - btm - 2.1.3 - test - - - org.quartz-scheduler - quartz - 2.2.1 - test - - - org.slf4j - slf4j-jdk14 - ${slf4j.version} - test - - - - - - - ${basedir}/src/main/resources - true - - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - copy-TIMs - - org.terracotta.modules - ${project.build.outputDirectory}/META-INF/terracotta/TIMs - **/META-INF/maven/**,**/license.txt,**/thirdpartylicenses.txt - - process-resources - - copy-dependencies - - - - - - org.terracotta - maven-forge-plugin - - - create-manifest - package - - manifest - - - ${basedir}/.. - ${project.build.directory}/MANIFEST.MF - - Apache Software License, Version 2.0 - Supported - ${project.artifactId} - ${project.description} - - - - - enforce-dependencies - - enforceDependencies - - verify - - net.sf.ehcache.internal - ehcache-core - ${project.version} - - - - - - - - - - devmode - - - devmode - true - - true - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - list-dependencies - - ${project.build.outputDirectory}/META-INF/devmode/${project.groupId}/${project.artifactId}/dependencies.txt - - - list - - compile - - - - - - - - - fullmode - - - devmode - false - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - - create-javadoc - prepare-package - - jar - - - - - org.hibernate - hibernate-core - ${hibernate-core.version} - - - ${skipJavadoc} - true - 128m - 512 - true -
ehcache]]>
- ${project.name} ${project.version} API - ${project.name} ${project.version} API - Copyright 2001-{currentYear}, Terracotta, Inc. - ${basedir}/src/main/java/net/sf/ehcache/overview.html - true - - net.sf.ehcache.internal:ehcache-core - -
-
-
-
- - - org.apache.maven.plugins - maven-shade-plugin - - record-shader - true - true - - - net.sf.ehcache.internal:* - org.terracotta.internal:statistics - com.terracotta:clustered-entity-management - - - - - *:* - - META-INF/maven/com.terracotta/** - META-INF/maven/net.sf.ehcache.internal/** - META-INF/maven/org.terracotta.internal/** - **/license.txt - **/thirdpartylicenses.txt - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - **/LICENSE - **/LICENSE.txt - **/NOTICE - **/NOTICE.txt - **/ASL2.0 - **/DEPENDENCIES - - - - true - ${project.build.directory}/dependency-reduced-pom.xml - - - MANIFEST.MF - - - META-INF/MANIFEST.MF - ${project.build.directory}/MANIFEST.MF - - - - - - shade-jar - package - - shade - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.7 - - - unpack-jar-for-bundling - package - - run - - - - - - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - - ${project.build.directory} - - bitronix.tm;resolution:=optional, - bitronix.tm.resource.ehcache;resolution:=optional, - com.atomikos.*;resolution:=optional, - com.atomikos.icatch.jta;resolution:=optional, - weblogic.transaction;resolution:=optional, - javax.transaction;resolution:=optional, - javax.servlet;resolution:=optional, - javax.net.ssl;resolution:=optional, - javax.activation;resolution:=optional, - javax.xml.stream;resolution:=optional, - javax.xml.transform.sax;resolution:=optional, - javax.xml.transform.dom;resolution:=optional, - javax.xml.transform.stream;resolution:=optional, - org.hibernate.*;resolution:=optional, - org.terracotta.toolkit.*;resolution:=optional, - org.quartz.*;resolution:=optional, - org.terracotta.quartz.*;resolution:=optional, - !sun.misc,* - - net.sf.ehcache.* - org.terracotta.* - JavaSE-1.6 - - *;scope=provided|runtime - - - - generate-osgi-headers - package - - manifest - - - - - - org.codehaus.gmaven - groovy-maven-plugin - ${groovy-maven-plugin.version} - - - repackage-jar - package - - execute - - - - def jarFile = new File(project.build.directory, "${project.artifactId}-${project.version}.jar") - ant.copy(file: new File(project.build.directory, "dependency-reduced-pom.xml"), - tofile: new File(project.build.outputDirectory, "META-INF/maven/${project.groupId}/${project.artifactId}/pom.xml")) - ant.jar(destfile: jarFile, basedir: new File(project.build.outputDirectory).getAbsolutePath(), manifest: new File(project.build.directory, "MANIFEST.MF")) - - - - - -
-
-
-
- - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - JIRA - https://jira.terracotta.org/jira/browse/EHC - - -
Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/pom.xml (revision 0) @@ -1,101 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - management-ehcache-impl-parent - 2.10.8.1.63 - .. - - - management-ehcache-common - management-ehcache-common - A common library shared between different management-ehcache implementation versions - - - false - - - - - org.terracotta - management-core-resources - - - net.sf.ehcache.internal - ehcache-core - ${project.version} - provided - - - gf-40 - gf.javax.servlet-api - - - org.eclipse.jetty - jetty-servlet - - - junit - junit - test - - - commons-io - commons-io - 2.6 - test - - - org.easymock - easymock - test - - - org.mockito - mockito-core - test - - - org.powermock - powermock-api-easymock - test - - - org.powermock - powermock-module-junit4 - test - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/ehcache-rest-agent/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/ehcache-rest-agent/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/ehcache-rest-agent/pom.xml (revision 0) @@ -1,220 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache - management-ehcache-impl-parent - 2.10.8.1.63 - .. - - - net.sf.ehcache.internal - ehcache-rest-agent - ehcache-rest-agent - - Ehcache REST implementation - - - rest-management-private-classpath - .class_terracotta - true - false - - - - - net.sf.ehcache - management-ehcache-impl-v1 - ${project.version} - - - net.sf.ehcache - management-ehcache-impl-v2 - ${project.version} - - - gf-40 - gf.javax.servlet-api - 3.1.0 - - - org.eclipse.jetty - jetty-servlet - - - javax.xml.bind - jaxb-api - 2.3.0 - - - - - - - org.apache.maven.plugins - maven-jar-plugin - - - - - - - devmode - - - devmode - true - - true - - - - .class - - - - - org.apache.maven.plugins - maven-dependency-plugin - - - list-dependencies - - ${project.build.outputDirectory}/META-INF/devmode/${project.groupId}/${project.artifactId}/dependencies.txt - - - list - - compile - - - - - - org.apache.maven.plugins - maven-shade-plugin - - reduced-pom-only-shader - ${project.build.directory}/dependency-reduced-pom.xml - true - true - false - false - - - - org.slf4j:* - - - - - - package - - shade - - - - - - - - - - fullmode - - - devmode - false - - - - - - org.apache.maven.plugins - maven-shade-plugin - - record-shader - ${project.build.directory}/dependency-reduced-pom.xml - true - true - false - true - - - - org.slf4j:* - - - - - *:* - - META-INF/*.SF - META-INF/*.DSA - META-INF/*.RSA - - - - - - - - - - package - - shade - - - - - - org.codehaus.gmaven - groovy-maven-plugin - - - fix-content - package - - execute - - - - ${basedir}/src/scripts - - - import Util - Util.packageAgentJar(project) - - - - - - - - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/pom.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/pom.xml (revision 0) @@ -1,82 +0,0 @@ - - - 4.0.0 - - - net.sf.ehcache.internal - ehcache-terracotta-root - 2.10.8.1.63 - - - ehcache-terracotta-bootstrap - ehcache-terracotta-bootstrap - jar - - - false - - - - - net.sf.ehcache.internal - ehcache-core - ${project.version} - provided - - - org.terracotta.toolkit - terracotta-toolkit-api-internal - - - com.terracotta - clustered-entity-management - - - org.mockito - mockito-core - test - - - junit - junit - test - - - net.sf.ehcache.internal - ehcache-core - test-jar - ${project.version} - test - - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - terracotta-snapshots - http://www.terracotta.org/download/reflector/snapshots - - - terracotta-releases - http://www.terracotta.org/download/reflector/releases - - - - - - deploy-sonatype - - true - - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/simplelog.properties =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/simplelog.properties (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/simplelog.properties (revision 0) @@ -1,17 +0,0 @@ -# - Default logging detail level for all instances of SimpleLog. Must be one of ("trace", "debug", "info", "warn", "error", or "fatal"). If not specified, defaults to "info". -org.apache.commons.logging.simplelog.defaultlog=fatal - -# Logging detail level for a SimpleLog instance named "xxxxx". Must be one of ("trace", "debug", "info", "warn", "error", or "fatal"). If not specified, the default logging detail level is used. -#org.apache.commons.logging.simplelog.log.xxxxx - -# Set to true if you want the Log instance name to be included in output messages. Defaults to false. -org.apache.commons.logging.simplelog.showlogname=true - -#Set to true if you want the last component of the name to be included in output messages. Defaults to true. -org.apache.commons.logging.simplelog.showShortLogname=false - -# Set to true if you want the current date and time to be included in output messages. Default is false. -#org.apache.commons.logging.simplelog.showdatetime - -# The date and time format to be used in the output messages. The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat. If the format is not specified or is invalid, the default format is used. The default format is yyyy/MM/dd HH:mm:ss:SSS zzz. -#org.apache.commons.logging.simplelog.dateTimeFormat Index: rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/bin/package.sh =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/bin/package.sh (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/bin/package.sh (revision 0) @@ -1,52 +0,0 @@ -#!/bin/bash - -cygwin=false -if [ `uname | grep CYGWIN` ]; then - cygwin=true -fi - -if [ "$JAVA_HOME" = "" ]; then - echo "JAVA_HOME is not defined" - exit 1 -fi - -appname=events - -unset CDPATH -root=`dirname $0`/.. -root=`cd $root && pwd` - -jetty1=$root/jetty6.1/9081 -jetty2=$root/jetty6.1/9082 -webapp_lib=$root/webapps/$appname/WEB-INF/lib - -tc_install_dir=$root/bin/`$root/bin/relative-paths.sh tc_install_dir` -ehcache_jars_dir=$root/bin/`$root/bin/relative-paths.sh ehcache_jars_dir` - -# package ehcache-core and ehcache-terracotta -cp $ehcache_jars_dir/lib/ehcache*.jar $webapp_lib - -# package toolkit runtime. It could be in 2 different places depending on which kit (ehcache vs tc) -toolkit_runtime=$tc_install_dir/common/terracotta-toolkit*-runtime*.jar - -if [ ! -f $toolkit_runtime ]; then - # not found under 'common', try 'lib' - toolkit_runtime=$ehcache_jars_dir/lib/terracotta-toolkit*-runtime*.jar - if [ ! -f $toolkit_runtime ]; then - echo "Couldn't locate toolkit runtime jar" - exit 1 - fi -fi - -cp $toolkit_runtime $webapp_lib - -if [ $? -eq 0 ]; then - echo "Deploying demo..." - cp -r $root/webapps $jetty1 - cp -r $root/webapps $jetty2 - echo "Done." - exit 0 -else - echo "Error packaging sample" - exit 1 -fi Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/ccs/AbstractEhcacheConcurrencyStrategy.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/ccs/AbstractEhcacheConcurrencyStrategy.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/ccs/AbstractEhcacheConcurrencyStrategy.java (revision 0) @@ -1,91 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.sf.ehcache.hibernate.ccs; - -import net.sf.ehcache.hibernate.EhCache; -import org.hibernate.cache.Cache; -import org.hibernate.cache.CacheConcurrencyStrategy; -import org.hibernate.cache.CacheException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Superclass of all Ehcache specific cache concurrency strategies. - * - * @author Chris Dennis - */ -@Deprecated -abstract class AbstractEhcacheConcurrencyStrategy implements CacheConcurrencyStrategy { - - private static final Logger LOG = LoggerFactory.getLogger(EhcacheReadOnlyCache.class); - - /** - * Ehcache instance this strategy accesses. - */ - protected EhCache cache; - - /** - * {@inheritDoc} - * - * @throws CacheException if the underlying cache is not an Ehcache - */ - public final void setCache(Cache cache) throws CacheException { - if (cache instanceof EhCache) { - this.cache = (EhCache) cache; - } else { - throw new CacheException("Ehcache concurrency strategies must be used with Ehcache caches"); - } - } - - /** - * {@inheritDoc} - */ - public final Cache getCache() { - return cache; - } - - /** - * {@inheritDoc} - */ - public final String getRegionName() { - return cache.getRegionName(); - } - - /** - * {@inheritDoc} - */ - public final void remove(Object key) throws CacheException { - cache.remove(key); - } - - /** - * {@inheritDoc} - */ - public final void clear() throws CacheException { - cache.clear(); - } - - /** - * {@inheritDoc} - */ - public final void destroy() { - try { - cache.destroy(); - } catch (Exception e) { - LOG.warn("could not destroy cache", e); - } - } -} Index: rctags/ehcache-2.10.8.1.63/distribution/colorcache/.settings/org.eclipse.m2e.core.prefs =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/colorcache/.settings/org.eclipse.m2e.core.prefs (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/colorcache/.settings/org.eclipse.m2e.core.prefs (revision 0) @@ -1,5 +0,0 @@ -#Mon Apr 02 19:15:55 PDT 2012 -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/SerializedReadCommittedClusteredSoftLock.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/SerializedReadCommittedClusteredSoftLock.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/SerializedReadCommittedClusteredSoftLock.java (revision 0) @@ -1,59 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.modules.ehcache.transaction; - -import net.sf.ehcache.transaction.TransactionID; - -import org.terracotta.modules.ehcache.ToolkitInstanceFactory; - -import java.io.Serializable; - -public class SerializedReadCommittedClusteredSoftLock implements Serializable { - - private static final long serialVersionUID = -766870846218858666L; - - private final TransactionID transactionID; - private final Object deserializedKey; - private transient volatile ReadCommittedClusteredSoftLock softLock; - - public SerializedReadCommittedClusteredSoftLock(TransactionID transactionID, Object deserializedKey) { - this.transactionID = transactionID; - this.deserializedKey = deserializedKey; - } - - public ReadCommittedClusteredSoftLock getSoftLock(ToolkitInstanceFactory toolkitInstanceFactory, - ReadCommittedClusteredSoftLockFactory factory) { - ReadCommittedClusteredSoftLock rv = softLock; - if (rv != null) { return rv; } - synchronized (this) { - softLock = new ReadCommittedClusteredSoftLock(toolkitInstanceFactory, factory, transactionID, deserializedKey); - rv = softLock; - } - return rv; - } - - @Override - public boolean equals(Object object) { - if (object instanceof SerializedReadCommittedClusteredSoftLock) { - SerializedReadCommittedClusteredSoftLock other = (SerializedReadCommittedClusteredSoftLock) object; - - if (!transactionID.equals(other.transactionID)) { return false; } - if (!deserializedKey.equals(other.deserializedKey)) { return false; } - - return true; - } - return false; - } - - @Override - public int hashCode() { - int hashCode = 31; - - hashCode *= transactionID.hashCode(); - hashCode *= deserializedKey.hashCode(); - - return hashCode; - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/UnboundedPool.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/UnboundedPool.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/UnboundedPool.java (revision 0) @@ -1,201 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.pool.impl; - -import java.util.Collection; -import java.util.Collections; - -import net.sf.ehcache.pool.Pool; -import net.sf.ehcache.pool.PoolAccessor; -import net.sf.ehcache.pool.PoolEvictor; -import net.sf.ehcache.pool.PoolParticipant; -import net.sf.ehcache.pool.SizeOfEngine; - -/** - * A no-op pool which does not enforce any resource consumption limit. - * - * @author Ludovic Orban - * @author Alex Snaps - */ -public class UnboundedPool implements Pool { - - /** - * An accessor that just is unbounded - */ - public static final PoolAccessor UNBOUNDED_ACCESSOR = new UnboundedPoolAccessor(); - - /** - * Create an UnboundedPool instance - */ - public UnboundedPool() { - } - - /** - * {@inheritDoc} - */ - public long getSize() { - return -1L; - } - - /** - * {@inheritDoc} - */ - public long getMaxSize() { - return -1L; - } - - /** - * {@inheritDoc} - */ - public void setMaxSize(long newSize) { - } - - /** - * {@inheritDoc} - */ - public PoolAccessor createPoolAccessor(PoolParticipant participant, int maxDepth, boolean abortWhenMaxDepthExceeded) { - return new UnboundedPoolAccessor(); - } - - /** - * {@inheritDoc} - */ - public PoolAccessor createPoolAccessor(PoolParticipant participant, SizeOfEngine sizeOfEngine) { - return new UnboundedPoolAccessor(); - } - - /** - * {@inheritDoc} - */ - public void registerPoolAccessor(PoolAccessor accessor) { - //no-op - } - - /** - * {@inheritDoc} - */ - public void removePoolAccessor(PoolAccessor accessor) { - //no-op - } - - /** - * {@inheritDoc} - */ - public Collection getPoolAccessors() { - return Collections.emptyList(); - } - - /** - * {@inheritDoc} - */ - public PoolEvictor getEvictor() { - throw new UnsupportedOperationException(); - } - - /** - * The PoolAccessor class of the UnboundedPool - */ - private static final class UnboundedPoolAccessor implements PoolAccessor { - - private UnboundedPoolAccessor() { - } - - /** - * {@inheritDoc} - */ - public long add(Object key, Object value, Object container, boolean force) { - return 0L; - } - - /** - * {@inheritDoc} - */ - public boolean canAddWithoutEvicting(Object key, Object value, Object container) { - return true; - } - - /** - * {@inheritDoc} - */ - public long delete(long sizeOf) throws IllegalArgumentException { -// if (sizeOf < 0L) { -// throw new IllegalArgumentException("cannot delete negative size"); -// } - return 0L; - } - - /** - * {@inheritDoc} - */ - public long replace(long currentSize, Object key, Object value, Object container, boolean force) { - return 0L; - } - - /** - * {@inheritDoc} - */ - public long getSize() { - return -1L; - } - - /** - * {@inheritDoc} - */ - public void unlink() { - } - - /** - * {@inheritDoc} - */ - public void clear() { - } - - /** - * {@inheritDoc} - */ - public PoolParticipant getParticipant() { - throw new UnsupportedOperationException(); - } - - /** - * {@inheritDoc} - */ - public void setMaxSize(final long newValue) { - } - - /** - * {@inheritDoc} - */ - public long getPoolOccupancy() { - return -1L; - } - - /** - * {@inheritDoc} - */ - public long getPoolSize() { - return Long.MAX_VALUE; - } - - /** - * {@inheritDoc} - */ - public boolean hasAbortedSizeOf() { - return false; - } - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeAtomikosXATest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeAtomikosXATest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeAtomikosXATest.java (revision 0) @@ -1,34 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.ehcache.tests.txns; - -import org.terracotta.ehcache.tests.AbstractCacheTestBase; -import org.terracotta.test.util.TestBaseUtil; - -import com.atomikos.icatch.config.UserTransactionService; -import com.atomikos.icatch.config.imp.AbstractUserTransactionService; -import com.atomikos.icatch.jta.UserTransactionManager; -import com.atomikos.util.Atomikos; -import com.tc.test.config.model.TestConfig; - -import java.util.ArrayList; -import java.util.List; - -public class SuspendResumeAtomikosXATest extends AbstractCacheTestBase { - - public SuspendResumeAtomikosXATest(TestConfig testConfig) { - super("basic-xa-test.xml", testConfig, SuspendResumeClient.class); - testConfig.getClientConfig().setParallelClients(false); - } - - @Override - protected List getExtraJars() { - List extraJars = new ArrayList(); - 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 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 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("
"); - out.println("Title:
"); - out.println("Date (e.g. MM/dd/yyyy):
"); - out.println(""); - 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(""); - out.println(""); - out.println(""); - Iterator it = result.iterator(); - while (it.hasNext()) { - Event event = (Event) it.next(); - out.println(""); - out.println(""); - out.println(""); - out.println(""); - } - out.println("
Event titleEvent date
" + event.getTitle() + "" + dateFormatter.format(event.getDate()) + "
"); - } - } - - 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 @@ - - - - - - - - - - - - - - - - - Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/NoOpOnTimeoutStore.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/NoOpOnTimeoutStore.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/NoOpOnTimeoutStore.java (revision 0) @@ -1,535 +0,0 @@ -/** - * Copyright Terracotta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions and limitations under the - * License. - */ - -package org.terracotta.modules.ehcache.store.nonstop; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.Element; -import net.sf.ehcache.Status; -import net.sf.ehcache.config.CacheConfiguration; -import net.sf.ehcache.search.Attribute; -import net.sf.ehcache.search.NullResults; -import net.sf.ehcache.search.Results; -import net.sf.ehcache.search.attribute.AttributeExtractor; -import net.sf.ehcache.store.ElementValueComparator; -import net.sf.ehcache.store.Policy; -import net.sf.ehcache.store.StoreListener; -import net.sf.ehcache.store.StoreQuery; -import net.sf.ehcache.store.TerracottaStore; -import net.sf.ehcache.writer.CacheWriterManager; -import net.sf.ehcache.writer.writebehind.WriteBehind; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Implementation of {@link TerracottaStore} which returns null for all get operations and does nothing for puts and - * removes. - * - * @author Abhishek Sanoujam - */ -public final class NoOpOnTimeoutStore implements TerracottaStore { - - /** - * the singleton instance - */ - private static final NoOpOnTimeoutStore INSTANCE = new NoOpOnTimeoutStore(); - - /** - * private constructor - */ - private NoOpOnTimeoutStore() { - // - } - - /** - * Returns the singleton instance - * - * @return the singleton instance - */ - public static NoOpOnTimeoutStore getInstance() { - return INSTANCE; - } - - /** - * {@inheritDoc} - */ - @Override - public void addStoreListener(StoreListener listener) { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public boolean bufferFull() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean containsKey(Object key) { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean containsKeyInMemory(Object key) { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean containsKeyOffHeap(Object key) { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean containsKeyOnDisk(Object key) { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void dispose() { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public Results executeQuery(StoreQuery query) { - return NullResults.INSTANCE; - } - - /** - * {@inheritDoc} - */ - @Override - public void expireElements() { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public void flush() { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public Element get(Object key) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Policy getInMemoryEvictionPolicy() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public int getInMemorySize() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public long getInMemorySizeInBytes() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public Object getInternalContext() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public List getKeys() { - return Collections.EMPTY_LIST; - } - - /** - * {@inheritDoc} - */ - @Override - public Object getMBean() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public int getOffHeapSize() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public long getOffHeapSizeInBytes() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public int getOnDiskSize() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public long getOnDiskSizeInBytes() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasAbortedSizeOf() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Element getQuiet(Object key) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Map getAllQuiet(Collection keys) { - Map rv = new HashMap(); - for (Object key : keys) { - rv.put(key, null); - } - return rv; - } - - /** - * {@inheritDoc} - */ - @Override - public Map getAll(Collection keys) { - return getAllQuiet(keys); - } - - /** - * {@inheritDoc} - */ - @Override - public int getSize() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public Status getStatus() { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public int getTerracottaClusteredSize() { - return 0; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isCacheCoherent() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isClusterCoherent() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean isNodeCoherent() { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean put(Element element) throws CacheException { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public void putAll(Collection elements) throws CacheException { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public Element putIfAbsent(Element element) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws CacheException { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Element remove(Object key) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public void removeAll(Collection keys) { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public void removeAll() throws CacheException { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public Element removeElement(Element element, ElementValueComparator comparator) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public void removeStoreListener(StoreListener listener) { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public Element removeWithWriter(Object key, CacheWriterManager writerManager) throws CacheException { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public boolean replace(Element old, Element element, ElementValueComparator comparator) { - return false; - } - - /** - * {@inheritDoc} - */ - @Override - public Element replace(Element element) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public void setAttributeExtractors(Map extractors) { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public void setInMemoryEvictionPolicy(Policy policy) { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public void setNodeCoherent(boolean coherent) throws UnsupportedOperationException { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public void waitUntilClusterCoherent() throws UnsupportedOperationException { - // no-op - } - - @Override - public Set getSearchAttributes() { - return Collections.emptySet(); - } - - /** - * {@inheritDoc} - */ - @Override - public Attribute getSearchAttribute(String attributeName) { - return new Attribute(attributeName); - } - - /** - * {@inheritDoc} - */ - @Override - public Set getLocalKeys() { - return Collections.EMPTY_SET; - } - - /** - * {@inheritDoc} - */ - @Override - public CacheConfiguration.TransactionalMode getTransactionalMode() { - return null; - } - - /** - * {@inheritDoc} - */ - public Element unlockedGet(Object key) { - return null; - } - - /** - * {@inheritDoc} - */ - public Element unlockedGetQuiet(Object key) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public Element unsafeGet(Object key) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public void quickClear() { - // no-op - } - - /** - * {@inheritDoc} - */ - @Override - public int quickSize() { - return 0; - } - - /** - * {@inheritDoc} - */ - public Element unsafeGetQuiet(Object key) { - return null; - } - - /** - * {@inheritDoc} - */ - @Override - public void recalculateSize(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public WriteBehind createWriteBehind() { - throw new UnsupportedOperationException(); - } - - @Override - public void notifyCacheEventListenersChanged() { - // no-op - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/CacheCopyOnRwPoolTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/CacheCopyOnRwPoolTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/CacheCopyOnRwPoolTest.java (revision 0) @@ -1,183 +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.io.Serializable; - -import net.sf.ehcache.config.CacheConfiguration; -import net.sf.ehcache.config.Configuration; -import net.sf.ehcache.config.DiskStoreConfiguration; -import net.sf.ehcache.config.MemoryUnit; -import net.sf.ehcache.config.PersistenceConfiguration; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static junit.framework.Assert.assertTrue; - -/** - * Tests for Cache copy on r/w with pools - * - * @author Ludovic Orban - */ -public class CacheCopyOnRwPoolTest { - - private CacheManager cacheManager; - - @Before - public void setUp() throws Exception { - cacheManager = new CacheManager( - new Configuration() - .diskStore(new DiskStoreConfiguration().path(System.getProperty("java.io.tmpdir"))) - .maxBytesLocalHeap(50, MemoryUnit.KILOBYTES) - .maxBytesLocalDisk(200, MemoryUnit.KILOBYTES) - ); - } - - @After - public void tearDown() { - cacheManager.shutdown(); - cacheManager = null; - } - - @Test - public void testMemoryOnly() throws Exception { - cacheManager.addCache(new Cache( - new CacheConfiguration() - .name("memoryOnlyCache") - .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE)) - .overflowToDisk(false) - )); - cacheManager.addCache(new Cache( - new CacheConfiguration() - .name("memoryOnlyCache_copy") - .copyOnRead(true) - .copyOnWrite(true) - .persistence(new PersistenceConfiguration().strategy(PersistenceConfiguration.Strategy.NONE)) - .overflowToDisk(false) - )); - - Cache cache = cacheManager.getCache("memoryOnlyCache"); - assertTrue(!cache.isDiskStore()); - Cache copyCache = cacheManager.getCache("memoryOnlyCache_copy"); - - cache.put(new Element(1000, new CrazyObject())); - copyCache.put(new Element(1000, new CrazyObject())); - - long cacheSize = cache.getStatistics().getLocalHeapSizeInBytes(); - System.out.println("cache size : " + cacheSize); - assertTrue(cacheSize != 0); - long copyCacheSize = copyCache.getStatistics().getLocalHeapSizeInBytes(); - System.out.println("copyCache size : " + copyCacheSize); - assertTrue(copyCacheSize != 0); - assertTrue(cacheSize != copyCacheSize); - } - - @Test - public void testOverflowToDisk() throws Exception { - cacheManager.addCache(new Cache( - new CacheConfiguration() - .overflowToDisk(true) - .name("overflowToDiskCache") - )); - cacheManager.addCache(new Cache( - new CacheConfiguration() - .overflowToDisk(true) - .name("overflowToDiskCache_copy") - .copyOnRead(true) - .copyOnWrite(true) - )); - - Cache cache = cacheManager.getCache("overflowToDiskCache"); - Cache copyCache = cacheManager.getCache("overflowToDiskCache_copy"); - - cache.put(new Element(1000, new CrazyObject())); - copyCache.put(new Element(1000, new CrazyObject())); - - Thread.sleep(1000); - - long cacheSize = cache.getStatistics().getLocalHeapSizeInBytes(); - System.out.println("cache size : " + cacheSize); - assertTrue(cacheSize != 0); - long copyCacheSize = copyCache.getStatistics().getLocalHeapSizeInBytes(); - System.out.println("copyCache size : " + copyCacheSize); - assertTrue(copyCacheSize != 0); - assertTrue(cacheSize != copyCacheSize); - - long cacheDiskSize = cache.getStatistics().getLocalDiskSizeInBytes(); - System.out.println("cache disk size : " + cacheDiskSize); - assertTrue(cacheDiskSize != 0); - long copyCacheDiskSize = copyCache.getStatistics().getLocalDiskSizeInBytes(); - System.out.println("copyCache disk size : " + copyCacheDiskSize); - assertTrue(copyCacheDiskSize != 0); - assertTrue(cacheDiskSize != copyCacheDiskSize); - } - - @Test - public void testDiskPersistent() throws Exception { - cacheManager.addCache(new Cache( - new CacheConfiguration() - .overflowToDisk(true) - .diskPersistent(true) - .name("diskPersistentCache") - )); - cacheManager.addCache(new Cache( - new CacheConfiguration() - .overflowToDisk(true) - .diskPersistent(true) - .name("diskPersistentCache_copy") - .copyOnRead(true) - .copyOnWrite(true) - )); - - Cache cache = cacheManager.getCache("diskPersistentCache"); - Cache copyCache = cacheManager.getCache("diskPersistentCache_copy"); - - cache.put(new Element(1000, new CrazyObject())); - copyCache.put(new Element(1000, new CrazyObject())); - - Thread.sleep(1000); - - long cacheSize = cache.getStatistics().getLocalHeapSizeInBytes(); - System.out.println("cache size : " + cacheSize); - assertTrue(cacheSize != 0); - long copyCacheSize = copyCache.getStatistics().getLocalHeapSizeInBytes(); - System.out.println("copyCache size : " + copyCacheSize); - assertTrue(copyCacheSize != 0); - assertTrue(cacheSize != copyCacheSize); - - long cacheDiskSize = cache.getStatistics().getLocalDiskSizeInBytes(); - System.out.println("cache disk size : " + cacheDiskSize); - assertTrue(cacheDiskSize != 0); - long copyCacheDiskSize = copyCache.getStatistics().getLocalDiskSizeInBytes(); - System.out.println("copyCache disk size : " + copyCacheDiskSize); - assertTrue(copyCacheDiskSize != 0); - assertTrue(cacheDiskSize != copyCacheDiskSize); - } - - static class CrazyObject implements Serializable { - - public Object writeReplace() { - return new byte[1024]; - } - - public Object readResolve() { - return new CrazyObject(); - } - } -} - Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/UnclusteredClient.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/UnclusteredClient.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/UnclusteredClient.java (revision 0) @@ -1,31 +0,0 @@ -package org.terracotta.ehcache.tests; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.Element; - -import org.terracotta.toolkit.Toolkit; - -public class UnclusteredClient extends ClientBase { - - public UnclusteredClient(String[] args) { - super("test-unclustered", args); - } - - public static void main(String[] args) { - new UnclusteredClient(args).run(); - } - - @Override - protected void runTest(Cache cache, Toolkit toolkit) throws Throwable { - Element element = cache.get("key"); - if (element != null) { - throw new AssertionError(); - } - - cache.put(new Element("key", "value")); - - element = cache.get("key"); - Object value = element.getObjectValue(); - if (!"value".equals(value)) { throw new AssertionError("unexpected value: " + value); } - } -} \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/LocalReadsAndExceptionOnWritesTimeoutStore.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/LocalReadsAndExceptionOnWritesTimeoutStore.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/nonstop/LocalReadsAndExceptionOnWritesTimeoutStore.java (revision 0) @@ -1,338 +0,0 @@ -/** - * Copyright Terracotta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file - * except in compliance with the License. You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions and limitations under the - * License. - */ - -package org.terracotta.modules.ehcache.store.nonstop; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.Element; -import net.sf.ehcache.Status; -import net.sf.ehcache.config.CacheConfiguration; -import net.sf.ehcache.search.Attribute; -import net.sf.ehcache.search.Results; -import net.sf.ehcache.search.SearchException; -import net.sf.ehcache.search.attribute.AttributeExtractor; -import net.sf.ehcache.store.ElementValueComparator; -import net.sf.ehcache.store.Policy; -import net.sf.ehcache.store.StoreListener; -import net.sf.ehcache.store.StoreQuery; -import net.sf.ehcache.store.TerracottaStore; -import net.sf.ehcache.terracotta.TerracottaNotRunningException; -import net.sf.ehcache.writer.CacheWriterManager; -import net.sf.ehcache.writer.writebehind.WriteBehind; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * LocalReadsAndExceptionOnWritesTimeoutStore - */ -public class LocalReadsAndExceptionOnWritesTimeoutStore implements TerracottaStore { - - private final TerracottaStore reader; - private final TerracottaStore writer = ExceptionOnTimeoutStore.getInstance(); - - /** - * Constructor accepting the {@link TerracottaStore} - */ - public LocalReadsAndExceptionOnWritesTimeoutStore(TerracottaStore delegate) { - reader = new LocalReadsOnTimeoutStore(delegate); - } - - public LocalReadsAndExceptionOnWritesTimeoutStore() { - reader = NoOpOnTimeoutStore.getInstance(); - } - - @Override - public int getSize() { - return reader.getSize(); - } - - @Override - public int getInMemorySize() { - return reader.getInMemorySize(); - } - - @Override - public int getOffHeapSize() { - return reader.getOffHeapSize(); - } - - @Override - public int getOnDiskSize() { - return reader.getOnDiskSize(); - } - - @Override - public int getTerracottaClusteredSize() { - return reader.getTerracottaClusteredSize(); - } - - @Override - public long getInMemorySizeInBytes() { - return reader.getInMemorySizeInBytes(); - } - - @Override - public long getOffHeapSizeInBytes() { - return reader.getOffHeapSizeInBytes(); - } - - @Override - public long getOnDiskSizeInBytes() { - return reader.getOnDiskSizeInBytes(); - } - - @Override - public boolean hasAbortedSizeOf() { - return reader.hasAbortedSizeOf(); - } - - @Override - public Status getStatus() { - return reader.getStatus(); - } - - @Override - public boolean containsKey(Object key) { - return reader.containsKey(key); - } - - @Override - public boolean containsKeyOnDisk(Object key) { - return reader.containsKeyOnDisk(key); - } - - @Override - public boolean containsKeyOffHeap(Object key) { - return reader.containsKeyOffHeap(key); - } - - @Override - public boolean containsKeyInMemory(Object key) { - return reader.containsKeyInMemory(key); - } - - @Override - public Element get(Object key) { - return reader.get(key); - } - - @Override - public Element getQuiet(Object key) { - return reader.getQuiet(key); - } - - @Override - public List getKeys() { - return reader.getKeys(); - } - - @Override - public boolean bufferFull() { - return reader.bufferFull(); - } - - @Override - public Policy getInMemoryEvictionPolicy() { - return reader.getInMemoryEvictionPolicy(); - } - - @Override - public Results executeQuery(StoreQuery query) throws SearchException { - return reader.executeQuery(query); - } - - @Override - public Set getSearchAttributes() { - return reader.getSearchAttributes(); - } - - @Override - public Attribute getSearchAttribute(String attributeName) { - return reader.getSearchAttribute(attributeName); - } - - @Override - public Map getAllQuiet(Collection keys) { - return reader.getAllQuiet(keys); - } - - @Override - public Map getAll(Collection keys) { - return reader.getAll(keys); - } - - @Override - public Object getInternalContext() { - return reader.getInternalContext(); - } - - @Override - public boolean isCacheCoherent() { - return reader.isCacheCoherent(); - } - - @Override - public boolean isClusterCoherent() throws TerracottaNotRunningException { - return reader.isClusterCoherent(); - } - - @Override - public boolean isNodeCoherent() throws TerracottaNotRunningException { - return reader.isNodeCoherent(); - } - - @Override - public void waitUntilClusterCoherent() throws UnsupportedOperationException, TerracottaNotRunningException, InterruptedException { - reader.waitUntilClusterCoherent(); - } - - @Override - public Object getMBean() { - return reader.getMBean(); - } - - @Override - public Element unsafeGet(Object key) { - return reader.unsafeGet(key); - } - - @Override - public void quickClear() { - writer.quickClear(); - } - - @Override - public int quickSize() { - return reader.quickSize(); - } - - @Override - public Set getLocalKeys() { - return reader.getLocalKeys(); - } - - @Override - public CacheConfiguration.TransactionalMode getTransactionalMode() { - return reader.getTransactionalMode(); - } - - @Override - public boolean put(Element element) throws IllegalArgumentException, IllegalStateException, CacheException { - return writer.put(element); - } - - @Override - public void putAll(Collection elements) throws CacheException { - writer.putAll(elements); - } - - @Override - public Element remove(Object key) throws IllegalStateException { - return writer.remove(key); - } - - @Override - public void removeAll(Collection keys) throws IllegalStateException { - writer.removeAll(keys); - } - - @Override - public void removeAll() throws IllegalStateException, CacheException { - writer.removeAll(); - } - - @Override - public void flush() throws IllegalStateException, CacheException, IOException { - writer.flush(); - } - - @Override - public Element putIfAbsent(Element element) throws NullPointerException { - return writer.putIfAbsent(element); - } - - @Override - public Element replace(Element element) throws NullPointerException { - return writer.replace(element); - } - - @Override - public void addStoreListener(StoreListener listener) { - writer.addStoreListener(listener); - } - - @Override - public void dispose() { - writer.dispose(); - } - - @Override - public void expireElements() { - writer.expireElements(); - } - - @Override - public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws CacheException { - return writer.putWithWriter(element, writerManager); - } - - @Override - public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException { - return writer.removeElement(element, comparator); - } - - @Override - public void removeStoreListener(StoreListener listener) { - writer.removeStoreListener(listener); - } - - @Override - public Element removeWithWriter(Object key, CacheWriterManager writerManager) throws CacheException { - return writer.removeWithWriter(key, writerManager); - } - - @Override - public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException, IllegalArgumentException { - return writer.replace(old, element, comparator); - } - - @Override - public void setAttributeExtractors(Map extractors) { - writer.setAttributeExtractors(extractors); - } - - @Override - public void setInMemoryEvictionPolicy(Policy policy) { - writer.setInMemoryEvictionPolicy(policy); - } - - @Override - public void setNodeCoherent(boolean coherent) throws UnsupportedOperationException { - writer.setNodeCoherent(coherent); - } - - @Override - public void recalculateSize(Object key) { - throw new UnsupportedOperationException(); - } - - @Override - public WriteBehind createWriteBehind() { - throw new UnsupportedOperationException(); - } - - @Override - public void notifyCacheEventListenersChanged() { - writer.notifyCacheEventListenersChanged(); - } -} Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/ValueModeHandler.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/ValueModeHandler.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/ValueModeHandler.java (revision 0) @@ -1,27 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.modules.ehcache.store; - -import net.sf.ehcache.Element; -import net.sf.ehcache.ElementData; - -import java.io.IOException; -import java.io.Serializable; - -public interface ValueModeHandler { - - public Object getRealKeyObject(String portableKey); - - public Object getRealKeyObject(String portableKey, ClassLoader classLoader); - - public String createPortableKey(Object key) throws IOException; - - public ElementData createElementData(Element element); - - /** - * Returns null for null values otherwise creates an {@link Element} with the specified key-value and returns it - */ - public Element createElement(Object key, Serializable value); - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/VmUtils.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/VmUtils.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/util/VmUtils.java (revision 0) @@ -1,46 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * - */ -package net.sf.ehcache.util; - -/** - * Misc. VM utilities. - * - * @author Ludovic Orban - */ -public class VmUtils { - - private static boolean inGoogleAppEngine; - - static { - try { - Class.forName("com.google.apphosting.api.DeadlineExceededException"); - inGoogleAppEngine = true; - } catch (ClassNotFoundException cnfe) { - inGoogleAppEngine = false; - } - } - - /** - * @return true if the code is being executed by Google's App Engine, false otherwise. - */ - public static boolean isInGoogleAppEngine() { - return inGoogleAppEngine; - } -} Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/event/TerracottaNodeImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/event/TerracottaNodeImpl.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/event/TerracottaNodeImpl.java (revision 0) @@ -1,60 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.modules.ehcache.event; - -import org.terracotta.toolkit.cluster.ClusterNode; - -/** - * A bridge from ClusterNode in Toolkit to TerracottaNode in Ehcache-space. - */ -public class TerracottaNodeImpl implements net.sf.ehcache.cluster.ClusterNode { - - private final ClusterNode node; - - public TerracottaNodeImpl(ClusterNode node) { - this.node = node; - } - - @Override - public String getHostname() { - return this.node.getAddress().getHostName(); - } - - @Override - public String getId() { - return this.node.getId(); - } - - @Override - public String getIp() { - return this.node.getAddress().getHostAddress(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((node == null) ? 0 : node.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - TerracottaNodeImpl other = (TerracottaNodeImpl) obj; - if (node == null) { - if (other.node != null) return false; - } else if (!node.equals(other.node)) return false; - return true; - } - - @Override - public String toString() { - return "TerracottaNodeImpl{" + - "node=" + node + - '}'; - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/XAExecutionListener.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/XAExecutionListener.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/transaction/xa/XAExecutionListener.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.transaction.xa; - -/** - * Listener interface which provides callback hooks for listening to the 2PC lifecycle - * - * @author Ludovic Orban - */ -public interface XAExecutionListener { - - /** - * Called when the resource is about to prepare - * @param xaResource the XAResource about to prepare - */ - void beforePrepare(EhcacheXAResource xaResource); - - /** - * Called when the resource committed or rolled back - * @param xaResource the XAResource which committed or rolled back - */ - void afterCommitOrRollback(EhcacheXAResource xaResource); - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/HibernateStatsImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/HibernateStatsImpl.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/HibernateStatsImpl.java (revision 0) @@ -1,319 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.hibernate.management.impl; - -import java.util.ArrayList; -import java.util.List; - -import javax.management.MBeanNotificationInfo; -import javax.management.NotCompliantMBeanException; -import javax.management.Notification; -import javax.management.openmbean.CompositeData; -import javax.management.openmbean.TabularData; - -import net.sf.ehcache.hibernate.management.api.HibernateStats; - -import org.hibernate.SessionFactory; -import org.hibernate.stat.Statistics; - -/** - * Implementation of {@link HibernateStats} - * - *

- * - * @author Abhishek Sanoujam - * - */ -public class HibernateStatsImpl extends BaseEmitterBean implements HibernateStats { - private static final double MILLIS_PER_SECOND = 1000; - private static final MBeanNotificationInfo NOTIFICATION_INFO; - - private final SessionFactory sessionFactory; - - static { - final String[] notifTypes = new String[] {}; - final String name = Notification.class.getName(); - final String description = "Hibernate Statistics Event"; - NOTIFICATION_INFO = new MBeanNotificationInfo(notifTypes, name, description); - } - - /** - * Constructor accepting the backing {@link SessionFactory} - * - * @param sessionFactory - * @throws NotCompliantMBeanException - */ - public HibernateStatsImpl(SessionFactory sessionFactory) throws NotCompliantMBeanException { - super(HibernateStats.class); - this.sessionFactory = sessionFactory; - } - - /** - * @return statistics - */ - private Statistics getStatistics() { - return sessionFactory.getStatistics(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#clearStats() - */ - public void clearStats() { - getStatistics().clear(); - sendNotification(CACHE_STATISTICS_RESET); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#disableStats() - */ - public void disableStats() { - setStatisticsEnabled(false); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#enableStats() - */ - public void enableStats() { - setStatisticsEnabled(true); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getCloseStatementCount() - */ - public long getCloseStatementCount() { - return getStatistics().getCloseStatementCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getConnectCount() - */ - public long getConnectCount() { - return getStatistics().getConnectCount(); - } - - /** - * Not supported right now - * - */ - public long getDBSQLExecutionSample() { - throw new UnsupportedOperationException("Use getQueryExecutionCount() instead"); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getFlushCount() - */ - public long getFlushCount() { - return getStatistics().getFlushCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getOptimisticFailureCount() - */ - public long getOptimisticFailureCount() { - return getStatistics().getOptimisticFailureCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getPrepareStatementCount() - */ - public long getPrepareStatementCount() { - return getStatistics().getPrepareStatementCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getQueryExecutionCount() - */ - public long getQueryExecutionCount() { - return getStatistics().getQueryExecutionCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getQueryExecutionRate() - */ - public double getQueryExecutionRate() { - long startTime = getStatistics().getStartTime(); - long now = System.currentTimeMillis(); - double deltaSecs = (now - startTime) / MILLIS_PER_SECOND; - return getQueryExecutionCount() / deltaSecs; - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getQueryExecutionSample() - */ - public long getQueryExecutionSample() { - throw new UnsupportedOperationException("TODO: need to impl. rates for query execution"); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getSessionCloseCount() - */ - public long getSessionCloseCount() { - return getStatistics().getSessionCloseCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getSessionOpenCount() - */ - public long getSessionOpenCount() { - return getStatistics().getSessionOpenCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getSuccessfulTransactionCount() - */ - public long getSuccessfulTransactionCount() { - return getStatistics().getSuccessfulTransactionCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getTransactionCount() - */ - public long getTransactionCount() { - return getStatistics().getTransactionCount(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#isStatisticsEnabled() - */ - public boolean isStatisticsEnabled() { - return getStatistics().isStatisticsEnabled(); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#setStatisticsEnabled(boolean) - */ - public void setStatisticsEnabled(boolean flag) { - getStatistics().setStatisticsEnabled(flag); - sendNotification(CACHE_STATISTICS_ENABLED, flag); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getEntityStats() - */ - public TabularData getEntityStats() { - List result = new ArrayList(); - Statistics statistics = getStatistics(); - for (String entity : statistics.getEntityNames()) { - EntityStats entityStats = new EntityStats(entity, statistics.getEntityStatistics(entity)); - result.add(entityStats.toCompositeData()); - } - TabularData td = EntityStats.newTabularDataInstance(); - td.putAll(result.toArray(new CompositeData[result.size()])); - return td; - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getCollectionStats() - */ - public TabularData getCollectionStats() { - List result = new ArrayList(); - Statistics statistics = getStatistics(); - for (String roleName : statistics.getCollectionRoleNames()) { - CollectionStats collectionStats = new CollectionStats(roleName, statistics.getCollectionStatistics(roleName)); - result.add(collectionStats.toCompositeData()); - } - TabularData td = CollectionStats.newTabularDataInstance(); - td.putAll(result.toArray(new CompositeData[result.size()])); - return td; - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.hibernate.management.api.HibernateStats#getQueryStats() - */ - public TabularData getQueryStats() { - List result = new ArrayList(); - Statistics statistics = getStatistics(); - for (String query : statistics.getQueries()) { - QueryStats queryStats = new QueryStats(query, statistics.getQueryStatistics(query)); - result.add(queryStats.toCompositeData()); - } - TabularData td = QueryStats.newTabularDataInstance(); - td.putAll(result.toArray(new CompositeData[result.size()])); - return td; - } - - /** - * {@inheritDoc} - */ - public TabularData getCacheRegionStats() { - List list = new ArrayList(); - Statistics statistics = getStatistics(); - for (String region : statistics.getSecondLevelCacheRegionNames()) { - CacheRegionStats l2CacheStats = new CacheRegionStats(region, statistics.getSecondLevelCacheStatistics(region)); - list.add(l2CacheStats.toCompositeData()); - } - TabularData td = CacheRegionStats.newTabularDataInstance(); - td.putAll(list.toArray(new CompositeData[list.size()])); - return td; - } - - /** - * {@inheritDoc} - */ - @Override - protected void doDispose() { - // no-op - } - - /** - * @see BaseEmitterBean#getNotificationInfo() - */ - @Override - public MBeanNotificationInfo[] getNotificationInfo() { - return new MBeanNotificationInfo[]{NOTIFICATION_INFO}; - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/CacheConfigConflictTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/CacheConfigConflictTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/CacheConfigConflictTest.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.config; - -import java.util.Arrays; - -import junit.framework.TestCase; -import net.sf.ehcache.CacheManager; - -import org.junit.experimental.categories.Category; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.terracotta.test.categories.CheckShorts; - -@Category(CheckShorts.class) -public class CacheConfigConflictTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(CacheConfigConflictTest.class); - - public void testConflictingValuesFromConfig() { - CacheManager cacheManager = new CacheManager(this.getClass().getResourceAsStream("/ehcache-conflict-eternal.xml")); - try { - LOG.info("Cache names: " + Arrays.asList(cacheManager.getCacheNames())); - } finally { - cacheManager.shutdown(); - } - } - - public void testConflictingValuesProgrammatic() { - CacheConfiguration cacheConfig = new CacheConfiguration("name", 10); - - // case 1: eternal=true, followed by non conflicting TTI&TTL - cacheConfig.setEternal(true); - cacheConfig.timeToIdleSeconds(0); - cacheConfig.timeToLiveSeconds(0); - assertEquals(0, cacheConfig.getTimeToIdleSeconds()); - assertEquals(0, cacheConfig.getTimeToIdleSeconds()); - - // case 2: eternal=true, followed by conflicting TTI&TTL - // eternal=true takes more precedance than tti/ttl, order doesn't matter - cacheConfig.setEternal(true); - cacheConfig.timeToIdleSeconds(10); - assertEquals(0, cacheConfig.getTimeToIdleSeconds()); - - cacheConfig.timeToLiveSeconds(20); - assertEquals(0, cacheConfig.getTimeToIdleSeconds()); - - // case 3: eternal=false, followed non-conflicting TTI&TTL - // reset eternal - cacheConfig.eternal(false); - cacheConfig.timeToIdleSeconds(10); - assertEquals(10, cacheConfig.getTimeToIdleSeconds()); - - cacheConfig.timeToLiveSeconds(20); - assertEquals(20, cacheConfig.getTimeToLiveSeconds()); - - // case 4: setting eternal again resets tti/ttl - cacheConfig.eternal(true); - assertEquals(0, cacheConfig.getTimeToIdleSeconds()); - assertEquals(0, cacheConfig.getTimeToLiveSeconds()); - - // case 5: after a reset, TTI&TTL are still 0 - cacheConfig.eternal(false); - assertEquals(0, cacheConfig.getTimeToIdleSeconds()); - assertEquals(0, cacheConfig.getTimeToLiveSeconds()); - - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/terracotta/TerracottaClusteredInstanceHelper.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/terracotta/TerracottaClusteredInstanceHelper.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/terracotta/TerracottaClusteredInstanceHelper.java (revision 0) @@ -1,187 +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.CacheException; -import net.sf.ehcache.config.TerracottaClientConfiguration; -import net.sf.ehcache.util.ClassLoaderUtil; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * A small helper class that knows how to create terracotta store factories - * - * @author teck - * @author Abhishek Sanoujam - */ -class TerracottaClusteredInstanceHelper { - private static final Logger LOGGER = LoggerFactory.getLogger(TerracottaClusteredInstanceHelper.class); - - /** - * Singleton instance - */ - private static TerracottaClusteredInstanceHelper instance = new TerracottaClusteredInstanceHelper(); - - /** - * Private constructor - */ - private TerracottaClusteredInstanceHelper() { - lookupTerracottaRuntime(); - } - - /** - * Returns the singleton instance - * - * @return - */ - public static TerracottaClusteredInstanceHelper getInstance() { - return instance; - } - - /* - * THIS METHOD IS NOT FOR PUBLIC USE - * Used in tests only via reflection - * - * @param testHelper - */ - private static void setTestMode(TerracottaClusteredInstanceHelper testHelper) { - instance = testHelper; - } - - /** - * Enum for type of Terracotta runtime - */ - static enum TerracottaRuntimeType { - /** - * Enum representing Enterprise Express mode - */ - EnterpriseExpress(ENTERPRISE_EXPRESS_FACTORY), - /** - * Enum representing Express mode - */ - Express(EXPRESS_FACTORY); - - private final String factoryClassName; - - /** - * Private constructor - * - * @param factoryClassName - */ - private TerracottaRuntimeType(String factoryClassName) { - this.factoryClassName = factoryClassName; - } - - /** - * Returns the factory class for this mode or null if class is not present in classpath - * - * @return the factory class for this mode or null if class is not present in classpath - */ - public Class getFactoryClassOrNull() { - try { - return Class.forName(factoryClassName); - } catch (ClassNotFoundException e) { - return null; - } - } - } - - private static final String ENTERPRISE_EXPRESS_FACTORY = "net.sf.ehcache.terracotta.ExpressEnterpriseTerracottaClusteredInstanceFactory"; - private static final String EXPRESS_FACTORY = "net.sf.ehcache.terracotta.StandaloneTerracottaClusteredInstanceFactory"; - - private volatile TerracottaRuntimeType terracottaRuntimeType; - - /** - * Lookup the current terracotta runtime - * - * @return the current terracotta runtime - */ - private TerracottaRuntimeType lookupTerracottaRuntime() { - if (terracottaRuntimeType == null) { - final TerracottaRuntimeType[] lookupSequence = {TerracottaRuntimeType.EnterpriseExpress, TerracottaRuntimeType.Express}; - for (TerracottaRuntimeType type : lookupSequence) { - if (type.getFactoryClassOrNull() != null) { - terracottaRuntimeType = type; - break; - } - } - } - return terracottaRuntimeType; - } - - /** - * Locate and decide which terracotta ClusteredInstanceFactory should be used. If the standalone factory class is available - * it is preferred - * - * @param terracottaConfig - * @return the selected terracotta store factory - */ - ClusteredInstanceFactory newClusteredInstanceFactory(TerracottaClientConfiguration terracottaConfig, ClassLoader loader) { - lookupTerracottaRuntime(); - if (terracottaRuntimeType == null) { - throw new CacheException("Terracotta cache classes are not available, you are missing jar(s) most likely"); - } - - if (terracottaRuntimeType == TerracottaRuntimeType.EnterpriseExpress || terracottaRuntimeType == TerracottaRuntimeType.Express) { - assertExpress(terracottaConfig); - } else { - throw new CacheException("Unknown Terracotta runtime type - " + terracottaRuntimeType); - } - - // assert the old ehcache-terracotta-xxx.jar no longer needed on the classpath since Vincente - if (TerracottaClusteredInstanceHelper.class.getResource("/terracotta-ehcache-version.properties") != null) { - LOGGER.warn("ehcache-terracotta jar is detected in the current classpath. The use of ehcache-terracotta jar " - + "is no longer needed in this version of Ehcache."); - } - - Class factoryClass = terracottaRuntimeType.getFactoryClassOrNull(); - if (factoryClass == null) { - throw new CacheException("Not able to get factory class for: " + terracottaRuntimeType.name()); - } - try { - return (ClusteredInstanceFactory) ClassLoaderUtil.createNewInstance(getClass().getClassLoader(), factoryClass.getName(), - new Class[] {TerracottaClientConfiguration.class, ClassLoader.class}, new Object[] {terracottaConfig, loader}); - } catch (CacheException ce) { - if (ce.getCause() instanceof NoClassDefFoundError) { - throw new CacheException("Could not create ClusteredInstanceFactory due to missing class." - + " Please verify that terracotta-toolkit is in your classpath.", ce.getCause().getCause()); - } else { - throw ce; - } - } - } - - private static void assertExpress(TerracottaClientConfiguration terracottaConfig) { - // This is required in standalone but in non-standalone, this stuff is picked up through - // the normal tc-config mechanisms instead - if (terracottaConfig == null) { - throw new CacheException("Terracotta caches are defined but no element was used " - + "to specify the Terracotta configuration."); - } - } - - /** - * Returns the terracotta runtime type or null if no runtime could be found - * - * @return the terracotta runtime type or null if no runtime could be found - */ - TerracottaRuntimeType getTerracottaRuntimeTypeOrNull() { - return terracottaRuntimeType; - } - -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/ExpiryListenerClient2.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/ExpiryListenerClient2.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/ExpiryListenerClient2.java (revision 0) @@ -1,24 +0,0 @@ -package org.terracotta.ehcache.tests; - -import net.sf.ehcache.Cache; - -import org.terracotta.toolkit.Toolkit; - -import junit.framework.Assert; - - -public class ExpiryListenerClient2 extends ClientBase { - - public ExpiryListenerClient2(String[] args) { - super("test", args); - } - - public static void main(String[] args) { - new ExpiryListenerClient2(args).run(); - } - - @Override - protected void runTest(Cache cache, Toolkit toolkit) throws Throwable { - Assert.assertEquals(0, cache.getSize()); - } -} \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/DiskCacheStoreTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/DiskCacheStoreTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/DiskCacheStoreTest.java (revision 0) @@ -1,14 +0,0 @@ -package net.sf.ehcache.store; - -import org.junit.Test; - -/** - * @author Alex Snaps - */ -public class DiskCacheStoreTest { - - @Test - public void testUnpinFlushes() { -// DiskCacheStore store = new DiskCacheStore(new OnHeapCachingTier(10), DiskStore.create(), ); - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/commons-logging.properties =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/commons-logging.properties (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/commons-logging.properties (revision 0) @@ -1,3 +0,0 @@ -# Use this to force commons logging to use Jdk14Logger. -# If it finds log4j in the classpath it will use that. -# org.apache.commons.logging.Log=org.apache.commons.logging.impl.Jdk14Logger \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/jetty6.1/9081/conf.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/jetty6.1/9081/conf.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/jetty6.1/9081/conf.xml (revision 0) @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /webapps - false - true - false - - - - - - - - ./logs/console.yyyy_mm_dd.log - false - 90 - GMT - - - - - - Redirecting stderr/stdout to - - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/InvalidConfigTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/InvalidConfigTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/InvalidConfigTest.java (revision 0) @@ -1,36 +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 junit.framework.TestCase; -import net.sf.ehcache.CacheException; -import net.sf.ehcache.CacheManager; - -public class InvalidConfigTest extends TestCase { - - public void testInvalidBooleanAttribute() { - try { - CacheManager cacheManager = new CacheManager(InvalidConfigTest.class.getResourceAsStream("/invalid-config-test.xml")); - fail("Should have failed as invalid value for boolean type attribute used in config"); - } catch (CacheException e) { - if (!e.getMessage().contains("Invalid value specified for attribute 'coherent'")) { - throw e; - } - } - } - -} Index: rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/jetty6.1/9082/conf.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/jetty6.1/9082/conf.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/events/src/assemble/jetty6.1/9082/conf.xml (revision 0) @@ -1,63 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /webapps - false - true - false - - - - - - - - ./logs/console.yyyy_mm_dd.log - false - 90 - GMT - - - - - - Redirecting stderr/stdout to - - - - Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/EventManager.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/EventManager.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/EventManager.java (revision 0) @@ -1,238 +0,0 @@ -/* - * All content copyright (c) 2003-2009 Terracotta, Inc., except as may otherwise be noted in a separate copyright - * notice. All rights reserved. - */ -package org.terracotta.ehcache.tests.container.hibernate.domain; - -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.SessionFactory; - -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.ListIterator; - -public class EventManager { - - private final SessionFactory sessionFactory; - - public EventManager(SessionFactory sessionFactory) { - this.sessionFactory = sessionFactory; - } - - public List listEmailsOfEvent(Long eventId) { - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - List emailList = new ArrayList(); - Event event = (Event) session.load(Event.class, eventId); - for (Iterator it = event.getParticipants().iterator(); it.hasNext(); ) { - Person person = (Person)it.next(); - emailList.addAll(person.getEmailAddresses()); - } - - session.getTransaction().commit(); - return emailList; - } - - public Long createAndStoreEvent(String title, Person organizer, Date theDate) { - - Session session = sessionFactory.getCurrentSession(); - - session.beginTransaction(); - - Event theEvent = new Event(); - theEvent.setTitle(title); - theEvent.setDate(theDate); - theEvent.setOrganizer(organizer); - - Long eventId = (Long) session.save(theEvent); - - session.getTransaction().commit(); - return eventId; - } - - public Long createAndStorePerson(String firstName, String lastName) { - - Session session = sessionFactory.getCurrentSession(); - - session.beginTransaction(); - - Person person = new Person(); - person.setFirstname(firstName); - person.setLastname(lastName); - - Long personId = (Long) session.save(person); - - session.getTransaction().commit(); - return personId; - } - - public Long createAndStorePerson(Person person) { - - Session session = sessionFactory.getCurrentSession(); - - session.beginTransaction(); - - Long personId = (Long) session.save(person); - - session.getTransaction().commit(); - return personId; - } - - public List listEvents() { - - Session session = sessionFactory.getCurrentSession(); - - session.beginTransaction(); - - List result = session.createQuery("from Event").setCacheable(true).list(); - - session.getTransaction().commit(); - - return result; - } - - /** - * Call setEntity() on a cacheable query - see FORGE-265 - */ - public List listEventsOfOrganizer(Person organizer) { - - Session session = sessionFactory.getCurrentSession(); - - session.beginTransaction(); - - Query query = session.createQuery("from Event ev where ev.organizer = :organizer"); - - query.setCacheable(true); - query.setEntity("organizer", organizer); - List result = query.list(); - - session.getTransaction().commit(); - - return result; - } - - /** - * Use a Criteria query - see FORGE-247 - */ - public List listEventsWithCriteria() { - Session session = sessionFactory.getCurrentSession(); - - session.beginTransaction(); - - List result = session.createCriteria(Event.class) - .setCacheable(true) - .list(); - - session.getTransaction().commit(); - - return result; - } - - public void addPersonToEvent(Long personId, Long eventId) { - - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - Person aPerson = (Person) session.load(Person.class, personId); - Event anEvent = (Event) session.load(Event.class, eventId); - - aPerson.getEvents().add(anEvent); - - session.getTransaction().commit(); - } - - public Long addPersonToAccount(Long personId, Account account) { - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - Person aPerson = (Person) session.load(Person.class, personId); - account.setPerson(aPerson); - - Long accountId = (Long) session.save(account); - - session.getTransaction().commit(); - return accountId; - } - - public Account getAccount(Long accountId) { - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - Account account = (Account) session.load(Account.class, accountId); - - session.getTransaction().commit(); - return account; - } - - public void addEmailToPerson(Long personId, String emailAddress) { - - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - Person aPerson = (Person) session.load(Person.class, personId); - - // The getEmailAddresses() might trigger a lazy load of the collection - aPerson.getEmailAddresses().add(emailAddress); - - session.getTransaction().commit(); - } - - public void addPhoneNumberToPerson(Long personId, PhoneNumber pN) { - - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - Person aPerson = (Person) session.load(Person.class, personId); - pN.setPersonId(personId.longValue()); - aPerson.getPhoneNumbers().add(pN); - - session.getTransaction().commit(); - } - - public void addTalismanToPerson(Long personId, String talisman) { - - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - Person aPerson = (Person) session.load(Person.class, personId); - aPerson.addTalisman(talisman); - - session.getTransaction().commit(); - } - - public Long createHolidayCalendar() { - - Session session = sessionFactory.getCurrentSession(); - session.beginTransaction(); - - // delete all existing calendars - List calendars = session.createQuery("from HolidayCalendar").setCacheable(true).list(); - for (ListIterator li = calendars.listIterator(); li.hasNext(); ) { - session.delete(li.next()); - } - - HolidayCalendar calendar = new HolidayCalendar(); - calendar.init(); - - Long calendarId = (Long) session.save(calendar); - - session.getTransaction().commit(); - return calendarId; - } - - public HolidayCalendar getHolidayCalendar() { - Session session = sessionFactory.getCurrentSession(); - - session.beginTransaction(); - - List calendars = session.createQuery("from HolidayCalendar").setCacheable(true).list(); - - session.getTransaction().commit(); - - return calendars.isEmpty() ? null : (HolidayCalendar)calendars.get(0); - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/ehcacheUTF8.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/ehcacheUTF8.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/ehcacheUTF8.xml (revision 0) @@ -1,29 +0,0 @@ - - - - - - - - - - - - - - - Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapClearTestHelper.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapClearTestHelper.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapClearTestHelper.java (revision 0) @@ -1,123 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.ehcache.tests.servermap; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.Element; - -import org.terracotta.ehcache.tests.mbean.DSOMBean; -import org.terracotta.toolkit.Toolkit; -import org.terracotta.toolkit.concurrent.ToolkitBarrier; - -import com.tc.util.concurrent.ThreadUtil; - -import junit.framework.Assert; - -/** - * This class is maintained in both ehcache-terracotta-system-tests and ehcache-terracotta-ee-system-tests projects - * (READ: any changes to this class should also be made to same class in other project) - */ -public abstract class ServerMapClearTestHelper { - - public static void doTest(Cache cache, Toolkit clusteringToolkit, DSOMBean dsoMBean) throws Throwable { - // node 1 populates cache - // both nodes asserts cache populated - // node 2 clears cache - // cache + localCache on both nodes are cleared - - int numElements = 10; - ToolkitBarrier barrier = clusteringToolkit.getBarrier("clearTestBarrier", 2); - int index = barrier.await(); - if (index == 0) { - debug(index, "Populating cache"); - for (int i = 0; i < numElements; i++) { - cache.put(new Element(getKey(i), getValue(i))); - } - } else { - debug(index, "waiting for other node to populate cache"); - } - barrier.await(); - - debug(index, "Asserting cache is populated"); - if (index == 0) { - ThreadUtil.reallySleep(10000); // Allow other client to hit the barrier - long initialGetValueReqCount = getGlobalServerMapGetValueRequestsCount(dsoMBean); - debug(index, "should hit local cache for this node"); - checkElements(index, dsoMBean, cache, numElements, initialGetValueReqCount, 0); - - } - barrier.await(); - - if (index != 0) { - ThreadUtil.reallySleep(10000); // Allow other client to hit the barrier - long initialGetValueReqCount = getGlobalServerMapGetValueRequestsCount(dsoMBean); - debug(index, "should NOT hit local cache for this node"); - checkElements(index, dsoMBean, cache, numElements, initialGetValueReqCount, numElements); - } - - barrier.await(); - if (index != 0) { - debug(index, "Clearing cache"); - cache.removeAll(); - debug(index, "Cache cleared"); - } else { - debug(index, "Waiting for other node to clear cache"); - } - barrier.await(); - - debug(index, "Asserting size 0 after cache clear"); - Assert.assertEquals("Cache size should be zero after clear", 0, cache.getSize()); - debug(index, "Size=0 asserted"); - - barrier.await(); - debug(index, "Asserting both cache and local cache is cleared"); - for (int i = 0; i < numElements; i++) { - String key = getKey(i); - boolean isElementInMemory = cache.isElementInMemory(key); - boolean isElementOnDisk = cache.isElementOnDisk(key); - Element element = cache.get(key); - - // debug(index, "isElementInMemory: " + isElementInMemory + " isElementOnDisk: " + isElementOnDisk - // + " elementIsNull:" + (element == null)); - - Assert.assertFalse("Element for key: " + key + " should not be present in memory", isElementInMemory); - Assert.assertFalse("Element for key: " + key + " should not be present on disk", isElementOnDisk); - Assert.assertNull("Element for key: " + key + " should be null", element); - } - - } - - private static void checkElements(int index, DSOMBean dsoMBean, Cache cache, int numElements, - long initialGetValueReqCount, int requestsMade) { - for (int i = 0; i < numElements; i++) { - Element element = cache.get(getKey(i)); - Assert.assertNotNull(element); - Assert.assertEquals(getValue(i), element.getObjectValue()); - } - - long actual = getGlobalServerMapGetValueRequestsCount(dsoMBean); - String msg = "expecting (" + initialGetValueReqCount + "+" + requestsMade + ") " - + (initialGetValueReqCount + requestsMade) + " Actual: " + actual; - debug(index, msg); - Assert - .assertEquals("GET_VALUE requests count should match: " + msg, initialGetValueReqCount + requestsMade, actual); - } - - private static long getGlobalServerMapGetValueRequestsCount(DSOMBean dsoMBean) { - return dsoMBean.getGlobalServerMapGetValueRequestsCount(); - } - - private static void debug(int index, String string) { - System.out.println("Node-" + index + ": " + string); - } - - private static String getValue(int i) { - return "value-" + i; - } - - private static String getKey(int i) { - return "key-" + i; - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/SampledEhcacheMBeans.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/SampledEhcacheMBeans.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/SampledEhcacheMBeans.java (revision 0) @@ -1,137 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.management.sampled; - -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import net.sf.ehcache.hibernate.management.impl.EhcacheHibernateMbeanNames; - -/** - * Utility class used for getting {@link ObjectName}'s for sampled MBeans - * - *

- * - * @author Abhishek Sanoujam - * @since 1.7 - */ -public abstract class SampledEhcacheMBeans { - - /** - * Type used for sampled cache manager mbean - */ - public static final String SAMPLED_CACHE_MANAGER_TYPE = "SampledCacheManager"; - - /** - * Type used for sampled cache mbean - */ - public static final String SAMPLED_CACHE_TYPE = "SampledCache"; - - /** - * Type used for store mbean - */ - public static final String STORE_TYPE = "Store"; - - /** - * Group id for all sampled mbeans registered - */ - public static final String GROUP_ID = "net.sf.ehcache"; - - /** - * Returns an ObjectName for the passed cacheManagerName - * - * @param cacheManagerName - * @return An {@link ObjectName} using the input name of cache manager - * @throws MalformedObjectNameException - */ - public static ObjectName getCacheManagerObjectName(String clientUUID, String cacheManagerName) throws MalformedObjectNameException { - ObjectName objectName = new ObjectName(GROUP_ID + ":type=" + SAMPLED_CACHE_MANAGER_TYPE + ",name=" - + EhcacheHibernateMbeanNames.mbeanSafe(cacheManagerName) + getBeanNameSuffix(clientUUID)); - return objectName; - } - - private static String getBeanNameSuffix(String clientUUID) { - String suffix = ""; - if (clientUUID != null && !clientUUID.trim().equals("")) { - suffix = ",node=" + clientUUID; - } - return suffix; - } - - /** - * Returns an ObjectName for the passed cacheManagerName, cacheName - * combination - * - * @param cacheManagerName - * @param cacheName - * @return An {@link ObjectName} representing the cache using the passed - * cache and the cache manager name - * @throws MalformedObjectNameException - */ - public static ObjectName getCacheObjectName(String clientUUID, String cacheManagerName, String cacheName) - throws MalformedObjectNameException { - ObjectName objectName = new ObjectName(GROUP_ID + ":type=" + SAMPLED_CACHE_TYPE + "," + SAMPLED_CACHE_MANAGER_TYPE + "=" - + EhcacheHibernateMbeanNames.mbeanSafe(cacheManagerName) + ",name=" + EhcacheHibernateMbeanNames.mbeanSafe(cacheName) - + getBeanNameSuffix(clientUUID)); - return objectName; - } - - /** - * Returns an ObjectName for the passed cacheManagerName, cacheName - * combination - * - * @param cacheManagerName - * @param cacheName - * @return An {@link ObjectName} representing the cache using the passed - * cache and the cache manager name - * @throws MalformedObjectNameException - */ - static ObjectName getStoreObjectName(String clientUUID, String cacheManagerName, String cacheName) throws MalformedObjectNameException { - ObjectName objectName = new ObjectName(GROUP_ID + ":type=" + STORE_TYPE + "," + SAMPLED_CACHE_MANAGER_TYPE + "=" - + EhcacheHibernateMbeanNames.mbeanSafe(cacheManagerName) + ",name=" + EhcacheHibernateMbeanNames.mbeanSafe(cacheName) - + getBeanNameSuffix(clientUUID)); - return objectName; - } - - /** - * Returns an ObjectName that can be used for querying all Cache - * ObjectName's for the passed cacheManagerName - * - * @param cacheManagerName - * @return An {@link ObjectName} which can be used for querying all Cache - * ObjectName's for the input cache manager name - * @throws MalformedObjectNameException - */ - public static ObjectName getQueryCacheManagerObjectName(String clientUUID, String cacheManagerName) - throws MalformedObjectNameException { - ObjectName objectName = new ObjectName(GROUP_ID + ":*," + SAMPLED_CACHE_MANAGER_TYPE + "=" - + EhcacheHibernateMbeanNames.mbeanSafe(cacheManagerName) + getBeanNameSuffix(clientUUID)); - return objectName; - } - - /** - * Returns an ObjectName that can be used to query all objectNames of {@link #SAMPLED_CACHE_MANAGER_TYPE} - * - * @return An {@link ObjectName} that can be used to query all ObjectName's - * of {@value #SAMPLED_CACHE_MANAGER_TYPE} - * @throws MalformedObjectNameException - */ - public static ObjectName getQueryCacheManagersObjectName(String clientUUID) throws MalformedObjectNameException { - ObjectName objectName = new ObjectName(GROUP_ID + ":type=" + SAMPLED_CACHE_MANAGER_TYPE + ",*" + getBeanNameSuffix(clientUUID)); - return objectName; - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/memory-store-eviction-policy-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/memory-store-eviction-policy-test.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/memory-store-eviction-policy-test.xml (revision 0) @@ -1,11 +0,0 @@ - - - - - - - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriterManagerException.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriterManagerException.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/writer/CacheWriterManagerException.java (revision 0) @@ -1,43 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.sf.ehcache.writer; - -import net.sf.ehcache.CacheException; - -/** - * An exception specifically for throwing exceptions that happen with a {@link CacheWriterManager} implementation. - * - * @author Geert Bevin - * @version $Id: CacheWriterManagerException.java 5594 2012-05-07 16:04:31Z cdennis $ - */ -public class CacheWriterManagerException extends CacheException { - /** - * Construct a new exception - * - * @param cause the underlying cause for this exception - */ - public CacheWriterManagerException(RuntimeException cause) { - super(cause); - } - - /** - * {@inheritDoc} - */ - @Override - public RuntimeException getCause() { - return (RuntimeException)super.getCause(); - } -} Index: rctags/ehcache-2.10.8.1.63/distribution/events/src/main/resources/hibernate.cfg.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/distribution/events/src/main/resources/hibernate.cfg.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/distribution/events/src/main/resources/hibernate.cfg.xml (revision 0) @@ -1,40 +0,0 @@ - - - - - - true - Events - true - - - org.h2.Driver - jdbc:h2:tcp://localhost/target/data/events - sa - - - - 1 - - - org.hibernate.dialect.H2Dialect - - - thread - - - true - net.sf.ehcache.hibernate.EhCacheProvider - ehcache.xml - - - true - - - update - - - - Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesOneL1Verifier.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesOneL1Verifier.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesOneL1Verifier.java (revision 0) @@ -1,39 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.ehcache.tests.servermap; - -import net.sf.ehcache.Cache; - -import org.terracotta.toolkit.Toolkit; -import org.terracotta.ehcache.tests.ClientBase; - -import junit.framework.Assert; - -public class ServerMapL2EvictionReachesOneL1Verifier extends ClientBase { - - public ServerMapL2EvictionReachesOneL1Verifier(String[] args) { - super("test", args); - } - - public static void main(String[] args) { - new ServerMapL2EvictionReachesOneL1Verifier(args).run(); - } - - @Override - protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { - System.out.println("in the verifier"); - - EvictionCountingEventListener countingListener = new EvictionCountingEventListener( - clusteringToolkit - .getAtomicLong("EvictionCounter")); - cache.getCacheEventNotificationService().registerListener(countingListener); - - getBarrierForAllClients().await(); - long value = countingListener.getEvictedCount(); - System.out.println("After sleeping 2 mins: value=" + value); - Assert.assertTrue("Expected at most " + ServerMapL2EvictionReachesOneL1TestClient.EXPECTED_EVICTION_COUNT - + " elements to have been evicted, value=" + value, - (value <= ServerMapL2EvictionReachesOneL1TestClient.EXPECTED_EVICTION_COUNT)); - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/TryLockTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/TryLockTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/TryLockTest.java (revision 0) @@ -1,47 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.ehcache.tests; - -import net.sf.ehcache.Cache; - -import org.terracotta.toolkit.Toolkit; -import org.terracotta.toolkit.concurrent.locks.ToolkitReadWriteLock; - -import com.tc.test.config.model.TestConfig; - -// test for ENG-680, should be enabled when implemented -public class TryLockTest extends AbstractCacheTestBase { - - public TryLockTest(TestConfig testConfig) { - super(testConfig, TryLockTestClient.class, TryLockTestClient.class); - disableTest(); - } - - public static class TryLockTestClient extends ClientBase { - - public TryLockTestClient(String[] args) { - super(args); - } - - @Override - protected void runTest(Cache cache, Toolkit myToolkit) throws Throwable { - ToolkitReadWriteLock myLock = myToolkit.getReadWriteLock("abc"); - int index = waitForAllClients(); - - if (index == 0) { - myLock.writeLock().lock(); - myLock.writeLock().unlock(); - } - - waitForAllClients(); - - if (index != 0) { - assertTrue(myLock.readLock().tryLock()); - // assertTrue(myLock.readLock().tryLock(2, TimeUnit.SECONDS)); - this works - } - - waitForAllClients(); - } - } -} Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/src/main/resources/META-INF/services/com.terracotta.management.ApplicationEhCacheService =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/src/main/resources/META-INF/services/com.terracotta.management.ApplicationEhCacheService (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v2/src/main/resources/META-INF/services/com.terracotta.management.ApplicationEhCacheService (revision 0) @@ -1 +0,0 @@ -com.terracotta.management.ApplicationEhCacheV2 \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/FactoryConfiguration.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/FactoryConfiguration.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/FactoryConfiguration.java (revision 0) @@ -1,186 +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; - -/** - * A class to represent the CacheManagerEventListener configuration. - * - * @param - * the concrete factory type - * - * @author Greg Luck - * @version $Id: FactoryConfiguration.java 5594 2012-05-07 16:04:31Z cdennis $ - */ -public class FactoryConfiguration implements Cloneable { - /** - * class name. - */ - protected String fullyQualifiedClassPath; - - /** - * properties. - */ - protected String properties; - - /** - * A property separator. By default it is a comma, but other separators can be configured. - */ - protected String propertySeparator; - - /** - * Clones this object, following the usual contract. - * - * @return a copy, which independent other than configurations than cannot change. - */ - @Override - public T clone() { - FactoryConfiguration config; - try { - config = (FactoryConfiguration) super.clone(); - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - - return (T) config; - } - - /** - * Sets the class name. - * - * @param fullyQualifiedClassPath - */ - public final void setClass(String fullyQualifiedClassPath) { - this.fullyQualifiedClassPath = fullyQualifiedClassPath; - } - - /** - * @return this configuration instance - * @see #setClass(String) - */ - public T className(String fullyQualifiedClassPath) { - setClass(fullyQualifiedClassPath); - return (T) this; - } - - /** - * Getter. - */ - public final String getFullyQualifiedClassPath() { - return fullyQualifiedClassPath; - } - - /** - * Sets the configuration properties. - * - * @param properties - */ - public final void setProperties(String properties) { - this.properties = properties; - } - - /** - * @return this configuration instance - * @see #setProperties(String) - */ - public T properties(String properties) { - setProperties(properties); - return (T) this; - } - - /** - * Getter. - */ - public final String getProperties() { - return properties; - } - - /** - * Setter - */ - public void setPropertySeparator(String propertySeparator) { - this.propertySeparator = propertySeparator; - } - - /** - * @return this configuration instance - * @see #setPropertySeparator(String) - */ - public T propertySeparator(String propertySeparator) { - setPropertySeparator(propertySeparator); - return (T) this; - } - - /** - * Getter - */ - public String getPropertySeparator() { - return propertySeparator; - } - - /** - * Overrided hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((fullyQualifiedClassPath == null) ? 0 : fullyQualifiedClassPath.hashCode()); - result = prime * result + ((properties == null) ? 0 : properties.hashCode()); - result = prime * result + ((propertySeparator == null) ? 0 : propertySeparator.hashCode()); - return result; - } - - /** - * Overrided equals - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - FactoryConfiguration other = (FactoryConfiguration) obj; - if (fullyQualifiedClassPath == null) { - if (other.fullyQualifiedClassPath != null) { - return false; - } - } else if (!fullyQualifiedClassPath.equals(other.fullyQualifiedClassPath)) { - return false; - } - if (properties == null) { - if (other.properties != null) { - return false; - } - } else if (!properties.equals(other.properties)) { - return false; - } - if (propertySeparator == null) { - if (other.propertySeparator != null) { - return false; - } - } else if (!propertySeparator.equals(other.propertySeparator)) { - return false; - } - return true; - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/annotationfiltered/AnnotationFilteredPackage.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/annotationfiltered/AnnotationFilteredPackage.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/annotationfiltered/AnnotationFilteredPackage.java (revision 0) @@ -1,26 +0,0 @@ -/** - * Copyright 2011 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.annotationfiltered; - -/** - * - * @author cdennis - */ -public class AnnotationFilteredPackage { - - private final byte[] bigArray = new byte[16 * 1024]; -} Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/impl/CacheManagerEntityBuilderV2.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/impl/CacheManagerEntityBuilderV2.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/impl/CacheManagerEntityBuilderV2.java (revision 0) @@ -1,89 +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.resource.CacheManagerEntityV2; -import net.sf.ehcache.management.sampled.CacheManagerSampler; -import net.sf.ehcache.management.service.AccessorPrefix; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.terracotta.management.resource.AgentEntityV2; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -/** - * @author brandony - */ -final class CacheManagerEntityBuilderV2 extends ConstrainableEntityBuilderSupportV2 { - private static final Logger LOG = LoggerFactory.getLogger(CacheManagerEntityBuilderV2.class); - - private static final String CM_NAME_ACCESSOR = AccessorPrefix.get + "Name"; - - private final List cmSamplers = new ArrayList(); - - static CacheManagerEntityBuilderV2 createWith(CacheManagerSampler sampler) { - return new CacheManagerEntityBuilderV2(sampler); - } - - CacheManagerEntityBuilderV2(CacheManagerSampler sampler) { - addSampler(sampler); - } - - CacheManagerEntityBuilderV2 add(CacheManagerSampler sampler) { - addSampler(sampler); - return this; - } - - CacheManagerEntityBuilderV2 add(Set constraintAttributes) { - addConstraints(constraintAttributes); - return this; - } - - Collection build() { - Collection cmes = new ArrayList(cmSamplers.size()); - - for (CacheManagerSampler cms : cmSamplers) { - CacheManagerEntityV2 cme = new CacheManagerEntityV2(); - cme.setName(cms.getName()); - cme.setAgentId(AgentEntityV2.EMBEDDED_AGENT_ID); - // cme.setVersion(this.getClass().getPackage().getImplementationVersion()); - - if (getAttributeConstraints() != null && !getAttributeConstraints().isEmpty() && getAttributeConstraints() - .size() < CacheManagerSampler.class.getMethods().length) { - buildAttributeMapByAttribute(CacheManagerSampler.class, cms, cme.getAttributes(), getAttributeConstraints(), - CM_NAME_ACCESSOR); - } else { - buildAttributeMapByApi(CacheManagerSampler.class, cms, cme.getAttributes(), getAttributeConstraints(), - CM_NAME_ACCESSOR); - } - - cmes.add(cme); - } - - return cmes; - } - - @Override - Logger getLog() { - return LOG; - } - - @Override - protected Set getExcludedAttributeNames(CacheManagerSampler cacheManagerSampler) { - return Collections.emptySet(); - } - - private void addSampler(CacheManagerSampler sampler) { - if (sampler == null) { - throw new IllegalArgumentException("sampler == null"); - } - cmSamplers.add(sampler); - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/NonstopConfigurationElement.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/NonstopConfigurationElement.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/NonstopConfigurationElement.java (revision 0) @@ -1,77 +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.NonstopConfiguration; -import net.sf.ehcache.config.TimeoutBehaviorConfiguration; -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 NonstopConfiguration} - * - * @author Abhishek Sanoujam - * - */ -public class NonstopConfigurationElement extends SimpleNodeElement { - - private final NonstopConfiguration nonstopConfiguration; - - /** - * Constructor accepting the parent and the {@link NonstopConfiguration} - * - * @param parent - * @param nonstopConfiguration - */ - public NonstopConfigurationElement(NodeElement parent, NonstopConfiguration nonstopConfiguration) { - super(parent, "nonstop"); - this.nonstopConfiguration = nonstopConfiguration; - init(); - } - - private void init() { - if (nonstopConfiguration == null) { - return; - } - if (nonstopConfiguration.getTimeoutBehavior() != null && !isDefault(nonstopConfiguration.getTimeoutBehavior())) { - addChildElement(new TimeoutBehaviorConfigurationElement(this, nonstopConfiguration.getTimeoutBehavior())); - } - addAttribute(new SimpleNodeAttribute("enabled", nonstopConfiguration.isEnabled()).optional(true).defaultValue( - NonstopConfiguration.DEFAULT_ENABLED)); - addAttribute(new SimpleNodeAttribute("immediateTimeout", nonstopConfiguration.isImmediateTimeout()).optional(true).defaultValue( - NonstopConfiguration.DEFAULT_IMMEDIATE_TIMEOUT)); - addAttribute(new SimpleNodeAttribute("timeoutMillis", nonstopConfiguration.getTimeoutMillis()).optional(true).defaultValue( - NonstopConfiguration.DEFAULT_TIMEOUT_MILLIS)); - addAttribute(new SimpleNodeAttribute("searchTimeoutMillis", nonstopConfiguration.getSearchTimeoutMillis()).optional(true).defaultValue( - NonstopConfiguration.DEFAULT_SEARCH_TIMEOUT_MILLIS)); - } - - private boolean isDefault(TimeoutBehaviorConfiguration timeoutBehavior) { - boolean rv = true; - if (!NonstopConfiguration.DEFAULT_TIMEOUT_BEHAVIOR.getType().equals(timeoutBehavior.getType())) { - rv = false; - } - if (!NonstopConfiguration.DEFAULT_TIMEOUT_BEHAVIOR.getProperties().equals(timeoutBehavior.getProperties())) { - rv = false; - } - if (!NonstopConfiguration.DEFAULT_TIMEOUT_BEHAVIOR.getPropertySeparator().equals(timeoutBehavior.getPropertySeparator())) { - rv = false; - } - return rv; - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/ConfigurationSource.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/ConfigurationSource.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/generator/ConfigurationSource.java (revision 0) @@ -1,231 +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.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.config.Configuration; -import net.sf.ehcache.config.ConfigurationFactory; - -/** - * Class encapsulating the source of configuration for a cache manager - * - *

- * - * @author Abhishek Sanoujam - * - */ -public abstract class ConfigurationSource { - /** - * protected constructor - */ - protected ConfigurationSource() { - // - } - - /** - * Utility factory method for creating a {@link ConfigurationSource} based on a file. - * - * @param file - * @return ConfigurationSource for the input file - */ - public static ConfigurationSource getConfigurationSource(File file) { - return new FileNameSource(file); - } - - /** - * Utility factory method for creating a {@link ConfigurationSource} based on {@link URL} - * - * @param configFileURL - * @return ConfigurationSource for the input URL - */ - public static ConfigurationSource getConfigurationSource(URL configFileURL) { - return new URLConfigurationSource(configFileURL); - } - - /** - * Utility factory method for creating a {@link ConfigurationSource} based on InputStream - * - * @param configFileStream - * @return ConfigurationSource for the input InputStream - */ - public static ConfigurationSource getConfigurationSource(InputStream configFileStream) { - return new InputStreamConfigurationSource(configFileStream); - } - - /** - * Utility factory method for creating a {@link ConfigurationSource} based on default settings (default ehcache.xml in classpath if one - * is present or an ehcache-failsafe provided with the kit - * - * @return Default ConfigurationSource - */ - public static ConfigurationSource getConfigurationSource() { - return DefaultConfigurationSource.INSTANCE; - } - - /** - * Abstract method used for creating a {@link Configuration} based on the source - * - * @return {@link Configuration} based on the source - */ - public abstract Configuration createConfiguration(); - - /** - * {@link ConfigurationSource} based on file name - * - */ - private static class FileNameSource extends ConfigurationSource { - - private final File file; - - /** - * Constructor accepting the file name - * - * @param fileName - */ - public FileNameSource(File file) { - this.file = file; - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.config.generator.ConfigurationSource#getConfiguration() - */ - @Override - public Configuration createConfiguration() { - return ConfigurationFactory.parseConfiguration(file); - } - - @Override - public String toString() { - return "FileNameSource [file=" + file + "]"; - } - } - - /** - * {@link ConfigurationSource} based on URL - * - */ - private static class URLConfigurationSource extends ConfigurationSource { - private final URL url; - - /** - * Constructor accepting a URL - * - * @param url - */ - public URLConfigurationSource(URL url) { - this.url = url; - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.config.generator.ConfigurationSource#createConfiguration() - */ - @Override - public Configuration createConfiguration() { - return ConfigurationFactory.parseConfiguration(url); - } - - @Override - public String toString() { - return "URLConfigurationSource [url=" + url + "]"; - } - } - - /** - * {@link ConfigurationSource} based on {@link InputStream} - * - */ - private static class InputStreamConfigurationSource extends ConfigurationSource { - private final InputStream stream; - - /** - * Constructor accepting {@link InputStream} - * - * @param stream - */ - public InputStreamConfigurationSource(InputStream stream) { - this.stream = stream; - stream.mark(Integer.MAX_VALUE); - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.config.generator.ConfigurationSource#createConfiguration() - */ - @Override - public Configuration createConfiguration() { - try { - stream.reset(); - return ConfigurationFactory.parseConfiguration(stream); - } catch (IOException e) { - throw new CacheException(e); - } - } - - @Override - public String toString() { - return "InputStreamConfigurationSource [stream=" + stream + "]"; - } - - } - - /** - * Default {@link ConfigurationSource} based on default ehcache.xml in classpath (if one is present) or the ehcache-failsafe.xml - * provided with the kit - * - */ - private static class DefaultConfigurationSource extends ConfigurationSource { - - /** - * Singleton instance of {@link DefaultConfigurationSource} - */ - public static final DefaultConfigurationSource INSTANCE = new DefaultConfigurationSource(); - - /** - * private constructor - */ - public DefaultConfigurationSource() { - // - } - - /** - * {@inheritDoc} - * - * @see net.sf.ehcache.config.generator.ConfigurationSource#createConfiguration() - */ - @Override - public Configuration createConfiguration() { - return ConfigurationFactory.parseConfiguration(); - } - - @Override - public String toString() { - return "DefaultConfigurationSource [ ehcache.xml or ehcache-failsafe.xml ]"; - } - - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheConfiguration.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheConfiguration.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheConfiguration.java (revision 0) @@ -1,347 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.management; - -import java.io.Serializable; - -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.config.TerracottaConfiguration.Consistency; -import net.sf.ehcache.hibernate.management.impl.EhcacheHibernateMbeanNames; - - -/** - * A JMX MBean implementation and decorator to net.sf.ehcache.CacheConfiguration - * - * @author Greg Luck - * @version $Id: CacheConfiguration.java 5594 2012-05-07 16:04:31Z cdennis $ - * @since 1.3 - */ -public class CacheConfiguration implements CacheConfigurationMBean, Serializable { - - private static final long serialVersionUID = -8944774509593267228L; - - private final transient net.sf.ehcache.config.CacheConfiguration cacheConfiguration; - - private final ObjectName objectName; - - /** - * Constructs using a backing CacheConfiguration - * - * @param cache - */ - public CacheConfiguration(net.sf.ehcache.Ehcache cache) { - cacheConfiguration = cache.getCacheConfiguration(); - objectName = createObjectName(cache.getCacheManager().toString(), cache.getName()); - } - - /** - * Creates an object name using the scheme "net.sf.ehcache:type=CacheConfiguration,CacheManager=,name=" - */ - static ObjectName createObjectName(String cacheManagerName, String cacheName) { - ObjectName objectName; - try { - objectName = new ObjectName("net.sf.ehcache:type=CacheConfiguration,CacheManager=" + cacheManagerName + ",name=" - + EhcacheHibernateMbeanNames.mbeanSafe(cacheName)); - } catch (MalformedObjectNameException e) { - throw new CacheException(e); - } - return objectName; - } - - /** - * Accessor - */ - public String getName() { - return cacheConfiguration.getName(); - } - - /** - * Accessor - */ - public boolean isLoggingEnabled() { - return cacheConfiguration.getLogging(); - } - - /** - * setLoggingEnabled - * - * @param enable - */ - public void setLoggingEnabled(boolean enable) { - cacheConfiguration.setLogging(enable); - } - /** - * Accessor - * - * @deprecated use {@link #getMaxEntriesLocalHeap()} - */ - @Deprecated - public int getMaxElementsInMemory() { - return cacheConfiguration.getMaxElementsInMemory(); - } - - /** - * setMaxElementsInMemory - * - * @param maxElements - * @deprecated use {@link #setMaxEntriesLocalHeap(long)} - */ - @Deprecated - public void setMaxElementsInMemory(int maxElements) { - cacheConfiguration.setMaxElementsInMemory(maxElements); - } - - /** - * Accessor - * - * @deprecated use {@link #getMaxEntriesLocalDisk()} - */ - @Deprecated - public int getMaxElementsOnDisk() { - return cacheConfiguration.getMaxElementsOnDisk(); - } - - /** - * setMaxElementsOnDisk - * - * @param maxElements - * @deprecated use {@link #setMaxEntriesLocalDisk(long)} - */ - @Deprecated - public void setMaxElementsOnDisk(int maxElements) { - cacheConfiguration.setMaxElementsOnDisk(maxElements); - } - - /** - * Accessor - * @return a String representation of the policy - */ - public String getMemoryStoreEvictionPolicy() { - return cacheConfiguration.getMemoryStoreEvictionPolicy().toString(); - } - - /** - * setMemoryStoreEvictionPolicy - * - * @param memoryStoreEvictionPolicy - */ - public void setMemoryStoreEvictionPolicy(String memoryStoreEvictionPolicy) { - cacheConfiguration.setMemoryStoreEvictionPolicy(memoryStoreEvictionPolicy); - } - - /** - * Accessor - */ - public boolean isEternal() { - return cacheConfiguration.isEternal(); - } - - /** - * setEternal - * - * @param eternal - */ - public void setEternal(boolean eternal) { - cacheConfiguration.setEternal(eternal); - } - - /** - * Accessor - */ - public long getTimeToIdleSeconds() { - return cacheConfiguration.getTimeToIdleSeconds(); - } - - /** - * setTimeToIdleSeconds - * - * @param tti - */ - public void setTimeToIdleSeconds(long tti) { - cacheConfiguration.setTimeToIdleSeconds(tti); - } - - /** - * Accessor - */ - public long getTimeToLiveSeconds() { - return cacheConfiguration.getTimeToLiveSeconds(); - } - - /** - * setTimeToLiveSeconds - * - * @param ttl - */ - public void setTimeToLiveSeconds(long ttl) { - cacheConfiguration.setTimeToLiveSeconds(ttl); - } - - /** - * Accessor - */ - public boolean isOverflowToDisk() { - return cacheConfiguration.isOverflowToDisk(); - } - - /** - * setOverflowToDisk - * - * @param overflowToDisk - */ - public void setOverflowToDisk(boolean overflowToDisk) { - cacheConfiguration.setOverflowToDisk(overflowToDisk); - } - - /** - * Accessor - */ - public boolean isDiskPersistent() { - return cacheConfiguration.isDiskPersistent(); - } - - /** - * setDiskPersistent - * - * @param diskPersistent - */ - public void setDiskPersistent(boolean diskPersistent) { - cacheConfiguration.setDiskPersistent(diskPersistent); - } - - /** - * Accessor - */ - public int getDiskSpoolBufferSizeMB() { - return cacheConfiguration.getDiskSpoolBufferSizeMB(); - } - - /** - * setDiskSpoolBufferSizeMB - * - * @param diskSpoolBufferSizeMB - */ - public void setDiskSpoolBufferSizeMB(int diskSpoolBufferSizeMB) { - cacheConfiguration.setDiskSpoolBufferSizeMB(diskSpoolBufferSizeMB); - } - - /** - * Accessor - */ - public long getDiskExpiryThreadIntervalSeconds() { - return cacheConfiguration.getDiskExpiryThreadIntervalSeconds(); - } - - /** - * setDiskExpiryThreadIntervalSeconds - * - * @param diskExpiryThreadIntervalSeconds - */ - public final void setDiskExpiryThreadIntervalSeconds(long diskExpiryThreadIntervalSeconds) { - cacheConfiguration.setDiskExpiryThreadIntervalSeconds(diskExpiryThreadIntervalSeconds); - } - - /** - * Accessor - */ - public boolean isTerracottaClustered() { - return cacheConfiguration.isTerracottaClustered(); - } - - /** - * Accessor - */ - public String getTerracottaConsistency() { - Consistency consistency = cacheConfiguration.getTerracottaConsistency(); - return consistency != null ? consistency.name() : "na"; - } - - /** - * @return the object name for this MBean - */ - ObjectName getObjectName() { - return objectName; - } - - /** - * Accessor - */ - public boolean isOverflowToOffHeap() { - return cacheConfiguration.isOverflowToOffHeap(); - } - - /** - * Accessor - * @deprecated use {@link #getMaxBytesLocalOffHeap()} - */ - @Deprecated - public long getMaxMemoryOffHeapInBytes() { - return cacheConfiguration.getMaxMemoryOffHeapInBytes(); - } - - /** - * Maximum number of entries that may be stored in the local disk store. - */ - public long getMaxEntriesLocalDisk() { - return cacheConfiguration.getMaxEntriesLocalDisk(); - } - - /** - * Maximum number of entries that may be stored in local heap memory store. - */ - public long getMaxEntriesLocalHeap() { - return cacheConfiguration.getMaxEntriesLocalHeap(); - } - - /** - * Maximum number of entries that may be stores in the local disk store. - */ - public void setMaxEntriesLocalDisk(long maxEntries) { - cacheConfiguration.setMaxEntriesLocalDisk(maxEntries); - } - - /** - * Maximum number of entries that may be stored in local heap memory store. - */ - public void setMaxEntriesLocalHeap(long maxEntries) { - cacheConfiguration.setMaxEntriesLocalHeap(maxEntries); - } - - /** - * Maximum number of bytes that may be stored in the local disk store. - */ - public long getMaxBytesLocalDisk() { - return cacheConfiguration.getMaxBytesLocalDisk(); - } - - /** - * Maximum number of bytes that may be stored in local heap memory store. - */ - public long getMaxBytesLocalHeap() { - return cacheConfiguration.getMaxBytesLocalHeap(); - } - - /** - * Maximum number of bytes that may be stored in local off-heap memory store. - */ - public long getMaxBytesLocalOffHeap() { - return cacheConfiguration.getMaxBytesLocalOffHeap(); - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/regions/EhcacheGeneralDataRegion.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/regions/EhcacheGeneralDataRegion.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/hibernate/regions/EhcacheGeneralDataRegion.java (revision 0) @@ -1,135 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.sf.ehcache.hibernate.regions; - -import java.util.Properties; - -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.Element; -import net.sf.ehcache.constructs.nonstop.NonStopCacheException; -import net.sf.ehcache.hibernate.nonstop.HibernateNonstopCacheExceptionHandler; -import net.sf.ehcache.hibernate.strategy.EhcacheAccessStrategyFactory; - -import org.hibernate.cache.CacheException; -import org.hibernate.cache.GeneralDataRegion; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * An Ehcache specific GeneralDataRegion. - *

- * GeneralDataRegion instances are used for both the timestamps and query caches. - * - * @author Chris Dennis - * @author Greg Luck - * @author Emmanuel Bernard - * @author Abhishek Sanoujam - */ -abstract class EhcacheGeneralDataRegion extends EhcacheDataRegion implements GeneralDataRegion { - - private static final Logger LOG = LoggerFactory.getLogger(EhcacheGeneralDataRegion.class); - - /** - * Creates an EhcacheGeneralDataRegion using the given Ehcache instance as a backing. - */ - public EhcacheGeneralDataRegion(EhcacheAccessStrategyFactory accessStrategyFactory, Ehcache cache, Properties properties) { - super(accessStrategyFactory, cache, properties); - } - - /** - * {@inheritDoc} - */ - public Object get(Object key) throws CacheException { - try { - LOG.debug("key: {}", key); - if (key == null) { - return null; - } else { - Element element = cache.get(key); - if (element == null) { - LOG.debug("Element for key {} is null", key); - return null; - } else { - return element.getObjectValue(); - } - } - } catch (net.sf.ehcache.CacheException e) { - if (e instanceof NonStopCacheException) { - HibernateNonstopCacheExceptionHandler.getInstance().handleNonstopCacheException((NonStopCacheException) e); - return null; - } else { - throw new CacheException(e); - } - } - } - - /** - * {@inheritDoc} - */ - public void put(Object key, Object value) throws CacheException { - LOG.debug("key: {} value: {}", key, value); - try { - Element element = new Element(key, value); - cache.put(element); - } catch (IllegalArgumentException e) { - throw new CacheException(e); - } catch (IllegalStateException e) { - throw new CacheException(e); - } catch (net.sf.ehcache.CacheException e) { - if (e instanceof NonStopCacheException) { - HibernateNonstopCacheExceptionHandler.getInstance().handleNonstopCacheException((NonStopCacheException) e); - } else { - throw new CacheException(e); - } - } - } - - /** - * {@inheritDoc} - */ - public void evict(Object key) throws CacheException { - try { - cache.remove(key); - } catch (ClassCastException e) { - throw new CacheException(e); - } catch (IllegalStateException e) { - throw new CacheException(e); - } catch (net.sf.ehcache.CacheException e) { - if (e instanceof NonStopCacheException) { - HibernateNonstopCacheExceptionHandler.getInstance().handleNonstopCacheException((NonStopCacheException) e); - } else { - throw new CacheException(e); - } - } - } - - /** - * {@inheritDoc} - */ - public void evictAll() throws CacheException { - try { - cache.removeAll(); - } catch (IllegalStateException e) { - throw new CacheException(e); - } catch (net.sf.ehcache.CacheException e) { - if (e instanceof NonStopCacheException) { - HibernateNonstopCacheExceptionHandler.getInstance().handleNonstopCacheException((NonStopCacheException) e); - } else { - throw new CacheException(e); - } - } - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/tc-config.xml =================================================================== diff -u -N -r11322 -r11323 Binary files differ Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/src/main/resources/META-INF/services/com.terracotta.management.ApplicationEhCacheService =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/src/main/resources/META-INF/services/com.terracotta.management.ApplicationEhCacheService (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/src/main/resources/META-INF/services/com.terracotta.management.ApplicationEhCacheService (revision 0) @@ -1 +0,0 @@ -com.terracotta.management.ApplicationEhCacheV1 \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/TerracottaIT.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/TerracottaIT.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/TerracottaIT.java (revision 0) @@ -1,77 +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 junit.framework.Assert; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.Ignore; - -import java.io.File; - -/** - * These tests require a Terracotta server running on localhost. - *

- * If running this interactively, start terracotta with mvn tc:start. - * To stop mvn tc:stop - *

- * This test is set up in Maven as an integration test. Terracotta is set up to start and stop pre and post the - * integration tests phase. - * - * @author Greg Luck - */ -@Ignore("Client hangs") -public class TerracottaIT { - - /** - * the CacheManager instance - */ - protected CacheManager manager; - - /** - * setup test - */ - @Before - public void setUp() throws Exception { - manager = new CacheManager(AbstractCacheTest.TEST_CONFIG_DIR + File.separator - + "terracotta" + File.separator + "ehcache-terracotta-localhost.xml"); - } - - /** - * teardown - */ - @After - public void tearDown() throws Exception { - if (manager != null) { - manager.shutdown(); - } - } - - /** - * Tests that we can put something into a cache with Terracotta" - */ - @Test - public void testIntegration() { - Cache cache1 = manager.getCache("clustered-1"); - manager.addCache("defaults"); - Cache defaults = manager.getCache("defaults"); - - cache1.put(new Element("key1", "value1")); - Assert.assertEquals("value1", cache1.get("key1")); - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/coherence/NoLocksCreatedTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/coherence/NoLocksCreatedTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/coherence/NoLocksCreatedTest.java (revision 0) @@ -1,173 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.modules.ehcache.coherence; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.Element; - -import org.terracotta.test.util.TestBaseUtil; -import org.terracotta.toolkit.Toolkit; -import org.terracotta.ehcache.tests.AbstractCacheTestBase; -import org.terracotta.ehcache.tests.ClientBase; -import org.terracotta.test.util.JMXUtils; - -import com.tc.management.beans.L2MBeanNames; -import com.tc.object.locks.LockID; -import com.tc.objectserver.locks.LockMBean; -import com.tc.properties.TCPropertiesConsts; -import com.tc.stats.api.DSOMBean; -import com.tc.test.config.model.TestConfig; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.remote.JMXConnector; - -import junit.framework.Assert; - -/** - * @author Abhishek Sanoujam - */ -public class NoLocksCreatedTest extends AbstractCacheTestBase { - - public NoLocksCreatedTest(TestConfig testConfig) { - super("cache-coherence-test.xml", testConfig, App.class); - testConfig.addTcProperty(TCPropertiesConsts.L1_LOCKMANAGER_TIMEOUT_INTERVAL, "9000000"); - } - - @Override - protected List getExtraJars() { - return Arrays.asList(TestBaseUtil.jarFor(LockID.class)); - } - - public static class App extends ClientBase { - - public App(String[] args) { - super("strictCache", args); - } - - public static void main(String[] args) { - new App(args).run(); - } - - @Override - protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { - DSOClientMBeanCoordinator coordinator = new DSOClientMBeanCoordinator(); - coordinator.startDSOClientMBeanCoordinator(); - - List locks = coordinator.getLocks(); - System.out.println("Initial locks: " + locks); - int initial = locks.size(); - cache.setNodeCoherent(false); - Assert.assertEquals(false, cache.isNodeCoherent()); - Assert.assertEquals(false, cache.isClusterCoherent()); - - System.out.println("Adding 1000 elements in INCOHERENT mode..."); - long now = System.currentTimeMillis(); - for (int i = 0; i < 1000; i++) { - cache.put(new Element("key" + i, "value" + i)); - } - long t2 = System.currentTimeMillis(); - cache.setNodeCoherent(true); - cache.waitUntilClusterCoherent(); - long incoherentPutTime = System.currentTimeMillis() - now; - System.out.println("Time taken for 1000 puts: " + incoherentPutTime + " msecs. Time for setting node coherent: " - + (System.currentTimeMillis() - t2) + " msecs"); - Assert.assertTrue(cache.isNodeCoherent()); - Assert.assertTrue(cache.isClusterCoherent()); - - List locksAfterPuts = coordinator.getLocks(); - System.out.println("Number of locks:- initialCount: " + initial + " after INCOHERENT puts: " - + locksAfterPuts.size()); - // System.out.println("After put locks: " + locksAfterPuts); - // we do create some CONCURRENT TXN locks, assert not more that 50 or so more locks created - Assert.assertTrue((initial + 50) > locksAfterPuts.size()); - - initial = locksAfterPuts.size(); - // get in incoherent mode - cache.setNodeCoherent(false); - now = System.currentTimeMillis(); - for (int i = 0; i < 5000; i++) { - cache.get("key" + (i % 1000)); - } - long incoherentGetTime = System.currentTimeMillis() - now; - System.out.println("Time taken for 5000 INCOHERENT gets: " + incoherentGetTime + " msecs"); - List locksAfterGets = coordinator.getLocks(); - System.out.println("Number of locks:- Before: " + initial + " After INCOHERENT gets: " + locksAfterGets.size()); - // System.out.println("Locks after INCOHERENT gets: " + locksAfterGets); - // no locks should be created still - Assert.assertEquals("No extra locks should have been created in INCOHERENT gets", initial, locksAfterGets.size()); - cache.setNodeCoherent(true); - cache.waitUntilClusterCoherent(); - Assert.assertTrue(cache.isNodeCoherent()); - Assert.assertTrue(cache.isClusterCoherent()); - - // do some gets in coherent mode, - now = System.currentTimeMillis(); - for (int i = 0; i < 5000; i++) { - cache.get("key" + (i % 1000)); - } - long coherentGetTime = System.currentTimeMillis() - now; - System.out.println("Time taken for 5000 COHERENT gets: " + coherentGetTime + " msecs"); - - locksAfterGets = coordinator.getLocks(); - System.out.println("Number of locks:- Before: " + initial + " After COHERENT gets: " + locksAfterGets.size()); - // no locks should be created still - Assert.assertEquals("Extra locks should have been created in COHERENT gets", initial + 1000, - locksAfterGets.size()); - - // assert puts in coherent mode also creates locks - initial = locksAfterGets.size(); - Assert.assertTrue(cache.isNodeCoherent()); - Assert.assertTrue(cache.isClusterCoherent()); - System.out.println("Adding 1000 elements in COHERENT mode..."); - now = System.currentTimeMillis(); - for (int i = 0; i < 1000; i++) { - cache.put(new Element("new-key" + i, "value" + i)); - } - long coherentPutTime = System.currentTimeMillis() - now; - System.out.println("Time taken for 1000 puts(): " + coherentPutTime + " msecs"); - Assert.assertTrue(cache.isNodeCoherent()); - Assert.assertTrue(cache.isClusterCoherent()); - - locksAfterPuts = coordinator.getLocks(); - System.out.println("Number of locks:- initialCount: " + initial + " after COHERENT puts: " - + locksAfterPuts.size()); - // System.out.println("After put locks: " + locksAfterPuts); - // we do create some CONCURRENT TXN locks, assert not more that 50 or so more locks created - Assert.assertEquals("Coherent puts should have created locks", initial + 1000, locksAfterPuts.size()); - } - - private class DSOClientMBeanCoordinator { - - private DSOMBean dsoMBean; - private MBeanServerConnection mbsc; - - public void startDSOClientMBeanCoordinator() { - try { - JMXConnector jmxc = JMXUtils.getJMXConnector("localhost", - getTestControlMbean().getGroupsData()[0].getJmxPort(0)); - mbsc = jmxc.getMBeanServerConnection(); - } catch (IOException e) { - throw new AssertionError(e); - } - dsoMBean = MBeanServerInvocationHandler.newProxyInstance(mbsc, L2MBeanNames.DSO, DSOMBean.class, false); - } - - public List getLocks() { - ArrayList rv = new ArrayList(); - LockMBean[] locks = dsoMBean.getLocks(); - for (LockMBean lockMBean : locks) { - rv.add(lockMBean.getLockID()); - } - return rv; - } - } - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/loader/ComponentA.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/loader/ComponentA.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/loader/ComponentA.java (revision 0) @@ -1,60 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.loader; - -/** - * Written for Dead-lock poc - * - * @author Greg Luck - * @version $Id: ComponentA.java 5594 2012-05-07 16:04:31Z cdennis $ - */ -public class ComponentA { - - private String name; - private ComponentB b; - - /** - * @param name - * @param b - */ - public ComponentA(String name, ComponentB b) { - this.name = name; - this.b = b; - } - - /** - * @return - */ - public String getName() { - return name; - } - - /** - * @return - */ - public ComponentB getB() { - return b; - } - - /** - * @return - */ - public String toString() { - return "A[" + name + "," + b + "]"; - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheManagerMBean.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheManagerMBean.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/CacheManagerMBean.java (revision 0) @@ -1,99 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.management; - -import java.util.List; - -/** - * An MBean interface for those attributes and operations we wish to expose on net.sf.ehcache.CacheManager - * @author Greg Luck - * @version $Id: CacheManagerMBean.java 10789 2018-04-26 02:08:13Z adahanne $ - * @since 1.3 - */ -public interface CacheManagerMBean { - - /** - * Gets the status attribute of the Ehcache - * - * @return The status value, as a String from the Status enum class - */ - String getStatus(); - - /** - * Gets the name of the cache manager - * - * @return The name of the CacheManager - */ - String getName(); - - /** - * Shuts down the CacheManager. - *

- * If the shutdown occurs on the singleton, then the singleton is removed, so that if a singleton access method - * is called, a new singleton will be created. - */ - void shutdown(); - - - /** - * Clears the contents of all caches in the CacheManager, but without - * removing any caches. - *

- * This method is not synchronized. It only guarantees to clear those elements in a cache - * at the time that the {@link net.sf.ehcache.Ehcache#removeAll()} mehod on each cache is called. - */ - void clearAll(); - - - /** - * Returns a JMX Cache bean - * - */ - Cache getCache(String name); - - - /** - * Gets the cache names managed by the CacheManager - */ - String[] getCacheNames() throws IllegalStateException; - - /** - * Gets a list of caches in this CacheManager - * @return a list of JMX Cache objects - */ - List getCaches(); - - /** - * Get the committed transactions count - * @return the committed transactions count - */ - long getTransactionCommittedCount(); - - /** - * Get the rolled back transactions count - * @return the rolled back transactions count - */ - long getTransactionRolledBackCount(); - - /** - * Get the timed out transactions count. Note that only transactions which failed to - * commit due to a timeout are taken into account - * @return the timed out transactions count - */ - long getTransactionTimedOutCount(); - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/statistics/beans/ProxiedDynamicMBean.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/statistics/beans/ProxiedDynamicMBean.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/statistics/beans/ProxiedDynamicMBean.java (revision 0) @@ -1,171 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.statistics.beans; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.TreeMap; - -import javax.management.Attribute; -import javax.management.AttributeList; -import javax.management.AttributeNotFoundException; -import javax.management.DynamicMBean; -import javax.management.InvalidAttributeValueException; -import javax.management.MBeanAttributeInfo; -import javax.management.MBeanException; -import javax.management.MBeanInfo; -import javax.management.ReflectionException; - -/** - * The ProxiedDynamicMBean. Supports truly dynamic mbeans in an easy - * manner. - * - * @author cschanck - */ -public class ProxiedDynamicMBean implements DynamicMBean { - - private final TreeMap map = new TreeMap(); - private ArrayList attributeInfoList; - private MBeanInfo mbi; - private final String beanName; - private final String beanDescription; - - /** - * Instantiates a new proxied dynamic m bean. - * - * @param beanName the bean name - * @param beanDescription the bean description - * @param attributeStandins the attribute standins - */ - public ProxiedDynamicMBean(String beanName, String beanDescription, Collection attributeStandins) { - this.beanName = beanName; - this.beanDescription = beanDescription; - initialize(attributeStandins); - } - - /** - * Initialize. - * - * @param attributeStandins the attribute standins - */ - public void initialize(Collection attributeStandins) { - for (AttributeProxy as : attributeStandins) { - map.put(as.getName(), as); - } - attributeInfoList = new ArrayList(map.size()); - - for (Map.Entry ent : map.entrySet()) { - AttributeProxy standin = ent.getValue(); - MBeanAttributeInfo tmpInfo = new MBeanAttributeInfo(standin.getName(), standin.getTypeClass().getName(), - standin.getDescription(), standin.isRead(), standin.isWrite(), false); - attributeInfoList.add(tmpInfo); - } - - mbi = new MBeanInfo(getClass().getName(), beanDescription, attributeInfoList.toArray(new MBeanAttributeInfo[0]), null, null, null); - } - - /** - * Gets the bean name. - * - * @return the bean name - */ - public String getBeanName() { - return beanName; - } - - /** - * Get a specific attribtue - */ - public Object getAttribute(String name) throws AttributeNotFoundException { - - AttributeProxy attr = map.get(name); - if (attr != null && attr.isRead()) { - return attr.get(name); - } - return ""; - - } - - /** - * Set an attribtue by name - */ - public void setAttribute(Attribute attribute) throws InvalidAttributeValueException, MBeanException, AttributeNotFoundException { - - String name = attribute.getName(); - AttributeProxy attr = map.get(name); - if (attr != null && attr.isWrite()) { - attr.set(name, attribute.getValue()); - } - } - - /** - * Get a list of attributes. - */ - public AttributeList getAttributes(String[] names) { - - AttributeList list = new AttributeList(); - for (String name : names) { - AttributeProxy attr = map.get(name); - if (attr != null && attr.isRead()) { - Object value = attr.get(name); - list.add(new Attribute(name, value)); - } - - } - - return list; - - } - - /** - * Set an attribute list. - */ - public AttributeList setAttributes(AttributeList list) { - - Attribute[] attrs = list.toArray(new Attribute[0]); - - AttributeList retlist = new AttributeList(); - - for (Attribute attr : attrs) { - String name = attr.getName(); - AttributeProxy a = map.get(name); - if (a != null && a.isWrite()) { - a.set(name, attr.getValue()); - retlist.add(attr); - } - } - - return retlist; - - } - - /** - * Not implemented. - */ - public Object invoke(String name, Object[] args, String[] sig) throws MBeanException, ReflectionException { - return null; - } - - /** - * Accessor for mbean info - */ - public MBeanInfo getMBeanInfo() { - return mbi; - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/OffheapStoreInOssTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/OffheapStoreInOssTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/OffheapStoreInOssTest.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 net.sf.ehcache.Cache; -import net.sf.ehcache.CacheException; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.config.CacheConfiguration; - -import net.sf.ehcache.config.Configuration; -import org.junit.Assert; -import org.junit.Test; - -/** - * @author hhuynh - */ -public class OffheapStoreInOssTest { - - @Test - public void testOffheapInOss() throws Exception { - Configuration config = new Configuration(); - CacheManager manager = new CacheManager(config); - try { - Cache cache = new Cache(new CacheConfiguration("test", 1).overflowToOffHeap(true).maxMemoryOffHeap("1M")); - manager.addCache(cache); - Assert.fail(); - } catch (CacheException e) { - // expected - Assert.assertTrue(e.getMessage().contains("You must use an enterprise version of Ehcache")); - } finally { - manager.shutdown(); - } - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/cluster/TopologyListenerImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/cluster/TopologyListenerImpl.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/cluster/TopologyListenerImpl.java (revision 0) @@ -1,75 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package org.terracotta.modules.ehcache.cluster; - -import net.sf.ehcache.cluster.ClusterNode; -import net.sf.ehcache.cluster.ClusterTopologyListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.atomic.AtomicInteger; - -public class TopologyListenerImpl implements ClusterTopologyListener { - - private static Logger LOG = LoggerFactory.getLogger(TopologyListenerImpl.class.getName()); - - private final AtomicInteger nodesJoined = new AtomicInteger(); - private final AtomicInteger nodesLeft = new AtomicInteger(); - private final AtomicInteger clusterOffline = new AtomicInteger(); - private final AtomicInteger clusterOnline = new AtomicInteger(); - private String clusterId = "UNINITIALIZED"; - - @Override - public void clusterOffline(ClusterNode arg0) { - LOG.info(arg0.getId() + " ...Cluster Offline."); - clusterOffline.incrementAndGet(); - } - - @Override - public void clusterOnline(ClusterNode arg0) { - LOG.info(this.clusterId + " received Cluster Online for " + arg0.getId()); - clusterOnline.incrementAndGet(); - } - - @Override - public void nodeJoined(ClusterNode arg0) { - LOG.info(this.clusterId + " received Node Joined for " + arg0.getId()); - nodesJoined.incrementAndGet(); - - } - - @Override - public void nodeLeft(ClusterNode arg0) { - LOG.info(arg0.getId() + " ...Node Left"); - nodesLeft.incrementAndGet(); - - } - - @Override - public void clusterRejoined(ClusterNode oldNode, ClusterNode newNode) { - LOG.info(oldNode.getId() + " Rejoined as " + newNode.getId()); - } - - public int getNodesJoined() { - return nodesJoined.get(); - } - - public int getNodesLeft() { - return nodesLeft.get(); - } - - public int getClusterOffline() { - return clusterOffline.get(); - } - - public int getClusterOnline() { - return clusterOnline.get(); - } - - public void setClusterId(String clusterId) { - this.clusterId = clusterId; - } - -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/local-tx-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/local-tx-test.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/local-tx-test.xml (revision 0) @@ -1,39 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/loader/BaseComponentLoader.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/loader/BaseComponentLoader.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/loader/BaseComponentLoader.java (revision 0) @@ -1,151 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.loader; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.Status; - -import java.util.Collection; -import java.util.Map; -import java.util.Properties; - - -/** - * Written for Dead-lock poc - * - * @author Greg Luck - * @version $Id: BaseComponentLoader.java 10789 2018-04-26 02:08:13Z adahanne $ - */ -public class BaseComponentLoader extends CacheLoaderFactory implements CacheLoader { - - /** - * - */ - protected Properties props; - - /** - * Create a cache loader - */ - public CacheLoader createCacheLoader(Map arg0) { - Properties p = new Properties(); - p.putAll(arg0); - return createCacheLoader(p); - } - - /** - * create a ehCache Cache loader - */ - public net.sf.ehcache.loader.CacheLoader createCacheLoader(Ehcache cache, Properties properties) { - this.props = properties; - return this; - } - - /** - * @param arg0 - * @return - * @throws CacheException - */ - public Object load(Object arg0) throws CacheException { - return load(arg0, null); - } - - /** - * @param arg0 - * @param argument - * @return - * @throws CacheException - */ - public Object load(Object arg0, Object argument) throws CacheException { - throw new UnsupportedOperationException("Method not implemented"); - } - - /** - * @param keys - * @return - * @throws CacheException - */ - public Map loadAll(Collection keys) throws CacheException { - return loadAll(keys, null); - } - - /** - * @param keys - * @param argument - * @return - * @throws CacheException - */ - public Map loadAll(Collection keys, Object argument) throws CacheException { - throw new UnsupportedOperationException("Method not implemented"); - } - - /** - * Gets the name of a CacheLoader - * - * @return the name of this CacheLoader - */ - public String getName() { - return null; - } - - /** - * Creates a clone of this extension. This method will only be called by ehcache before a - * cache is initialized. - *

- * Implementations should throw CloneNotSupportedException if they do not support clone - * but that will stop them from being used with defaultCache. - * - * @return a clone - * @throws CloneNotSupportedException if the extension could not be cloned. - */ - public CacheLoader clone(Ehcache cache) throws CloneNotSupportedException { - return null; - } - - /** - * Notifies providers to initialise themselves. - *

- * This method is called during the Cache's initialise method after it has changed it's - * status to alive. Cache operations are legal in this method. - * - * @throws net.sf.ehcache.CacheException - */ - public void init() { - //nothing required - } - - /** - * Providers may be doing all sorts of exotic things and need to be able to clean up on - * dispose. - *

- * Cache operations are illegal when this method is called. The cache itself is partly - * disposed when this method is called. - * - * @throws net.sf.ehcache.CacheException - */ - public void dispose() throws net.sf.ehcache.CacheException { - //no op - } - - /** - * @return the status of the extension - */ - public Status getStatus() { - return null; - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/distribution/ehcache-florian.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/distribution/ehcache-florian.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/distribution/ehcache-florian.xml (revision 0) @@ -1,74 +0,0 @@ - - - - - - - - - - - - - - \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/ImmutableValueElementCopyStrategy.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/ImmutableValueElementCopyStrategy.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/ImmutableValueElementCopyStrategy.java (revision 0) @@ -1,55 +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 net.sf.ehcache.Element; - -/** - * @author Alex Snaps - * @author Ludovic Orban - */ -public class ImmutableValueElementCopyStrategy implements ReadWriteCopyStrategy { - - private static final long serialVersionUID = 6938731518478806173L; - - private final ReadWriteSerializationCopyStrategy copyStrategy = new ReadWriteSerializationCopyStrategy(); - - /** - * Deep copies some object and returns an internal storage-ready copy - * - * @param value the value to copy - * @return the storage-ready copy - */ - public Element copyForWrite(Element value, ClassLoader loader) { - if (value == null) { - return null; - } - return copyStrategy.duplicateElementWithNewValue(value, value.getObjectValue()); - } - - /** - * Reconstruct an object from its storage-ready copy. - * - * @param storedValue the storage-ready copy - * @return the original object - */ - public Element copyForRead(Element storedValue, ClassLoader loader) { - if (storedValue == null) { - return null; - } - return copyStrategy.duplicateElementWithNewValue(storedValue, storedValue.getObjectValue()); - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/non-stop-cache-disposal-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/non-stop-cache-disposal-test.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/non-stop-cache-disposal-test.xml (revision 0) @@ -1,14 +0,0 @@ - - - - - - - - - - - \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/LegacyCopyStrategyAdapter.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/LegacyCopyStrategyAdapter.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/compound/LegacyCopyStrategyAdapter.java (revision 0) @@ -1,53 +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 net.sf.ehcache.Element; - -/** - * ReadWriteCopyStrategy adaptor for a legacy CopyStrategy instance - * - * @author Ludovic Orban - */ -public class LegacyCopyStrategyAdapter implements ReadWriteCopyStrategy { - - private static final long serialVersionUID = -6986893869400882078L; - - private final CopyStrategy legacyCopyStrategy; - - /** - * create a LegacyCopyStrategyAdapter - * - * @param legacyCopyStrategy the legacy CopyStrategy to adapt - */ - public LegacyCopyStrategyAdapter(CopyStrategy legacyCopyStrategy) { - this.legacyCopyStrategy = legacyCopyStrategy; - } - - /** - * {@inheritDoc} - */ - public Element copyForWrite(Element value, ClassLoader loader) { - return legacyCopyStrategy.copy(value); - } - - /** - * {@inheritDoc} - */ - public Element copyForRead(Element storedValue, ClassLoader loader) { - return legacyCopyStrategy.copy(storedValue); - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/InternalCacheEventListener.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/InternalCacheEventListener.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/event/InternalCacheEventListener.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; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.Ehcache; -import net.sf.ehcache.Element; - -/** - * Ehcache internal interface for listening on cache events. - * - * @author Alex Snaps - */ -interface InternalCacheEventListener extends Cloneable { - - /** - * Called immediately after an element removal. - *

- * The method causing the remove will block until this method returns. - *

- * This notification is not called for the following special case: - *

    - *
  1. removeAll was called - *
- * - * @param cache the cache emitting the notification - * @param element the element just deleted. - */ - void notifyElementRemoved(Ehcache cache, Element element) throws CacheException; - - /** - * Called immediately after an element has been put into the cache. - *

- * The method causing the put will block until this method returns. - *

- * Implementers may wish to have access to the Element's fields, including value, so the - * element is provided. Implementers should be careful not to modify the element. The - * effect of any modifications is undefined. - * - * @param cache the cache emitting the notification - * @param element the element which was just put into the cache. - */ - void notifyElementPut(Ehcache cache, Element element) throws CacheException; - - /** - * Give the listener a chance to cleanup and free resources when no longer needed - */ - void dispose(); -} Index: rctags/ehcache-2.10.8.1.63/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/QueryResourceServiceImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/QueryResourceServiceImpl.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/QueryResourceServiceImpl.java (revision 0) @@ -1,64 +0,0 @@ -package net.sf.ehcache.management.resource.services; - -import java.util.Collection; -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import net.sf.ehcache.management.resource.QueryResultsEntity; -import net.sf.ehcache.management.service.CacheManagerService; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.terracotta.management.ServiceExecutionException; -import org.terracotta.management.ServiceLocator; -import org.terracotta.management.resource.exceptions.ExceptionUtils; -import org.terracotta.management.resource.exceptions.ResourceRuntimeException; -import org.terracotta.management.resource.services.validator.RequestValidator; - -/** - * @author gkeim - */ -@Path("/agents/cacheManagers/query") -public final class QueryResourceServiceImpl { - public final static String ATTR_QUERY_KEY = "text"; - - private static final Logger LOG = LoggerFactory.getLogger(QueryResourceServiceImpl.class); - - private final RequestValidator validator; - - private final CacheManagerService cacheMgrSvc; - - public QueryResourceServiceImpl() { - this.validator = ServiceLocator.locate(RequestValidator.class); - this.cacheMgrSvc = ServiceLocator.locate(CacheManagerService.class); - } - - @GET - @Produces(MediaType.APPLICATION_JSON) - public Collection executeQuery(@Context UriInfo info) { - LOG.debug(String.format("Invoking executeQuery: %s", info.getRequestUri())); - - validator.validateSafe(info); - - String cacheManagerName = info.getPathSegments().get(1).getMatrixParameters().getFirst("names"); - - MultivaluedMap qParams = info.getQueryParameters(); - List querys = qParams.get(ATTR_QUERY_KEY); - String queryString = querys.size() > 0 ? querys.get(0) : null; - - try { - return cacheMgrSvc.executeQuery(cacheManagerName, queryString); - } catch (ServiceExecutionException e) { - Throwable t = ExceptionUtils.getRootCause(e); - throw new ResourceRuntimeException("Failed to execute query", t, Response.Status.BAD_REQUEST.getStatusCode()); - } - } -} Index: rctags/ehcache-2.10.8.1.63/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/ElementsResourceServiceImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/ElementsResourceServiceImpl.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/ElementsResourceServiceImpl.java (revision 0) @@ -1,61 +0,0 @@ -/* - * All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright - * notice. All rights reserved. - */ - -package net.sf.ehcache.management.resource.services; - -import net.sf.ehcache.management.service.CacheService; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.terracotta.management.ServiceExecutionException; -import org.terracotta.management.ServiceLocator; -import org.terracotta.management.resource.exceptions.ResourceRuntimeException; -import org.terracotta.management.resource.services.validator.RequestValidator; - -import javax.ws.rs.DELETE; -import javax.ws.rs.Path; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -/** - * A resource service interface for implementations interacting with cache elements. - * - * @author brandony - */ -@Path("/agents/cacheManagers/caches/elements") -public final class ElementsResourceServiceImpl { - private static final Logger LOG = LoggerFactory.getLogger(ElementsResourceServiceImpl.class); - - private final CacheService cacheSvc; - - private final RequestValidator validator; - - public ElementsResourceServiceImpl() { - this.validator = ServiceLocator.locate(RequestValidator.class); - this.cacheSvc = ServiceLocator.locate(CacheService.class); - } - - /** - * Remove elements from the cache. - * - * @param info - * for this resource request - */ - @DELETE - public void deleteElements(@Context UriInfo info) { - LOG.debug(String.format("Invoking ElementsResourceServiceImpl.deleteElements: %s", info.getRequestUri())); - - validator.validate(info); - String cacheManagerName = info.getPathSegments().get(1).getMatrixParameters().getFirst("names"); - String cacheName = info.getPathSegments().get(2).getMatrixParameters().getFirst("names"); - - try { - cacheSvc.clearCache(cacheManagerName, cacheName); - } catch (ServiceExecutionException e) { - throw new ResourceRuntimeException("Failed to delete element", e, Response.Status.BAD_REQUEST.getStatusCode()); - } - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/SampledCounterProxy.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/SampledCounterProxy.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/SampledCounterProxy.java (revision 0) @@ -1,181 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.management.sampled; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import net.sf.ehcache.statistics.extended.ExtendedStatistics.Statistic; -import net.sf.ehcache.util.counter.sampled.SampledCounter; -import net.sf.ehcache.util.counter.sampled.TimeStampedCounterValue; - -import org.terracotta.statistics.archive.Timestamped; - -/** - * The Class SampledCounterProxy. - * - * @param the element type - * @author cschanck - */ -public class SampledCounterProxy implements SampledCounter { - - /** The rate. */ - protected final Statistic rate; - - /** - * Instantiates a new sampled counter proxy. - * - * @param rate the rate - */ - public SampledCounterProxy(Statistic rate) { - this.rate = rate; - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.sampled.SampledCounter#getMostRecentSample() - */ - @Override - public TimeStampedCounterValue getMostRecentSample() { - return new TimeStampedCounterValue(System.currentTimeMillis(), rate.value().longValue()); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.sampled.SampledCounter#getAllSampleValues() - */ - @Override - public TimeStampedCounterValue[] getAllSampleValues() { - ArrayList arr = new ArrayList(); - for (Timestamped ts : rate.history()) { - arr.add(new TimeStampedCounterValue(ts.getTimestamp(), ts.getSample().longValue())); - } - return sortAndPresent(arr); - } - - /** - * Sort and present the List of values - * - * @param arr - * @return - */ - protected TimeStampedCounterValue[] sortAndPresent(List arr) { - Collections.sort(arr, new Comparator() { - - @Override - public int compare(TimeStampedCounterValue o1, TimeStampedCounterValue o2) { - return (int) (o1.getTimestamp() - o2.getTimestamp()); - } - }); - return arr.toArray(new TimeStampedCounterValue[arr.size()]); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.Counter#setValue(long) - */ - @Override - public void setValue(long newValue) { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.Counter#increment() - */ - @Override - public long increment() { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.Counter#decrement() - */ - @Override - public long decrement() { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.Counter#getAndSet(long) - */ - @Override - public long getAndSet(long newValue) { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.Counter#getValue() - */ - @Override - public long getValue() { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.Counter#increment(long) - */ - @Override - public long increment(long amount) { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.Counter#decrement(long) - */ - @Override - public long decrement(long amount) { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.sampled.SampledCounter#shutdown() - */ - @Override - public void shutdown() { - throw new UnsupportedOperationException(); - } - - /* - * (non-Javadoc) - * - * @see net.sf.ehcache.util.counter.sampled.SampledCounter#getAndReset() - */ - @Override - public long getAndReset() { - throw new UnsupportedOperationException(); - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/transaction/TxStoreHelper.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/transaction/TxStoreHelper.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/transaction/TxStoreHelper.java (revision 0) @@ -1,17 +0,0 @@ -package net.sf.ehcache.transaction; - -import net.sf.ehcache.store.Store; - -/** - * @author Ludovic Orban - */ -public class TxStoreHelper { - - public static Store getUnderlyingStore(AbstractTransactionStore abstractTransactionStore) { - Store store = abstractTransactionStore.underlyingStore; - while (store instanceof AbstractTransactionStore) { - store = ((AbstractTransactionStore)store).underlyingStore; - } - return store; - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/DefaultCacheOptionalTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/DefaultCacheOptionalTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/config/DefaultCacheOptionalTest.java (revision 0) @@ -1,75 +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 java.util.Arrays; - -import junit.framework.Assert; -import junit.framework.TestCase; -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheException; -import net.sf.ehcache.CacheManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Abhishek Sanoujam - */ -public class DefaultCacheOptionalTest extends TestCase { - - private static final Logger LOG = LoggerFactory.getLogger(DefaultCacheOptionalTest.class); - - private CacheManager cacheManager; - - @Override - public void tearDown() { - if (cacheManager != null) { - cacheManager.shutdown(); - } - } - - public void testDefaultCacheIsOptional() { - cacheManager = new CacheManager(this.getClass().getResourceAsStream("/no-default-cache.xml")); - String[] cacheNames = cacheManager.getCacheNames(); - LOG.info("Cache names: " + Arrays.asList(cacheNames)); - Assert.assertEquals(1, cacheNames.length); - Assert.assertEquals("sampleCache", cacheNames[0]); - - // adding caches by name should fail as no default cache config specified - try { - cacheManager.addCache("someNewCache"); - fail("Adding cache by name with no default config should fail"); - } catch (CacheException e) { - LOG.info("Got expected exception - " + e.getMessage()); - } - - try { - cacheManager.addCacheIfAbsent("someNewCache"); - fail("Adding cache by name with no default config should fail"); - } catch (CacheException e) { - LOG.info("Got expected exception - " + e.getMessage()); - } - - // adding actual caches should work - CacheConfiguration config = new CacheConfiguration("some-name", 92843); - Cache cache = new Cache(config); - cacheManager.addCache(cache); - LOG.info("Added concrete cache successfully"); - - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/resources/resourceclassloader/private-classpath.jar =================================================================== diff -u -N -r11322 -r11323 Binary files differ Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/PrimitiveType.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/PrimitiveType.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/sizeof/PrimitiveType.java (revision 0) @@ -1,114 +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 static net.sf.ehcache.pool.sizeof.JvmInformation.CURRENT_JVM_INFORMATION; - -/** - * Primitive types in the VM type system and their sizes - * @author Alex Snaps - */ -enum PrimitiveType { - - /** - * boolean.class - */ - BOOLEAN(boolean.class, 1), - /** - * byte.class - */ - BYTE(byte.class, 1), - /** - * char.class - */ - CHAR(char.class, 2), - /** - * short.class - */ - SHORT(short.class, 2), - /** - * int.class - */ - INT(int.class, 4), - /** - * float.class - */ - FLOAT(float.class, 4), - /** - * double.class - */ - DOUBLE(double.class, 8), - /** - * long.class - */ - LONG(long.class, 8); - - private Class type; - private int size; - - - private PrimitiveType(Class type, int size) { - this.type = type; - this.size = size; - } - - /** - * Returns the size in memory this type occupies - * @return size in bytes - */ - public int getSize() { - return size; - } - - /** - * The representing type - * @return the type - */ - public Class getType() { - return type; - } - - /** - * The size of a pointer - * @return size in bytes - */ - public static int getReferenceSize() { - return CURRENT_JVM_INFORMATION.getJavaPointerSize(); - } - - /** - * The size on an array - * @return size in bytes - */ - public static long getArraySize() { - return CURRENT_JVM_INFORMATION.getObjectHeaderSize() + INT.getSize(); - } - - /** - * Finds the matching PrimitiveType for a type - * @param type the type to find the PrimitiveType for - * @return the PrimitiveType instance or null if none found - */ - public static PrimitiveType forType(final Class type) { - for (PrimitiveType primitiveType : values()) { - if (primitiveType.getType() == type) { - return primitiveType; - } - } - return null; - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/basic-cache-sync-write-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/basic-cache-sync-write-test.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/basic-cache-sync-write-test.xml (revision 0) @@ -1,17 +0,0 @@ - - - - - - - - - - - - - Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/SystemPropTcConfigTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/SystemPropTcConfigTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/ehcache/tests/SystemPropTcConfigTest.java (revision 0) @@ -1,54 +0,0 @@ -/* - * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright - * notice. All rights reserved. - */ -package org.terracotta.ehcache.tests; - -import com.tc.test.config.model.TestConfig; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; - -public class SystemPropTcConfigTest extends AbstractCacheTestBase { - - public SystemPropTcConfigTest(TestConfig testConfig) { - super("basic-cache-test.xml", testConfig); - - System.out.println("adding extra -Dtc.config"); - testConfig.getClientConfig().addExtraClientJvmArg("-Dtc.config=tc-config.xml"); - } - - @Override - protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable { - if ((exitCode == 0)) { throw new AssertionError("Client " + clientName + " exited with exit code: " + exitCode); } - - FileReader fr = null; - boolean containsException = false; - boolean containsErrorMsg = false; - String errorMessage = "The Terracotta config file should not be set through -Dtc.config in this usage."; - try { - fr = new FileReader(output); - BufferedReader reader = new BufferedReader(fr); - String st = ""; - while ((st = reader.readLine()) != null) { - if (st.contains("net.sf.ehcache.CacheException")) containsException = true; - if (st.contains(errorMessage)) containsErrorMsg = true; - } - } catch (Exception e) { - throw new AssertionError(e); - } finally { - try { - fr.close(); - } catch (Exception e) { - // - } - } - - if (!containsException) { throw new AssertionError( - "Expecting client to fail with exception: net.sf.ehcache.CacheException"); } - - if (!containsErrorMsg) { throw new AssertionError("Expecting client to fail with message: " + errorMessage); } - } - -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/servermap/servermap-maxSize-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/servermap/servermap-maxSize-test.xml (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/resources/servermap/servermap-maxSize-test.xml (revision 0) @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/hibernate/HibernateCacheTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/hibernate/HibernateCacheTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/hibernate/HibernateCacheTest.java (revision 0) @@ -1,270 +0,0 @@ -/* - * To change this template, choose Tools | Templates - * and open the template in the editor. - */ -package net.sf.ehcache.hibernate; - -import java.lang.reflect.Method; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Status; -import net.sf.ehcache.hibernate.domain.Event; -import net.sf.ehcache.hibernate.domain.EventManager; -import net.sf.ehcache.hibernate.domain.Item; -import net.sf.ehcache.hibernate.domain.Person; -import net.sf.ehcache.hibernate.domain.PhoneNumber; -import net.sf.ehcache.hibernate.domain.VersionedItem; - -import org.hibernate.HibernateException; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.Transaction; -import org.hibernate.cache.access.SoftLock; -import org.hibernate.cfg.Configuration; -import org.hibernate.stat.QueryStatistics; -import org.hibernate.stat.SecondLevelCacheStatistics; -import org.hibernate.stat.Statistics; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.terracotta.test.categories.CheckShorts; - -import static org.hamcrest.CoreMatchers.equalTo; -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; - -/** - * @author Chris Dennis - */ -@Category(CheckShorts.class) -public class HibernateCacheTest { - - private static SessionFactory sessionFactory; - private static Configuration config; - - public synchronized static SessionFactory getSessionFactory() { - if (sessionFactory == null) { - try { - sessionFactory = config.buildSessionFactory(); - } catch (HibernateException ex) { - System.err.println("Initial SessionFactory creation failed." + ex); - throw new ExceptionInInitializerError(ex); - } - } - return sessionFactory; - } - - @BeforeClass - public static void setUp() { - System.setProperty("derby.system.home", "target/derby"); - config = new Configuration().configure("/hibernate-config/hibernate.cfg.xml"); - config.setProperty("hibernate.hbm2ddl.auto", "create"); - getSessionFactory().getStatistics().setStatisticsEnabled(true); - } - - @AfterClass - public static void tearDown() { - getSessionFactory().close(); - } - - @Before - public void clearCaches() { - for (CacheManager manager : CacheManager.ALL_CACHE_MANAGERS) { - for (String s : manager.getCacheNames()) { - final Cache cache = manager.getCache(s); - if(cache.getStatus() == Status.STATUS_ALIVE) { - cache.removeAll(); - } - } - } - } - - @Test - public void testQueryCacheInvalidation() throws Exception { - Session s = getSessionFactory().openSession(); - Transaction t = s.beginTransaction(); - Item i = new Item(); - i.setName("widget"); - i.setDescription("A really top-quality, full-featured widget."); - s.persist(i); - t.commit(); - s.close(); - - SecondLevelCacheStatistics slcs = s.getSessionFactory().getStatistics().getSecondLevelCacheStatistics(Item.class.getName()); - - assertEquals(1, slcs.getPutCount()); - assertEquals(1, slcs.getElementCountInMemory()); - assertEquals(1, slcs.getEntries().size()); - - s = getSessionFactory().openSession(); - t = s.beginTransaction(); - i = (Item) s.get(Item.class, i.getId()); - - assertEquals(1, slcs.getHitCount()); - assertEquals(0, slcs.getMissCount()); - - i.setDescription("A bog standard item"); - - t.commit(); - s.close(); - - assertEquals(2, slcs.getPutCount()); - - Object entry = slcs.getEntries().get(i.getId()); - Map map; - if (entry instanceof Map) { - map = (Map) entry; - } else { - Method valueMethod = entry.getClass().getDeclaredMethod("getValue", (Class[]) null); - valueMethod.setAccessible(true); - map = (Map) valueMethod.invoke(entry, (Object[]) null); - } - assertTrue(map.get("description").equals("A bog standard item")); - assertTrue(map.get("name").equals("widget")); - - // cleanup - s = getSessionFactory().openSession(); - t = s.beginTransaction(); - s.delete(i); - t.commit(); - s.close(); - } - - @Test - public void testEmptySecondLevelCacheEntry() throws Exception { - getSessionFactory().evictEntity(Item.class.getName()); - Statistics stats = getSessionFactory().getStatistics(); - stats.clear(); - SecondLevelCacheStatistics statistics = stats.getSecondLevelCacheStatistics(Item.class.getName()); - Map cacheEntries = statistics.getEntries(); - assertEquals(0, cacheEntries.size()); - } - - @Test - public void testStaleWritesLeaveCacheConsistent() { - Session s = getSessionFactory().openSession(); - Transaction txn = s.beginTransaction(); - VersionedItem item = new VersionedItem(); - item.setName("steve"); - item.setDescription("steve's item"); - s.save(item); - txn.commit(); - s.close(); - - Long initialVersion = item.getVersion(); - - // manually revert the version property - item.setVersion(new Long(item.getVersion().longValue() - 1)); - - try { - s = getSessionFactory().openSession(); - txn = s.beginTransaction(); - s.update(item); - txn.commit(); - s.close(); - fail("expected stale write to fail"); - } catch (Throwable expected) { - // expected behavior here - if (txn != null) { - try { - txn.rollback(); - } catch (Throwable ignore) { - } - } - } finally { - if (s != null && s.isOpen()) { - try { - s.close(); - } catch (Throwable ignore) { - } - } - } - - // check the version value in the cache... - SecondLevelCacheStatistics slcs = getSessionFactory().getStatistics().getSecondLevelCacheStatistics(VersionedItem.class.getName()); - - Object entry = slcs.getEntries().get(item.getId()); - Long cachedVersionValue; - if (entry instanceof SoftLock) { - //FIXME don't know what to test here - //cachedVersionValue = new Long( ( (ReadWriteCache.Lock) entry).getUnlockTimestamp() ); - } else { - cachedVersionValue = (Long) ((Map) entry).get("_version"); - assertEquals(initialVersion.longValue(), cachedVersionValue.longValue()); - } - - - // cleanup - s = getSessionFactory().openSession(); - txn = s.beginTransaction(); - item = (VersionedItem) s.load(VersionedItem.class, item.getId()); - s.delete(item); - txn.commit(); - s.close(); - - } - - @Test - public void testGeneralUsage() { - EventManager mgr = new EventManager(getSessionFactory()); - Statistics stats = getSessionFactory().getStatistics(); - - // 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()); - } - - QueryStatistics queryStats = stats.getQueryStatistics("from Event"); - assertEquals("Cache Miss Count", 1L, queryStats.getCacheMissCount()); - assertEquals("Cache Hit Count", 0L, queryStats.getCacheHitCount()); - assertEquals("Cache Put Count", 1L, queryStats.getCachePutCount()); - } -} Index: rctags/ehcache-2.10.8.1.63/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/services/QueryResourceServiceImplV2.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/services/QueryResourceServiceImplV2.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/services/QueryResourceServiceImplV2.java (revision 0) @@ -1,63 +0,0 @@ -package net.sf.ehcache.management.resource.services; - -import java.util.List; - -import javax.ws.rs.GET; -import javax.ws.rs.Path; -import javax.ws.rs.Produces; -import javax.ws.rs.core.Context; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.MultivaluedMap; -import javax.ws.rs.core.Response; -import javax.ws.rs.core.UriInfo; - -import net.sf.ehcache.management.service.CacheManagerServiceV2; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.terracotta.management.ServiceExecutionException; -import org.terracotta.management.ServiceLocator; -import org.terracotta.management.resource.ResponseEntityV2; -import org.terracotta.management.resource.exceptions.ExceptionUtils; -import org.terracotta.management.resource.exceptions.ResourceRuntimeException; -import org.terracotta.management.resource.services.validator.RequestValidator; - -/** - * @author gkeim - */ -@Path("/v2/agents/cacheManagers/query") -public final class QueryResourceServiceImplV2 { - public final static String ATTR_QUERY_KEY = "text"; - - private static final Logger LOG = LoggerFactory.getLogger(QueryResourceServiceImplV2.class); - - private final RequestValidator validator; - - private final CacheManagerServiceV2 cacheMgrSvc; - - public QueryResourceServiceImplV2() { - this.validator = ServiceLocator.locate(RequestValidator.class); - this.cacheMgrSvc = ServiceLocator.locate(CacheManagerServiceV2.class); - } - - @GET - @Produces(MediaType.APPLICATION_JSON) - public ResponseEntityV2 executeQuery(@Context UriInfo info) { - LOG.debug(String.format("Invoking executeQuery: %s", info.getRequestUri())); - - validator.validateSafe(info); - - String cacheManagerName = info.getPathSegments().get(2).getMatrixParameters().getFirst("names"); - - MultivaluedMap qParams = info.getQueryParameters(); - List querys = qParams.get(ATTR_QUERY_KEY); - String queryString = querys.size() > 0 ? querys.get(0) : null; - - try { - return cacheMgrSvc.executeQuery(cacheManagerName, queryString); - } catch (ServiceExecutionException e) { - Throwable t = ExceptionUtils.getRootCause(e); - throw new ResourceRuntimeException("Failed to execute query", t, Response.Status.BAD_REQUEST.getStatusCode()); - } - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/PooledBasedBackEndTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/PooledBasedBackEndTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/store/PooledBasedBackEndTest.java (revision 0) @@ -1,307 +0,0 @@ -package net.sf.ehcache.store; - -import net.sf.ehcache.Element; -import net.sf.ehcache.pool.PoolAccessor; -import net.sf.ehcache.pool.PoolParticipant; -import net.sf.ehcache.store.cachingtier.HeapCacheBackEnd; -import net.sf.ehcache.store.cachingtier.PooledBasedBackEnd; -import org.junit.Test; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicLong; - -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.notNullValue; -import static org.hamcrest.Matchers.nullValue; -import static org.hamcrest.Matchers.sameInstance; -import static org.junit.Assert.assertThat; - -/** - * @author Alex Snaps - */ -public class PooledBasedBackEndTest { - - @Test - public void testPoolIsMaintained() { - PooledBasedBackEnd pooledBasedBackEnd = new PooledBasedBackEnd(new LruPolicy()); - final TestPoolAccessor poolAccessor = new TestPoolAccessor(); - final TestEvictionCallback evictionCallback = new TestEvictionCallback(); - pooledBasedBackEnd.registerEvictionCallback(evictionCallback); - pooledBasedBackEnd.registerAccessor(poolAccessor); - - poolAccessor.size = 1; - assertThat(poolAccessor.sum.get(), is(0L)); - pooledBasedBackEnd.putIfAbsent("key", "value"); - assertThat(poolAccessor.sum.get(), is(1L)); - poolAccessor.size = 3; - pooledBasedBackEnd.remove("key"); - assertThat(poolAccessor.sum.get(), is(0L)); - pooledBasedBackEnd.putIfAbsent("key", "value"); - assertThat(poolAccessor.sum.get(), is(3L)); - poolAccessor.size = 4; - pooledBasedBackEnd.replace("key", "value", "newValue"); - assertThat(poolAccessor.sum.get(), is(4L)); - pooledBasedBackEnd.remove("key"); - assertThat(poolAccessor.sum.get(), is(0L)); - - pooledBasedBackEnd.putIfAbsent("key", "value"); - assertThat(poolAccessor.sum.get(), is(4L)); - poolAccessor.fail = true; - assertThat(pooledBasedBackEnd.putIfAbsent("key2", "value"), nullValue()); - assertThat(pooledBasedBackEnd.get("key2"), nullValue()); - assertThat(poolAccessor.sum.get(), is(4L)); - assertThat(evictionCallback.counter.get(), is(3L)); - - assertThat(pooledBasedBackEnd.replace("key", "value2", "value3"), is(false)); - assertThat(poolAccessor.sum.get(), is(4L)); - assertThat(evictionCallback.counter.get(), is(3L)); - - assertThat(pooledBasedBackEnd.replace("key", "value", "value3"), is(true)); // this is forced, won't fail! - assertThat(poolAccessor.sum.get(), is(4L)); - assertThat(evictionCallback.counter.get(), is(3L)); - - poolAccessor.size = 12; - pooledBasedBackEnd.recalculateSize("key2"); - assertThat(poolAccessor.sum.get(), is(4L)); - assertThat(evictionCallback.counter.get(), is(3L)); - - pooledBasedBackEnd.recalculateSize("key"); - assertThat(poolAccessor.sum.get(), is(60L)); - assertThat(evictionCallback.counter.get(), is(3L)); - - poolAccessor.size = 8; - assertThat(pooledBasedBackEnd.remove("key", "value"), is(false)); - assertThat(poolAccessor.sum.get(), is(60L)); - assertThat(evictionCallback.counter.get(), is(3L)); - - assertThat(pooledBasedBackEnd.remove("key", "value3"), is(true)); - assertThat(poolAccessor.sum.get(), is(0L)); - assertThat(evictionCallback.counter.get(), is(3L)); - - assertThat(pooledBasedBackEnd.keySet().isEmpty(), is(true)); - } - - @Test - public void testPoolIsMaintainedMultiThreaded() throws InterruptedException { - final Random random = new Random(); - final PooledBasedBackEnd pooledBasedBackEnd = new PooledBasedBackEnd(new LruPolicy()); - final TestPoolAccessor poolAccessor = new TestPoolAccessor() { - - ThreadLocal localCounter = new ThreadLocal() { - @Override - protected Integer initialValue() { - return 0; - } - }; - - @Override - public long add(final Object key, final Object value, final Object container, final boolean force) { - final int size = localCounter.get() % 20; - localCounter.set(size + 1); - super.sum.addAndGet(size); - return size; - } - }; - final TestEvictionCallback evictionCallback = new TestEvictionCallback(); - pooledBasedBackEnd.registerEvictionCallback(evictionCallback); - pooledBasedBackEnd.registerAccessor(poolAccessor); - final long seed = random.nextLong(); - - for(int i = 0; i < 10000; i++) { - String kv = Integer.toString(i); - pooledBasedBackEnd.putIfAbsent(kv, kv); - } - - Runnable randomAccessor = new Runnable() { - - Random r = new Random(seed); - - @Override - public void run() { - for (int i = 0; i < 500000; i++) { - final String kv; - final List rv; - switch(r.nextInt(7)) { - case 0: -// SEE EHC-1006 - rv = pooledBasedBackEnd.getRandomValues(1); - if (!rv.isEmpty() && rv.get(0) != null) { - pooledBasedBackEnd.recalculateSize(rv.get(0)); - } - break; - case 1 : - rv = pooledBasedBackEnd.getRandomValues(1); - if (!rv.isEmpty() && rv.get(0) != null) { - pooledBasedBackEnd.remove(rv.get(0)); - } - break; - case 2 : - rv = pooledBasedBackEnd.getRandomValues(1); - if (!rv.isEmpty() && rv.get(0) != null) { - pooledBasedBackEnd.remove(rv.get(0), rv.get(0)); - } - break; - case 3 : - rv = pooledBasedBackEnd.getRandomValues(2); - if (rv.size() > 1 && rv.get(0) != null && rv.get(1) != null ) { - pooledBasedBackEnd.replace(rv.get(0), rv.get(0), new String(rv.get(1))); - } - break; - default: - kv = Integer.toString(r.nextInt(20000)); - pooledBasedBackEnd.putIfAbsent(kv, new String(kv)); - } - } - } - }; - -// Thread[] threads = new Thread[1]; - Thread[] threads = new Thread[Runtime.getRuntime().availableProcessors() * 2]; - for (int i = 0, threadsLength = threads.length; i < threadsLength; i++) { - threads[i] = new Thread(randomAccessor); - threads[i].start(); - } - - for (Thread thread : threads) { - thread.join(); - } - - for (String s : pooledBasedBackEnd.keySet()) { - pooledBasedBackEnd.remove(s); - } - - assertThat(pooledBasedBackEnd.size(), is(0)); - assertThat(poolAccessor.sum.get(), is(0L)); - } - - @Test - public void testRemoveNotifiesEvictionCallback() { - PooledBasedBackEnd backEnd = new PooledBasedBackEnd(new LruPolicy()); - backEnd.registerAccessor(new TestPoolAccessor()); - final Map evicted = new HashMap(); - backEnd.registerEvictionCallback(new HeapCacheBackEnd.EvictionCallback() { - @Override - public void evicted(final Object key, final Object value) { - evicted.put(key, value); - } - }); - backEnd.remove("foo"); - assertThat(evicted.size(), is(0)); - final Element theElement = new Element("foo", "bar"); - backEnd.putIfAbsent("foo", theElement); - assertThat(evicted.size(), is(0)); - backEnd.remove("foo"); - assertThat(evicted.size(), is(1)); - assertThat(evicted.containsKey("foo"), is(true)); - assertThat((Element) evicted.get("foo"), sameInstance(theElement)); - assertThat(backEnd.get("foo"), nullValue()); - } - - @Test - public void testRemoveSupportsNoEvictionCallbackBeingRegistered() { - PooledBasedBackEnd backEnd = new PooledBasedBackEnd(new LruPolicy()); - backEnd.registerAccessor(new TestPoolAccessor()); - backEnd.remove("foo"); - backEnd.putIfAbsent("foo", new Element("foo", "bar")); - assertThat(backEnd.remove("foo"), notNullValue()); - assertThat(backEnd.get("foo"), nullValue()); - } - - private static class TestPoolAccessor implements PoolAccessor { - - volatile long size = 8; - volatile boolean fail = false; - private final AtomicLong sum = new AtomicLong(); - private long replaceNewSize = 60; - - @Override - public long add(final Object key, final Object value, final Object container, final boolean force) { - if(!force && fail) { - return -1; - } - sum.addAndGet(size); - return size; - } - - @Override - public boolean canAddWithoutEvicting(final Object key, final Object value, final Object container) { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public long delete(final long size) { - if(size < 0) { - throw new IllegalArgumentException("WTF?! " + size); - } - sum.addAndGet(-size); - return size; - } - - @Override - public long replace(final long currentSize, final Object key, final Object value, final Object container, final boolean force) { - if (!force && fail) { - return -1; - } - final long newSize = replaceNewSize - currentSize; - sum.addAndGet(newSize); - return newSize; - } - - @Override - public long getSize() { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public void unlink() { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public void clear() { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public PoolParticipant getParticipant() { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public void setMaxSize(final long newValue) { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public boolean hasAbortedSizeOf() { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public long getPoolOccupancy() { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - - @Override - public long getPoolSize() { - throw new UnsupportedOperationException("Someone... i.e. YOU! should think about implementing this someday!"); - } - } - - private static class TestEvictionCallback implements HeapCacheBackEnd.EvictionCallback { - - AtomicLong counter = new AtomicLong(); - ConcurrentMap evicted = new ConcurrentHashMap(); - - @Override - public void evicted(final String key, final String value) { - evicted.put(key, value); - counter.incrementAndGet(); - } - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/hibernate/domain/Account.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/hibernate/domain/Account.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/hibernate/domain/Account.java (revision 0) @@ -1,35 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ - -package org.terracotta.modules.ehcache.hibernate.domain; - -public class Account { - - private Long id; - private Person person; - - public Account() { - // - } - - public Person getPerson() { - return person; - } - - public void setPerson(Person person) { - this.person = person; - } - - public Long getId() { - return id; - } - - public void setId(Long id) { - this.id = id; - } - - public String toString() { - return super.toString(); - } -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicDeadBucketWriteBehindTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicDeadBucketWriteBehindTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/org/terracotta/modules/ehcache/writebehind/BasicDeadBucketWriteBehindTest.java (revision 0) @@ -1,89 +0,0 @@ -/* - * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright - * notice. All rights reserved. - */ -package org.terracotta.modules.ehcache.writebehind; - -import org.terracotta.ehcache.tests.AbstractCacheTestBase; -import org.terracotta.modules.ehcache.async.AsyncCoordinatorImpl; - -import com.tc.l2.L2DebugLogging.LogLevel; -import com.tc.test.config.model.TestConfig; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class BasicDeadBucketWriteBehindTest extends AbstractCacheTestBase { - private int totalWriteCount = 0; - private int totalDeleteCount = 0; - - public BasicDeadBucketWriteBehindTest(TestConfig testConfig) { - super("basic-writebehind-test.xml", testConfig, WriteBehindClient1.class, WriteBehindClient2.class); - testConfig.getClientConfig().setParallelClients(false); - configureTCLogging(AsyncCoordinatorImpl.class.getName(), LogLevel.DEBUG); - } - - @Override - protected void postClientVerification() { - System.out.println("[Clients processed a total of " + totalWriteCount + " writes]"); - if (totalWriteCount < 1001 || totalWriteCount > 1900) { throw new AssertionError(totalWriteCount); } - - System.out.println("[Clients processed a total of " + totalDeleteCount + " deletes]"); - if (totalDeleteCount < 101 || totalDeleteCount > 190) { throw new AssertionError(totalDeleteCount); } - } - - @Override - protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable { - super.evaluateClientOutput(clientName, exitCode, output); - - FileReader fr = null; - BufferedReader reader = null; - StringBuilder strBuilder = new StringBuilder(); - try { - fr = new FileReader(output); - reader = new BufferedReader(fr); - String st = ""; - while ((st = reader.readLine()) != null) { - strBuilder.append(st); - } - } catch (Exception e) { - throw new AssertionError(e); - } finally { - try { - fr.close(); - reader.close(); - } catch (Exception e) { - // - } - } - - // Detect the number of writes that have happened - int writeCount = detectLargestCount(strBuilder.toString(), - Pattern.compile("\\[WriteBehindCacheWriter written (\\d+) for " + clientName - + "\\]")); - totalWriteCount += writeCount; - System.out.println("[" + clientName + " processed " + writeCount + " writes]"); - - // Detect the number of deletes that have happened - int deleteCount = detectLargestCount(strBuilder.toString(), - Pattern.compile("\\[WriteBehindCacheWriter deleted (\\d+) for " + clientName - + "\\]")); - totalDeleteCount += deleteCount; - System.out.println("[" + clientName + " processed " + deleteCount + " deletes]"); - } - - private int detectLargestCount(String clientOutput, Pattern pattern) { - Matcher matcher = pattern.matcher(clientOutput); - int count = 0; - while (matcher.find()) { - int parsedCount = Integer.parseInt(matcher.group(1)); - if (parsedCount > count) { - count = parsedCount; - } - } - return count; - } -} \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-impl-v1/src/main/java/net/sf/ehcache/management/service/impl/CacheEntityBuilder.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/CacheEntityBuilder.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/CacheEntityBuilder.java (revision 0) @@ -1,111 +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.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import net.sf.ehcache.management.resource.CacheEntity; -import net.sf.ehcache.management.sampled.CacheSampler; -import net.sf.ehcache.management.service.AccessorPrefix; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.terracotta.management.resource.AgentEntity; - -/** - * @author brandony - */ -final class CacheEntityBuilder extends ConstrainableEntityBuilderSupport { - private static final Logger LOG = LoggerFactory.getLogger(CacheEntityBuilder.class); - - private static final String C_NAME_ACCESSOR = AccessorPrefix.get + "CacheName"; - - private final Map> samplersByCMName = new HashMap>(); - - static CacheEntityBuilder createWith(CacheSampler sampler, - String cacheManagerName) { - return new CacheEntityBuilder(sampler, cacheManagerName); - } - - private CacheEntityBuilder(CacheSampler sampler, - String cacheManagerName) { - addSampler(sampler, cacheManagerName); - } - - CacheEntityBuilder add(CacheSampler sampler, - String cacheManagerName) { - addSampler(sampler, cacheManagerName); - return this; - } - - CacheEntityBuilder add(Set constraintAttributes) { - addConstraints(constraintAttributes); - return this; - } - - Collection build() { - Collection ces = new ArrayList(samplersByCMName.values().size()); - - for (Map.Entry> entry : samplersByCMName.entrySet()) { - for (CacheSampler sampler : entry.getValue()) { - CacheEntity ce = new CacheEntity(); - ce.setCacheManagerName(entry.getKey()); - ce.setName(sampler.getCacheName()); - ce.setAgentId(AgentEntity.EMBEDDED_AGENT_ID); - ce.setVersion(this.getClass().getPackage().getImplementationVersion()); - - if (getAttributeConstraints() != null && !getAttributeConstraints().isEmpty() && getAttributeConstraints() - .size() < CacheSampler.class.getMethods().length) { - buildAttributeMapByAttribute(CacheSampler.class, sampler, ce.getAttributes(), getAttributeConstraints(), - C_NAME_ACCESSOR); - } else { - buildAttributeMapByApi(CacheSampler.class, sampler, ce.getAttributes(), getAttributeConstraints(), - C_NAME_ACCESSOR); - } - - ces.add(ce); - } - } - - return ces; - } - - Logger getLog() { - return LOG; - } - - @Override - protected Set getExcludedAttributeNames(CacheSampler sampler) { - if (sampler.isLocalHeapCountBased()) { - Set excludedNames = new HashSet(); - excludedNames.add("LocalHeapSizeInBytes"); - excludedNames.add("LocalHeapSizeInBytesSample"); - return excludedNames; - } - return Collections.emptySet(); - } - - private void addSampler(CacheSampler sampler, - String cacheManagerName) { - if (sampler == null) throw new IllegalArgumentException("sampler == null"); - - if (cacheManagerName == null) throw new IllegalArgumentException("cacheManagerName == null"); - - Set samplers = samplersByCMName.get(cacheManagerName); - - if (samplers == null) { - samplers = new HashSet(); - samplersByCMName.put(cacheManagerName, samplers); - } - - samplers.add(sampler); - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/DefaultSizeOfEngine.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/DefaultSizeOfEngine.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/DefaultSizeOfEngine.java (revision 0) @@ -1,206 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.pool.impl; - -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.pool.Size; -import net.sf.ehcache.pool.SizeOfEngine; -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.pool.sizeof.MaxDepthExceededException; -import net.sf.ehcache.pool.sizeof.filter.AnnotationSizeOfFilter; -import net.sf.ehcache.pool.sizeof.filter.CombinationSizeOfFilter; -import net.sf.ehcache.pool.sizeof.filter.ResourceSizeOfFilter; -import net.sf.ehcache.pool.sizeof.filter.SizeOfFilter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author Alex Snaps - */ -public class DefaultSizeOfEngine implements SizeOfEngine { - - /** - * System property defining a user specific resource based size-of filter. - *

- * The resource pointed to by this property must be a list of fully qualified - * field or class names, one per line: - *

-     * # This is a comment
-     * org.mycompany.domain.MyType
-     * org.mycompany.domain.MyOtherType.myField
-     * 
- * Fields or types matching against lines in this resource will be ignored - * when calculating the size of the object graph. - */ - public static final String USER_FILTER_RESOURCE = "net.sf.ehcache.sizeof.filter"; - - private static final Logger LOG = LoggerFactory.getLogger(DefaultSizeOfEngine.class.getName()); - private static final String VERBOSE_DEBUG_LOGGING = "net.sf.ehcache.sizeof.verboseDebugLogging"; - - private static final SizeOfFilter DEFAULT_FILTER; - private static final boolean USE_VERBOSE_DEBUG_LOGGING; - - static { - Collection filters = new ArrayList(); - filters.add(new AnnotationSizeOfFilter()); - try { - filters.add(new ResourceSizeOfFilter(SizeOfEngine.class.getResource("builtin-sizeof.filter"))); - } catch (IOException e) { - LOG.warn("Built-in sizeof filter could not be loaded: {}", e); - } - SizeOfFilter userFilter = getUserFilter(); - if (userFilter != null) { - filters.add(userFilter); - } - DEFAULT_FILTER = new CombinationSizeOfFilter(filters.toArray(new SizeOfFilter[filters.size()])); - - USE_VERBOSE_DEBUG_LOGGING = getVerboseSizeOfDebugLogging(); - } - - private final SizeOf sizeOf; - private final int maxDepth; - private final boolean abortWhenMaxDepthExceeded; - - /** - * Creates a default size of engine using the best available sizing algorithm. - * @param maxDepth the max object graph that will be traversed. - * @param abortWhenMaxDepthExceeded true if the object traversal should be aborted when the max depth is exceeded - */ - public DefaultSizeOfEngine(int maxDepth, boolean abortWhenMaxDepthExceeded) { - this(maxDepth, abortWhenMaxDepthExceeded, false); - } - - /** - * Creates a default size of engine using the best available sizing algorithm. - * @param maxDepth the max object graph that will be traversed. - * @param abortWhenMaxDepthExceeded true if the object traversal should be aborted when the max depth is exceeded - * @param silent true if no info log explaining which agent was chosen should be printed - */ - public DefaultSizeOfEngine(int maxDepth, boolean abortWhenMaxDepthExceeded, boolean silent) { - this.maxDepth = maxDepth; - this.abortWhenMaxDepthExceeded = abortWhenMaxDepthExceeded; - SizeOf bestSizeOf; - try { - bestSizeOf = new AgentSizeOf(DEFAULT_FILTER); - if (!silent) { - LOG.info("using Agent sizeof engine"); - } - } catch (UnsupportedOperationException e) { - try { - bestSizeOf = new UnsafeSizeOf(DEFAULT_FILTER); - if (!silent) { - LOG.info("using Unsafe sizeof engine"); - } - } catch (UnsupportedOperationException f) { - try { - bestSizeOf = new ReflectionSizeOf(DEFAULT_FILTER); - if (!silent) { - LOG.info("using Reflection sizeof engine"); - } - } catch (UnsupportedOperationException g) { - throw new CacheException("A suitable SizeOf engine could not be loaded: " + e + ", " + f + ", " + g); - } - } - } - - this.sizeOf = bestSizeOf; - } - - private DefaultSizeOfEngine(DefaultSizeOfEngine defaultSizeOfEngine, int maxDepth, boolean abortWhenMaxDepthExceeded) { - this.sizeOf = defaultSizeOfEngine.sizeOf; - this.maxDepth = maxDepth; - this.abortWhenMaxDepthExceeded = abortWhenMaxDepthExceeded; - } - - /** - * {@inheritDoc} - */ - public SizeOfEngine copyWith(int maxDepth, boolean abortWhenMaxDepthExceeded) { - return new DefaultSizeOfEngine(this, maxDepth, abortWhenMaxDepthExceeded); - } - - private static SizeOfFilter getUserFilter() { - String userFilterProperty = System.getProperty(USER_FILTER_RESOURCE); - - if (userFilterProperty != null) { - List filterUrls = new ArrayList(); - try { - filterUrls.add(new URL(userFilterProperty)); - } catch (MalformedURLException e) { - LOG.debug("MalformedURLException using {} as a URL", userFilterProperty); - } - try { - filterUrls.add(new File(userFilterProperty).toURI().toURL()); - } catch (MalformedURLException e) { - LOG.debug("MalformedURLException using {} as a file URL", userFilterProperty); - } - filterUrls.add(Thread.currentThread().getContextClassLoader().getResource(userFilterProperty)); - for (URL filterUrl : filterUrls) { - SizeOfFilter filter; - try { - filter = new ResourceSizeOfFilter(filterUrl); - LOG.info("Using user supplied filter @ {}", filterUrl); - return filter; - } catch (IOException e) { - LOG.debug("IOException while loading user size-of filter resource", e); - } - } - } - return null; - } - - private static boolean getVerboseSizeOfDebugLogging() { - - String verboseString = System.getProperty(VERBOSE_DEBUG_LOGGING, "false").toLowerCase(); - - return verboseString.equals("true"); - } - - /** - * {@inheritDoc} - */ - public Size sizeOf(final Object key, final Object value, final Object container) { - Size size; - try { - size = sizeOf.deepSizeOf(maxDepth, abortWhenMaxDepthExceeded, key, value, container); - } catch (MaxDepthExceededException e) { - LOG.warn(e.getMessage()); - LOG.warn("key type: {}", key.getClass().getName()); - LOG.warn("key: {}", key); - LOG.warn("value type: {}", value.getClass().getName()); - LOG.warn("value: {}", value); - LOG.warn("container: {}", container); - size = new Size(e.getMeasuredSize(), false); - } - - if (USE_VERBOSE_DEBUG_LOGGING && LOG.isDebugEnabled()) { - LOG.debug("size of {}/{}/{} -> {}", new Object[]{key, value, container, size.getCalculated()}); - } - return size; - } -} Index: rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/AbstractManagementServer.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/AbstractManagementServer.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/AbstractManagementServer.java (revision 0) @@ -1,110 +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; - -import java.util.List; -import java.util.ServiceLoader; -import java.util.concurrent.CopyOnWriteArrayList; - -import net.sf.ehcache.CacheException; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.management.service.ManagementServerLifecycle; - -import net.sf.ehcache.management.service.impl.RemoteAgentEndpointImpl; -import org.terracotta.management.ServiceLocator; -import org.terracotta.management.embedded.StandaloneServer; - -import com.terracotta.management.ApplicationEhCacheService; - -/** - * - * ManagementServerImpl comes in 2 flavors : open source and ee - * This class defines common behavior between those two. - * - * @author Anthony Dahanne - * - */ -public abstract class AbstractManagementServer implements ManagementServer { - - protected RemoteAgentEndpointImpl remoteAgentEndpointImpl; - - protected StandaloneServer standaloneServer; - - protected final List managementServerLifecycles = new CopyOnWriteArrayList(); - - /** - * {@inheritDoc} - */ - @Override - public void start() { - try { - standaloneServer.start(); - } catch (Exception e) { - for (ManagementServerLifecycle samplerRepoService : managementServerLifecycles) { - samplerRepoService.dispose(); - } - ServiceLocator.unload(); - throw new CacheException("error starting management server", e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void stop() { - try { - for (ManagementServerLifecycle samplerRepoService : managementServerLifecycles) { - samplerRepoService.dispose(); - } - standaloneServer.stop(); - ServiceLocator.unload(); - } catch (Exception e) { - throw new CacheException("error stopping management server", e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void register(CacheManager managedResource) { - for (ManagementServerLifecycle samplerRepoService : managementServerLifecycles) { - samplerRepoService.register(managedResource); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void unregister(CacheManager managedResource) { - for (ManagementServerLifecycle samplerRepoService : managementServerLifecycles) { - samplerRepoService.unregister(managedResource); - } - } - - /** - * {@inheritDoc} - */ - @Override - public boolean hasRegistered() { - boolean hasRegistered = true; - for (ManagementServerLifecycle samplerRepoService : managementServerLifecycles) { - hasRegistered = hasRegistered && samplerRepoService.hasRegistered(); - } - return hasRegistered; - } - - protected ServiceLoader applicationEhCacheServiceLoader() { - ServiceLoader sl = ServiceLoader.load(ApplicationEhCacheService.class, - getClass().getClassLoader()); - if (!sl.iterator().hasNext()) { - throw new CacheException("ServiceLoader found no ApplicationEhCacheService implementation"); - } - return sl; - } - -} Index: rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/net/sf/ehcache/osgi/OddCacheLoader.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/net/sf/ehcache/osgi/OddCacheLoader.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/system-tests/src/test/java/net/sf/ehcache/osgi/OddCacheLoader.java (revision 0) @@ -1,13 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. - */ -package net.sf.ehcache.osgi; - - -public class OddCacheLoader extends IncrementingCacheLoader { - - public OddCacheLoader() { - super(false, 10000); - } - -} \ No newline at end of file Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/search/impl/SearchManager.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/search/impl/SearchManager.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/search/impl/SearchManager.java (revision 0) @@ -1,85 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.search.impl; - -import java.util.Map; -import java.util.Set; - -import net.sf.ehcache.Element; -import net.sf.ehcache.search.Attribute; -import net.sf.ehcache.search.Results; -import net.sf.ehcache.search.attribute.AttributeExtractor; -import net.sf.ehcache.search.attribute.DynamicAttributesExtractor; -import net.sf.ehcache.store.StoreQuery; - -/** - * Interface for ehcache search engine implementations - * - * @author teck - */ -public interface SearchManager { - - /** - * Execute a query against the given cache - * - * @param query query to execute - * @param attributeExtractors defined attribute extractors for the cache - * @param dynamicIndexer dynamic attribute extractor (if any) - * @return search results - */ - Results executeQuery(StoreQuery query, Map attributeExtractors, DynamicAttributesExtractor - dynamicIndexer); - - /** - * Notify an element added to a segment of a given cache - * - * @param cacheName cache name - * @param segmentId segment of cache - * @param element element being added to cache - * @param serializedKey serialized form of the element key - * @param extractors the attribute extractors for the cache - * @param dynamicIndexer dynamic attribute extractor (if any) - */ - void put(String cacheName, int segmentId, Element element, byte[] serializedKey, Map extractors, - DynamicAttributesExtractor dynamicIndexer); - - /** - * Notify an element removed from a segment of a given cache - * - * @param cacheName cache name - * @param uniqueKey unique key of element - * @param segmentId segment of cache - * @param isRemoval true if called as a result of actual storage engine removal (as opposed to move), false otherwise - */ - void remove(String cacheName, Object uniqueKey, int segmentId, boolean isRemoval); - - /** - * Clear a segment of the given cache - * - * @param cacheName cache name to clear - * @param segmentId segment of cache - */ - void clear(String cacheName, int segmentId); - - /** - * Returns all known search attributes for cache with given name - * @param cacheName - * @return - */ - Set getSearchAttributes(String cacheName); - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/CacheConfiguration.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/CacheConfiguration.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/config/CacheConfiguration.java (revision 0) @@ -1,3128 +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.Cache; -import net.sf.ehcache.CacheException; -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.EhcacheDefaultClassLoader; -import net.sf.ehcache.Element; -import net.sf.ehcache.config.PersistenceConfiguration.Strategy; -import net.sf.ehcache.config.PinningConfiguration.Store; -import net.sf.ehcache.config.TerracottaConfiguration.Consistency; -import net.sf.ehcache.event.NotificationScope; -import net.sf.ehcache.search.attribute.DynamicAttributesExtractor; -import net.sf.ehcache.store.MemoryStoreEvictionPolicy; -import net.sf.ehcache.store.compound.ReadWriteCopyStrategy; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; - -import static net.sf.ehcache.config.Configuration.getAllActiveCaches; - -/** - * A value object used to represent cache configuration. - *

Construction Patterns

- * The recommended way of creating a Cache in Ehcache 2.0 and above is to create a CacheConfiguration object - * and pass it to the Cache constructor. See {@link net.sf.ehcache.Cache#Cache(CacheConfiguration)}. - *

- * This class supports setter injection and also the fluent builder pattern. - * e.g. - * Cache cache = new Cache(new CacheConfiguration("test2", 1000).eternal(true).memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.FIFO)); - *

- * Rather than proliferation of new constructors as new versions of Ehcache come out, it intended to add the new configuration to this - * class. - *

- * Another way to set configuration is declaratively in the ehcache.xml configuration file. - * e.g. - *

{@code
- * 
- * }
- *

- *

Dynamic Configuration

- * CacheConfiguration instances retrieved from Cache instances allow the dynamic - * modification of certain configuration properties. Currently the dynamic - * properties are: - *
    - *
  • Time To Idle
  • - *
  • Time To Live
  • - *
  • Max Entries in Local Heap
  • - *
  • Max Entries on Local Disk
  • - *
- * Dynamic changes are however not persistent across cache restarts. On restart - * the cache configuration will be reloaded from its original source, erasing any - * changes made previously at runtime. - *

- * Users should also take care of synchronizing threads externally, if a CacheConfiguration instance is - * going to be mutated by multiple threads concurrently. While CacheConfiguration instances will - * make changes properly visible to all threads, logic within individual methods (e.g. validation) isn't - * trying to provide any "thread safeness". - * - * @author Greg Luck - * @author Chris Dennis - * @version $Id: CacheConfiguration.java 10789 2018-04-26 02:08:13Z adahanne $ - */ -public class CacheConfiguration implements Cloneable { - - /** - * Default value for clearOnFlush - */ - public static final boolean DEFAULT_CLEAR_ON_FLUSH = true; - - /** - * The default interval between runs of the expiry thread. - */ - public static final long DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS = 120; - - /** - * Set a buffer size for the spool of approx 30MB. - */ - public static final int DEFAULT_SPOOL_BUFFER_SIZE = 30; - - /** - * Default number of diskAccessStripes. - */ - public static final int DEFAULT_DISK_ACCESS_STRIPES = 1; - - /** - * Logging is off by default. - */ - public static final boolean DEFAULT_LOGGING = false; - - /** - * The default memory store eviction policy is LRU. - */ - public static final MemoryStoreEvictionPolicy DEFAULT_MEMORY_STORE_EVICTION_POLICY = MemoryStoreEvictionPolicy.LRU; - - /** - * The default cacheWriterConfiguration - */ - public static final CacheWriterConfiguration DEFAULT_CACHE_WRITER_CONFIGURATION = new CacheWriterConfiguration(); - - /** - * Default value for copyOnRead - */ - public static final boolean DEFAULT_COPY_ON_READ = false; - - /** - * Default value for copyOnRead - */ - public static final boolean DEFAULT_COPY_ON_WRITE = false; - - /** - * Default value for ttl - */ - public static final long DEFAULT_TTL = 0; - - /** - * Default value for tti - */ - public static final long DEFAULT_TTI = 0; - - /** - * Default value for maxElementsOnDisk - */ - public static final int DEFAULT_MAX_ELEMENTS_ON_DISK = 0; - - /** - * Default value for maxEntriesInCache - */ - public static final long DEFAULT_MAX_ENTRIES_IN_CACHE = 0; - - /** - * Default value for transactionalMode - */ - public static final TransactionalMode DEFAULT_TRANSACTIONAL_MODE = TransactionalMode.OFF; - - /** - * Default value for statistics - */ - public static final boolean DEFAULT_STATISTICS = true; - - /** - * Default value for diskPersistent - * - * @deprecated The {@code diskPersistent} attribute has been replaced with {@link #persistence(PersistenceConfiguration)}. - */ - @Deprecated - public static final boolean DEFAULT_DISK_PERSISTENT = false; - - /** - * Default copyStrategyConfiguration - */ - public static final CopyStrategyConfiguration DEFAULT_COPY_STRATEGY_CONFIGURATION = new CopyStrategyConfiguration(); - - /** - * Default maxBytesOnHeap value - */ - public static final long DEFAULT_MAX_BYTES_ON_HEAP = 0; - - /** - * Default maxBytesOffHeap value - */ - public static final long DEFAULT_MAX_BYTES_OFF_HEAP = 0; - - /** - * Default maxBytesOnDisk value - */ - public static final long DEFAULT_MAX_BYTES_ON_DISK = 0; - - /** - * Default eternal value - */ - public static final boolean DEFAULT_ETERNAL_VALUE = false; - - - private static final Logger LOG = LoggerFactory.getLogger(CacheConfiguration.class.getName()); - private static final int HUNDRED_PERCENT = 100; - private static final int MINIMUM_RECOMMENDED_IN_MEMORY = 100; - - /** - * the name of the cache. - */ - protected volatile String name; - - /** - * Timeout in milliseconds for CacheLoader related calls - */ - protected volatile long cacheLoaderTimeoutMillis; - - /** - * the maximum objects to be held in the {@link net.sf.ehcache.store.MemoryStore}. - *

- * 0 translates to no-limit. - */ - protected volatile Integer maxEntriesLocalHeap; - - /** - * the maximum objects to be held in the {@link net.sf.ehcache.store.disk.DiskStore}. - *

- * 0 translates to no-limit. - */ - protected volatile int maxElementsOnDisk = DEFAULT_MAX_ELEMENTS_ON_DISK; - - /** - * the maximum entries to be held in the cache - */ - protected volatile long maxEntriesInCache = DEFAULT_MAX_ENTRIES_IN_CACHE; - - /** - * The policy used to evict elements from the {@link net.sf.ehcache.store.MemoryStore}. - * This can be one of: - *

    - *
  1. LRU - least recently used - *
  2. LFU - Less frequently used - *
  3. FIFO - first in first out, the oldest element by creation time - *
- * The default value is LRU - * - * @since 1.2 - */ - protected volatile MemoryStoreEvictionPolicy memoryStoreEvictionPolicy = DEFAULT_MEMORY_STORE_EVICTION_POLICY; - - /** - * Sets whether the MemoryStore should be cleared when - * {@link net.sf.ehcache.Ehcache#flush flush()} is called on the cache - true by default. - */ - protected volatile boolean clearOnFlush = DEFAULT_CLEAR_ON_FLUSH; - - /** - * Sets whether elements are eternal. If eternal, timeouts are ignored and the element - * is never expired. - */ - protected volatile boolean eternal = DEFAULT_ETERNAL_VALUE; - - /** - * the time to idle for an element before it expires. Is only used - * if the element is not eternal.A value of 0 means do not check for idling. - */ - protected volatile long timeToIdleSeconds = DEFAULT_TTI; - - /** - * Sets the time to idle for an element before it expires. Is only used - * if the element is not eternal. This attribute is optional in the configuration. - * A value of 0 means do not check time to live. - */ - protected volatile long timeToLiveSeconds = DEFAULT_TTL; - - /** - * whether elements can overflow to disk when the in-memory cache - * has reached the set limit. - * - * @deprecated The {@code overflowToDisk} attribute has been replaced with {@link Strategy#LOCALTEMPSWAP}. - */ - @Deprecated - protected volatile Boolean overflowToDisk; - - /** - * For caches that overflow to disk, whether the disk cache persists between CacheManager instances. - * - * @deprecated The {@code diskPersistent} attribute has been replaced with {@link #persistence(PersistenceConfiguration)}. - */ - @Deprecated - protected volatile Boolean diskPersistent; - - /** - * The size of the disk spool used to buffer writes - */ - protected volatile int diskSpoolBufferSizeMB = DEFAULT_SPOOL_BUFFER_SIZE; - - /** - * The number of concurrent disk access stripes. - */ - protected volatile int diskAccessStripes = DEFAULT_DISK_ACCESS_STRIPES; - - /** - * The interval in seconds between runs of the disk expiry thread. - *

- * 2 minutes is the default. - * This is not the same thing as time to live or time to idle. When the thread runs it checks - * these things. So this value is how often we check for expiry. - */ - protected volatile long diskExpiryThreadIntervalSeconds = DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS; - - /** - * Indicates whether logging is enabled or not. False by default. - * Only used when cache is clustered with Terracotta. - */ - protected volatile boolean logging = DEFAULT_LOGGING; - - /** - * whether elements can overflow to off heap memory when the in-memory cache - * has reached the set limit. - */ - protected volatile Boolean overflowToOffHeap; - - /** - * The event listener factories added by BeanUtils. - */ - protected volatile List cacheEventListenerConfigurations = - new ArrayList(); - - /** - * The cache extension factories added by BeanUtils. - */ - protected volatile List cacheExtensionConfigurations = - new ArrayList(); - - /** - * The BootstrapCacheLoaderFactoryConfiguration. - */ - protected BootstrapCacheLoaderFactoryConfiguration bootstrapCacheLoaderFactoryConfiguration; - - /** - * The CacheExceptionHandlerFactoryConfiguration. - */ - protected CacheExceptionHandlerFactoryConfiguration cacheExceptionHandlerFactoryConfiguration; - - /** - * The TerracottaConfiguration. - */ - protected TerracottaConfiguration terracottaConfiguration; - - /** - * The PinningConfiguration. - */ - protected volatile PinningConfiguration pinningConfiguration; - - /** - * The CacheWriterConfiguration. - */ - protected CacheWriterConfiguration cacheWriterConfiguration = DEFAULT_CACHE_WRITER_CONFIGURATION; - - /** - * The cache loader factories added by BeanUtils. - */ - protected volatile List cacheLoaderConfigurations = new ArrayList(); - - /** - * The cache decorator factories added by BeanUtils. - */ - protected volatile List cacheDecoratorConfigurations = - new ArrayList(); - - /** - * The listeners for this configuration. - */ - protected volatile Set listeners = new CopyOnWriteArraySet(); - - private volatile Set dynamicSearchListeners = new CopyOnWriteArraySet(); - - private DynamicAttributesExtractor flexIndexer; - private volatile boolean frozen; - private volatile TransactionalMode transactionalMode; - private volatile boolean statistics = DEFAULT_STATISTICS; - private volatile CopyStrategyConfiguration copyStrategyConfiguration = DEFAULT_COPY_STRATEGY_CONFIGURATION.copy(); - private volatile SizeOfPolicyConfiguration sizeOfPolicyConfiguration; - private volatile PersistenceConfiguration persistenceConfiguration; - private volatile ElementValueComparatorConfiguration elementValueComparatorConfiguration = - new ElementValueComparatorConfiguration(); - private volatile Boolean copyOnRead; - private volatile Boolean copyOnWrite; - private volatile boolean conflictingEternalValuesWarningLogged; - private volatile Searchable searchable; - private String maxBytesLocalHeapInput; - private String maxBytesLocalOffHeapInput; - private String maxBytesLocalDiskInput; - private Long maxBytesLocalHeap; - private Long maxBytesLocalOffHeap; - private Long maxBytesLocalDisk; - private Integer maxBytesLocalHeapPercentage; - private Integer maxBytesLocalOffHeapPercentage; - private Integer maxBytesLocalDiskPercentage; - private PoolUsage onHeapPoolUsage; - private PoolUsage offHeapPoolUsage; - private PoolUsage onDiskPoolUsage; - private volatile boolean maxEntriesLocalDiskExplicitlySet; - private volatile boolean maxBytesLocalDiskExplicitlySet; - private volatile boolean maxBytesLocalOffHeapExplicitlySet; - private volatile ClassLoader classLoader = EhcacheDefaultClassLoader.getInstance(); - - /** - * Default constructor. - *

- * Note that an empty Cache is not valid and must have extra configuration added which can be done - * through the fluent methods in this class. Call validateConfiguration() to check your configuration. - * - * @see #validateCompleteConfiguration - */ - public CacheConfiguration() { - // empty constructor - } - - /** - * Create a new cache configuration. - *

- * Extra configuration can added after construction via the fluent methods in this class. - * Call validateConfiguration() to check your configuration. - * - * @param name the name of the cache. Note that "default" is a reserved name for the defaultCache. - * @param maxEntriesLocalHeap the maximum number of elements in memory, before they are evicted (0 == no limit) - * @see #validateCompleteConfiguration() - */ - public CacheConfiguration(String name, int maxEntriesLocalHeap) { - this.name = name; - verifyGreaterThanOrEqualToZero((long) maxEntriesLocalHeap, "maxEntriesLocalHeap"); - this.maxEntriesLocalHeap = maxEntriesLocalHeap; - } - - /** - * Clones this object, following the usual contract. - * - * @return a copy, which independent other than configurations than cannot change. - */ - @Override - public CacheConfiguration clone() { - CacheConfiguration config; - try { - config = (CacheConfiguration) super.clone(); - } catch (CloneNotSupportedException e) { - throw new RuntimeException(e); - } - - cloneCacheEventListenerConfigurations(config); - - cloneCacheExtensionConfigurations(config); - - if (bootstrapCacheLoaderFactoryConfiguration != null) { - config.bootstrapCacheLoaderFactoryConfiguration = bootstrapCacheLoaderFactoryConfiguration.clone(); - } - - if (cacheExceptionHandlerFactoryConfiguration != null) { - config.cacheExceptionHandlerFactoryConfiguration = cacheExceptionHandlerFactoryConfiguration.clone(); - } - - if (terracottaConfiguration != null) { - config.terracottaConfiguration = terracottaConfiguration.clone(); - } - - if (cacheWriterConfiguration != null) { - config.cacheWriterConfiguration = cacheWriterConfiguration.clone(); - } - - cloneCacheLoaderConfigurations(config); - - cloneCacheDecoratorConfigurations(config); - - config.listeners = new CopyOnWriteArraySet(); - config.dynamicSearchListeners = new CopyOnWriteArraySet(); - - return config; - } - - private void cloneCacheEventListenerConfigurations(CacheConfiguration config) { - List copy = new ArrayList(); - for (CacheEventListenerFactoryConfiguration item : cacheEventListenerConfigurations) { - copy.add(item.clone()); - } - config.cacheEventListenerConfigurations = copy; - } - - private void cloneCacheExtensionConfigurations(CacheConfiguration config) { - List copy = new ArrayList(); - for (CacheConfiguration.CacheExtensionFactoryConfiguration item : cacheExtensionConfigurations) { - copy.add(item.clone()); - } - config.cacheExtensionConfigurations = copy; - } - - private void cloneCacheLoaderConfigurations(CacheConfiguration config) { - List copy = new ArrayList(); - for (CacheConfiguration.CacheLoaderFactoryConfiguration item : cacheLoaderConfigurations) { - copy.add(item.clone()); - } - config.cacheLoaderConfigurations = copy; - } - - private void cloneCacheDecoratorConfigurations(CacheConfiguration config) { - List copy = new ArrayList(); - for (CacheDecoratorFactoryConfiguration item : cacheDecoratorConfigurations) { - copy.add(item.clone()); - } - config.cacheDecoratorConfigurations = copy; - } - - private void assertArgumentNotNull(String name, Object object) { - if (object == null) { - throw new IllegalArgumentException(name + " cannot be null"); - } - } - - /** - * Sets the name of the cache. - *

- * Cache names have constraints on the characters they can use: - *

    - *
  • the '/' character is illegal,
  • - *
  • the '#' character does not work with RMI replication,
  • - *
  • caches that are registered as MBeans must obey the {@link javax.management.ObjectName} rules for unquoted value. - * This means the following characters are illegal: ',', '=', ':', '"', '*' and '?'.
  • - *
- * Note that caches inside a clustered cache manager are by default registered as MBean. - * - * @param name the cache name. This must be unique. - */ - public final void setName(String name) { - checkDynamicChange(); - assertArgumentNotNull("Cache name", name); - this.name = name; - } - - /** - * Builder to set the name of the cache. - *

- * Cache names have constraints on the characters they can use: - *

    - *
  • the '/' character is illegal,
  • - *
  • the '#' character does not work with RMI replication,
  • - *
  • caches that are registered as MBeans must obey the {@link javax.management.ObjectName} rules for unquoted value. - * This means the following characters are illegal: ',', '=', ':', '"', '*' and '?'.
  • - *
- * Note that caches inside a clustered cache manager are by default registered as MBean. - * - * @param name the cache name. This must be unique. - * @return this configuration instance - * @see #setName(String) - */ - public final CacheConfiguration name(String name) { - setName(name); - return this; - } - - /** - * Enables or disables logging for the cache - *

- * This property can be modified dynamically while the cache is operating. - * Only used when cache is clustered with Terracotta - * - * @param enable If true, enables logging otherwise disables logging - */ - public final void setLogging(boolean enable) { - checkDynamicChange(); - boolean oldLoggingEnabled = this.logging; - this.logging = enable; - fireLoggingChanged(oldLoggingEnabled, enable); - } - - /** - * Enables or disables offheap store for the cache. - * - * @param overflowToOffHeap If true, enables offheap store otherwise disables it. - */ - public final void setOverflowToOffHeap(boolean overflowToOffHeap) { - checkDynamicChange(); - this.overflowToOffHeap = overflowToOffHeap; - } - - /** - * Builder to enable or disable offheap store for the cache. - * - * @param overflowToOffHeap If true, enables offheap store otherwise disables it. - * @return this configuration instance - * @see #setOverflowToOffHeap(boolean) - */ - public CacheConfiguration overflowToOffHeap(boolean overflowToOffHeap) { - setOverflowToOffHeap(overflowToOffHeap); - return this; - } - - /** - * Sets the SizeOfPolicyConfiguration for this cache. - * - * @param sizeOfPolicyConfiguration the SizeOfPolicy Configuration - */ - public void addSizeOfPolicy(SizeOfPolicyConfiguration sizeOfPolicyConfiguration) { - this.sizeOfPolicyConfiguration = sizeOfPolicyConfiguration; - } - - /** - * Builder to set the SizeOfPolicyConfiguration for this cache. - * - * @param sizeOfPolicyConfiguration the SizeOfPolicy Configuration - * @return this configuration instance - * @see #addSizeOfPolicy(SizeOfPolicyConfiguration) - */ - public CacheConfiguration sizeOfPolicy(SizeOfPolicyConfiguration sizeOfPolicyConfiguration) { - addSizeOfPolicy(sizeOfPolicyConfiguration); - return this; - } - - /** - * Sets the PersistenceConfiguration for this cache. - * - * @param persistenceConfiguration the Persistence Configuration - */ - public void addPersistence(PersistenceConfiguration persistenceConfiguration) { - if (diskPersistent != null) { - throw new InvalidConfigurationException("Cannot use both and diskPersistent in a single cache configuration."); - } - if (Boolean.TRUE.equals(overflowToDisk)) { - throw new InvalidConfigurationException("Cannot use both and overflowToDisk in a single cache configuration."); - } - this.persistenceConfiguration = persistenceConfiguration; - } - - /** - * Builder to set the PersistenceConfiguration for this cache. - * - * @param persistenceConfiguration the Persistence Configuration - * @return this configuration instance - * @see #addPersistence(PersistenceConfiguration) - */ - public CacheConfiguration persistence(PersistenceConfiguration persistenceConfiguration) { - addPersistence(persistenceConfiguration); - return this; - } - - /** - * Sets the max off heap memory size allocated for this cache. - * - * @param maxMemoryOffHeap the max off heap memory size allocated for this cache. - * @deprecated See {@link #setMaxBytesLocalOffHeap(java.lang.String)} - */ - @Deprecated - public final void setMaxMemoryOffHeap(String maxMemoryOffHeap) { - checkDynamicChange(); - assertArgumentNotNull("Cache maxMemoryOffHeap", maxMemoryOffHeap); - setMaxBytesLocalOffHeap(maxMemoryOffHeap); - } - - /** - * Builder to set the max off heap memory size allocated for this cache. - * - * @param maxMemoryOffHeap the max off heap memory size allocated for this cache. - * @return this configuration instance - * @deprecated See {@link #maxBytesLocalOffHeap(long, net.sf.ehcache.config.MemoryUnit)} - */ - @Deprecated - public CacheConfiguration maxMemoryOffHeap(String maxMemoryOffHeap) { - setMaxMemoryOffHeap(maxMemoryOffHeap); - return this; - } - - /** - * Builder to enable or disable logging for the cache - *

- * This property can be modified dynamically while the cache is operating. - * Only used when cache is clustered with Terracotta - * - * @param enable If true, enables logging otherwise disables logging - * @return this configuration instance - * @see #setLogging(boolean) - */ - public final CacheConfiguration logging(boolean enable) { - setLogging(enable); - return this; - } - - /** - * Sets the maximum objects to be held in memory (0 = no limit). - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxElementsInMemory The maximum number of elements in memory, before they are evicted (0 == no limit) - * @deprecated use {@link #setMaxEntriesLocalHeap(long)} - */ - @Deprecated - public final void setMaxElementsInMemory(int maxElementsInMemory) { - setMaxEntriesLocalHeap(maxElementsInMemory); - } - - /** - * Sets the maximum objects to be held in local heap memory (0 = no limit). - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxEntriesLocalHeap The maximum number of elements in memory, before they are evicted (0 == no limit) - */ - public final void setMaxEntriesLocalHeap(long maxEntriesLocalHeap) { - verifyGreaterThanOrEqualToZero(maxEntriesLocalHeap, "maxEntriesLocalHeap"); - if (maxEntriesLocalHeap > Integer.MAX_VALUE) { - throw new IllegalArgumentException("Values larger than Integer.MAX_VALUE are not currently supported."); - } - - checkDynamicChange(); - if (onHeapPoolUsage != null && onHeapPoolUsage != PoolUsage.None) { - throw new InvalidConfigurationException("MaxEntriesLocalHeap is not compatible with " + - "MaxBytesLocalHeap set on cache"); - } - int oldCapacity = this.maxEntriesLocalHeap == null ? 0 : this.maxEntriesLocalHeap; - int newCapacity = (int) maxEntriesLocalHeap; - this.maxEntriesLocalHeap = (int) maxEntriesLocalHeap; - fireMemoryCapacityChanged(oldCapacity, newCapacity); - } - - /** - * Builder that sets the maximum objects to be held in memory (0 = no limit). - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxElementsInMemory The maximum number of elements in memory, before they are evicted (0 == no limit) - * @return this configuration instance - * @deprecated use {@link #maxEntriesLocalHeap(int)} - */ - @Deprecated - public final CacheConfiguration maxElementsInMemory(int maxElementsInMemory) { - setMaxElementsInMemory(maxElementsInMemory); - return this; - } - - /** - * Builder that sets the maximum objects to be held in memory (0 = no limit). - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxElementsInMemory The maximum number of elements in memory, before they are evicted (0 == no limit) - * @return this configuration instance - */ - public final CacheConfiguration maxEntriesLocalHeap(int maxElementsInMemory) { - setMaxEntriesLocalHeap(maxElementsInMemory); - return this; - } - - /** - * Sets the timeout for CacheLoader execution (0 = no timeout). - * - * @param cacheLoaderTimeoutMillis the timeout in milliseconds. - */ - public final void setCacheLoaderTimeoutMillis(long cacheLoaderTimeoutMillis) { - checkDynamicChange(); - this.cacheLoaderTimeoutMillis = cacheLoaderTimeoutMillis; - } - - /** - * Builder that sets the timeout for CacheLoader execution (0 = no timeout). - - * @param timeoutMillis the timeout in milliseconds. - * @return this configuration instance - */ - public CacheConfiguration timeoutMillis(long timeoutMillis) { - setCacheLoaderTimeoutMillis(timeoutMillis); - return this; - } - - /** - * Sets the eviction policy. An invalid argument will set it to LRU. - * - * @param memoryStoreEvictionPolicy a String representation of the policy. One of "LRU", "LFU" or "FIFO". - */ - public final void setMemoryStoreEvictionPolicy(String memoryStoreEvictionPolicy) { - assertArgumentNotNull("Cache memoryStoreEvictionPolicy", memoryStoreEvictionPolicy); - setMemoryStoreEvictionPolicyFromObject(MemoryStoreEvictionPolicy.fromString(memoryStoreEvictionPolicy)); - } - - /** - * Builder that sets the eviction policy. An invalid argument will set it to null. - * - * @param memoryStoreEvictionPolicy a String representation of the policy. One of "LRU", "LFU" or "FIFO". - * @return this configuration instance - * @see #setMemoryStoreEvictionPolicy(String) - */ - public final CacheConfiguration memoryStoreEvictionPolicy(String memoryStoreEvictionPolicy) { - setMemoryStoreEvictionPolicy(memoryStoreEvictionPolicy); - return this; - } - - /** - * Sets the eviction policy. This method has a strange name to workaround a problem with XML parsing. - */ - public final void setMemoryStoreEvictionPolicyFromObject(MemoryStoreEvictionPolicy memoryStoreEvictionPolicy) { - checkDynamicChange(); - if (null == memoryStoreEvictionPolicy) { - this.memoryStoreEvictionPolicy = DEFAULT_MEMORY_STORE_EVICTION_POLICY; - } else { - this.memoryStoreEvictionPolicy = memoryStoreEvictionPolicy; - } - } - - /** - * Builder which Sets the eviction policy. An invalid argument will set it to null. - * - * @return this configuration instance - * @see #setMemoryStoreEvictionPolicyFromObject(MemoryStoreEvictionPolicy) - */ - public final CacheConfiguration memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy memoryStoreEvictionPolicy) { - setMemoryStoreEvictionPolicyFromObject(memoryStoreEvictionPolicy); - return this; - } - - /** - * Sets whether the MemoryStore should be cleared when - * {@link net.sf.ehcache.Ehcache#flush flush()} is called on the cache - true by default. - * - * @param clearOnFlush true to clear on flush - */ - public final void setClearOnFlush(boolean clearOnFlush) { - checkDynamicChange(); - this.clearOnFlush = clearOnFlush; - } - - /** - * Builder which sets whether the MemoryStore should be cleared when - * {@link net.sf.ehcache.Ehcache#flush flush()} is called on the cache - true by default. - * - * @param clearOnFlush true to clear on flush - * @return this configuration instance - * @see #setClearOnFlush(boolean) - */ - public final CacheConfiguration clearOnFlush(boolean clearOnFlush) { - setClearOnFlush(clearOnFlush); - return this; - } - - /** - * Sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. False by default. - * - * @param eternal true for eternal - */ - public final void setEternal(boolean eternal) { - checkDynamicChange(); - isEternalValueConflictingWithTTIOrTTL(eternal, getTimeToLiveSeconds(), getTimeToIdleSeconds()); - this.eternal = eternal; - if (eternal) { - setTimeToIdleSeconds(0); - setTimeToLiveSeconds(0); - } - } - - private boolean isEternalValueConflictingWithTTIOrTTL(boolean newEternalValue, long newTTLValue, long newTTIValue) { - boolean conflicting = false; - - if (newEternalValue && (newTTLValue != 0 || newTTIValue != 0)) { - conflicting = true; - } - - if (conflicting && !conflictingEternalValuesWarningLogged) { - conflictingEternalValuesWarningLogged = true; - LOG.warn("Cache '" + getName() + "' is set to eternal but also has TTI/TTL set. " - + " To avoid this warning, clean up the config " + "removing conflicting values of eternal," - + " TTI and TTL. Effective configuration for Cache '" + getName() + "' will be eternal='" + newEternalValue - + "', timeToIdleSeconds='0', timeToLiveSeconds='0'."); - } - return conflicting; - } - - /** - * Builder which sets whether elements are eternal. If eternal, timeouts are ignored and the element is never expired. False by default. - * - * @param eternal true for eternal - * @return this configuration instance - * @see #setEternal(boolean) - */ - public final CacheConfiguration eternal(boolean eternal) { - setEternal(eternal); - return this; - } - - /** - * Sets the time to idle for an element before it expires. Is only used if the element is not eternal. This can be overidden in - * {@link net.sf.ehcache.Element} - *

- * This property can be modified dynamically while the cache is operating. - * - * @param timeToIdleSeconds the default amount of time to live for an element from its last accessed or modified date - */ - public final void setTimeToIdleSeconds(long timeToIdleSeconds) { - checkDynamicChange(); - verifyGreaterThanOrEqualToZero(timeToIdleSeconds, "timeToIdleSeconds"); - if (!isEternalValueConflictingWithTTIOrTTL(eternal, 0, timeToIdleSeconds)) { - long oldTti = this.timeToIdleSeconds; - long newTti = timeToIdleSeconds; - this.timeToIdleSeconds = timeToIdleSeconds; - fireTtiChanged(oldTti, newTti); - } - } - - /** - * Builder which sets the time to idle for an element before it expires. Is only used if the element is not eternal. - * This default can be overridden in {@link net.sf.ehcache.Element} - *

- * This property can be modified dynamically while the cache is operating. - * - * @param timeToIdleSeconds the default amount of time to live for an element from its last accessed or modified date - * @return this configuration instance - * @see #setTimeToIdleSeconds(long) - */ - public final CacheConfiguration timeToIdleSeconds(long timeToIdleSeconds) { - setTimeToIdleSeconds(timeToIdleSeconds); - return this; - } - - /** - * Sets the time to idle for an element before it expires. Is only used if the element is not eternal. - * This default can be overridden in {@link net.sf.ehcache.Element} - *

- * This property can be modified dynamically while the cache is operating. - * - * @param timeToLiveSeconds the default amount of time to live for an element from its creation date - */ - public final void setTimeToLiveSeconds(long timeToLiveSeconds) { - checkDynamicChange(); - verifyGreaterThanOrEqualToZero(timeToLiveSeconds, "timeToLiveSeconds"); - if (!isEternalValueConflictingWithTTIOrTTL(eternal, timeToLiveSeconds, 0)) { - long oldTtl = this.timeToLiveSeconds; - long newTtl = timeToLiveSeconds; - this.timeToLiveSeconds = timeToLiveSeconds; - fireTtlChanged(oldTtl, newTtl); - } - } - - /** - * Builder which sets the time to idle for an element before it expires. Is only used if the element is not eternal. - * This default can be overridden in {@link net.sf.ehcache.Element} - *

- * This property can be modified dynamically while the cache is operating. - * - * @param timeToLiveSeconds the default amount of time to live for an element from its creation date - * @return this configuration instance - * @see #setTimeToLiveSeconds(long) - */ - public final CacheConfiguration timeToLiveSeconds(long timeToLiveSeconds) { - setTimeToLiveSeconds(timeToLiveSeconds); - return this; - } - - /** - * Sets whether elements can overflow to disk when the in-memory cache has reached the set limit. - * - * @param overflowToDisk whether to use the disk store - * @deprecated The {@code overflowToDisk} attribute has been replaced with {@link Strategy#LOCALTEMPSWAP}. - */ - @Deprecated - public final void setOverflowToDisk(boolean overflowToDisk) { - checkDynamicChange(); - if (persistenceConfiguration != null && Boolean.TRUE.equals(overflowToDisk)) { - throw new InvalidConfigurationException("Cannot use both and overflowToDisk in a single cache configuration."); - } - this.overflowToDisk = overflowToDisk; - validateConfiguration(); - } - - /** - * Builder which sets whether elements can overflow to disk when the in-memory cache has reached the set limit. - * - * @param overflowToDisk whether to use the disk store - * @return this configuration instance - * @see #setOverflowToDisk(boolean) - * @deprecated The {@code overflowToDisk} attribute has been replaced with {@link Strategy#LOCALTEMPSWAP}. - */ - @Deprecated - public final CacheConfiguration overflowToDisk(boolean overflowToDisk) { - setOverflowToDisk(overflowToDisk); - return this; - } - - /** - * Sets whether the disk store persists between CacheManager instances. Note that this operates independently of {@link #overflowToDisk}. - * - * @param diskPersistent whether to persist the cache to disk between JVM restarts - * @deprecated The {@code diskPersistent} attribute has been replaced with {@link #persistence(PersistenceConfiguration)}. - */ - @Deprecated - public final void setDiskPersistent(boolean diskPersistent) { - checkDynamicChange(); - if (persistenceConfiguration != null) { - throw new InvalidConfigurationException("Cannot use both and diskPersistent in a single cache configuration."); - } - this.diskPersistent = diskPersistent; - validateConfiguration(); - } - - /** - * Builder which sets whether the disk store persists between CacheManager instances. Note that this operates independently of {@link #overflowToDisk}. - * - * @param diskPersistent whether to persist the cache to disk between JVM restarts. - * @return this configuration instance - * @see #setDiskPersistent(boolean) - * @deprecated The {@code diskPersistent} attribute has been replaced with {@link #persistence(PersistenceConfiguration)}. - */ - @Deprecated - public final CacheConfiguration diskPersistent(boolean diskPersistent) { - setDiskPersistent(diskPersistent); - return this; - } - - /** - * Sets the disk spool size, which is used to buffer writes to the DiskStore. - * If not set it defaults to {@link #DEFAULT_SPOOL_BUFFER_SIZE} - * - * @param diskSpoolBufferSizeMB a positive number - */ - public void setDiskSpoolBufferSizeMB(int diskSpoolBufferSizeMB) { - checkDynamicChange(); - if (diskSpoolBufferSizeMB <= 0) { - this.diskSpoolBufferSizeMB = DEFAULT_SPOOL_BUFFER_SIZE; - } else { - this.diskSpoolBufferSizeMB = diskSpoolBufferSizeMB; - } - } - - /** - * Builder which sets the disk spool size, which is used to buffer writes to the DiskStore. - * If not set it defaults to {@link #DEFAULT_SPOOL_BUFFER_SIZE} - * - * @param diskSpoolBufferSizeMB a positive number - * @return this configuration instance - * @see #setDiskSpoolBufferSizeMB(int) - */ - public final CacheConfiguration diskSpoolBufferSizeMB(int diskSpoolBufferSizeMB) { - setDiskSpoolBufferSizeMB(diskSpoolBufferSizeMB); - return this; - } - - /** - * Sets the number of disk stripes. RandomAccessFiles used to access the data file. By default there - * is one stripe. - * - * @param stripes number of stripes (rounded up to a power-of-2) - */ - public void setDiskAccessStripes(int stripes) { - checkDynamicChange(); - if (stripes <= 0) { - this.diskAccessStripes = DEFAULT_DISK_ACCESS_STRIPES; - } else { - this.diskAccessStripes = stripes; - } - } - - /** - * Builder which sets the number of disk stripes. RandomAccessFiles used to access the data file. By default there - * is one stripe. - * - * @return this configuration instance - * @see #setDiskAccessStripes(int) - */ - public final CacheConfiguration diskAccessStripes(int stripes) { - setDiskAccessStripes(stripes); - return this; - } - - /** - * Sets the maximum number elements on Disk. 0 means unlimited. - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxElementsOnDisk the maximum number of Elements to allow on the disk. 0 means unlimited. - * @deprecated use {@link #setMaxEntriesLocalDisk(long)} for unclustered caches and {@link #setMaxEntriesInCache(long)} for clustered caches. - */ - public void setMaxElementsOnDisk(int maxElementsOnDisk) { - if (onDiskPoolUsage != null && onDiskPoolUsage != PoolUsage.None) { - throw new InvalidConfigurationException("MaxEntriesLocalDisk is not compatible with " + - "MaxBytesLocalDisk set on cache"); - } - verifyGreaterThanOrEqualToZero((long) maxElementsOnDisk, "maxElementsOnDisk"); - checkDynamicChange(); - int oldCapacity = this.maxElementsOnDisk; - this.maxElementsOnDisk = maxElementsOnDisk; - fireDiskCapacityChanged(oldCapacity, this.maxElementsOnDisk); - } - - /** - * Sets the maximum number of entries in the cache. Only applies to terracotta clustered caches. - *

- * The values for maxEntriesInCache must be equal or superior to 0 and are interpreted as follows: - *

    - *
  • {@code maxEntriesInCache == 0} means no capacity based eviction, but resource based eviction can happen.
  • - *
  • {@code maxEntriesInCache > 0} means both capacity based and resource based eviction can happen - *
- *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxEntriesInCache maximum number of entries in cache - */ - public void setMaxEntriesInCache(long maxEntriesInCache) { - checkDynamicChange(); - verifyGreaterThanOrEqualToZero((long)maxEntriesInCache, "maxEntriesInCache"); - checkIfCachePinned(maxEntriesInCache); - long oldValue = this.maxEntriesInCache; - this.maxEntriesInCache = maxEntriesInCache; - fireMaxEntriesInCacheChanged(oldValue, this.maxEntriesInCache); - } - - private void checkIfCachePinned(long maxEntriesInCache) { - if (maxEntriesInCache != DEFAULT_MAX_ENTRIES_IN_CACHE && - getPinningConfiguration() != null && Store.INCACHE.equals(getPinningConfiguration().getStore())) { - throw new InvalidConfigurationException("Setting maxEntriesInCache on an in-cache pinned cache is not legal"); - } - } - - - /** - * Sets the maximum number elements on Disk. 0 means unlimited. - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxEntriesLocalDisk the maximum number of Elements to allow on the disk. 0 means unlimited. - */ - public void setMaxEntriesLocalDisk(long maxEntriesLocalDisk) { - if (isTerracottaClustered()) { - throw new InvalidConfigurationException("MaxEntriesLocalDisk is not applicable for Terracotta clustered caches"); - } - verifyGreaterThanOrEqualToZero(maxEntriesLocalDisk, "maxEntriesLocalDisk"); - if (maxEntriesLocalDisk > Integer.MAX_VALUE) { - throw new IllegalArgumentException("Values greater than Integer.MAX_VALUE are not currently supported."); - } - // This check against pool usage is only there to see if this configuration backs up a running cache - if (onDiskPoolUsage != null && isTerracottaClustered()) { - throw new IllegalStateException("Can't use local disks with Terracotta clustered caches!"); - } - maxEntriesLocalDiskExplicitlySet = true; - setMaxElementsOnDisk((int)maxEntriesLocalDisk); - } - - /** - * Builder which sets the maximum number elements on Disk. 0 means unlimited. - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxElementsOnDisk the maximum number of Elements to allow on the disk. 0 means unlimited. - * @return this configuration instance - * @see #setMaxElementsOnDisk(int) - * @deprecated use {@link #maxEntriesLocalDisk(int)} for unclustered caches and {@link #maxEntriesInCache(long)} for clustered caches. - */ - public final CacheConfiguration maxElementsOnDisk(int maxElementsOnDisk) { - setMaxElementsOnDisk(maxElementsOnDisk); - return this; - } - - /** - * Builder which sets the maximum number entries in cache. - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxEntriesInCache the maximum number of entries to allow in the cache. - * @return this configuration instance - * @see #setMaxEntriesInCache(long) - */ - public final CacheConfiguration maxEntriesInCache(long maxEntriesInCache) { - setMaxEntriesInCache(maxEntriesInCache); - return this; - } - - /** - * Builder which sets the maximum number elements on Disk. 0 means unlimited. - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxElementsOnDisk the maximum number of Elements to allow on the disk. 0 means unlimited. - * @return this configuration instance - * @see #setMaxElementsOnDisk(int) - */ - public final CacheConfiguration maxEntriesLocalDisk(int maxElementsOnDisk) { - setMaxEntriesLocalDisk(maxElementsOnDisk); - return this; - } - - /** - * Sets the interval in seconds between runs of the disk expiry thread. - *

- * 2 minutes is the default. - * This is not the same thing as time to live or time to idle. When the thread runs it checks - * these things. So this value is how often we check for expiry. - */ - public final void setDiskExpiryThreadIntervalSeconds(long diskExpiryThreadIntervalSeconds) { - checkDynamicChange(); - if (diskExpiryThreadIntervalSeconds <= 0) { - this.diskExpiryThreadIntervalSeconds = DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS; - } else { - this.diskExpiryThreadIntervalSeconds = diskExpiryThreadIntervalSeconds; - } - } - - /** - * Builder which sets the interval in seconds between runs of the disk expiry thread. - *

- * 2 minutes is the default. - * This is not the same thing as time to live or time to idle. When the thread runs it checks - * these things. So this value is how often we check for expiry. - * - * @return this configuration instance - * @see #setDiskExpiryThreadIntervalSeconds(long) - */ - public final CacheConfiguration diskExpiryThreadIntervalSeconds(long diskExpiryThreadIntervalSeconds) { - setDiskExpiryThreadIntervalSeconds(diskExpiryThreadIntervalSeconds); - return this; - } - - /** - * Freeze this configuration. Any subsequent changes will throw a CacheException - */ - public void freezeConfiguration() { - frozen = true; - if (searchable != null) { - searchable.freezeConfiguration(); - } - } - - /** - * @return true is this configuration is frozen - it cannot be changed dynamically. - */ - public boolean isFrozen() { - return frozen; - } - - /** - * Getter to the configured ReadWriteCopyStrategy. - * This will always return the same unique instance per cache - * - * @return the {@link ReadWriteCopyStrategy} for instance for this cache - */ - public ReadWriteCopyStrategy getCopyStrategy() { - // todo really make this pluggable through config! - return copyStrategyConfiguration.getCopyStrategyInstance(getClassLoader()); - } - - /** - * Whether the Cache should copy elements it returns - * - * @param copyOnRead true, if copyOnRead - */ - public CacheConfiguration copyOnRead(boolean copyOnRead) { - this.setCopyOnRead(copyOnRead); - return this; - } - - /** - * Whether the Cache should copy elements it returns - * - * @return true, is copyOnRead - */ - public boolean isCopyOnRead() { - validateTransactionalSettings(); - return copyOnRead; - } - - /** - * Whether the Cache should copy elements it returns - * - * @param copyOnRead true, if copyOnRead - */ - public void setCopyOnRead(final boolean copyOnRead) { - this.copyOnRead = copyOnRead; - } - - /** - * Whether the Cache should copy elements it gets - * - * @param copyOnWrite true, if copyOnWrite - */ - public CacheConfiguration copyOnWrite(boolean copyOnWrite) { - this.copyOnWrite = copyOnWrite; - return this; - } - - /** - * Whether the Cache should copy elements it gets - * - * @return true, if copyOnWrite - */ - public boolean isCopyOnWrite() { - validateTransactionalSettings(); - return copyOnWrite; - } - - /** - * Whether the Cache should copy elements it gets - * - * @param copyOnWrite true, if copyOnWrite - */ - public void setCopyOnWrite(final boolean copyOnWrite) { - this.copyOnWrite = copyOnWrite; - } - - /** - * Sets the CopyStrategyConfiguration for this cache - * - * @param copyStrategyConfiguration the CopyStrategy Configuration - */ - public void addCopyStrategy(CopyStrategyConfiguration copyStrategyConfiguration) { - this.copyStrategyConfiguration = copyStrategyConfiguration; - } - - /** - * Sets the ElementValueComparatorConfiguration for this cache - * The default configuration will setup a {@link net.sf.ehcache.store.DefaultElementValueComparator} - * - * @param elementValueComparatorConfiguration the ElementComparator Configuration - */ - public void addElementValueComparator(ElementValueComparatorConfiguration elementValueComparatorConfiguration) { - this.elementValueComparatorConfiguration = elementValueComparatorConfiguration; - } - - /** - * Add configuration to make this cache searchable - * - * @param searchable search config to add - */ - public final void addSearchable(Searchable searchable) { - checkDynamicChange(); - this.searchable = searchable; - } - - /** - * The maximum amount of bytes the cache should occupy on heap - * @return value in bytes, 0 if none set - */ - public long getMaxBytesLocalHeap() { - return maxBytesLocalHeap == null ? DEFAULT_MAX_BYTES_ON_HEAP : maxBytesLocalHeap; - } - - /** - * Setter for maxBytesLocalHeap as a String. Value can have a one char unit suffix or be a percentage (ending in %) - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxBytesHeap String representation of the size, can be relative (in %) - */ - public void setMaxBytesLocalHeap(final String maxBytesHeap) { - assertArgumentNotNull("Cache maxBytesLocalHeap", maxBytesHeap); - if (isPercentage(maxBytesHeap)) { - maxBytesLocalHeapPercentage = parsePercentage(maxBytesHeap); - } else { - setMaxBytesLocalHeap(MemoryUnit.parseSizeInBytes(maxBytesHeap)); - } - maxBytesLocalHeapInput = maxBytesHeap; - } - - /** - * Setter for maxBytesLocalHeap in bytes - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxBytesHeap max bytes in heap in bytes - */ - public void setMaxBytesLocalHeap(final Long maxBytesHeap) { - if (onHeapPoolUsage != null && getMaxEntriesLocalHeap() > 0) { - throw new InvalidConfigurationException("MaxEntriesLocalHeap is not compatible with " + - "MaxBytesLocalHeap set on cache"); - } - if (onHeapPoolUsage != null && onHeapPoolUsage != PoolUsage.Cache) { - throw new IllegalStateException("A Cache can't switch memory pool!"); - } - checkDynamicChange(); - verifyGreaterThanZero(maxBytesHeap, "maxBytesLocalHeap"); - Long oldValue = this.maxBytesLocalHeap; - this.maxBytesLocalHeap = maxBytesHeap; - fireMaxBytesOnLocalHeapChanged(oldValue, maxBytesHeap); - } - - private void fireMaxBytesOnLocalHeapChanged(final Long oldValue, final Long newValue) { - if ((oldValue != null && !oldValue.equals(newValue)) || (newValue != null && !newValue.equals(oldValue))) { - for (CacheConfigurationListener listener : listeners) { - listener.maxBytesLocalHeapChanged(oldValue != null ? oldValue : 0, newValue); - } - } - } - - private void fireMaxBytesOnLocalDiskChanged(final Long oldValue, final Long newValue) { - if ((oldValue != null && !oldValue.equals(newValue)) || (newValue != null && !newValue.equals(oldValue))) { - for (CacheConfigurationListener listener : listeners) { - listener.maxBytesLocalDiskChanged(oldValue != null ? oldValue : 0, newValue); - } - } - } - - private void fireDynamicAttributesExtractorAdded(DynamicAttributesExtractor oldValue, DynamicAttributesExtractor newValue) { - if (oldValue != newValue) { - for (DynamicSearchListener lsnr : dynamicSearchListeners) { - lsnr.extractorChanged(oldValue, newValue); - } - } - } - - /** - * Sets the maxOnHeap size - * @param amount the amount of unit - * @param memoryUnit the actual unit - * @return this - */ - - public CacheConfiguration maxBytesLocalHeap(final long amount, final MemoryUnit memoryUnit) { - setMaxBytesLocalHeap(memoryUnit.toBytes(amount)); - return this; - } - - /** - * The maximum amount of bytes the cache should occupy off heap - * @return value in bytes, 0 if none set - */ - public long getMaxBytesLocalOffHeap() { - return maxBytesLocalOffHeap == null ? DEFAULT_MAX_BYTES_OFF_HEAP : maxBytesLocalOffHeap; - } - - /** - * The string form of the maximum amount of bytes the cache should occupy off heap - * @return value as string in bytes - */ - public String getMaxBytesLocalOffHeapAsString() { - return maxBytesLocalOffHeapInput != null ? maxBytesLocalOffHeapInput : Long.toString(getMaxBytesLocalOffHeap()); - } - - /** - * Setter for maximum bytes off heap as a String. Value can have a one char unit suffix or be a percentage (ending in %) - *

- * Changes to this property once the cache is operating will have no effect. - * - * @param maxBytesOffHeap String representation of the size, can be relative (in %) - */ - public void setMaxBytesLocalOffHeap(final String maxBytesOffHeap) { - assertArgumentNotNull("Cache maxBytesLocalOffHeap", maxBytesOffHeap); - if (isPercentage(maxBytesOffHeap)) { - maxBytesLocalOffHeapPercentage = parsePercentage(maxBytesOffHeap); - } else { - setMaxBytesLocalOffHeap(MemoryUnit.parseSizeInBytes(maxBytesOffHeap)); - } - maxBytesLocalOffHeapInput = maxBytesOffHeap; - maxBytesLocalOffHeapExplicitlySet = true; - } - - /** - * Getter for maximum bytes off heap expressed as a percentage - * @return percentage (between 0 and 100) - */ - public Integer getMaxBytesLocalOffHeapPercentage() { - return maxBytesLocalOffHeapPercentage; - } - - /** - * Getter for maximum bytes on heap expressed as a percentage - * @return percentage (between 0 and 100) - */ - public Integer getMaxBytesLocalHeapPercentage() { - return maxBytesLocalHeapPercentage; - } - - /** - * The string form of the maximum amount of bytes the cache should occupy on heap - * @return value as string in bytes - */ - public String getMaxBytesLocalHeapAsString() { - return maxBytesLocalHeapInput != null ? maxBytesLocalHeapInput : Long.toString(getMaxBytesLocalHeap()); - } - - /** - * Getter for maximum bytes on disk expressed as a percentage - * @return percentage (between 0 and 100) - */ - public Integer getMaxBytesLocalDiskPercentage() { - return maxBytesLocalDiskPercentage; - } - - private int parsePercentage(final String stringValue) { - String trimmed = stringValue.trim(); - int percentage = Integer.parseInt(trimmed.substring(0, trimmed.length() - 1)); - if (percentage > HUNDRED_PERCENT || percentage < 0) { - throw new IllegalArgumentException("Percentage need values need to be between 0 and 100 inclusive, but got : " + percentage); - } - return percentage; - } - - private boolean isPercentage(final String stringValue) { - String trimmed = stringValue.trim(); - return trimmed.charAt(trimmed.length() - 1) == '%'; - } - - /** - * Sets the maximum amount of bytes the cache being configured will use on the OffHeap tier - *

- * Changes to this property once the cache is operating will have no effect. - * - * @param maxBytesOffHeap max bytes on disk in bytes - */ - public void setMaxBytesLocalOffHeap(final Long maxBytesOffHeap) { - if (offHeapPoolUsage != null) { - throw new IllegalStateException("OffHeap can't be set dynamically!"); - } - verifyGreaterThanZero(maxBytesOffHeap, "maxBytesLocalOffHeap"); - this.maxBytesLocalOffHeapExplicitlySet = true; - this.maxBytesLocalOffHeap = maxBytesOffHeap; - } - - /** - * Sets the maxOffHeap tier size - *

- * Changes to this property once the cache is operating will have no effect. - * - * @param amount the amount of unit - * @param memoryUnit the actual unit - * @return this - */ - public CacheConfiguration maxBytesLocalOffHeap(final long amount, final MemoryUnit memoryUnit) { - setMaxBytesLocalOffHeap(memoryUnit.toBytes(amount)); - return this; - } - - /** - * The maximum amount of bytes the cache should occupy on disk - * @return value in bytes, 0 if none set - */ - public long getMaxBytesLocalDisk() { - return maxBytesLocalDisk == null ? DEFAULT_MAX_BYTES_ON_DISK : maxBytesLocalDisk; - } - - /** - * The string form of the maximum amount of bytes the cache should occupy on disk - * @return value as string in bytes - */ - public String getMaxBytesLocalDiskAsString() { - return maxBytesLocalDiskInput != null ? maxBytesLocalDiskInput : Long.toString(getMaxBytesLocalDisk()); - } - - /** - * Setter for maxBytesOnDisk as a String. Value can have a one char unit suffix or be a percentage (ending in %) - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxBytesDisk String representation of the size, can be relative (in %) - */ - public void setMaxBytesLocalDisk(final String maxBytesDisk) { - assertArgumentNotNull("Cache maxBytesLocalDisk", maxBytesDisk); - if (isPercentage(maxBytesDisk)) { - maxBytesLocalDiskPercentage = parsePercentage(maxBytesDisk); - } else { - setMaxBytesLocalDisk(MemoryUnit.parseSizeInBytes(maxBytesDisk)); - } - maxBytesLocalDiskExplicitlySet = true; - maxBytesLocalDiskInput = maxBytesDisk; - } - - /** - * Sets the maximum amount of bytes the cache being configured will use on the OnDisk tier - *

- * This property can be modified dynamically while the cache is operating. - * - * @param maxBytesDisk max bytes on disk in bytes - */ - public void setMaxBytesLocalDisk(final Long maxBytesDisk) { - if (isTerracottaClustered()) { - throw new InvalidConfigurationException("MaxBytesLocalDisk is not applicable for Terracotta clustered caches"); - } - if (onDiskPoolUsage != null && getMaxEntriesLocalDisk() > 0) { - throw new InvalidConfigurationException("MaxEntriesLocalDisk is not compatible with " + - "MaxBytesLocalDisk set on cache"); - } - if (onDiskPoolUsage != null && onDiskPoolUsage != PoolUsage.Cache) { - throw new IllegalStateException("A Cache can't switch disk pool!"); - } - checkDynamicChange(); - verifyGreaterThanZero(maxBytesDisk, "maxBytesLocalDisk"); - maxBytesLocalDiskExplicitlySet = true; - Long oldValue = this.maxBytesLocalDisk; - this.maxBytesLocalDisk = maxBytesDisk; - fireMaxBytesOnLocalDiskChanged(oldValue, maxBytesDisk); - } - - /** - * Sets the maxOnDisk size - *

- * This property can be modified dynamically while the cache is operating. - * - * @param amount the amount of unit - * @param memoryUnit the actual unit - * @return this - */ - public CacheConfiguration maxBytesLocalDisk(final long amount, final MemoryUnit memoryUnit) { - setMaxBytesLocalDisk(memoryUnit.toBytes(amount)); - return this; - } - - /** - * Sets dynamic search attributes extractor - * @param extractor extractor to use - */ - public void setDynamicAttributesExtractor(DynamicAttributesExtractor extractor) { - if (searchable == null || !searchable.isDynamicIndexingAllowed()) { - throw new IllegalArgumentException("Dynamic search attribute extraction not supported"); - } - if (extractor == null && this.flexIndexer != null) { - throw new IllegalArgumentException("Dynamic search attributes extractor cannot be set to null by user"); - } - DynamicAttributesExtractor old = this.flexIndexer; - this.flexIndexer = extractor; - fireDynamicAttributesExtractorAdded(old, this.flexIndexer); - } - - /** - * Sets dynamic search attributes extractor - * @param extractor extractor to use - * @return this - */ - public CacheConfiguration dynamicAttributeExtractor(DynamicAttributesExtractor extractor) { - setDynamicAttributesExtractor(extractor); - return this; - } - - private void verifyGreaterThanZero(final Long fieldVal, final String fieldName) { - if (fieldVal != null && fieldVal < 1) { - throw new IllegalArgumentException("Illegal value " + fieldVal + " for " + fieldName + ": has to be larger than 0"); - } - } - - private void verifyGreaterThanOrEqualToZero(final Long fieldVal, final String fieldName) { - if (fieldVal != null && fieldVal < 0) { - throw new IllegalArgumentException("Illegal value " + fieldVal + " for " + fieldName + ": has to be larger than or equal to 0"); - } - } - - /** - * Returns the copyStrategyConfiguration - * - * @return the copyStrategyConfiguration - */ - public CopyStrategyConfiguration getCopyStrategyConfiguration() { - return this.copyStrategyConfiguration; - } - - /** - * Returns the elementComparatorConfiguration - * - * @return the elementComparatorConfiguration - */ - public ElementValueComparatorConfiguration getElementValueComparatorConfiguration() { - return elementValueComparatorConfiguration; - } - - /** - * Checks whether the user explicitly set the maxBytesOnHeapPercentage - * @return true if set by user, false otherwise - * @see #setMaxBytesLocalHeap(String) - */ - public boolean isMaxBytesLocalHeapPercentageSet() { - return maxBytesLocalHeapPercentage != null; - } - - /** - * Checks whether the user explicitly set the maxBytesOffHeapPercentage - * @return true if set by user, false otherwise - * @see #setMaxBytesLocalOffHeap(String) - */ - public boolean isMaxBytesLocalOffHeapPercentageSet() { - return maxBytesLocalOffHeapPercentage != null; - } - - /** - * Checks whether the user explicitly set the maxBytesOnDiskPercentage - * @return true if set by user, false otherwise - * @see #setMaxBytesLocalDisk(String) - */ - public boolean isMaxBytesLocalDiskPercentageSet() { - return maxBytesLocalDiskPercentage != null; - } - - /** - * Sets up the CacheConfiguration for runtime consumption, also registers this cache configuration with the cache manager's configuration - * @param cacheManager The CacheManager as part of which the cache is being setup - */ - public void setupFor(final CacheManager cacheManager) { - setupFor(cacheManager, true, null); - } - - /** - * Sets up the CacheConfiguration for runtime consumption - * @param cacheManager The CacheManager as part of which the cache is being setup - * @param register true to register this cache configuration with the cache manager. - */ - public void setupFor(final CacheManager cacheManager, final boolean register, final String parentCache) { - final Collection errors = validate(cacheManager.getConfiguration()); - configCachePools(cacheManager.getConfiguration()); - errors.addAll(verifyPoolAllocationsBeforeAddingTo(cacheManager, - cacheManager.getConfiguration().getMaxBytesLocalHeap(), - cacheManager.getConfiguration().getMaxBytesLocalOffHeap(), - cacheManager.getConfiguration().getMaxBytesLocalDisk(), parentCache)); - if (!errors.isEmpty()) { - throw new InvalidConfigurationException(errors); - } - - - if (!isTerracottaClustered()) { - updateCacheManagerPoolSizes(cacheManager); - } - - if (register) { - registerCacheConfiguration(cacheManager); - } - if (cacheManager.getConfiguration().isMaxBytesLocalHeapSet() || cacheManager.getConfiguration().isMaxBytesLocalDiskSet()) { - /*Adding Ourself as the first listener the order of the listener is - important as DefaultCacheConfigurationListener does validation checking on pool sizes*/ - addConfigurationListener(new DefaultCacheConfigurationListener(cacheManager)); - } - - consolidatePersistenceSettings(cacheManager); - - if (overflowToOffHeap == null && (cacheManager.getConfiguration().isMaxBytesLocalOffHeapSet() || getMaxBytesLocalOffHeap() > 0)) { - overflowToOffHeap = true; - } - if ((persistenceConfiguration != null && Strategy.LOCALTEMPSWAP.equals(persistenceConfiguration.getStrategy()))) { - overflowToDisk = true; - } - if (overflowToDisk == null && cacheManager.getConfiguration().isMaxBytesLocalDiskSet() || getMaxBytesLocalDisk() > 0) { - if (persistenceConfiguration != null && Strategy.LOCALRESTARTABLE.equals(persistenceConfiguration.getStrategy())) { - throw new InvalidConfigurationException("Cannot use localRestartable persistence and disk overflow in the same cache"); - } else if (!isTerracottaClustered()) { - overflowToDisk = true; - } else { - LOG.warn("Clustered cache " + getName() + " will not use the local disk pool defined at cache manager level."); - } - } - warnMaxEntriesLocalHeap(register, cacheManager); - warnMaxEntriesForOverflowToOffHeap(register); - warnSizeOfPolicyConfiguration(); - freezePoolUsages(cacheManager); - warnTieredSizing(); - } - - private void consolidatePersistenceSettings(CacheManager manager) { - if (persistenceConfiguration == null) { - if (diskPersistent == Boolean.TRUE) { - persistenceConfiguration = new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP); - } - } else { - switch (persistenceConfiguration.getStrategy()) { - case DISTRIBUTED: - case NONE: - diskPersistent = Boolean.FALSE; - break; - case LOCALTEMPSWAP: - if (diskPersistent == null) { - diskPersistent = Boolean.FALSE; - } - break; - case LOCALRESTARTABLE: - diskPersistent = Boolean.TRUE; - break; - default: - break; - } - } - - if (persistenceConfiguration != null && persistenceConfiguration.getSynchronousWrites()) { - switch (persistenceConfiguration.getStrategy()) { - case NONE: - case LOCALTEMPSWAP: - throw new InvalidConfigurationException("Persistence: synchronousWrites=\"true\" is not supported " - + "with strategy \"localTempSwap\" or \"none\""); - default: - break; - } - } - } - - private void warnMaxEntriesForOverflowToOffHeap(final boolean register) { - if (overflowToOffHeap != null && overflowToOffHeap && register) { - if (getMaxEntriesLocalHeap() > 0 && getMaxEntriesLocalHeap() < MINIMUM_RECOMMENDED_IN_MEMORY) { - LOG.warn("The " + getName() + " cache is configured for off-heap and has a maxEntriesLocalHeap/maxElementsInMemory of " - + getMaxEntriesLocalHeap() + ". It is recommended to set maxEntriesLocalHeap/maxElementsInMemory to at least " - + MINIMUM_RECOMMENDED_IN_MEMORY + " elements when using an off-heap store, otherwise performance " - + "will be seriously degraded."); - } - } - } - - private void warnMaxEntriesLocalHeap(final boolean register, CacheManager cacheManager) { - if (getMaxEntriesLocalHeap() == 0 && register) { - if (getMaxBytesLocalHeap() == 0 && (!cacheManager.getConfiguration().isMaxBytesLocalHeapSet())) { - LOG.warn("Cache: " + getName() + - " has a maxElementsInMemory of 0. This might lead to performance degradation or OutOfMemoryError at Terracotta client." + - "From Ehcache 2.0 onwards this has been changed to mean a store" + - " with no capacity limit. Set it to 1 if you want" + - " no elements cached in memory"); - } - } - } - - private void warnSizeOfPolicyConfiguration() { - if (isTerracottaClustered() && getSizeOfPolicyConfiguration() != null) { - LOG.warn("Terracotta clustered cache: " + getName() + " has a sizeOf policy configuration specificed. " + - "SizeOfPolicyConfiguration is unsupported for Terracotta clustered caches."); - } - } - - private void freezePoolUsages(final CacheManager cacheManager) { - if (getMaxBytesLocalHeap() > 0) { - onHeapPoolUsage = CacheConfiguration.PoolUsage.Cache; - } else if (cacheManager.getConfiguration().isMaxBytesLocalHeapSet()) { - onHeapPoolUsage = CacheConfiguration.PoolUsage.CacheManager; - } else { - onHeapPoolUsage = CacheConfiguration.PoolUsage.None; - } - - if (getMaxBytesLocalOffHeap() > 0) { - offHeapPoolUsage = CacheConfiguration.PoolUsage.Cache; - } else if (cacheManager.getConfiguration().isMaxBytesLocalOffHeapSet()) { - offHeapPoolUsage = CacheConfiguration.PoolUsage.CacheManager; - } else { - offHeapPoolUsage = CacheConfiguration.PoolUsage.None; - } - - if (isTerracottaClustered()) { - onDiskPoolUsage = CacheConfiguration.PoolUsage.None; - } else { - if (getMaxBytesLocalDisk() > 0) { - onDiskPoolUsage = CacheConfiguration.PoolUsage.Cache; - } else if (cacheManager.getConfiguration().isMaxBytesLocalDiskSet()) { - onDiskPoolUsage = CacheConfiguration.PoolUsage.CacheManager; - } else { - onDiskPoolUsage = CacheConfiguration.PoolUsage.None; - } - } - } - - private void warnTieredSizing() { - if (isOverflowToOffHeap()) { - if (getMaxBytesLocalHeap() >= getMaxBytesLocalOffHeap() && getMaxBytesLocalOffHeap() != 0) { - LOG.warn("Configuration problem for cache " + getName() + ": MaxBytesLocalHeap equal or greater than MaxBytesLocalOffHeap. " + - "This will result in useless off heap storage."); - } - if (isOverflowToDisk()) { - if (getMaxBytesLocalOffHeap() >= getMaxBytesLocalDisk() && getMaxBytesLocalDisk() != 0) { - LOG.warn("Configuration problem for cache " + getName() + ": MaxBytesLocalOffHeap equal or greater than MaxBytesLocalDisk. " + - "This will result in useless disk storage."); - } - } - } - - if (isOverflowToDisk()) { - if (getMaxEntriesLocalHeap() >= getMaxEntriesLocalDisk() && getMaxEntriesLocalDisk() != 0) { - LOG.warn("Configuration problem for cache " + getName() + ": MaxEntriesLocalHeap equal or greater than MaxEntriesLocalDisk. " + - "This will result in useless disk storage."); - } - } - - } - - private void registerCacheConfiguration(final CacheManager cacheManager) { - Map configMap = cacheManager.getConfiguration().getCacheConfigurations(); - if (!configMap.containsKey(getName())) { - cacheManager.getConfiguration().addCache(this, false); - } - } - - private void updateCacheManagerPoolSizes(final CacheManager cacheManager) { - if (cacheManager.getOnHeapPool() != null) { - cacheManager.getOnHeapPool().setMaxSize(cacheManager.getOnHeapPool().getMaxSize() - getMaxBytesLocalHeap()); - } - if (cacheManager.getOnDiskPool() != null) { - cacheManager.getOnDiskPool().setMaxSize(cacheManager.getOnDiskPool().getMaxSize() - getMaxBytesLocalDisk()); - } - } - - /** - * Will verify that we don't overallocate pools - * @param cacheManager The cacheManager that will manage the cache - * @param managerMaxBytesLocalHeap bytes for local heap - * @param managerMaxBytesLocalOffHeap bytes for local offheap - * @param managerMaxBytesLocalDisk bytes for local disk - * @param parentCacheName cacheName for parentCache to be used when initializing shadow caches - * @return a list with potential errors - */ - List verifyPoolAllocationsBeforeAddingTo(CacheManager cacheManager, - long managerMaxBytesLocalHeap, - long managerMaxBytesLocalOffHeap, - long managerMaxBytesLocalDisk, - String parentCacheName) { - final List configErrors = new ArrayList(); - - long totalOnHeapAssignedMemory = 0; - long totalOffHeapAssignedMemory = 0; - long totalOnDiskAssignedMemory = 0; - - boolean isUpdate = false; - for (Cache cache : getAllActiveCaches(cacheManager)) { - if (cache.getName().equals(parentCacheName)) { - // Do not add parent cache when calculating memory requirements for shadow cache. - continue; - } - isUpdate = cache.getName().equals(getName()) || isUpdate; - final CacheConfiguration config = cache.getCacheConfiguration(); - totalOnHeapAssignedMemory += config.getMaxBytesLocalHeap(); - totalOffHeapAssignedMemory += config.getMaxBytesLocalOffHeap(); - totalOnDiskAssignedMemory += config.getMaxBytesLocalDisk(); - } - - if (!isUpdate) { - totalOnHeapAssignedMemory += getMaxBytesLocalHeap(); - totalOffHeapAssignedMemory += getMaxBytesLocalOffHeap(); - totalOnDiskAssignedMemory += getMaxBytesLocalDisk(); - } - - verifyLocalHeap(managerMaxBytesLocalHeap, configErrors, totalOnHeapAssignedMemory); - verifyLocalOffHeap(managerMaxBytesLocalOffHeap, configErrors, totalOffHeapAssignedMemory); - verifyLocalDisk(managerMaxBytesLocalDisk, configErrors, totalOnDiskAssignedMemory); - - if (managerMaxBytesLocalHeap > 0 && managerMaxBytesLocalHeap - totalOnHeapAssignedMemory == 0) { - LOG.warn("All the onHeap memory has been assigned, there is none left for dynamically added caches"); - } - - if (Runtime.getRuntime().maxMemory() - totalOnHeapAssignedMemory < 0) { - // todo this could be a nicer message (with actual values) - configErrors.add(new ConfigError("You've assigned more memory to the on-heap than the VM can sustain, " + - "please adjust your -Xmx setting accordingly")); - } - - if (totalOnHeapAssignedMemory / (float) Runtime.getRuntime().maxMemory() > CacheManager.ON_HEAP_THRESHOLD) { - LOG.warn("You've assigned over 80% of your VM's heap to be used by the cache!"); - } - - return configErrors; - } - - private void verifyLocalDisk(final long managerMaxBytesLocalDisk, - final List configErrors, final long totalOnDiskAssignedMemory) { - if ((isMaxBytesLocalDiskPercentageSet() || getMaxBytesLocalDisk() > 0) - && managerMaxBytesLocalDisk > 0 && managerMaxBytesLocalDisk - totalOnDiskAssignedMemory < 0) { - configErrors.add(new ConfigError("Cache '" + getName() - + "' over-allocates CacheManager's localOnDisk limit!")); - } - } - - private void verifyLocalOffHeap(final long managerMaxBytesLocalOffHeap, - final List configErrors, final long totalOffHeapAssignedMemory) { - if ((isMaxBytesLocalOffHeapPercentageSet() || getMaxBytesLocalOffHeap() > 0) - && managerMaxBytesLocalOffHeap > 0 && managerMaxBytesLocalOffHeap - totalOffHeapAssignedMemory < 0) { - configErrors.add(new ConfigError("Cache '" + getName() - + "' over-allocates CacheManager's localOffHeap limit!")); - } - } - - private void verifyLocalHeap(final long managerMaxBytesLocalHeap, - final List configErrors, final long totalOnHeapAssignedMemory) { - if ((isMaxBytesLocalHeapPercentageSet() || getMaxBytesLocalHeap() > 0) - && managerMaxBytesLocalHeap > 0 && managerMaxBytesLocalHeap - totalOnHeapAssignedMemory < 0) { - configErrors.add(new ConfigError("Cache '" + getName() - + "' over-allocates CacheManager's localOnHeap limit!")); - } - } - - /** - * Configures the cache pools - * @param configuration the Configuration of the CacheManager managing this cache - */ - void configCachePools(Configuration configuration) { - - long cacheAssignedMem; - if (getMaxBytesLocalHeapPercentage() != null) { - cacheAssignedMem = configuration.getMaxBytesLocalHeap() * getMaxBytesLocalHeapPercentage() / HUNDRED_PERCENT; - setMaxBytesLocalHeap(cacheAssignedMem); - } - - if (offHeapPoolUsage == null && getMaxBytesLocalOffHeapPercentage() != null) { - cacheAssignedMem = configuration.getMaxBytesLocalOffHeap() * getMaxBytesLocalOffHeapPercentage() / HUNDRED_PERCENT; - setMaxBytesLocalOffHeap(cacheAssignedMem); - } - - if (getMaxBytesLocalDiskPercentage() != null) { - cacheAssignedMem = configuration.getMaxBytesLocalDisk() * getMaxBytesLocalDiskPercentage() / HUNDRED_PERCENT; - setMaxBytesLocalDisk(cacheAssignedMem); - } - - } - - /** - * Validates the configuration - * @param configuration the CacheManager configuration this is going to be used with - * @return the errors in the config - */ - public Collection validate(final Configuration configuration) { - - final Collection errors = new ArrayList(); - - verifyClusteredCacheConfiguration(errors); - - if (maxEntriesLocalHeap == null && !configuration.isMaxBytesLocalHeapSet() && maxBytesLocalHeap == null) { - errors.add(new CacheConfigError("If your CacheManager has no maxBytesLocalHeap set, you need to either set " + - "maxEntriesLocalHeap or maxBytesLocalHeap at the Cache level", getName())); - } - - if (configuration.isMaxBytesLocalHeapSet() && Runtime.getRuntime().maxMemory() - configuration.getMaxBytesLocalHeap() < 0) { - errors.add(new ConfigError("You've assigned more memory to the on-heap than the VM can sustain, " + - "please adjust your -Xmx setting accordingly")); - } - - if (maxEntriesInCache != DEFAULT_MAX_ENTRIES_IN_CACHE) { - if (!isTerracottaClustered()) { - errors.add(new CacheConfigError("maxEntriesInCache is not applicable to unclustered caches.", getName())); - } - } - - //commenting this check until fixed for cachemanger is fixed - //if (isOverflowToOffHeapSet() && !maxBytesLocalOffHeapExplicitlySet) { - // errors.add(new CacheConfigError("\"overFlowToOffHeap\" is set, but \"maxBytesLocalOffHeap\" is not set.", getName())); - //} - - if (persistenceConfiguration != null && persistenceConfiguration.getStrategy() == null) { - errors.add(new CacheConfigError("Persistence configuration found with no strategy set.", getName())); - } - - errors.addAll(validateCachePools(configuration)); - - return errors; - } - - private void verifyClusteredCacheConfiguration(final Collection errors) { - if (!isTerracottaClustered()) { return; } - - if (getPinningConfiguration() != null && getPinningConfiguration().getStore() == PinningConfiguration.Store.INCACHE - && getMaxElementsOnDisk() != 0) { - errors.add(new CacheConfigError("maxElementsOnDisk may not be used on a pinned cache.", getName())); - } - - if (maxEntriesLocalDiskExplicitlySet) { - errors.add(new CacheConfigError("You can't set maxEntriesLocalDisk when clustering your cache with Terracotta, " + - "local disks won't be used! To control elements going in the cache cluster wide, " + - "use maxEntriesInCache instead", getName())); - } - - - if (maxBytesLocalDiskExplicitlySet) { - errors.add(new CacheConfigError("You can't set maxBytesLocalDisk when clustering your cache with Terracotta", - getName())); - } - - if (maxElementsOnDisk != DEFAULT_MAX_ELEMENTS_ON_DISK) { - errors.add(new CacheConfigError("maxElementsOnDisk is not used with clustered caches. Use maxEntriesInCache " + - "to set maximum cache size.", getName())); - } - } - - /** - * Validates the CacheConfiguration against the CacheManager's Configuration - * @param configuration The CacheManager Configuration - * @return the list of errors encountered, or an empty list - */ - List validateCachePools(final Configuration configuration) { - List errors = new ArrayList(); - - if (configuration.isMaxBytesLocalHeapSet() - && getMaxEntriesLocalHeap() > 0) { - errors.add(new CacheConfigError("maxEntriesLocalHeap is not compatible with " + - "maxBytesLocalHeap set on cache manager", getName())); - } - if (getMaxBytesLocalHeap() > 0 && getMaxEntriesLocalHeap() > 0) { - errors.add(new CacheConfigError("maxEntriesLocalHeap is not compatible with " + - "maxBytesLocalHeap set on cache", getName())); - } - if (isMaxBytesLocalHeapPercentageSet() && !configuration.isMaxBytesLocalHeapSet()) { - errors.add(new CacheConfigError("Defines a percentage maxBytesOnHeap value but no CacheManager " + - "wide value was configured", getName())); - } - if (isMaxBytesLocalOffHeapPercentageSet() && !configuration.isMaxBytesLocalOffHeapSet()) { - errors.add(new CacheConfigError("Defines a percentage maxBytesOffHeap value but no CacheManager " + - "wide value was configured", getName())); - } - if (isMaxBytesLocalDiskPercentageSet() && !configuration.isMaxBytesLocalDiskSet()) { - errors.add(new CacheConfigError("Defines a percentage maxBytesOnDisk value but no CacheManager " + - "wide value was configured", getName())); - } - return errors; - } - - /** - * Whether this cache is Count based - * @return true if maxEntries set, false otherwise - */ - public boolean isCountBasedTuned() { - return (maxEntriesLocalHeap != null && maxEntriesLocalHeap > 0) || maxElementsOnDisk > 0; - } - - /** - * Checks whether the overflowing to off heap behavior was explicitly set - * @return true if explicitly set, false otherwise - */ - public boolean isOverflowToOffHeapSet() { - return overflowToOffHeap != null; - } - - - /** - * Configuration for the CacheEventListenerFactory. - */ - public static final class CacheEventListenerFactoryConfiguration extends FactoryConfiguration { - private NotificationScope notificationScope = NotificationScope.ALL; - - /** - * Used by BeanHandler to set the mode during parsing. Convert listenFor string to uppercase and - * look up enum constant in NotificationScope. - */ - public void setListenFor(String listenFor) { - if (listenFor == null) { - throw new IllegalArgumentException("listenFor must be non-null"); - } - this.notificationScope = NotificationScope.valueOf(NotificationScope.class, listenFor.toUpperCase()); - } - - /** - * @return this factory configuration instance - * @see #setListenFor(String) - */ - public final CacheEventListenerFactoryConfiguration listenFor(String listenFor) { - setListenFor(listenFor); - return this; - } - - /** - * Get the value mode in terms of the mode enum - */ - public NotificationScope getListenFor() { - return this.notificationScope; - } - } - - /** - * Used by BeanUtils to add cacheEventListenerFactory elements to the cache configuration. - */ - public final void addCacheEventListenerFactory(CacheEventListenerFactoryConfiguration factory) { - checkDynamicChange(); - cacheEventListenerConfigurations.add(factory); - validateConfiguration(); - } - - /** - * @return this configuration instance - * @see #addCacheEventListenerFactory(CacheEventListenerFactoryConfiguration) - */ - public final CacheConfiguration cacheEventListenerFactory(CacheEventListenerFactoryConfiguration factory) { - addCacheEventListenerFactory(factory); - return this; - } - - /** - * Configuration for the CacheExtensionFactoryConfiguration. - */ - public static final class CacheExtensionFactoryConfiguration extends FactoryConfiguration { - } - - /** - * Used by BeanUtils to add cacheExtensionFactory elements to the cache configuration. - */ - public final void addCacheExtensionFactory(CacheExtensionFactoryConfiguration factory) { - checkDynamicChange(); - cacheExtensionConfigurations.add(factory); - } - - /** - * @return this configuration instance - * @see #addCacheExtensionFactory(CacheExtensionFactoryConfiguration) - */ - public final CacheConfiguration cacheExtensionFactory(CacheExtensionFactoryConfiguration factory) { - /** - * {@inheritDoc} - */ - addCacheExtensionFactory(factory); - return this; - } - - /** - * Configuration for the BootstrapCacheLoaderFactoryConfiguration. - */ - public static final class BootstrapCacheLoaderFactoryConfiguration extends - FactoryConfiguration { - } - - /** - * Allows BeanHandler to add the CacheManagerEventListener to the configuration. - */ - public final void addBootstrapCacheLoaderFactory(BootstrapCacheLoaderFactoryConfiguration factory) { - checkDynamicChange(); - this.bootstrapCacheLoaderFactoryConfiguration = factory; - } - - /** - * @return this configuration instance - * @see #addBootstrapCacheLoaderFactory(BootstrapCacheLoaderFactoryConfiguration) - */ - public final CacheConfiguration bootstrapCacheLoaderFactory(BootstrapCacheLoaderFactoryConfiguration factory) { - addBootstrapCacheLoaderFactory(factory); - return this; - } - - /** - * Configuration for the BootstrapCacheLoaderFactoryConfiguration. - */ - public static final class CacheExceptionHandlerFactoryConfiguration extends - FactoryConfiguration { - } - - /** - * Add the CacheExceptionHandlerFactory to the configuration. - *

- * Note that this will not have any effect when creating a cache solely through its constructed. The exception - * handler will only be taken into account when {@link ConfigurationHelper} is used, for example through - * {@link net.sf.ehcache.CacheManager}. - */ - public final void addCacheExceptionHandlerFactory(CacheExceptionHandlerFactoryConfiguration factory) { - checkDynamicChange(); - this.cacheExceptionHandlerFactoryConfiguration = factory; - } - - /** - * @return this configuration instance - * @see #addCacheExceptionHandlerFactory(CacheExceptionHandlerFactoryConfiguration) - */ - public final CacheConfiguration cacheExceptionHandlerFactory(CacheExceptionHandlerFactoryConfiguration factory) { - addCacheExceptionHandlerFactory(factory); - return this; - } - - /** - * Configuration for the CacheLoaderFactoryConfiguration. - */ - public static final class CacheLoaderFactoryConfiguration extends FactoryConfiguration { - } - - /** - * Used by BeanUtils to add each cacheLoaderFactory to the cache configuration. - * - * @param factory - */ - public final void addCacheLoaderFactory(CacheLoaderFactoryConfiguration factory) { - checkDynamicChange(); - cacheLoaderConfigurations.add(factory); - } - - /** - * Configuration for the CacheDecoratorFactoryConfiguration. - */ - public static final class CacheDecoratorFactoryConfiguration extends FactoryConfiguration { - } - - /** - * Used by BeanUtils to add each cacheDecoratorFactory to the cache configuration. - * - * @param factory - */ - public final void addCacheDecoratorFactory(CacheDecoratorFactoryConfiguration factory) { - checkDynamicChange(); - cacheDecoratorConfigurations.add(factory); - } - - /** - * @return this configuration instance - * @see #addCacheLoaderFactory(CacheLoaderFactoryConfiguration) - */ - public final CacheConfiguration cacheLoaderFactory(CacheLoaderFactoryConfiguration factory) { - addCacheLoaderFactory(factory); - return this; - } - - /** - * Allows BeanHandler to add the TerracottaConfiguration to the configuration. - */ - public final void addTerracotta(TerracottaConfiguration terracottaConfiguration) { - this.terracottaConfiguration = terracottaConfiguration; - validateConfiguration(); - } - - /** - * Allows BeanHandler to add the PinningConfiguration to the configuration. - */ - public final void addPinning(PinningConfiguration pinningConfiguration) { - this.pinningConfiguration = pinningConfiguration; - validateConfiguration(); - } - - /** - * @return this configuration instance - * @see #addPinning(PinningConfiguration) - */ - public final CacheConfiguration pinning(PinningConfiguration pinningConfiguration) { - addPinning(pinningConfiguration); - return this; - } - - /** - * @return this configuration instance - * @see #addTerracotta(TerracottaConfiguration) - */ - public final CacheConfiguration terracotta(TerracottaConfiguration terracottaConfiguration) { - addTerracotta(terracottaConfiguration); - return this; - } - - /** - * @see #addSearchable(Searchable) - * @param searchable - * @return this - */ - public final CacheConfiguration searchable(Searchable searchable) { - addSearchable(searchable); - return this; - } - - /** - * Allows BeanHandler to add the CacheWriterConfiguration to the configuration. - */ - public final void addCacheWriter(CacheWriterConfiguration cacheWriterConfiguration) { - if (null == cacheWriterConfiguration) { - this.cacheWriterConfiguration = new CacheWriterConfiguration(); - } else { - this.cacheWriterConfiguration = cacheWriterConfiguration; - } - } - - /** - * @return this configuration instance - * @see #addCacheWriter(CacheWriterConfiguration) - */ - public final CacheConfiguration cacheWriter(CacheWriterConfiguration cacheWriterConfiguration) { - addCacheWriter(cacheWriterConfiguration); - return this; - } - - /** - * Sets the transactionalMode - * - * @param transactionalMode one of OFF, LOCAL, XA, XA_STRICT - */ - public final void setTransactionalMode(final String transactionalMode) { - assertArgumentNotNull("Cache transactionalMode", transactionalMode); - transactionalMode(TransactionalMode.valueOf(transactionalMode.toUpperCase())); - } - - /** - * Builder which sets the transactionalMode - * - * @param transactionalMode one of OFF, LOCAL, XA, XA_STRICT - * @return this configuration instance - * @see #setTransactionalMode(String) - */ - public final CacheConfiguration transactionalMode(String transactionalMode) { - setTransactionalMode(transactionalMode); - return this; - } - - /** - * Builder which sets the transactionalMode - * - * @param transactionalMode one of OFF, LOCAL, XA, XA_STRICT - * @return this configuration instance - * @see #setTransactionalMode(String) - */ - public final CacheConfiguration transactionalMode(TransactionalMode transactionalMode) { - if (transactionalMode == null) { - throw new IllegalArgumentException("TransactionalMode value must be non-null"); - } - if (this.transactionalMode != null) { - throw new InvalidConfigurationException("transactionalMode cannot be changed once set"); - } - this.transactionalMode = transactionalMode; - return this; - } - - /** - * Sets whether the cache's statistics are enabled. at startup - */ - @Deprecated - public final void setStatistics(boolean enabled) { - if (!enabled) { - LOG.warn("Statistics can no longer be enabled via configuration."); - return; - } - this.statistics = enabled; - } - - /** - * Builder which sets whether the cache's statistics are enabled. - * - * @return this configuration instance - * @see #setStatistics(boolean) - */ - @Deprecated - public final CacheConfiguration statistics(boolean statistics) { - setStatistics(statistics); - return this; - } - - /** - * Gets whether the cache's statistics will be enabled at startup - */ - public final boolean getStatistics() { - return true; - } - - /** - * Used to validate what should be a complete Cache Configuration. - */ - public void validateCompleteConfiguration() { - - validateConfiguration(); - - // Extra checks that a completed cache config should have - - if (name == null) { - throw new InvalidConfigurationException("Caches must be named."); - } - } - - /** - * Used to validate a Cache Configuration. - */ - public void validateConfiguration() { - if (terracottaConfiguration != null && terracottaConfiguration.isClustered()) { - if (overflowToDisk != null && overflowToDisk) { - throw new InvalidConfigurationException("overflowToDisk isn't supported for a clustered Terracotta cache"); - } - if (diskPersistent == Boolean.TRUE) { - throw new InvalidConfigurationException("diskPersistent isn't supported for a clustered Terracotta cache"); - } - if (persistenceConfiguration != null && !Strategy.DISTRIBUTED.equals(persistenceConfiguration.getStrategy())) { - throw new InvalidConfigurationException(persistenceConfiguration.getStrategy() + - " persistence strategy isn't supported for a clustered Terracotta cache"); - } - if (cacheEventListenerConfigurations != null) { - for (CacheEventListenerFactoryConfiguration listenerConfig : cacheEventListenerConfigurations) { - if (null == listenerConfig.getFullyQualifiedClassPath()) { - continue; - } - if (!listenerConfig.getFullyQualifiedClassPath().startsWith("net.sf.ehcache.") && - LOG.isWarnEnabled()) { - LOG.warn("The non-standard CacheEventListenerFactory '" + listenerConfig.getFullyQualifiedClassPath() + - "' is used with a clustered Terracotta cache, " + - "if the purpose of this listener is replication it is not supported in a clustered context"); - } - } - } - } - if (cacheWriterConfiguration != null) { - if (!cacheWriterConfiguration.getWriteBatching() && cacheWriterConfiguration.getWriteBatchSize() != 1) { - throw new InvalidConfigurationException("CacheWriter Batch Size !=1 and CacheWriter Batching " + - "turned off"); - } - } - } - - private void validateTransactionalSettings() { - boolean transactional = getTransactionalMode().isTransactional(); - if (copyOnRead == null) { - if (terracottaConfiguration != null && terracottaConfiguration.isCopyOnReadSet()) { - copyOnRead = terracottaConfiguration.isCopyOnRead(); - } else { - copyOnRead = transactional; - } - } - if (copyOnWrite == null) { - copyOnWrite = transactional; - } - - if (transactional) { - if (!copyOnRead || !copyOnWrite) { - throw new InvalidConfigurationException("A transactional cache has to be copyOnRead and copyOnWrite!"); - } - } - } - - /** - * Accessor - */ - public String getName() { - return name; - } - - /** - * Accessor - * - * @deprecated use {@link #getMaxEntriesLocalHeap()} - */ - @Deprecated - public int getMaxElementsInMemory() { - return (int)getMaxEntriesLocalHeap(); - } - - /** - * Accessor - */ - public long getCacheLoaderTimeoutMillis() { - return cacheLoaderTimeoutMillis; - } - - /** - * Accessor - * @deprecated use {@link #getMaxEntriesLocalDisk()} for unclustered caches and {@link #getMaxEntriesInCache()} for clustered caches. - */ - public int getMaxElementsOnDisk() { - return maxElementsOnDisk; - } - - /** - * Accessor - * - */ - public long getMaxEntriesInCache() { - return maxEntriesInCache; - } - - /** - * Configured maximum number of entries for the local disk store. - */ - public long getMaxEntriesLocalDisk() { - return maxElementsOnDisk; - } - - /** - * Configured maximum number of entries for the local memory heap. - */ - public long getMaxEntriesLocalHeap() { - return maxEntriesLocalHeap == null ? 0 : maxEntriesLocalHeap; - } - - /** - * Accessor - */ - public MemoryStoreEvictionPolicy getMemoryStoreEvictionPolicy() { - return memoryStoreEvictionPolicy; - } - - /** - * Accessor - */ - public boolean isClearOnFlush() { - return clearOnFlush; - } - - /** - * Accessor - */ - public boolean isEternal() { - return eternal; - } - - /** - * Accessor - */ - public long getTimeToIdleSeconds() { - return timeToIdleSeconds; - } - - /** - * Accessor - */ - public long getTimeToLiveSeconds() { - return timeToLiveSeconds; - } - - /** - * Accessor - * - * @deprecated The {@code overflowToDisk} attribute has been replaced with {@link Strategy#LOCALTEMPSWAP}. - */ - @Deprecated - public boolean isOverflowToDisk() { - return overflowToDisk == null ? false : overflowToDisk; - } - - /** - * Accessor - * - * @deprecated The {@code diskPersistent} attribute has been replaced with {@link #persistence(PersistenceConfiguration)}. - */ - @Deprecated - public boolean isDiskPersistent() { - Boolean persistent = diskPersistent; - return diskPersistent == null ? DEFAULT_DISK_PERSISTENT : persistent; - } - - /** - * Accessor - */ - public boolean isSearchable() { - return searchable != null; - } - - /** - * Accessor - */ - public int getDiskSpoolBufferSizeMB() { - return diskSpoolBufferSizeMB; - } - - /** - * Accessor - */ - public long getDiskExpiryThreadIntervalSeconds() { - return diskExpiryThreadIntervalSeconds; - } - - /** - * Accessor - */ - public int getDiskAccessStripes() { - return diskAccessStripes; - } - - /** - * Accessor - */ - public DynamicAttributesExtractor getDynamicExtractor() { - return flexIndexer; - } - /** - * Only used when cache is clustered with Terracotta - * - * @return true if logging is enabled otherwise false - */ - public boolean getLogging() { - return logging; - } - - /** - * Accessor - * - * @return true if offheap store is enabled, otherwise false. - */ - public boolean isOverflowToOffHeap() { - return overflowToOffHeap == null ? false : overflowToOffHeap; - } - - /** - * Accessor - * - * @return the SizeOfPolicy Configuration for this cache. - */ - public SizeOfPolicyConfiguration getSizeOfPolicyConfiguration() { - return sizeOfPolicyConfiguration; - } - - /** - * Accessor - * - * @return the persistence configuration for this cache. - */ - public PersistenceConfiguration getPersistenceConfiguration() { - return persistenceConfiguration; - } - - /** - * Accessor - * - * @return the max memory of the offheap store for this cache. - * @deprecated See {@link #getMaxBytesLocalOffHeapAsString()} - */ - @Deprecated - public String getMaxMemoryOffHeap() { - return maxBytesLocalOffHeapInput; - } - - /** - * Accessor - * - * @return the max memory of the offheap store for this cache, in bytes. - * @deprecated {@link #getMaxBytesLocalOffHeap()} - */ - @Deprecated - public long getMaxMemoryOffHeapInBytes() { - return getMaxBytesLocalOffHeap(); - } - - /** - * Accessor - */ - public List getCacheEventListenerConfigurations() { - return cacheEventListenerConfigurations; - } - - /** - * Accessor - * - * @return the configuration - */ - public List getCacheExtensionConfigurations() { - return cacheExtensionConfigurations; - } - - /** - * Accessor - * - * @return the configuration - */ - public List getCacheLoaderConfigurations() { - return cacheLoaderConfigurations; - } - - /** - * Accessor - * - * @return the configuration - */ - public List getCacheDecoratorConfigurations() { - return cacheDecoratorConfigurations; - } - - /** - * Accessor - * - * @return the configuration - */ - public BootstrapCacheLoaderFactoryConfiguration getBootstrapCacheLoaderFactoryConfiguration() { - return bootstrapCacheLoaderFactoryConfiguration; - } - - /** - * Accessor - * - * @return the configuration - */ - public CacheExceptionHandlerFactoryConfiguration getCacheExceptionHandlerFactoryConfiguration() { - return cacheExceptionHandlerFactoryConfiguration; - } - - /** - * Accessor - * - * @return the terracotta configuration - */ - public TerracottaConfiguration getTerracottaConfiguration() { - return terracottaConfiguration; - } - - /** - * Accessor - * - * @return the pinning configuration - */ - public PinningConfiguration getPinningConfiguration() { - return pinningConfiguration; - } - - /** - * Accessor - * - * @return the writer configuration - */ - public CacheWriterConfiguration getCacheWriterConfiguration() { - return cacheWriterConfiguration; - } - - /** - * Helper method to compute whether the cache is clustered or not - * - * @return True if the <terracotta/> element exists with {@code clustered="true"} - */ - public boolean isTerracottaClustered() { - return terracottaConfiguration != null && terracottaConfiguration.isClustered(); - } - - /** - * Accessor - * - * @return the CoherenceMode if Terracotta-clustered or null - */ - public Consistency getTerracottaConsistency() { - return terracottaConfiguration != null ? terracottaConfiguration.getConsistency() : null; - } - - /** - * To what transactionalMode was the Cache set - * - * @return transactionaMode - */ - public final TransactionalMode getTransactionalMode() { - if (transactionalMode == null) { - return DEFAULT_TRANSACTIONAL_MODE; - } - return transactionalMode; - } - - /** - * Helper method to compute whether the cache is XA transactional or not - * - * @return true if transactionalMode="xa_strict" - */ - public boolean isXaStrictTransactional() { - validateTransactionalSettings(); - return getTransactionalMode().equals(TransactionalMode.XA_STRICT); - } - - /** - * Helper method to compute whether the cache is local transactional or not - * - * @return true if transactionalMode="local" - */ - public boolean isLocalTransactional() { - validateTransactionalSettings(); - return getTransactionalMode().equals(TransactionalMode.LOCAL); - } - - /** - * Helper method to compute whether the cache is local_jta transactional or not - * - * @return true if transactionalMode="xa" - */ - public boolean isXaTransactional() { - validateTransactionalSettings(); - return getTransactionalMode().equals(TransactionalMode.XA); - } - - /** - * An enum to identify what pool a resource uses - */ - private static enum PoolUsage { - - CacheManager(true), Cache(true), None(false); - - private final boolean usingPool; - private PoolUsage(final boolean poolUser) { - this.usingPool = poolUser; - } - - public boolean isUsingPool() { - return usingPool; - } - } - /** - * Represents whether the Cache is transactional or not. - * - * @author alexsnaps - */ - public static enum TransactionalMode { - - /** - * No Transactions - */ - OFF(false), - - /** - * Local Transactions - */ - LOCAL(true), - - /** - * XA Transactions - */ - XA(true), - - /** - * XA Strict (true 2PC) Transactions - */ - XA_STRICT(true); - - private final boolean transactional; - - /** - * @param transactional - */ - TransactionalMode(final boolean transactional) { - this.transactional = transactional; - } - - /** - * @return transactional - */ - public boolean isTransactional() { - return transactional; - } - } - - /** - * Add a listener to this cache configuration - * - * @param listener listener instance to add - * @return true if a listener was added - */ - public boolean addConfigurationListener(CacheConfigurationListener listener) { - boolean added = listeners.add(listener); - if (added) { - listener.registered(this); - } - return added; - } - - /** - * Add a dynamic extractor configuration listener - * @param listener - * @return true if a listener was added - */ - public boolean addDynamicSearchListener(DynamicSearchListener listener) { - return dynamicSearchListeners.add(listener); - } - - /** - * Remove the supplied cache configuration listener. - * - * @param listener listener to remove - * @return true if a listener was removed - */ - public boolean removeConfigurationListener(CacheConfigurationListener listener) { - boolean removed = listeners.remove(listener); - if (removed) { - listener.deregistered(this); - } - return removed; - } - - private void fireTtiChanged(long oldTti, long newTti) { - if (oldTti != newTti) { - for (CacheConfigurationListener l : listeners) { - l.timeToIdleChanged(oldTti, newTti); - } - } - } - - private void fireTtlChanged(long oldTtl, long newTtl) { - if (oldTtl != newTtl) { - for (CacheConfigurationListener l : listeners) { - l.timeToLiveChanged(oldTtl, newTtl); - } - } - } - - private void fireLoggingChanged(boolean oldValue, boolean newValue) { - if (oldValue != newValue) { - for (CacheConfigurationListener l : listeners) { - l.loggingChanged(oldValue, newValue); - } - } - } - - private void fireDiskCapacityChanged(int oldCapacity, int newCapacity) { - if (oldCapacity != newCapacity) { - for (CacheConfigurationListener l : listeners) { - l.diskCapacityChanged(oldCapacity, newCapacity); - } - } - } - - private void fireMaxEntriesInCacheChanged(long oldCapacity, long newCapacity) { - if (oldCapacity != newCapacity) { - for (CacheConfigurationListener l : listeners) { - l.maxEntriesInCacheChanged(oldCapacity, newCapacity); - } - } - } - - private void fireMemoryCapacityChanged(int oldCapacity, int newCapacity) { - if (oldCapacity != newCapacity) { - for (CacheConfigurationListener l : listeners) { - l.memoryCapacityChanged(oldCapacity, newCapacity); - } - } - } - - private void checkDynamicChange() { - if (frozen) { - throw new CacheException("Dynamic configuration changes are disabled for this cache"); - } - } - - /** - * Intended for internal use only, and subject to change. - * This is required so that changes in store implementation's config - * (probably from other nodes) can propagate up to here - */ - public void internalSetTimeToIdle(long timeToIdle) { - this.timeToIdleSeconds = timeToIdle; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetTimeToLive(long timeToLive) { - this.timeToLiveSeconds = timeToLive; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetEternal(boolean eternal) { - this.eternal = eternal; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetMemCapacity(int capacity) { - this.maxEntriesLocalHeap = capacity; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetMemCapacityInBytes(long capacity) { - this.maxBytesLocalHeap = capacity; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetDiskCapacity(int capacity) { - this.maxElementsOnDisk = capacity; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetMaxEntriesInCache(int entries) { - this.maxEntriesInCache = entries; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetLogging(boolean logging) { - this.logging = logging; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetMaxBytesLocalOffheap(long maxBytesLocalOffheap) { - this.maxBytesLocalOffHeap = maxBytesLocalOffheap; - } - - /** - * Intended for internal use only, and subject to change. - */ - public void internalSetOverflowToOffheap(boolean overflowToOffHeap) { - this.overflowToOffHeap = overflowToOffHeap; - } - - /** - * Get the defined search attributes indexed by attribute name - * - * @return search attributes - */ - public Map getSearchAttributes() { - if (searchable == null) { - return Collections.emptyMap(); - } - return searchable.getSearchAttributes(); - } - - /** - * Get the search configuration for this cache (if any) - * - * @return search config (may be null) - */ - public Searchable getSearchable() { - return searchable; - } - - public ClassLoader getClassLoader() { - return this.classLoader; - } - - public void setClassLoader(ClassLoader classLoader) { - checkDynamicChange(); - this.classLoader = classLoader; - } - - /** - * Default listener class which handles the size changes of the cache - */ - private class DefaultCacheConfigurationListener extends AbstractCacheConfigurationListener { - private final CacheManager cacheManager; - - public DefaultCacheConfigurationListener(CacheManager cacheManager) { - this.cacheManager = cacheManager; - } - - @Override - public void maxBytesLocalHeapChanged(final long oldValue, final long newValue) { - if (getMaxBytesLocalHeap() > 0 - && cacheManager.getConfiguration().getCacheConfigurations().keySet().contains(getName()) - && cacheManager.getConfiguration().isMaxBytesLocalHeapSet()) { - long oldCacheManagerPoolSize = cacheManager.getOnHeapPool().getMaxSize(); - long newPoolFreeSize = oldCacheManagerPoolSize + oldValue - newValue; - //handle case of overallocation of cache - //Only resize the cache manager pool cache pool resizing will be handled by cache - if (newPoolFreeSize >= 0) { - cacheManager.getOnHeapPool().setMaxSize(newPoolFreeSize); - } else { - maxBytesLocalHeap = oldValue; - throw new InvalidConfigurationException("Cannot allocate heap size more " + - "than the cache pool size reverting to previous size " + maxBytesLocalHeap); - } - } - } - - @Override - public void maxBytesLocalDiskChanged(final long oldValue, final long newValue) { - if (getMaxBytesLocalDisk() > 0 - && cacheManager.getConfiguration().getCacheConfigurations().keySet().contains(getName()) - && cacheManager.getConfiguration().isMaxBytesLocalDiskSet()) { - long previous = cacheManager.getOnDiskPool().getMaxSize(); - long newPoolFreeSize = previous + oldValue - newValue; - //handle case of overallocation of cache - //Only resize the cache manager pool cache pool resizing will be handled by cache - if (newPoolFreeSize >= 0) { - cacheManager.getOnDiskPool().setMaxSize(newPoolFreeSize); - } else { - LOG.warn("Cannot allocate local disk size more than cache disk size, " + - "setting maxBytesLocalDisk {} to old value {}", maxBytesLocalDisk, oldValue); - maxBytesLocalDisk = oldValue; - throw new InvalidConfigurationException("Cannot allocate disk size more than " + - "the cache pool size reverting to previous size " + maxBytesLocalHeap); - } - } - } - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/ThreadKiller.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/ThreadKiller.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/ThreadKiller.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; - -import java.io.IOException; -import java.io.Serializable; - - -/** - * A class which throws a RuntimeException when serialized or deserialized. This - * should be enough to kill threads that do not have special handling. - * - * @author Greg Luck - * @version $Id: ThreadKiller.java 5594 2012-05-07 16:04:31Z cdennis $ - */ -public class ThreadKiller extends Object implements Serializable { - - private static final long serialVersionUID = 293659559026635155L; - - private void writeObject(java.io.ObjectOutputStream out) - throws IOException { - throw new Error("Thread killer strikes"); - - } - - private void readObject(java.io.ObjectInputStream in) - throws IOException, ClassNotFoundException { - throw new Error("Thread killer strikes"); - } - -} Index: rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/TerracottaToolkitBuilder.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/TerracottaToolkitBuilder.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/TerracottaToolkitBuilder.java (revision 0) @@ -1,200 +0,0 @@ -/* - * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. Licensed under the Apache - * License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain - * a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in - * writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS - * OF ANY KIND, either express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.terracotta.modules.ehcache; - -import org.terracotta.toolkit.Toolkit; -import org.terracotta.toolkit.ToolkitFactory; -import org.terracotta.toolkit.ToolkitInstantiationException; - -import java.util.Collections; -import java.util.HashSet; -import java.util.Properties; -import java.util.Set; - -public class TerracottaToolkitBuilder { - - private static final String TC_TUNNELLED_MBEAN_DOMAINS_KEY = "tunnelledMBeanDomains"; - private static final String TC_CONFIG_SNIPPET_KEY = "tcConfigSnippet"; - private static final String REJOIN_KEY = "rejoin"; - private static final String PRODUCT_ID_KEY = "productId"; - private static final String CLASSLOADER_KEY = "classloader"; - private static final String NONSTOP_INIT_ENABLED_KEY = "toolkit.nonstop.init.enabled"; - - private boolean rejoin; - private final TCConfigTypeStatus tcConfigTypeStatus = new TCConfigTypeStatus(); - private final Set tunnelledMBeanDomains = Collections.synchronizedSet(new HashSet()); - private String productId; - private ClassLoader classLoader; - private final boolean NONSTOP_INIT_ENABLED = Boolean.getBoolean(NONSTOP_INIT_ENABLED_KEY); - - public Toolkit buildToolkit() throws IllegalStateException { - if (tcConfigTypeStatus.getState() == TCConfigTypeState.INIT) { - // - throw new IllegalStateException( - "Please set the tcConfigSnippet or tcConfigUrl before attempting to create client"); - } - final String tcConfigOrUrl; - final boolean isUrl; - switch (tcConfigTypeStatus.getState()) { - case TC_CONFIG_SNIPPET: - tcConfigOrUrl = tcConfigTypeStatus.getTcConfigSnippet(); - isUrl = false; - break; - case TC_CONFIG_URL: - tcConfigOrUrl = tcConfigTypeStatus.getTcConfigUrl(); - isUrl = true; - break; - default: - throw new IllegalStateException("Unknown tc config type - " + tcConfigTypeStatus.getState()); - } - String toolkitUrl = createTerracottaToolkitUrl(isUrl, tcConfigOrUrl); - return createToolkit(toolkitUrl, getTerracottaToolkitProperties(isUrl, tcConfigOrUrl, classLoader)); - } - - private Toolkit createToolkit(String url, Properties props) { - try { - return ToolkitFactory.createToolkit(url, props); - } catch (ToolkitInstantiationException e) { - throw new RuntimeException(e); - } - } - - private Properties getTerracottaToolkitProperties(boolean isUrl, String tcConfigOrUrl, ClassLoader loader) { - Properties properties = new Properties(); - - if (loader != null) { - properties.put(CLASSLOADER_KEY, loader); - } - - properties.setProperty(TC_TUNNELLED_MBEAN_DOMAINS_KEY, getTunnelledDomainCSV()); - if (!isUrl) { - properties.setProperty(TC_CONFIG_SNIPPET_KEY, tcConfigOrUrl); - } - properties.setProperty(REJOIN_KEY, String.valueOf(rejoin)); - if (productId != null) { - properties.setProperty(PRODUCT_ID_KEY, productId); - } - properties.setProperty(NONSTOP_INIT_ENABLED_KEY, String.valueOf(NONSTOP_INIT_ENABLED)); - return properties; - } - - private String getTunnelledDomainCSV() { - StringBuilder sb = new StringBuilder(); - for (String domain : tunnelledMBeanDomains) { - sb.append(domain).append(","); - } - // remove last comma - return sb.deleteCharAt(sb.length() - 1).toString(); - } - - private String createTerracottaToolkitUrl(boolean isUrl, String tcConfigOrUrl) { - if (isUrl) { - return "toolkit:nonstop-terracotta://" + tcConfigOrUrl; - } else { - return "toolkit:nonstop-terracotta:"; - } - } - - public TerracottaToolkitBuilder addTunnelledMBeanDomain(String tunnelledMBeanDomain) { - this.tunnelledMBeanDomains.add(tunnelledMBeanDomain); - return this; - } - - public Set getTunnelledMBeanDomains() { - return Collections.unmodifiableSet(tunnelledMBeanDomains); - } - - public TerracottaToolkitBuilder removeTunnelledMBeanDomain(String tunnelledMBeanDomain) { - tunnelledMBeanDomains.remove(tunnelledMBeanDomain); - return this; - } - - public TerracottaToolkitBuilder setTCConfigSnippet(String tcConfig) throws IllegalStateException { - tcConfigTypeStatus.setTcConfigSnippet(tcConfig); - return this; - } - - public String getTCConfigSnippet() { - return tcConfigTypeStatus.getTcConfigSnippet(); - } - - public TerracottaToolkitBuilder setTCConfigUrl(String tcConfigUrl) throws IllegalStateException { - tcConfigTypeStatus.setTcConfigUrl(tcConfigUrl); - return this; - } - - public String getTCConfigUrl() { - return tcConfigTypeStatus.getTcConfigUrl(); - } - - public boolean isConfigUrl() { - return tcConfigTypeStatus.getState() == TCConfigTypeState.TC_CONFIG_URL; - } - - private static enum TCConfigTypeState { - INIT, TC_CONFIG_SNIPPET, TC_CONFIG_URL; - } - - private static class TCConfigTypeStatus { - private TCConfigTypeState state = TCConfigTypeState.INIT; - - private String tcConfigSnippet; - private String tcConfigUrl; - - public synchronized void setTcConfigSnippet(String tcConfigSnippet) { - if (state == TCConfigTypeState.TC_CONFIG_URL) { - // - throw new IllegalStateException("TCConfig url was already set to - " + tcConfigUrl); - } - this.state = TCConfigTypeState.TC_CONFIG_SNIPPET; - this.tcConfigSnippet = tcConfigSnippet; - } - - public synchronized void setTcConfigUrl(String tcConfigUrl) { - if (state == TCConfigTypeState.TC_CONFIG_SNIPPET) { - // - throw new IllegalStateException("TCConfig snippet was already set to - " + tcConfigSnippet); - } - this.state = TCConfigTypeState.TC_CONFIG_URL; - this.tcConfigUrl = tcConfigUrl; - } - - public synchronized String getTcConfigSnippet() { - return tcConfigSnippet; - } - - public synchronized String getTcConfigUrl() { - return tcConfigUrl; - } - - public TCConfigTypeState getState() { - return state; - } - - } - - public void setRejoinEnabled(boolean rejoin) { - this.rejoin = rejoin; - } - - public String getProductId() { - return productId; - } - - public TerracottaToolkitBuilder setClassLoader(ClassLoader loader) { - this.classLoader = loader; - return this; - } - - public TerracottaToolkitBuilder setProductId(final String productId) { - this.productId = productId; - return this; - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/StoreQuery.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/StoreQuery.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/main/java/net/sf/ehcache/store/StoreQuery.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.store; - -import java.util.List; -import java.util.Set; - -import net.sf.ehcache.Cache; -import net.sf.ehcache.search.Attribute; -import net.sf.ehcache.search.Direction; -import net.sf.ehcache.search.ExecutionHints; -import net.sf.ehcache.search.aggregator.Aggregator; -import net.sf.ehcache.search.aggregator.AggregatorInstance; -import net.sf.ehcache.search.expression.Criteria; - -/** - * An immutable query that a {@link Store} can execute - * - * @author teck - */ -public interface StoreQuery { - - /** - * Get the search criteria - * - * @return the search criteria - */ - Criteria getCriteria(); - - /** - * Are keys requested? - * - * @return true if keys requested - */ - boolean requestsKeys(); - - /** - * Are values requested? - * - * @return true if values requested - */ - boolean requestsValues(); - - /** - * Get the cache this query originated from - * - * @return cache - */ - Cache getCache(); - - /** - * This needs to be cleaned up. We don't want to introduce any kind of ordering here, as there simply is none. - *

- * Meanwhile, this is used to keep the ordering on BMQL created Queries. Yet, {@link net.sf.ehcache.search.query.QueryManagerBuilder - * QueryManagerBuilder}, which creates the {@link net.sf.ehcache.search.query.QueryManager QueryManager}, doesn't let us qualify the - * {@link net.sf.ehcache.search.Query Query} type further to add this "ordering" concept of "targets" to it.
- * And this "ordering" shouldn't become part of the QueryManager API neither as each implementation might require something different. - * - * @return select target names, searchAttribute or aggregator - * @see API-43 - * @deprecated - */ - @Deprecated - String[] getTargets(); - - /** - * Set the names of the select targets. These will either be searchAttribute names or - * aggregator display names, eg. 'ave(salary)' - * - * This is used by BMQL to form the return results. - * @deprecated - * @see StoreQuery#getTargets() - */ - @Deprecated - void targets(String[] targets); - - - /** - * Get the set of attributes requested by this query - * - * @return the requested attributes (if any) - */ - Set> requestedAttributes(); - - /** - * Get the set of attributes to group result set by - * @return attributes to group by (if any) - * @since 2.6 - */ - Set> groupByAttributes(); - - /** - * Get the requested search orderings - * - * @return the request sort orders (if any) - */ - List getOrdering(); - - /** - * Get the maximum number of results to return - * - * @return max results. A negative number means unlimited results - */ - int maxResults(); - - /** - * Get the requested aggregators - * - * @return the include aggregators (if any) - */ - List getAggregators(); - - /** - * Get execution hints for this query - * @return null if no hints were provided - */ - ExecutionHints getExecutionHints(); - - /** - * Get the requested aggregator instances - * - * @return the include aggregator instances (if any) - */ - List> getAggregatorInstances(); - - /** - * An attribute / direction ordering pair - */ - public interface Ordering { - /** - * Attribute to order by - * - * @return attribute - */ - Attribute getAttribute(); - - /** - * Ordering direction - * - * @return direction - */ - Direction getDirection(); - } - -} Index: rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/FilteredSizeOfTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/FilteredSizeOfTest.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/FilteredSizeOfTest.java (revision 0) @@ -1,269 +0,0 @@ -package net.sf.ehcache.pool.sizeof; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.net.URLClassLoader; - -import net.sf.ehcache.pool.SizeOfEngine; -import net.sf.ehcache.pool.impl.DefaultSizeOfEngine; -import net.sf.ehcache.pool.sizeof.annotationfiltered.AnnotationFilteredPackage; -import net.sf.ehcache.pool.sizeof.annotationfiltered.custom.CustomAnnotationFilteredPackage; -import net.sf.ehcache.pool.sizeof.filter.AnnotationSizeOfFilter; -import net.sf.ehcache.pool.sizeof.annotations.IgnoreSizeOf; -import net.sf.ehcache.pool.sizeof.filter.ResourceSizeOfFilter; -import net.sf.ehcache.pool.sizeof.resourcefiltered.ResourceFilteredPackage; - -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.Test; - -import static org.hamcrest.CoreMatchers.allOf; -import static org.hamcrest.core.IsEqual.equalTo; -import static org.hamcrest.core.IsInstanceOf.instanceOf; -import static org.hamcrest.number.OrderingComparison.greaterThan; -import static org.hamcrest.number.OrderingComparison.lessThan; -import static org.junit.Assert.assertThat; - -public class FilteredSizeOfTest extends AbstractSizeOfTest { - - private static long deepSizeOf(SizeOf sizeOf, Object... obj) { - return sizeOf.deepSizeOf(1000, true, obj).getCalculated(); - } - - @BeforeClass - public static void setup() { - deepSizeOf(new CrossCheckingSizeOf(), new Object()); - System.out.println("Testing for a " + System.getProperty("java.version") + " JDK " - + ") on a " + System.getProperty("sun.arch.data.model") + "-bit VM " - + "(compressed-oops: " + COMPRESSED_OOPS - + ", Hotspot CMS: " + HOTSPOT_CMS - + ")"); - } - - @Test - public void testAnnotationFiltering() throws Exception { - SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); - - assertThat(deepSizeOf(sizeOf, new AnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); - assertThat(deepSizeOf(sizeOf, new AnnotationFilteredClass()), equalTo(0L)); - assertThat(deepSizeOf(sizeOf, new AnnotationFilteredPackage()), equalTo(0L)); - - assertThat(deepSizeOf(sizeOf, new AnnotationFilteredFieldSubclass()), allOf(greaterThan(128L), lessThan(16 * 1024L))); - - long emptyReferrerSize = deepSizeOf(sizeOf, new Referrer(null)); - assertThat(deepSizeOf(sizeOf, new Referrer(new AnnotationFilteredClass())), equalTo(emptyReferrerSize)); - assertThat(deepSizeOf(sizeOf, new Referrer(new AnnotationFilteredPackage())), equalTo(emptyReferrerSize)); - assertThat(deepSizeOf(sizeOf, new Parent()), equalTo(0L)); - assertThat(deepSizeOf(sizeOf, new Child()), equalTo(0L)); - assertThat(deepSizeOf(sizeOf, new ChildChild()), equalTo(0L)); - assertThat(deepSizeOf(sizeOf, new ChildChildChild()), equalTo(0L)); - } - - @Test - public void testCustomAnnotationFiltering() throws Exception { - SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); - assertThat(deepSizeOf(sizeOf, new MatchingPatternOrNotAnnotationFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); - assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotation()), equalTo(0L)); - assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotationChild()), equalTo(0L)); - assertThat(deepSizeOf(sizeOf, new MatchingPatternAnnotationNoInheritedChild()), allOf(greaterThan(4L))); - assertThat(deepSizeOf(sizeOf, new NonMatchingPatternAnnotation1()), allOf(greaterThan(4L))); - assertThat(deepSizeOf(sizeOf, new NonMatchingPatternAnnotation2()), allOf(greaterThan(4L))); - assertThat(deepSizeOf(sizeOf, new CustomAnnotationFilteredPackage()), equalTo(0L)); - } - - @Test(expected=IllegalStateException.class) - public void testNotPossibleToHaveTwoIgnoreSizeOfAnnotations() throws Exception { - SizeOf sizeOf = new CrossCheckingSizeOf(new AnnotationSizeOfFilter()); - deepSizeOf(sizeOf, new AnnotatedTwice()); - } - - @Test - public void testResourceFiltering() throws Exception { - SizeOf sizeOf = new CrossCheckingSizeOf(new ResourceSizeOfFilter(FilteredSizeOfTest.class.getClassLoader().getResource("sizeof.filter.fields"))); - - assertThat(deepSizeOf(sizeOf, new ResourceFilteredField()), allOf(greaterThan(128L), lessThan(16 * 1024L))); - assertThat(deepSizeOf(sizeOf, new ResourceFilteredClass()), equalTo(0L)); - assertThat(deepSizeOf(sizeOf, new ResourceFilteredPackage()), equalTo(0L)); - - assertThat(deepSizeOf(sizeOf, new ResourceFilteredFieldSubclass()), allOf(greaterThan(128L), lessThan(16 * 1024L))); - - long emptyReferrerSize = deepSizeOf(sizeOf, new Referrer(null)); - assertThat(deepSizeOf(sizeOf, new Referrer(new ResourceFilteredClass())), equalTo(emptyReferrerSize)); - assertThat(deepSizeOf(sizeOf, new Referrer(new ResourceFilteredPackage())), equalTo(emptyReferrerSize)); - } - - private static SizeOfEngine getLoaderIsolatedEngine(int depth, boolean abort) { - ClassLoader current = FilteredSizeOfTest.class.getClassLoader(); - Assume.assumeThat(current, instanceOf(URLClassLoader.class)); - ClassLoader mirror = new URLClassLoader(((URLClassLoader) current).getURLs(), current) { - - @Override - protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if ("net.sf.ehcache.pool.impl.DefaultSizeOfEngine".equals(name)) { - Class klazz = findLoadedClass(name); - if (klazz == null) { - klazz = findClass(name); - if (resolve) { - resolveClass(klazz); - } - } - return klazz; - } else { - return super.loadClass(name, resolve); - } - } - }; - - try { - return (SizeOfEngine) mirror.loadClass("net.sf.ehcache.pool.impl.DefaultSizeOfEngine").getConstructor(Integer.TYPE, Boolean.TYPE).newInstance(1000, false); - } catch (Exception ex) { - throw new AssertionError(ex); - } - } - - private static void testSizeOfEngineFiltering(String filter) { - System.setProperty(DefaultSizeOfEngine.USER_FILTER_RESOURCE, filter); - try { - SizeOfEngine engine = getLoaderIsolatedEngine(1000, false); - - assertThat(engine.sizeOf(new ResourceFilteredField(), null, null).getCalculated(), allOf(greaterThan(128L), lessThan(16 * 1024L))); - assertThat(engine.sizeOf(new ResourceFilteredClass(), null, null).getCalculated(), equalTo(0L)); - assertThat(engine.sizeOf(new ResourceFilteredPackage(), null, null).getCalculated(), equalTo(0L)); - - assertThat(engine.sizeOf(new ResourceFilteredFieldSubclass(), null, null).getCalculated(), allOf(greaterThan(128L), lessThan(16 * 1024L))); - - long emptyReferrerSize = engine.sizeOf(new Referrer(null), null, null).getCalculated(); - assertThat(engine.sizeOf(new Referrer(new ResourceFilteredClass()), null, null).getCalculated(), equalTo(emptyReferrerSize)); - assertThat(engine.sizeOf(new Referrer(new ResourceFilteredPackage()), null, null).getCalculated(), equalTo(emptyReferrerSize)); - } finally { - System.clearProperty(DefaultSizeOfEngine.USER_FILTER_RESOURCE); - } - } - - @Test - public void testResourceFilterLoading() throws Exception { - testSizeOfEngineFiltering("sizeof.filter.fields"); - } - - @Test - public void testFileFilterLoading() throws Exception { - File tempFilterFile = File.createTempFile("FilteredSizeOfTest", ".filter"); - try { - tempFilterFile.deleteOnExit(); - FileOutputStream fout = new FileOutputStream(tempFilterFile); - try { - InputStream in = FilteredSizeOfTest.class.getResourceAsStream("/sizeof.filter.fields"); - try { - while (true) { - int read = in.read(); - if (read < 0) { - break; - } else { - fout.write(read); - } - } - } finally { - in.close(); - } - } finally { - fout.close(); - } - testSizeOfEngineFiltering(tempFilterFile.getAbsolutePath()); - } finally { - assertThat(tempFilterFile.delete(), equalTo(true)); - } - } - - @Test - public void testUrlFilterLoading() throws Exception { - testSizeOfEngineFiltering(FilteredSizeOfTest.class.getResource("/sizeof.filter.fields").toExternalForm()); - } - - public static class AnnotationFilteredField { - - @IgnoreSizeOf - private final byte[] bigArray = new byte[16 * 1024]; - private final byte[] smallArray = new byte[128]; - } - - public static class AnnotationFilteredFieldSubclass extends AnnotationFilteredField { - } - - @IgnoreSizeOf - public static class AnnotationFilteredClass { - - private final byte[] bigArray = new byte[16 * 1024]; - } - - @IgnoreSizeOf(inherited = true) - public static class Parent { - } - - public static class Child extends Parent { - } - - @IgnoreSizeOf - public static class ChildChild extends Child { - } - - public static class ChildChildChild extends ChildChild { - } - - @com.terracotta.ehcache.special.annotation.IgnoreSizeOf(inherited=true) - public static class MatchingPatternAnnotation { - } - - public static class MatchingPatternAnnotationChild extends MatchingPatternAnnotation{ - } - - @com.terracotta.ehcache.special.annotation.no.inherited.IgnoreSizeOf - public static class MatchingPatternAnnotationNoInherited { - } - - public static class MatchingPatternAnnotationNoInheritedChild extends MatchingPatternAnnotationNoInherited{ - } - - @com.terracotta.ehcache.special.annotation.IgnoreSizeOffff - public static class NonMatchingPatternAnnotation1 { - } - - @com.terracotta.special.annotation.IgnoreSizeOf - public static class NonMatchingPatternAnnotation2 { - } - - @com.terracotta.ehcache.special.annotation.IgnoreSizeOf - @IgnoreSizeOf - public static class AnnotatedTwice { - } - - public static class MatchingPatternOrNotAnnotationFilteredField { - @com.terracotta.ehcache.special.annotation.IgnoreSizeOf - private final byte[] matchingBigArray = new byte[16 * 1024]; - @com.terracotta.special.annotation.IgnoreSizeOf - private final byte[] nonMatchingSmallArray = new byte[128]; - } - - public static class ResourceFilteredField { - - private final byte[] bigArray = new byte[16 * 1024]; - private final byte[] smallArray = new byte[128]; - } - - public static class ResourceFilteredFieldSubclass extends ResourceFilteredField { - } - - public static class ResourceFilteredClass { - - private final byte[] bigArray = new byte[6 * 1024]; - } - - public static class Referrer { - - private final Object reference; - - public Referrer(Object obj) { - this.reference = obj; - } - } -} Index: rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshConfiguration.java =================================================================== diff -u -N --- rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshConfiguration.java (revision 11322) +++ rctags/ehcache-2.10.8.1.63/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshConfiguration.java (revision 0) @@ -1,779 +0,0 @@ -/** - * Copyright Terracotta, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.sf.ehcache.constructs.scheduledrefresh; - -import net.sf.ehcache.Ehcache; - -import java.io.Serializable; -import java.util.Properties; -import java.util.concurrent.TimeUnit; - -/** - * Configuration for a {@link ScheduledRefreshCacheExtension}. Can be - * initialized from a {@link Properties} object. Currently, the use of a - * clustered {@link org.terracotta.quartz.TerracottaJobStore} is not supported. - * This usage will be supported in the future. - * - * @author cschanck - */ -public class ScheduledRefreshConfiguration implements Serializable, Cloneable { - - /** - * Property keys for configuration. - */ - public enum PropKey { - /** - * Properties key for the batch size attribute. - */ - batchSize, - - /** - * Properties key for the key generator class name. - */ - keyGenerator, - - - /** - * Properties key for cron expression used to schedule this job. - */ - cronExpression, - - /** - * Properties key for enabling bulk load mode prior to exection of the - * refresh. - */ - useBulkload, - - /** - * Properties key for the quartz job count attribute. -