Index: rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/pom.xml (revision 11330) @@ -0,0 +1,87 @@ + + + 4.0.0 + + + net.sf.ehcache + management-ehcache-impl-parent + 2.10.9.0.363 + .. + + + management-ehcache-common + management-ehcache-common + A common library shared between different management-ehcache implementation versions + + + + org.terracotta + management-core-resources + + + net.sf.ehcache.internal + ehcache-core + ${project.version} + provided + + + javax.servlet + javax.servlet-api + + + org.eclipse.jetty + jetty-servlet + + + commons-io + commons-io + 2.6 + test + + + org.easymock + easymock + 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.9.0.363/distribution/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/distribution/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/distribution/pom.xml (revision 11330) @@ -0,0 +1,298 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + + + 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.9.0.363/distribution/colorcache/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/distribution/colorcache/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/distribution/colorcache/pom.xml (revision 11330) @@ -0,0 +1,154 @@ + + 4.0.0 + + org.terracotta.forge + forge-parent + 4.14 + + + net.sf.ehcache.examples + colorcache + 2.10.9.0.363 + colorcache + war + Clustered Ehcache sample with Terracotta + + 2.1.0 + 4.3.9.0.263 + 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} + + + javax.servlet + 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 + + + + + + + + + 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.9.0.363/README.txt =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/README.txt (revision 0) +++ rctags/ehcache-2.10.9.0.363/README.txt (revision 11330) @@ -0,0 +1,18 @@ +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.9.0.363/management-ehcache-v2/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-v2/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-v2/pom.xml (revision 11330) @@ -0,0 +1,72 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + .. + + + 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.9.0.363/third-party.txt =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/third-party.txt (revision 0) +++ rctags/ehcache-2.10.9.0.363/third-party.txt (revision 11330) @@ -0,0 +1,5 @@ +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.9.0.363/terracotta/bootstrap/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/pom.xml (revision 11330) @@ -0,0 +1,98 @@ + + + 4.0.0 + + + net.sf.ehcache.internal + ehcache-terracotta-root + 2.10.9.0.363 + + + ehcache-terracotta-bootstrap + ehcache-terracotta-bootstrap + jar + + + false + 1.19 + 0.11.1 + + + + + net.sf.ehcache.internal + ehcache-core + ${project.version} + provided + + + org.terracotta.toolkit + terracotta-toolkit-api-internal + ${terracotta-toolkit-api-internal.version} + + + com.terracotta + clustered-entity-management + ${clustered-entity-management.version} + + + org.mockito + mockito-core + 3.0.0 + test + + + junit + junit + 4.12 + test + + + org.hamcrest + hamcrest-core + + + + + org.hamcrest + hamcrest + + + 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.9.0.363/management-ehcache-impl/management-ehcache-impl-v1/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-impl-v1/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-impl-v1/pom.xml (revision 11330) @@ -0,0 +1,110 @@ + + + 4.0.0 + + + net.sf.ehcache + management-ehcache-impl-parent + 2.10.9.0.363 + .. + + + 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 + + + javax.servlet + javax.servlet-api + + + org.easymock + easymock + test + + + org.eclipse.jetty + jetty-servlet + test + + + org.mockito + mockito-core + + + org.powermock + powermock-api-easymock + test + + + org.powermock + powermock-module-junit4 + test + + + org.hamcrest + hamcrest + + + 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.9.0.363/ehcache-core/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/pom.xml (revision 11330) @@ -0,0 +1,537 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + + + 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 + + + commons-logging + commons-logging + + + org.codehaus.btm + btm + + + net.sf.hibernate + hibernate + + + org.hamcrest + hamcrest + + + junit + junit + + + hamcrest-core + org.hamcrest + + + + + dom4j + dom4j + + + javassist + javassist + + + org.hibernate + hibernate-ehcache + + + 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 + + 1 + false + ${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 + + + + + build-info + generate-resources + + buildinfo + + + ${basedir}/.. + + + + + 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} + + + + + + org.glassfish.corba + rmic + 4.2.1 + + + + + + + + + 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.9.0.363/distribution/events/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/distribution/events/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/distribution/events/pom.xml (revision 11330) @@ -0,0 +1,249 @@ + + 4.0.0 + + org.terracotta.forge + forge-parent + 4.14 + + + net.sf.ehcache.examples + events + 2.10.9.0.363 + events + war + Clustered Ehcache Terracotta as second level cache for Hibernate + + 2.1.0 + 4.3.9.0.263 + 1.1.116 + 1.1 + 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} + + + javax.servlet + 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 + + + + + + + + + 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.9.0.363/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/pom.xml (revision 11330) @@ -0,0 +1,486 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-parent + 2.25 + + + + ehcache-root + net.sf.ehcache + ehcache-root + pom + 2.10.9.0.363 + + + scm:svn:https://svn.terracotta.org/repo/ehcache/trunk/ehcache + + + + 1.7.25 + 1.0.1 + 2.1.1 + 1.19 + 2.1.20 + 0.11.1 + 1.0.5 + 2.2.3 + 9.4.28.v20200408 + 2.3.2 + 3.5.1-Final + 1.2 + false + + + + 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 + + + + + + + + + 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 + ${sizeof-agent.version} + provided + + + + + org.slf4j + slf4j-jdk14 + ${slf4j.version} + test + + + commons-logging + commons-logging + ${commons-logging.version} + test + + + org.codehaus.btm + btm + 2.1.3 + test + + + net.sf.hibernate + hibernate + 2.1.8 + test + + + org.hamcrest + hamcrest + 2.1 + test + + + junit + junit + 4.12 + test + + + hamcrest-core + org.hamcrest + + + + + 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 + + + + + org.apache.derby + derby + 10.5.3.0_1 + test + + + org.mockito + mockito-core + 3.0.0 + test + + + com.sun.xsom + xsom + 20100725 + test + + + org.beanshell + bsh + 1.3.0 + test + + + org.quartz-scheduler + quartz + ${quartz.version} + + + org.easymock + easymock + 4.0.2 + test + + + org.powermock + powermock-api-easymock + 2.0.2 + test + + + org.powermock + powermock-module-junit4 + 2.0.2 + test + + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.1.2 + + + + true + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + ${skipJavadoc} + 8 + -Xdoclint:all,-Xdoclint:-missing + true + + + + org.apache.maven.plugins + maven-checkstyle-plugin + 3.1.0 + + + org.apache.maven.plugins + maven-dependency-plugin + 3.1.1 + + + 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.3 + + + + + + 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.9.0.363/system-tests/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/pom.xml (revision 11330) @@ -0,0 +1,291 @@ + + 4.0.0 + + org.terracotta + system-tests-parent + 4.3.9.0.263 + + + net.sf.ehcache.internal + ehcache-terracotta-system-tests + 2.10.9.0.363 + ehcache-terracotta-system-tests + System tests for ehcache-terracotta + + 512m + 1024m + -XX:MaxPermSize=512m + true + 10.10.1.1 + 2.2.3 + 1.7.25 + 1.9 + + + + org.terracotta + terracotta + ${terracotta.core.version} + + + javax.servlet + 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.terracotta + terracotta-toolkit-runtime + ${terracotta.core.version} + test + + + org.ow2.asm + asm + 7.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 + + + commons-logging + commons-logging + + + commons-logging + commons-logging-api + + + + + org.terracotta.test + container-test-framework + + + org.quartz-scheduler + quartz + ${quartz.version} + + + io.rest-assured + rest-assured + + + 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.9.0.363/management-ehcache-impl/ehcache-rest-agent/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/ehcache-rest-agent/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/ehcache-rest-agent/pom.xml (revision 11330) @@ -0,0 +1,223 @@ + + + 4.0.0 + + + net.sf.ehcache + management-ehcache-impl-parent + 2.10.9.0.363 + .. + + + net.sf.ehcache.internal + ehcache-rest-agent + ehcache-rest-agent + + Ehcache REST implementation + + + rest-management-private-classpath + .class_terracotta + true + false + 2.3.2 + + + + + net.sf.ehcache + management-ehcache-impl-v1 + ${project.version} + + + net.sf.ehcache + management-ehcache-impl-v2 + ${project.version} + + + javax.servlet + javax.servlet-api + 3.1.0 + runtime + + + org.eclipse.jetty + jetty-servlet + + + org.glassfish.jaxb + jaxb-runtime + ${jaxb-runtime.version} + runtime + + + + + + + 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.9.0.363/ehcache/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache/pom.xml (revision 11330) @@ -0,0 +1,418 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + .. + + + 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 + + + org.terracotta + product-upgradability-testing-utils + 0.9.4 + test + + + org.codehaus.btm + btm + 2.1.3 + test + + + org.quartz-scheduler + quartz + 2.2.3 + test + + + org.slf4j + slf4j-jdk14 + + + + + + + ${basedir}/src/main/resources + true + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-TIMs + + org.terracotta.modules + ${project.build.outputDirectory}/META-INF/terracotta/TIMs + + 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 + 3.1.1 + + + create-javadoc + prepare-package + + jar + + + + + org.hibernate + hibernate-core + ${hibernate-core.version} + + + none + ${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 + + 8 +
+
+
+
+ + + 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 + 4.2.1 + + ${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;resolution:=optional, + javax.xml.transform.sax;resolution:=optional, + javax.xml.transform.dom;resolution:=optional, + javax.xml.transform.stream;resolution:=optional, + org.w3c.dom;resolution:=optional, + org.hibernate.*;resolution:=optional, + org.terracotta.toolkit.*;resolution:=optional, + org.quartz.*;resolution:=optional, + org.terracotta.quartz.*;resolution:=optional, + com.sun.management.*;resolution:="optional", + net.sf.ehcache.terracotta.security;resolution:=optional, + org.jboss.vfs;resolution:=optional, + sun.management.*;resolution:=optional, + !com.google.apphosting.api, + !sun.misc,* + + net.sf.ehcache.* + org.terracotta.* + JavaSE-1.8 + + *;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.9.0.363/TestCategories.properties =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/TestCategories.properties (revision 0) +++ rctags/ehcache-2.10.9.0.363/TestCategories.properties (revision 11330) @@ -0,0 +1,328 @@ +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.9.0.363/terracotta/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/pom.xml (revision 11330) @@ -0,0 +1,74 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + + + 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.9.0.363/management-ehcache-impl/management-ehcache-impl-v2/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-impl-v2/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-impl-v2/pom.xml (revision 11330) @@ -0,0 +1,137 @@ + + + 4.0.0 + + + net.sf.ehcache + management-ehcache-impl-parent + 2.10.9.0.363 + .. + + + 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.10 + provided + + + org.terracotta.toolkit + terracotta-toolkit-api-internal + provided + + + javax.servlet + javax.servlet-api + runtime + + + 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 + 2.1 + 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.9.0.363/ehcache-search-parser/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-search-parser/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-search-parser/pom.xml (revision 11330) @@ -0,0 +1,56 @@ + + + 4.0.0 + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + .. + + + 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 + + + org.hamcrest + hamcrest + + + net.sf.ehcache.internal + ehcache-core + test-jar + ${project.version} + test + + + Index: rctags/ehcache-2.10.9.0.363/management-ehcache-impl/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/pom.xml (revision 11330) @@ -0,0 +1,43 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + .. + + + 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.9.0.363/ehcache-scheduled-refresh/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/pom.xml (revision 11330) @@ -0,0 +1,49 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + .. + + + 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 + + + org.hamcrest + hamcrest + + + net.sf.ehcache.internal + ehcache-core + test-jar + ${project.version} + test + + + Index: rctags/ehcache-2.10.9.0.363/management-ehcache-v1/pom.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-v1/pom.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-v1/pom.xml (revision 11330) @@ -0,0 +1,72 @@ + + + 4.0.0 + + + net.sf.ehcache + ehcache-root + 2.10.9.0.363 + .. + + + 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.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsExplictLockingTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsExplictLockingTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsExplictLockingTest.java (revision 11330) @@ -0,0 +1,229 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.bulkops; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration.Consistency; + +import org.terracotta.ehcache.tests.AbstractCacheTestBase; +import org.terracotta.ehcache.tests.ClientBase; +import org.terracotta.toolkit.Toolkit; +import org.terracotta.toolkit.concurrent.ToolkitBarrier; + +import com.tc.test.config.model.TestConfig; + +import java.io.Serializable; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.BrokenBarrierException; + +import junit.framework.Assert; + +public class BulkOpsExplictLockingTest extends AbstractCacheTestBase { + private static final int NODE_COUNT = 2; + + public BulkOpsExplictLockingTest(TestConfig testConfig) { + super(testConfig, App.class, App.class); + } + + public static class App extends ClientBase { + private final ToolkitBarrier barrier; + + public App(String[] args) { + super(args); + this.barrier = getClusteringToolkit().getBarrier("test-barrier", NODE_COUNT); + } + + public static void main(String[] args) { + new App(args).run(); + } + + @Override + protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { + Cache dcv2Strong = createCache("dcv2Strong", cacheManager, Consistency.STRONG); + testBulkOpsWithExplictLocking(dcv2Strong); + Cache dcv2Eventual = createCache("dcv2Eventual", cacheManager, Consistency.EVENTUAL); + testBulkOpsWithExplictLocking(dcv2Eventual); + + } + + private void testBulkOpsWithExplictLocking(Cache cache) throws InterruptedException, BrokenBarrierException { + int index = barrier.await(); + int numOfElements = 100; + Set elements = new HashSet(); + for (int i = 0; i < numOfElements; i++) { + elements.add(new Element(new Key("key" + i, i), new Value("val" + i, i))); + } + Key key = new Key("key0", 0); + if (index == 0) { + cache.acquireWriteLockOnKey(key); + cache.putAll(elements); + } + + barrier.await(); + if (index == 0) { + Assert.assertTrue(cache.isWriteLockedByCurrentThread(key)); + } else { + Assert.assertFalse(cache.isWriteLockedByCurrentThread(key)); + } + + if (index == 0) { + cache.releaseWriteLockOnKey(key); + } + Assert.assertFalse(cache.isWriteLockedByCurrentThread(key)); + barrier.await(); + + while (cache.getSize() != numOfElements) { + Thread.sleep(1000); + } + Assert.assertEquals(numOfElements, cache.getSize()); + + Set keySet1 = new HashSet(); + for (int i = 0; i < numOfElements; i++) { + keySet1.add(new Key("key" + i, i)); + } + + cache.acquireReadLockOnKey(key); + Map rv = cache.getAll(keySet1); + cache.releaseReadLockOnKey(key); + Assert.assertEquals(numOfElements, rv.size()); + + for (Element element : rv.values()) { + Assert.assertTrue(elements.contains(element)); + } + + Collection values = rv.values(); + for (Element element : elements) { + Assert.assertTrue(values.contains(element)); + } + + Set keySet2 = new HashSet(); + for (int i = 0; i < numOfElements; i++) { + if (i % 2 == 0) { + keySet2.add(new Key("key" + i, i)); + } + } + + rv = cache.getAll(keySet2); + Assert.assertEquals(keySet2.size(), rv.size()); + + for (Element element : rv.values()) { + Assert.assertTrue(elements.contains(element)); + } + + Assert.assertEquals(keySet2, rv.keySet()); + System.out.println("verified by client now waiting for others..."); + barrier.await(); + + if (index != 0) { + cache.acquireWriteLockOnKey(key); + cache.removeAll(keySet2); + cache.releaseWriteLockOnKey(key); + System.out.println("removed " + keySet2.size() + " keys from " + cache.getName() + + ". Now waiting for others..."); + } + barrier.await(); + while (cache.getSize() != numOfElements - keySet2.size()) { + Thread.sleep(1000); + } + + Assert.assertEquals(numOfElements - keySet2.size(), cache.getSize()); + System.out.println("now checking removed in " + cache.getName() + " by client"); + for (Object k : keySet2) { + Assert.assertNull(cache.get(k)); + } + System.out.println("client, I am done with " + cache.getName()); + } + + private Cache createCache(String cacheName, CacheManager cm, Consistency consistency) { + CacheConfiguration cacheConfiguration = new CacheConfiguration(); + cacheConfiguration.setName(cacheName); + cacheConfiguration.setMaxElementsInMemory(100000); + cacheConfiguration.setEternal(false); + cacheConfiguration.setTimeToLiveSeconds(100000); + cacheConfiguration.setTimeToIdleSeconds(200000); + + TerracottaConfiguration tcConfiguration = new TerracottaConfiguration(); + tcConfiguration.setConsistency(Consistency.STRONG); + cacheConfiguration.addTerracotta(tcConfiguration); + + Cache cache = new Cache(cacheConfiguration); + cm.addCache(cache); + return cache; + } + } + + private static class Key implements Serializable { + private final String stringKey; + private final int intKey; + + public Key(String stringKey, int intKey) { + super(); + this.stringKey = stringKey; + this.intKey = intKey; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + intKey; + result = prime * result + ((stringKey == null) ? 0 : stringKey.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + Key other = (Key) obj; + if (intKey != other.intKey) return false; + if (stringKey == null) { + if (other.stringKey != null) return false; + } else if (!stringKey.equals(other.stringKey)) return false; + return true; + } + + } + + private static class Value implements Serializable { + private final String keyVal; + private final int intVal; + + public Value(String keyVal, int intVal) { + this.keyVal = keyVal; + this.intVal = intVal; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + intVal; + result = prime * result + ((keyVal == null) ? 0 : keyVal.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + Value other = (Value) obj; + if (intVal != other.intVal) return false; + if (keyVal == null) { + if (other.keyVal != null) return false; + } else if (!keyVal.equals(other.keyVal)) return false; + return true; + } + + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/constructs/eventual/package.html =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/constructs/eventual/package.html (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/constructs/eventual/package.html (revision 11330) @@ -0,0 +1,10 @@ + + + + +

Construct related to eventual operations

+ +This package contains a decorator which offers a strong view on an eventual consistent cache. + + + Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/BasicContainerJTATest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/BasicContainerJTATest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/BasicContainerJTATest.java (revision 11330) @@ -0,0 +1,63 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.ehcache.tests.container; + +import com.gargoylesoftware.htmlunit.WebClient; +import com.gargoylesoftware.htmlunit.WebResponse; +import com.tc.test.AppServerInfo; +import com.tc.test.server.appserver.deployment.AbstractStandaloneTwoServerDeploymentTest; +import com.tc.test.server.appserver.deployment.DeploymentBuilder; +import com.tc.test.server.appserver.deployment.WebApplicationServer; + +import junit.framework.Test; + +public class BasicContainerJTATest extends AbstractStandaloneTwoServerDeploymentTest { + + private static final String CONTEXT = "BasicContainerJTATest"; + + public BasicContainerJTATest() { + if (appServerInfo().getId() == AppServerInfo.JETTY || appServerInfo().getId() == AppServerInfo.TOMCAT + || appServerInfo().getId() == AppServerInfo.WEBSPHERE) { + // Jetty and Tomcat have no TM and we know the Websphere one is not compatible + disableTest(); + } + } + + public static Test suite() { + return new BasicContainerJTATestSetup(); + } + + public void testBasics() throws Exception { + System.out.println("Running test"); + WebClient conversation = new WebClient(); + + // do insert on server0 + WebResponse response1 = request(server0, "cmd=insert", conversation); + assertEquals("OK", response1.getContentAsString().trim()); + + // do query on server1 + response1 = request(server1, "cmd=query", conversation); + assertEquals("OK", response1.getContentAsString().trim()); + System.out.println("Test finished"); + } + + private WebResponse request(WebApplicationServer server, String params, WebClient con) throws Exception { + return server.ping("/" + CONTEXT + "/BasicJTATestServlet?" + params, con); + } + + private static class BasicContainerJTATestSetup extends AbstractStandaloneContainerJTATestSetup { + + public BasicContainerJTATestSetup() { + super(BasicContainerJTATest.class, "basic-xa-appserver-test.xml", CONTEXT); + } + + @Override + protected void configureWar(DeploymentBuilder builder) { + super.configureWar(builder); + builder.addServlet("BasicTestJTAServlet", "/BasicJTATestServlet/*", BasicJTATestServlet.class, null, false); + } + + } + +} Index: rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/writebehind/operations/WriteAllAsyncOperation.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/writebehind/operations/WriteAllAsyncOperation.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/writebehind/operations/WriteAllAsyncOperation.java (revision 11330) @@ -0,0 +1,28 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.writebehind.operations; + + +import net.sf.ehcache.Element; +import net.sf.ehcache.writer.CacheWriter; + +import java.util.Collection; + +/** + * Implements the write all operation for write behind + * + * @author Abhishek Maheshwari + */ + +public class WriteAllAsyncOperation implements BatchAsyncOperation { + private final Collection elements; + + public WriteAllAsyncOperation(Collection elements) { + this.elements = elements; + } + + public void performBatchOperation(CacheWriter cacheWriter) { + cacheWriter.writeAll(elements); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/ehcache-unloadablecachemanagerlistenerclass.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/ehcache-unloadablecachemanagerlistenerclass.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/ehcache-unloadablecachemanagerlistenerclass.xml (revision 11330) @@ -0,0 +1,175 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/store/disk/DiskStoreHelper.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/store/disk/DiskStoreHelper.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/store/disk/DiskStoreHelper.java (revision 11330) @@ -0,0 +1,59 @@ +package net.sf.ehcache.store.disk; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheStoreHelper; +import net.sf.ehcache.store.CacheStore; +import net.sf.ehcache.store.LegacyStoreWrapper; +import net.sf.ehcache.store.Store; + +import java.lang.reflect.Field; +import java.util.concurrent.Future; + +/** + * @author Alex Snaps + */ +public class DiskStoreHelper { + + public static Future flushAllEntriesToDisk(final Cache cache) { + CacheStoreHelper cacheStoreHelper = new CacheStoreHelper(cache); + return flushAllEntriesToDisk(cacheStoreHelper.getStore()); + } + + public static Future flushAllEntriesToDisk(final Store store) { + if (store instanceof CacheStore) { + final DiskStore authority = getField("authoritativeTier", store); + return flushAllEntriesToDisk(authority); + } else if (store instanceof LegacyStoreWrapper) { + final DiskStore authority = getField("disk", store); + return flushAllEntriesToDisk(authority); + } else if (store instanceof DiskStore) { + final DiskStorageFactory factory = getField("disk", store); + return factory.flush(); + } else if (store instanceof LegacyStoreWrapper) { + final DiskStore disk = getField("disk", store); + return flushAllEntriesToDisk(disk); + } else { + return null; + } + } + + private static T getField(final String fieldName, final Object obj) { + try { + Field field = null; + Class clazz = obj.getClass(); + while(field == null && clazz != null) { + try { + field = clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + clazz = clazz.getSuperclass(); + } catch (SecurityException e) { + throw new RuntimeException(e); + } + } + field.setAccessible(true); + return (T) field.get(obj); + } catch (IllegalAccessException e) { + throw new RuntimeException(e); + } + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/constructs/classloader/package.html =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/constructs/classloader/package.html (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/constructs/classloader/package.html (revision 11330) @@ -0,0 +1,10 @@ + + + + +

ClassLoader contstructs package

+ +This package contains decorators that are concerned with classloaders + + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/ehcache-disk.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/ehcache-disk.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/ehcache-disk.xml (revision 11330) @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/ExtendedStatistics.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/ExtendedStatistics.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/ExtendedStatistics.java (revision 11330) @@ -0,0 +1,552 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.statistics.extended; + +import net.sf.ehcache.CacheOperationOutcomes; +import net.sf.ehcache.store.StoreOperationOutcomes; +import net.sf.ehcache.transaction.xa.XaCommitOutcome; +import net.sf.ehcache.transaction.xa.XaRecoveryOutcome; +import net.sf.ehcache.transaction.xa.XaRollbackOutcome; +import org.terracotta.statistics.archive.Timestamped; + +import java.util.EnumSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * The ExtendedStatistics interface. + * + * @author cschanck + */ +public interface ExtendedStatistics { + + /** The Constant ALL_CACHE_PUT_OUTCOMES. */ + static final Set ALL_CACHE_PUT_OUTCOMES = EnumSet.allOf(CacheOperationOutcomes.PutOutcome.class); + + /** The Constant ALL_CACHE_GET_OUTCOMES. */ + static final Set ALL_CACHE_GET_OUTCOMES = EnumSet.allOf(CacheOperationOutcomes.GetOutcome.class); + + /** The Constant ALL_CACHE_MISS_OUTCOMES. */ + static final Set ALL_CACHE_MISS_OUTCOMES = EnumSet.of( + CacheOperationOutcomes.GetOutcome.MISS_EXPIRED, CacheOperationOutcomes.GetOutcome.MISS_NOT_FOUND); + + /** The Constant ALL_STORE_PUT_OUTCOMES. */ + static final Set ALL_STORE_PUT_OUTCOMES = EnumSet.allOf(StoreOperationOutcomes.PutOutcome.class); + + /** + * Sets the time to disable. + * + * @param time the time + * @param unit the unit + */ + void setTimeToDisable(long time, TimeUnit unit); + + /** + * Sets the always on. + * + * @param alwaysOn the new always on + */ + void setAlwaysOn(boolean alwaysOn); + + /** + * Gets the. + * + * @return the operation + */ + Operation get(); + + /** + * Put. + * + * @return the operation + */ + Operation put(); + + /** + * Removes the. + * + * @return the operation + */ + Operation remove(); + + /** + * single arg replace operation + * @return + */ + Operation replaceOneArg(); + + /** + * two arg replace operation + * @return + */ + Operation replaceTwoArg(); + + /** + * put if absent operation + * @return + */ + Operation putIfAbsent(); + + /** + * remove element operation + * @return + */ + Operation removeElement(); + + /** + * Heap get. + * + * @return the operation + */ + Operation heapGet(); + + /** + * Offheap get. + * + * @return the operation + */ + Operation offheapGet(); + + /** + * Disk get. + * + * @return the operation + */ + Operation diskGet(); + + /** + * Heap put. + * + * @return the operation + */ + Operation heapPut(); + + /** + * Offheap put. + * + * @return the operation + */ + Operation offheapPut(); + + /** + * Disk put. + * + * @return the operation + */ + Operation diskPut(); + + /** + * Heap remove. + * + * @return the operation + */ + Operation heapRemove(); + + /** + * Offheap remove. + * + * @return the operation + */ + Operation offheapRemove(); + + /** + * Disk remove. + * + * @return the operation + */ + Operation diskRemove(); + + /** + * Search. + * + * @return the operation + */ + Operation search(); + + /** + * Xa commit. + * + * @return the operation + */ + Operation xaCommit(); + + /** + * Xa rollback. + * + * @return the operation + */ + Operation xaRollback(); + + /** + * Xa recovery. + * + * @return the operation + */ + Operation xaRecovery(); + + /** + * Eviction. + * + * @return the operation + */ + Operation eviction(); + + /** + * Expiry. + * + * @return the operation + */ + Operation expiry(); + + /** + * Cluster events + * + * @return the operation + */ + Operation clusterEvent(); + + /** + * Nonstop events + * + * @return the operation + */ + Operation nonstop(); + + /** + * All get. + * + * @return the result + */ + Result allGet(); + + /** + * All miss. + * + * @return the result + */ + Result allMiss(); + + /** + * All put. + * + * @return the result + */ + Result allPut(); + + /** + * Heap all put. + * + * @return the result + */ + Result heapAllPut(); + + /** + * Off heap all put. + * + * @return the result + */ + Result offHeapAllPut(); + + /** + * Disk all put. + * + * @return the result + */ + Result diskAllPut(); + + /** + * Cache hit ratio. + * @return + */ + Statistic cacheHitRatio(); + + /** + * Nonstop timeout ratio + * @return + */ + Statistic nonstopTimeoutRatio(); + + /** + * Operations. + * + * @param the generic type + * @param outcome the outcome + * @param name the name + * @param tags the tags + * @return the sets the + */ + > Set> operations(Class outcome, String name, String... tags); + + /** + * Get the set of cache specific pass thru statistics for a nam/tags pair. Used for + * custom pass thru statistics, as opposed to well known standard ones. + * @param name name + * @param tags set of tags + * @return + */ + Set> passthru(String name, Set tags); + + /** + * The Interface Operation. + * + * @param the generic type + */ + public interface Operation> { + + /** + * Type. + * + * @return the class + */ + Class type(); + + /** + * Component. + * + * @param result the result + * @return the result + */ + Result component(T result); + + /** + * Compound. + * + * @param results the results + * @return the result + */ + Result compound(Set results); + + /** + * Ratio of. + * + * @param numerator the numerator + * @param denomiator the denomiator + * @return the statistic + */ + Statistic ratioOf(Set numerator, Set denomiator); + + /** + * Sets the always on. + * + * @param enable the new always on + */ + void setAlwaysOn(boolean enable); + + /** + * Checks if is always on. + * + * @return true, if is always on + */ + boolean isAlwaysOn(); + + /** + * Sets the window. + * + * @param time the time + * @param unit the unit + */ + void setWindow(long time, TimeUnit unit); + + /** + * Sets the history. + * + * @param samples the samples + * @param time the time + * @param unit the unit + */ + void setHistory(int samples, long time, TimeUnit unit); + + /** + * Gets the window size. + * + * @param unit the unit + * @return the window size + */ + long getWindowSize(TimeUnit unit); + + /** + * Gets the history sample size. + * + * @return the history sample size + */ + int getHistorySampleSize(); + + /** + * Gets the history sample time. + * + * @param unit the unit + * @return the history sample time + */ + long getHistorySampleTime(TimeUnit unit); + + } + + /** + * The Interface Result. + */ + public interface Result { + + /** + * Count. + * + * @return the statistic + */ + Statistic count(); + + /** + * Rate. + * + * @return the statistic + */ + Statistic rate(); + + /** + * Latency. + * + * @return the latency + */ + Latency latency(); + } + + /** + * The Latency interface. Provides min/max/average. + */ + public interface Latency { + + /** + * Minimum latency observed. + * + * @return Minimum observed latency. NULL if no operation was observed. + */ + Statistic minimum(); + + /** + * Maximum latency observed. + * + * @return Maximum observed latency. NULL if no operation was observed. + */ + Statistic maximum(); + + /** + * Average observed latency. + * + * @return Average observed latency. NULL if no operation was observed. + */ + Statistic average(); + } + + /** + * The Interface Statistic. + * + * @param the generic type + */ + public interface Statistic { + + /** + * Active. + * + * @return true, if successful + */ + boolean active(); + + /** + * Value. + * + * @return the t + */ + T value(); + + /** + * History. + * + * @return the list + */ + List> history(); + } + + /** + * Gets the size. + * + * @return the size + */ + Statistic size(); + + /** + * Gets the local heap size. + * + * @return the local heap size + */ + Statistic localHeapSize(); + + /** + * Gets the local heap size in bytes. + * + * @return the local heap size in bytes + */ + Statistic localHeapSizeInBytes(); + + /** + * Gets the local off heap size. + * + * @return the local off heap size + */ + Statistic localOffHeapSize(); + + /** + * Gets the local off heap size in bytes. + * + * @return the local off heap size in bytes + */ + Statistic localOffHeapSizeInBytes(); + + /** + * Gets the local disk size. + * + * @return the local disk size + */ + Statistic localDiskSize(); + + /** + * Gets the local disk size in bytes. + * + * @return the local disk size in bytes + */ + Statistic localDiskSizeInBytes(); + + /** + * Gets the remote size. + * + * @return the remote size + */ + Statistic remoteSize(); + + /** + * Gets the writer queue length. + * + * @return the writer queue length + */ + Statistic writerQueueLength(); + + /** + * Get the timestamp (millis) of the last cluster rejoin event + * + * @return statistic for cluster rejoin timestamp + */ + Statistic mostRecentRejoinTimeStampMillis(); + +} \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/CacheRegionUtils.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/CacheRegionUtils.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/CacheRegionUtils.java (revision 11330) @@ -0,0 +1,117 @@ +/** + * 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.awt.Color; + +/** + * CacheRegionUtils + * + * @author gkeim + */ +public abstract class CacheRegionUtils { + /** + * HIT_COLOR + */ + public static final Color HIT_COLOR = Color.green; + + /** + * MISS_COLOR + */ + public static final Color MISS_COLOR = Color.red; + + /** + * PUT_COLOR + */ + public static final Color PUT_COLOR = Color.blue; + + /** + * HIT_FILL_COLOR + */ + public static final Color HIT_FILL_COLOR = CacheRegionUtils.HIT_COLOR.brighter().brighter().brighter(); + + /** + * MISS_FILL_COLOR + */ + public static final Color MISS_FILL_COLOR = CacheRegionUtils.MISS_COLOR.brighter().brighter().brighter(); + + /** + * PUT_FILL_COLOR + */ + public static final Color PUT_FILL_COLOR = CacheRegionUtils.PUT_COLOR.brighter().brighter().brighter(); + + /** + * HIT_DRAW_COLOR + */ + public static final Color HIT_DRAW_COLOR = CacheRegionUtils.HIT_COLOR.darker(); + + /** + * MISS_DRAW_COLOR + */ + public static final Color MISS_DRAW_COLOR = CacheRegionUtils.MISS_COLOR.darker(); + + /** + * PUT_DRAW_COLOR + */ + public static final Color PUT_DRAW_COLOR = CacheRegionUtils.PUT_COLOR.darker(); + + + /** + * determineShortName + * + * @param fullName + */ + public static String determineShortName(String fullName) { + String result = fullName; + + if (fullName != null) { + String[] comps = fullName.split("\\."); + if (comps.length == 1) { + return fullName; + } + boolean truncate = true; + for (int i = 0; i < comps.length; i++) { + String comp = comps[i]; + char c = comp.charAt(0); + if (truncate && Character.isUpperCase(c)) { + truncate = false; + } + if (truncate) { + comps[i] = Character.toString(c); + } + } + result = join(comps, '.'); + } + + return result; + } + + /** + * join + * + * @param elements + * @param c + */ + private static String join(String[] elements, char c) { + if (elements == null) { return null; } + StringBuilder sb = new StringBuilder(); + for (String s : elements) { + sb.append(s).append(c); + } + return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : ""; + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/cache-consistency-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/cache-consistency-test.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/cache-consistency-test.xml (revision 11330) @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/.project =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/.project (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/.project (revision 11330) @@ -0,0 +1,23 @@ + + + ehcache-scheduled-refresh + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/constructs/CacheDecoratorFactoryTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/constructs/CacheDecoratorFactoryTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/constructs/CacheDecoratorFactoryTest.java (revision 11330) @@ -0,0 +1,99 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.constructs; + +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import junit.framework.TestCase; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.constructs.MockDecoratorFactory.MockDecoratorFactoryCache; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.terracotta.test.categories.CheckShorts; + +/** + * @author Abhishek Sanoujam + */ +@Category(CheckShorts.class) +public class CacheDecoratorFactoryTest extends TestCase { + + private static final Logger LOG = LoggerFactory.getLogger(CacheDecoratorFactoryTest.class); + + @Test + public void testCacheDecoratorFactory() { + CacheManager cacheManager = new CacheManager(getClass().getResourceAsStream("/ehcache-decorator-test.xml")); + List cacheNames = Arrays.asList(cacheManager.getCacheNames()); + LOG.info("" + cacheNames); + + assertEquals(12, cacheNames.size()); + + assertTrue(cacheNames.contains("noDecoratorCache")); + assertTrue(cacheNames.contains("oneDecoratorCache")); + assertTrue(cacheNames.contains("oneDecoratorFirst")); + assertTrue(cacheNames.contains("twoDecoratorCache")); + assertTrue(cacheNames.contains("twoDecoratorFirst")); + assertTrue(cacheNames.contains("twoDecoratorSecond")); + assertTrue(cacheNames.contains("fiveDecoratorCache")); + assertTrue(cacheNames.contains("fiveDecoratorFirst")); + assertTrue(cacheNames.contains("fiveDecoratorSecond")); + assertTrue(cacheNames.contains("fiveDecoratorThird")); + assertTrue(cacheNames.contains("fiveDecoratorFourth")); + assertTrue(cacheNames.contains("fiveDecoratorFifth")); + + cacheManager.shutdown(); + + } + + @Test + public void testCacheDecoratorFactoryProperties() { + CacheManager cacheManager = new CacheManager(getClass().getResourceAsStream("/ehcache-decorator-test.xml")); + List cacheNames = Arrays.asList(cacheManager.getCacheNames()); + assertEquals(12, cacheNames.size()); + + MockDecoratorFactoryCache cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("oneDecoratorFirst"); + assertEquals("oneFirst", cache.getProperties().getProperty("someKey")); + + cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("twoDecoratorFirst"); + assertEquals("twoFirst", cache.getProperties().getProperty("someKey")); + + cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("twoDecoratorSecond"); + assertEquals("twoSecond", cache.getProperties().getProperty("someKey")); + + cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("fiveDecoratorFirst"); + assertEquals("fiveFirst", cache.getProperties().getProperty("someKey")); + + cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("fiveDecoratorSecond"); + assertEquals("fiveSecond", cache.getProperties().getProperty("someKey")); + + cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("fiveDecoratorThird"); + assertEquals("fiveThird", cache.getProperties().getProperty("someKey")); + + cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("fiveDecoratorFourth"); + assertEquals("fiveFourth", cache.getProperties().getProperty("someKey")); + + cache = (MockDecoratorFactoryCache) cacheManager.getEhcache("fiveDecoratorFifth"); + assertEquals("fiveFifth", cache.getProperties().getProperty("someKey")); + + cacheManager.shutdown(); + + } +} Index: rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/CacheConfigChangeBridgeTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/CacheConfigChangeBridgeTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/CacheConfigChangeBridgeTest.java (revision 11330) @@ -0,0 +1,132 @@ +package org.terracotta.modules.ehcache.store; + +import net.sf.ehcache.config.CacheConfiguration; +import org.junit.Before; +import org.junit.Test; +import org.terracotta.toolkit.config.AbstractConfiguration; +import org.terracotta.toolkit.config.Configuration; +import org.terracotta.toolkit.events.ToolkitNotifier; +import org.terracotta.toolkit.internal.cache.ToolkitCacheInternal; +import org.terracotta.toolkit.store.ToolkitConfigFields; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +/** + * @author tim + */ +public class CacheConfigChangeBridgeTest { + + private ToolkitCacheInternal backend; + private CacheConfiguration cacheConfiguration; + private ToolkitNotifier notifier; + private TestConfiguration toolkitCacheConfig; + + @Before + public void setUp() throws Exception { + toolkitCacheConfig = new TestConfiguration(); + backend = when(mock(ToolkitCacheInternal.class).getConfiguration()) + .thenReturn(toolkitCacheConfig).getMock(); + cacheConfiguration = spy(new CacheConfiguration()); + notifier = mock(ToolkitNotifier.class); + } + + @Test + public void testConnectConfigsSetsUpLocalCacheConfiguration() throws Exception { + cacheConfiguration.freezeConfiguration(); + + CacheConfigChangeBridge bridge = new CacheConfigChangeBridge("foo", + backend, notifier, cacheConfiguration); + + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_TOTAL_COUNT_FIELD_NAME, 123); + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_TTI_SECONDS_FIELD_NAME, 321); + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_TTL_SECONDS_FIELD_NAME, 456); + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_COUNT_LOCAL_HEAP_FIELD_NAME, 42); + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_BYTES_LOCAL_HEAP_FIELD_NAME, 1L); + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_BYTES_LOCAL_OFFHEAP_FIELD_NAME, 2L); + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.OFFHEAP_ENABLED_FIELD_NAME, true); + + bridge.connectConfigs(); + + assertThat(cacheConfiguration.getMaxEntriesInCache(), is(123L)); + assertThat(cacheConfiguration.getTimeToLiveSeconds(), is(456L)); + assertThat(cacheConfiguration.getTimeToIdleSeconds(), is(321L)); + assertThat(cacheConfiguration.isEternal(), is(false)); + assertThat(cacheConfiguration.getMaxEntriesLocalHeap(), is(42L)); + assertThat(cacheConfiguration.getMaxBytesLocalHeap(), is(1L)); + assertThat(cacheConfiguration.getMaxBytesLocalOffHeap(), is(2L)); + assertThat(cacheConfiguration.isOverflowToOffHeap(), is(true)); + } + + @Test + public void testEmptyConfigFromToolkitCache() throws Exception { + CacheConfigChangeBridge bridge = new CacheConfigChangeBridge("foo", + backend, notifier, cacheConfiguration); + + bridge.connectConfigs(); + + // Empty config so only check for registration of the listener and nothing else. + verify(cacheConfiguration).addConfigurationListener(bridge); + verifyNoMoreInteractions(cacheConfiguration); + } + + @Test + public void testOverrideLocallyConfiguredExpiry() throws Exception { + cacheConfiguration.setEternal(false); + cacheConfiguration.setTimeToLiveSeconds(123); + cacheConfiguration.setTimeToIdleSeconds(321); + + CacheConfigChangeBridge bridge = new CacheConfigChangeBridge("foo", + backend, notifier, cacheConfiguration); + + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_TTI_SECONDS_FIELD_NAME, 0); + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_TTL_SECONDS_FIELD_NAME, 0); + + bridge.connectConfigs(); + + assertThat(cacheConfiguration.isEternal(), is(false)); + assertThat(cacheConfiguration.getTimeToLiveSeconds(), is(0L)); + assertThat(cacheConfiguration.getTimeToIdleSeconds(), is(0L)); + } + + @Test + public void testSetUnlimitedMaxEntriesInCache() throws Exception { + CacheConfigChangeBridge bridge = new CacheConfigChangeBridge("foo", + backend, notifier, cacheConfiguration); + + toolkitCacheConfig.internalSetConfigMapping(ToolkitConfigFields.MAX_TOTAL_COUNT_FIELD_NAME, -1); + + bridge.connectConfigs(); + + assertThat(cacheConfiguration.getMaxEntriesInCache(), is(0L)); + } + + private static class TestConfiguration extends AbstractConfiguration { + private final Map map = new HashMap(); + + @Override + protected void internalSetConfigMapping(final String key, final Serializable value) { + map.put(key, value); + } + + @Override + public Set getKeys() { + return map.keySet(); + } + + @Override + public Serializable getObjectOrNull(final String name) { + return map.get(name); + } + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/Person.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/Person.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/domain/Person.java (revision 11330) @@ -0,0 +1,108 @@ +/* + * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved. + */ + +package org.terracotta.ehcache.tests.container.hibernate.domain; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class Person { + + private Long id; + private int age; + private String firstname; + private String lastname; + private List events = new ArrayList(); // list semantics, e.g., indexed + private Set emailAddresses = new HashSet(); + private Set phoneNumbers = new HashSet(); + private List talismans = new ArrayList(); // a Bag of good-luck charms. + + public Person() { + // + } + + public List getEvents() { + return events; + } + + protected void setEvents(List events) { + this.events = events; + } + + public void addToEvent(Event event) { + this.getEvents().add(event); + event.getParticipants().add(this); + } + + public void removeFromEvent(Event event) { + this.getEvents().remove(event); + event.getParticipants().remove(this); + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getFirstname() { + return firstname; + } + + public void setFirstname(String firstname) { + this.firstname = firstname; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getLastname() { + return lastname; + } + + public void setLastname(String lastname) { + this.lastname = lastname; + } + + public Set getEmailAddresses() { + return emailAddresses; + } + + public void setEmailAddresses(Set emailAddresses) { + this.emailAddresses = emailAddresses; + } + + public Set getPhoneNumbers() { + return phoneNumbers; + } + + public void setPhoneNumbers(Set phoneNumbers) { + this.phoneNumbers = phoneNumbers; + } + + public void addTalisman(String name) { + talismans.add(name); + } + + public List getTalismans() { + return talismans; + } + + public void setTalismans(List talismans) { + this.talismans = talismans; + } + + public String toString() { + return getFirstname() + " " + getLastname(); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/loader/CompositeLoaderTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/loader/CompositeLoaderTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/loader/CompositeLoaderTest.java (revision 11330) @@ -0,0 +1,69 @@ +/** + * 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 org.junit.After; +import org.junit.Before; +import org.junit.Test; + + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + + +/** + * ComponentA is composed of ComponentB and some other fields. Tests the interactions between two loaders, where the first component's + * loader loads component B by using getWithLoader, which in turn invokes component B's loader. + * + * @author Greg Luck + * @version $Id: CompositeLoaderTest.java 5594 2012-05-07 16:04:31Z cdennis $ + */ +public class CompositeLoaderTest { + + private static final Logger LOG = LoggerFactory.getLogger(CompositeLoaderTest.class.getName()); + + /** + * Sets up the fixture, for example, open a network connection. + * This method is called before a test is executed. + */ + @Before + public void setUp() throws Exception { + CacheHelper.init(); + } + + /** + * Tears down the fixture, for example, close a network connection. + * This method is called after a test is executed. + */ + @After + public void tearDown() throws Exception { + CacheHelper.shutdown(); + } + + /** + * This test reproduces a deadlock found in 1.4-beta1 around loading interactions and getWithLoader. Now fixed. + */ + @Test + public void testCompositeLoad() { + LOG.info("Getting from cache"); + ComponentA compA = (ComponentA) CacheHelper.get("ehcache-loaderinteractions.xml", "ACache", "key1"); + LOG.info(compA.toString()); + + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/cachemanager-perf.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/cachemanager-perf.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/resources/cachemanager-perf.xml (revision 11330) @@ -0,0 +1,488 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/ElementValueComparatorConfigurationElement.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/ElementValueComparatorConfigurationElement.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/ElementValueComparatorConfigurationElement.java (revision 11330) @@ -0,0 +1,55 @@ +/** + * 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.ElementValueComparatorConfiguration; +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 net.sf.ehcache.config.generator.model.NodeElement} representing the + * {@link net.sf.ehcache.config.ElementValueComparatorConfiguration} + * + * @author Ludovic Orban + * + */ +public class ElementValueComparatorConfigurationElement extends SimpleNodeElement { + + private final ElementValueComparatorConfiguration elementValueComparatorConfiguration; + + /** + * Constructor accepting the parent and the {@link net.sf.ehcache.config.ElementValueComparatorConfiguration} + * + * @param parent + * @param elementValueComparatorConfiguration + */ + public ElementValueComparatorConfigurationElement(NodeElement parent, + ElementValueComparatorConfiguration elementValueComparatorConfiguration) { + super(parent, "elementValueComparator"); + this.elementValueComparatorConfiguration = elementValueComparatorConfiguration; + init(); + } + + private void init() { + if (elementValueComparatorConfiguration == null) { + return; + } + addAttribute(new SimpleNodeAttribute("class", elementValueComparatorConfiguration.getClassName()).optional(false)); + } + +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/util/RetryAssert.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/util/RetryAssert.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/util/RetryAssert.java (revision 11330) @@ -0,0 +1,80 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ + +package net.sf.ehcache.util; + +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.store.Store; + +import org.hamcrest.Matcher; +import org.junit.Assert; + +import java.util.concurrent.Callable; +import java.util.concurrent.TimeUnit; + +public class RetryAssert { + protected RetryAssert() { + // static only class + } + + public static void assertBy(long time, TimeUnit unit, Callable value, Matcher matcher) { + boolean interrupted = false; + long start = System.nanoTime(); + long end = start + unit.toNanos(time); + long sleep = Math.max(50, unit.toMillis(time) / 10); + AssertionError latest; + try { + while (true) { + try { + Assert.assertThat(value.call(), matcher); + return; + } catch (AssertionError e) { + latest = e; + } catch (Exception e) { + latest = new AssertionError(e); + } + + if (System.nanoTime() > end) { + break; + } else { + try { + Thread.sleep(sleep); + } catch (InterruptedException e) { + interrupted = true; + } + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + throw latest; + } + + public static Callable elementAt(final Ehcache cache, final Object key) { + return new Callable() { + public Element call() { + return cache.get(key); + } + }; + } + + public static Callable sizeOf(final Ehcache cache) { + return new Callable() { + public Integer call() throws Exception { + return cache.getSize(); + } + }; + } + + public static Callable sizeOnDiskOf(final Store store) { + return new Callable() { + public Integer call() throws Exception { + return store.getOnDiskSize(); + } + }; + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/LongSequence.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/LongSequence.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/LongSequence.java (revision 11330) @@ -0,0 +1,32 @@ +/** + * 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; + +/** + * A sequence producing longs + * + * @author teck + */ +public interface LongSequence { + + /** + * Get the next value in the sequence + * + * @return the next value + */ + long next(); +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/event/CacheEventListenerFactory.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/event/CacheEventListenerFactory.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/event/CacheEventListenerFactory.java (revision 11330) @@ -0,0 +1,39 @@ +/** + * 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 java.util.Properties; + +/** + * An abstract factory for creating listeners. Implementers should provide their own + * concrete factory extending this factory. It can then be configured in ehcache.xml. + * + * @author Greg Luck + * @version $Id: CacheEventListenerFactory.java 5594 2012-05-07 16:04:31Z cdennis $ + */ +public abstract class CacheEventListenerFactory { + + /** + * Create a CacheEventListener + * + * @param properties implementation specific properties. These are configured as comma + * separated name value pairs in ehcache.xml + * @return a constructed CacheEventListener + */ + public abstract CacheEventListener createCacheEventListener(Properties properties); + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/SetAsList.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/SetAsList.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/SetAsList.java (revision 11330) @@ -0,0 +1,212 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.util; + +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Set; + +/** + * Wraps a set to provide a list interface. + * All list methods not application to set throws an {@link UnsupportedOperationException} + * + * @author Chris Dennis + * @param + */ +public class SetAsList implements List { + + private final Set set; + private transient Object[] array; + + /** + * @param set + */ + public SetAsList(Set set) { + this.set = set; + } + + /** + * {@inheritDoc} + */ + public int size() { + return set.size(); + } + + /** + * {@inheritDoc} + */ + public boolean isEmpty() { + return set.isEmpty(); + } + + /** + * {@inheritDoc} + */ + public boolean contains(Object o) { + return set.contains(o); + } + + /** + * {@inheritDoc} + */ + public Iterator iterator() { + return set.iterator(); + } + + /** + * {@inheritDoc} + */ + public Object[] toArray() { + return set.toArray(); + } + + /** + * {@inheritDoc} + */ + public T[] toArray(T[] a) { + return set.toArray(a); + } + + /** + * {@inheritDoc} + */ + public boolean add(E e) { + return set.add(e); + } + + /** + * {@inheritDoc} + */ + public boolean remove(Object o) { + return set.remove(o); + } + + /** + * {@inheritDoc} + */ + public boolean containsAll(Collection c) { + return set.containsAll(c); + } + + /** + * {@inheritDoc} + */ + public boolean addAll(Collection c) { + return set.addAll(c); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public boolean addAll(int index, Collection c) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * {@inheritDoc} + */ + public boolean removeAll(Collection c) { + return set.removeAll(c); + } + + /** + * {@inheritDoc} + */ + public boolean retainAll(Collection c) { + return set.retainAll(c); + } + + /** + * {@inheritDoc} + */ + public void clear() { + set.clear(); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + * + * @param index Index + */ + public E get(int index) { + if (this.array == null) { + this.array = toArray(); + } + if (array.length <= index) { + throw new IndexOutOfBoundsException(); + } + return (E) this.array[index]; + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public E set(int index, E element) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public void add(int index, E element) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public E remove(int index) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public int indexOf(Object o) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public int lastIndexOf(Object o) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public ListIterator listIterator() { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public ListIterator listIterator(int index) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } + + /** + * Does not support List methods {@link UnsupportedOperationException}. + */ + public List subList(int fromIndex, int toIndex) { + throw new UnsupportedOperationException("Delegates to set, operation not supported"); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/filter/annotations/CustomAnnotation.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/filter/annotations/CustomAnnotation.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/pool/sizeof/filter/annotations/CustomAnnotation.java (revision 11330) @@ -0,0 +1,32 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.pool.sizeof.filter.annotations; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Retention(RetentionPolicy.RUNTIME) +@Target({ElementType.FIELD, ElementType.TYPE, ElementType.PACKAGE }) +public @interface CustomAnnotation { + boolean deprecated() default true; + short differentReturnType() default 10; + Class aClass() default Integer.class; + ExampleEnum anEnum() default ExampleEnum.TWO; + Deprecated anAnnotation() default @Deprecated; +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/JavaBeanAttributeExtractor.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/JavaBeanAttributeExtractor.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/JavaBeanAttributeExtractor.java (revision 11330) @@ -0,0 +1,163 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.search.attribute; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import net.sf.ehcache.Element; + +/** + * Extracts a search attribute determining the value as a javabean property on either + * the key or the value. If the property exists on both the key and the value an exception is thrown + * + * @author teck + */ +public class JavaBeanAttributeExtractor implements AttributeExtractor { + + private static final Object NO_VALUE = new Object(); + + private transient volatile MethodRef lastKeyMethod; + private transient volatile MethodRef lastValueMethod; + + private final String beanProperty; + + /** + * Constructor + * + * @param beanProperty the bean property name to extract + */ + public JavaBeanAttributeExtractor(String beanProperty) { + if (beanProperty == null) { + throw new NullPointerException(); + } + + beanProperty = beanProperty.trim(); + + if (beanProperty.length() == 0) { + throw new IllegalArgumentException("bean property empty"); + } + + this.beanProperty = beanProperty; + } + + /** + * {@inheritDoc} + */ + public Object attributeFor(Element element, String attributeName) throws AttributeExtractorException { + Object attribute = NO_VALUE; + + final Object key = element.getObjectKey(); + + if (key != null) { + MethodRef keyMethod = lastKeyMethod; + if (keyMethod == null || keyMethod.targetClass != key.getClass()) { + keyMethod = findMethod(key); + lastKeyMethod = keyMethod; + } + if (keyMethod.method != null) { + attribute = getValue(keyMethod.method, key); + } + } + + final Object value = element.getObjectValue(); + + if (value != null) { + MethodRef valueMethod = lastValueMethod; + if (valueMethod == null || valueMethod.targetClass != value.getClass()) { + valueMethod = findMethod(value); + lastValueMethod = valueMethod; + } + + if (valueMethod.method != null) { + if (attribute != NO_VALUE) { + throw new AttributeExtractorException("Bean property [" + beanProperty + "] present on both key and value"); + } + + return getValue(valueMethod.method, value); + } + } + + if (attribute != NO_VALUE) { + return attribute; + } + + throw new AttributeExtractorException("Bean property [" + beanProperty + "] not present on either key or value"); + } + + private MethodRef findMethod(Object obj) { + String upperFirstProp = "" + Character.toUpperCase(beanProperty.charAt(0)); + if (beanProperty.length() > 1) { + upperFirstProp += beanProperty.substring(1); + } + + final Class target = obj.getClass(); + + try { + return new MethodRef(target, target.getMethod("get" + upperFirstProp)); + } catch (SecurityException e) { + throw new AttributeExtractorException(e); + } catch (NoSuchMethodException e) { + // keep looking + } + + try { + Method m = target.getMethod("is" + upperFirstProp); + if (m.getReturnType().equals(Boolean.class) || m.getReturnType().equals(Boolean.TYPE)) { + return new MethodRef(target, m); + } + } catch (SecurityException e) { + throw new AttributeExtractorException(e); + } catch (NoSuchMethodException e) { + // + } + + // no applicable method available + return new MethodRef(target, null); + } + + private Object getValue(Method method, Object key) { + try { + return method.invoke(key); + } catch (Throwable t) { + if (t instanceof InvocationTargetException) { + t = t.getCause(); + } + + if (t instanceof Error) { + throw ((Error) t); + } + + throw new AttributeExtractorException("Error getting bean property [" + beanProperty + "] on instance of " + + key.getClass().getName(), t); + } + } + + /** + * A cached method lookup. Method is null to indicate the method is not present/accessible + */ + private static class MethodRef { + private final Class targetClass; + private final Method method; + + MethodRef(Class target, Method method) { + this.targetClass = target; + this.method = method; + } + } + +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/SimpleOsgiTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/SimpleOsgiTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/SimpleOsgiTest.java (revision 11330) @@ -0,0 +1,126 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package net.sf.ehcache.osgi; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages; +import static org.ops4j.pax.exam.CoreOptions.options; +import static org.terracotta.test.OsgiUtil.commonOptions; +import static org.terracotta.test.OsgiUtil.getMavenBundle; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.ops4j.pax.exam.Configuration; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.junit.PaxExam; +import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; +import org.ops4j.pax.exam.spi.reactors.PerMethod; +import org.terracotta.context.ContextManager; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Serializable; +import java.net.URL; + +/** + * Test a simple BigMemory usage with BM Go license key. The product name should include "BigMemory" and not "Ehcache" + * NOTE: this test only works in fullmode + * + * @author hhuynh + */ +@RunWith(PaxExam.class) +@ExamReactorStrategy(PerMethod.class) +public class SimpleOsgiTest { + + @Configuration + public Option[] config() { + return options(bootDelegationPackages("sun.*,jdk.*"), + // need this for REST agent test + getMavenBundle("net.sf.ehcache", "ehcache-ee", "ehcache"), + commonOptions()); + } + + @Test + public void testSimpleCache() throws Exception { + CacheManager manager = new CacheManager(SimpleOsgiTest.class.getResource("/net/sf/ehcache/osgi/simple-ehcache.xml")); + try { + Cache cache = manager.getCache("sampleCache1"); + Element element = new Element("key1", "value1"); + cache.put(element); + Element element1 = cache.get("key1"); + assertEquals("value1", element1.getObjectValue()); + assertEquals(1, cache.getSize()); + } finally { + manager.shutdown(); + } + } + + @Test + public void testValueClass() throws Exception { + CacheManager manager = new CacheManager(SimpleOsgiTest.class.getResource("/net/sf/ehcache/osgi/simple-ehcache.xml")); + try { + Cache cache = manager.getCache("sampleCache1"); + Element element = new Element("key1", new Value("value1")); + cache.put(element); + Element element1 = cache.get("key1"); + assertEquals("value1", ((Value) element1.getObjectValue()).v); + assertEquals(1, cache.getSize()); + } finally { + manager.shutdown(); + } + } + + @Test + public void testUsingNonExportedClass() { + try { + ContextManager cm = new ContextManager(); + fail("Expected class not found exception"); + } catch (Throwable e) { + // expected + } + } + + @Test + public void testRestAgent() throws Exception { + CacheManager manager = new CacheManager( + SimpleOsgiTest.class + .getResource("/net/sf/ehcache/osgi/rest-enabled-ehcache.xml")); + InputStream in = null; + try { + Cache testCache = manager.getCache("testCache"); + testCache.put(new Element("k", "v")); + assertEquals(1, testCache.getSize()); + URL url = new URL("http://localhost:9888/tc-management-api/agents"); + in = url.openStream(); + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + String line = null; + StringBuilder sb = new StringBuilder(); + while ((line = reader.readLine()) != null) { + sb.append(line.trim()).append("\n"); + } + System.out.println("Rest response: " + sb); + assertTrue(sb.toString().contains("\"agentId\":\"embedded\"")); + } finally { + manager.shutdown(); + if (in != null) { + in.close(); + } + } + } + + private static class Value implements Serializable { + public String v; + + public Value(String value) { + v = value; + } + } +} \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/writer/writebehind/OperationConverter.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/writer/writebehind/OperationConverter.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/writer/writebehind/OperationConverter.java (revision 11330) @@ -0,0 +1,34 @@ +/** + * 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; + +/** + * Interface that allows an converter to be implemented that can create an operation based + * on an arbitrary object. + * + * @param the operation type that should be converted to + * @author Geert Bevin + * @version $Id: OperationConverter.java 5594 2012-05-07 16:04:31Z cdennis $ + */ +public interface OperationConverter { + /** + * Convert an arbitrary object + * + * @param source the object to convert + * @return the converted operation instance + */ + public T convert(Object source); +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesL1Test.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesL1Test.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/servermap/ServerMapL2EvictionReachesL1Test.java (revision 11330) @@ -0,0 +1,21 @@ +package org.terracotta.ehcache.tests.servermap; + +import org.terracotta.ehcache.tests.AbstractCacheTestBase; + +import com.tc.test.config.model.TestConfig; + +public class ServerMapL2EvictionReachesL1Test extends AbstractCacheTestBase { + + public ServerMapL2EvictionReachesL1Test(TestConfig testConfig) { + super("/servermap/servermap-l2-eviction-reaches-l1-test.xml", testConfig, + ServerMapL2EvictionReachesL1TestClient.class); + testConfig.setDgcEnabled(true); + testConfig.setDgcIntervalInSec(60); + testConfig.addTcProperty("ehcache.evictor.logging.enabled", "true"); + + testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.l1.cachemanager.enabled=false"); + testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.ehcache.evictor.logging.enabled=true"); + testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.l1.lockmanager.timeout.interval=60000"); + } + +} Index: rctags/ehcache-2.10.9.0.363/distribution/events/src/assemble/bin/stop-sample.bat =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/distribution/events/src/assemble/bin/stop-sample.bat (revision 0) +++ rctags/ehcache-2.10.9.0.363/distribution/events/src/assemble/bin/stop-sample.bat (revision 11330) @@ -0,0 +1,13 @@ +@echo off + +setlocal + +set root=%~d0%~p0.. +set root="%root:"=%" + +cd %root% + +call bin/stop-jetty.bat 9081 +call bin/stop-jetty.bat 9082 + +endlocal \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/CacheManagerConfigEntity.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/CacheManagerConfigEntity.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/CacheManagerConfigEntity.java (revision 11330) @@ -0,0 +1,39 @@ +package net.sf.ehcache.management.resource; + +import org.terracotta.management.resource.VersionedEntity; + +/** + * @author brandony + */ +public class CacheManagerConfigEntity extends VersionedEntity { + private String cacheManagerName; + private String agentId; + + private String xml; + + public String getCacheManagerName() { + return cacheManagerName; + } + + public void setCacheManagerName(String cacheManagerName) { + this.cacheManagerName = cacheManagerName; + } + + public String getXml() { + return xml; + } + + public void setXml(String xml) { + this.xml = xml; + } + + @Override + public String getAgentId() { + return agentId; + } + + @Override + public void setAgentId(String agentId) { + this.agentId = agentId; + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/servermap/servermap-l2-eviction-reaches-l1-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/servermap/servermap-l2-eviction-reaches-l1-test.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/servermap/servermap-l2-eviction-reaches-l1-test.xml (revision 11330) @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheStatisticSampleEntityV2.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheStatisticSampleEntityV2.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheStatisticSampleEntityV2.java (revision 11330) @@ -0,0 +1,33 @@ +/* + * All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright + * notice. All rights reserved. + */ +package net.sf.ehcache.management.resource; + +import java.util.Map; + +/** + * @author brandony + */ +public class CacheStatisticSampleEntityV2 extends AbstractCacheEntityV2{ + + private String statName; + + private Map statValueByTimeMillis; + + public String getStatName() { + return statName; + } + + public void setStatName(String statName) { + this.statName = statName; + } + + public Map getStatValueByTimeMillis() { + return statValueByTimeMillis; + } + + public void setStatValueByTimeMillis(Map statValueByTimeMillis) { + this.statValueByTimeMillis = statValueByTimeMillis; + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/TimeStampedCounterValue.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/TimeStampedCounterValue.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/TimeStampedCounterValue.java (revision 11330) @@ -0,0 +1,68 @@ +/** + * 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.io.Serializable; + +/** + * A counter value at a particular time instance + * + * @author Abhishek Sanoujam + * @since 1.7 + */ +public class TimeStampedCounterValue implements Serializable { + private final long counterValue; + private final long timestamp; + + /** + * Constructor accepting the value of both timestamp and the counter value. + * + * @param timestamp + * @param value + */ + public TimeStampedCounterValue(long timestamp, long value) { + this.timestamp = timestamp; + this.counterValue = value; + } + + /** + * Get the counter value + * + * @return The counter value + */ + public long getCounterValue() { + return this.counterValue; + } + + /** + * Get value of the timestamp + * + * @return the timestamp associated with the current value + */ + public long getTimestamp() { + return this.timestamp; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "value: " + this.counterValue + ", timestamp: " + this.timestamp; + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/config/generator/xsom/XSDAttributeValueType.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/config/generator/xsom/XSDAttributeValueType.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/config/generator/xsom/XSDAttributeValueType.java (revision 11330) @@ -0,0 +1,264 @@ +/** + * 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.xsom; + +import net.sf.ehcache.config.MemoryUnit; + +import java.util.Iterator; +import java.util.Random; + +import com.sun.xml.xsom.XSAttributeDecl; +import com.sun.xml.xsom.XSFacet; +import com.sun.xml.xsom.XSRestrictionSimpleType; +import com.sun.xml.xsom.XSSimpleType; + +public abstract class XSDAttributeValueType { + + protected static final Random RANDOM = new Random(System.currentTimeMillis()); + protected String pattern; + public enum XsdType { + BOOLEAN, INTEGER, POSITIVE_INTEGER, NON_NEGATIVE_INTEGER, STRING, ANY_SIMPLE_TYPE, ENUMERATION; + } + protected String maxValue; + protected String minValue; + protected String length; + protected String maxLength; + protected String minLength; + + protected String totalDigits; + + private final XsdType type; + + public XSDAttributeValueType(XsdType type) { + this.type = type; + } + + public abstract String getRandomAllowedValue(); + + protected void fillUpRestrictions(XSAttributeDecl attributeDecl) { + XSSimpleType localType = attributeDecl.getType(); + XSRestrictionSimpleType restriction = localType.asRestriction(); + if (restriction != null) { + Iterator i = restriction.getDeclaredFacets().iterator(); + while (i.hasNext()) { + XSFacet facet = i.next(); + if (facet.getName().equals(XSFacet.FACET_MAXINCLUSIVE)) { + maxValue = facet.getValue().value; + } + if (facet.getName().equals(XSFacet.FACET_MININCLUSIVE)) { + minValue = facet.getValue().value; + } + if (facet.getName().equals(XSFacet.FACET_MAXEXCLUSIVE)) { + maxValue = String.valueOf(Integer.parseInt(facet.getValue().value) - 1); + } + if (facet.getName().equals(XSFacet.FACET_MINEXCLUSIVE)) { + minValue = String.valueOf(Integer.parseInt(facet.getValue().value) + 1); + } + if (facet.getName().equals(XSFacet.FACET_LENGTH)) { + length = facet.getValue().value; + } + if (facet.getName().equals(XSFacet.FACET_MAXLENGTH)) { + maxLength = facet.getValue().value; + } + if (facet.getName().equals(XSFacet.FACET_MINLENGTH)) { + minLength = facet.getValue().value; + } + if (facet.getName().equals(XSFacet.FACET_PATTERN)) { + pattern = facet.getValue().value; + } + if (facet.getName().equals(XSFacet.FACET_TOTALDIGITS)) { + totalDigits = facet.getValue().value; + } + } + } + } + + public static class XSDAttributeValueBooleanType extends XSDAttributeValueType { + + public XSDAttributeValueBooleanType() { + super(XsdType.BOOLEAN); + } + + @Override + public String getRandomAllowedValue() { + return RANDOM.nextInt() % 2 == 0 ? getTrue() : getFalse(); + } + + public String getTrue() { + return String.valueOf(true); + } + + public String getFalse() { + return String.valueOf(false); + } + + } + + public static class XSDAttributeValueIntegerType extends XSDAttributeValueType { + + public XSDAttributeValueIntegerType() { + super(XsdType.INTEGER); + } + + @Override + public String getRandomAllowedValue() { + return String.valueOf(RANDOM.nextInt()); + } + + } + + public static class XSDAttributeValuePositiveIntegerType extends XSDAttributeValueType { + + public XSDAttributeValuePositiveIntegerType() { + super(XsdType.POSITIVE_INTEGER); + } + + @Override + public String getRandomAllowedValue() { + return String.valueOf(Math.abs(RANDOM.nextInt() + 1)); + } + + } + + public static class XSDAttributeValueNonNegativeIntegerType extends XSDAttributeValueType { + + public XSDAttributeValueNonNegativeIntegerType() { + super(XsdType.NON_NEGATIVE_INTEGER); + } + + @Override + public String getRandomAllowedValue() { + return String.valueOf(Math.abs(RANDOM.nextInt())); + } + + } + + public static class XSDAttributeValueMemoryUnitType extends XSDAttributeValueType { + + public static final char[] unitChars; + + static { + MemoryUnit[] values = MemoryUnit.values(); + char [] chars = new char[values.length * 2]; + int i = 0; + for (MemoryUnit memoryUnit : values) { + chars[i++] = Character.toLowerCase(memoryUnit.getUnit()); + chars[i++] = Character.toUpperCase(memoryUnit.getUnit()); + } + unitChars = chars; + } + + public XSDAttributeValueMemoryUnitType() { + super(XsdType.NON_NEGATIVE_INTEGER); + } + + @Override + public String getRandomAllowedValue() { + int index = RANDOM.nextInt(unitChars.length + 1); + if(index < unitChars.length) { + return String.valueOf(Math.abs(RANDOM.nextInt())) + unitChars[index]; + } + return String.valueOf(Math.abs(RANDOM.nextInt())); + } + + } + + public static class XSDAttributeValueMemoryUnitOrPercentageType extends XSDAttributeValueType { + + public static final char[] unitChars; + + static { + MemoryUnit[] values = MemoryUnit.values(); + char [] chars = new char[values.length * 2 + 1]; + int i = 0; + for (MemoryUnit memoryUnit : values) { + chars[i++] = Character.toLowerCase(memoryUnit.getUnit()); + chars[i++] = Character.toUpperCase(memoryUnit.getUnit()); + } + chars[i] = '%'; + unitChars = chars; + } + + public XSDAttributeValueMemoryUnitOrPercentageType() { + super(XsdType.NON_NEGATIVE_INTEGER); + } + + @Override + public String getRandomAllowedValue() { + int index = RANDOM.nextInt(unitChars.length + 1); + if(index < unitChars.length) { + switch (unitChars[index]) { + case '%' : + return String.valueOf(Math.abs(RANDOM.nextInt(100) + 1)) + unitChars[index]; + default: + return String.valueOf(Math.abs(RANDOM.nextInt())) + unitChars[index]; + } + } + return String.valueOf(Math.abs(RANDOM.nextInt())); + } + + } + + public static class XSDAttributeValueStringType extends XSDAttributeValueType { + + private static final String[] RANDOM_VALUES = {"random_string_one", "random_string_two", "random_string_three", "random_string_four", + "random_string_five", }; + + public XSDAttributeValueStringType() { + super(XsdType.STRING); + } + + @Override + public String getRandomAllowedValue() { + return RANDOM_VALUES[RANDOM.nextInt(RANDOM_VALUES.length)]; + } + + } + + public static class XSDAttributeValueAnySimpleType extends XSDAttributeValueType { + + private static final String[] RANDOM_VALUES = {"any_simple_type_random_one", "any_simple_type_random_two", + "any_simple_type_random_three", "any_simple_type_random_four", "any_simple_type_random_five", }; + + public XSDAttributeValueAnySimpleType() { + super(XsdType.ANY_SIMPLE_TYPE); + } + + @Override + public String getRandomAllowedValue() { + return RANDOM_VALUES[RANDOM.nextInt(RANDOM_VALUES.length)]; + } + + } + + public static class XSDAttributeValueEnumerationType extends XSDAttributeValueType { + + private final String[] enumeration; + + public XSDAttributeValueEnumerationType(String[] enumeration) { + super(XsdType.ENUMERATION); + this.enumeration = enumeration; + } + + @Override + public String getRandomAllowedValue() { + return enumeration[RANDOM.nextInt(enumeration.length)]; + } + + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/ClusteredTransactionIDSerializationTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/ClusteredTransactionIDSerializationTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache/src/test/java/net/sf/ehcache/terracotta/upgradability/serialization/ClusteredTransactionIDSerializationTest.java (revision 11330) @@ -0,0 +1,59 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.terracotta.upgradability.serialization; + +import java.lang.reflect.Field; +import java.util.Comparator; +import java.util.Map; + +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.transaction.TransactionIDFactory; +import net.sf.ehcache.transaction.TransactionIDSerializedForm; +import org.junit.Test; +import org.terracotta.modules.ehcache.transaction.ClusteredTransactionID; + +import static org.mockito.Matchers.refEq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.terracotta.upgradability.serialization.SerializationUpgradabilityTesting.validateSerializedForm; + +/** + * + * @author cdennis + */ +public class ClusteredTransactionIDSerializationTest { + + private static final Comparator COMPARATOR = new Comparator() { + @Override + public int compare(ClusteredTransactionID o1, ClusteredTransactionID o2) { + return o1.equals(o2) && o1.getOwnerID().equals(o2.getOwnerID()) ? 0 : -1; + } + }; + + @Test + public void testBasic() throws Exception { + Field MANAGERS_MAP = CacheManager.class.getDeclaredField("CACHE_MANAGERS_MAP"); + MANAGERS_MAP.setAccessible(true); + CacheManager manager = mock(CacheManager.class); + ((Map) MANAGERS_MAP.get(null)).put("manager", manager); + TransactionIDFactory txnIdFactory = mock(TransactionIDFactory.class); + when(txnIdFactory.restoreTransactionID(refEq(new TransactionIDSerializedForm("manager", "cluster", "owner", 42L, 2)))) + .thenReturn(new ClusteredTransactionID("owner", "cluster", "manager", 42L, 2)); + when(manager.getOrCreateTransactionIDFactory()).thenReturn(txnIdFactory); + validateSerializedForm(new ClusteredTransactionID("owner", "cluster", "manager", 42L, 2), COMPARATOR, "serializedforms/ClusteredTransactionIDSerializationTest.testBasic.ser"); + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BlockingCacheTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BlockingCacheTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/store/BlockingCacheTest.java (revision 11330) @@ -0,0 +1,135 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.store; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheException; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.constructs.blocking.BlockingCache; + +import org.terracotta.ehcache.tests.AbstractCacheTestBase; +import org.terracotta.ehcache.tests.ClientBase; +import org.terracotta.toolkit.Toolkit; +import org.terracotta.toolkit.concurrent.ToolkitBarrier; + +import com.tc.test.config.model.TestConfig; + +import java.io.Serializable; + +import junit.framework.Assert; + +/** + * @author Alex Snaps + */ +public class BlockingCacheTest extends AbstractCacheTestBase { + + public BlockingCacheTest(TestConfig testConfig) { + super("blocking-cache.xml", testConfig, App.class, App.class, App.class); + } + + public static class App extends ClientBase { + private static final String KEY_1 = "funkyKey"; + private static final Serializable VALUE_1 = "A really cool value"; + private static final String KEY_2 = "otherFunkyKey"; + private static final Serializable VALUE_2 = "Even cooler value"; + private static final String KEY_3 = "theUeberFunkyKey"; + private static final Serializable VALUE_3 = "can't get any cooler value"; + private final ToolkitBarrier barrier; + + public App(String[] args) { + super("test1", args); + this.barrier = getClusteringToolkit().getBarrier("test-barrier", getParticipantCount()); + } + + public static void main(String[] args) { + new App(args).run(); + } + + @Override + protected void runTest(Cache testcache, Toolkit clusteringToolkit) throws Throwable { + final int index = barrier.await(); + + Ehcache cache = cacheManager.getCache("test1"); + Assert.assertNotNull("There should be a cache test from that manager!", cache); + BlockingCache blockingCache = new BlockingCache(cache); + cacheManager.replaceCacheWithDecoratedCache(cache, blockingCache); + cache = cacheManager.getEhcache("test1"); + + if (index == 0) { + // Node 0 blocks all other read to the key + Assert.assertNull("Key " + KEY_1 + " should not be present in the cache yet", cache.get(KEY_1)); + cache.put(new Element(KEY_2, VALUE_2)); + } + + barrier.await(); + + if (index != 0) { + // This call should block, until node 0 puts en element for KEY in the cache + Element element = cache.get(KEY_1); + Assert.assertNotNull("Node 0 should have put key " + KEY_1 + " in the cache", element); + Assert.assertEquals("Value for key " + KEY_1 + " should be " + VALUE_1, VALUE_1, element.getValue()); + } else { + Thread.sleep(2000); // Thinking about the meaning of life for a while + cache.put(new Element(KEY_1, VALUE_1)); + } + Element element = cache.get(KEY_2); + Assert.assertNotNull(element); + Assert.assertEquals("Value for key " + KEY_2 + " should be " + VALUE_2, VALUE_2, element.getValue()); + + barrier.await(); + + blockingCache.setTimeoutMillis(3000); + if (index == 0) { + // Should block all other get to the same key + cache.get(KEY_3); + } + + barrier.await(); + + switch (index) { + case 2: + Thread.sleep(2000); + Assert.assertNotNull(cache.get(KEY_3)); + break; + case 1: + try { + cache.get(KEY_3); + Assert.fail(); + } catch (CacheException e) { + // We failed aquiring the lock + } + break; + case 0: + Thread.sleep(3500); + cache.put(new Element(KEY_3, VALUE_3)); + break; + } + + barrier.await(); + + // This tests inline eviction (EHC-420) + Thread.sleep(22000); + + switch (index) { + case 0: + Assert.assertNull(cache.get(KEY_3)); + break; + } + + barrier.await(); + blockingCache.setTimeoutMillis(10000); + switch (index) { + case 0: + Thread.sleep(1500); + cache.put(new Element(KEY_3, VALUE_3)); + break; + default: + Assert.assertNotNull(cache.get(KEY_3)); + Assert.assertEquals(VALUE_3, cache.get(KEY_3).getValue()); + } + } + + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/basic-dcv2-cache-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/basic-dcv2-cache-test.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/basic-dcv2-cache-test.xml (revision 11330) @@ -0,0 +1,17 @@ + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/impl/CacheManagerConfigurationEntityBuilderV2.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/impl/CacheManagerConfigurationEntityBuilderV2.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/impl/CacheManagerConfigurationEntityBuilderV2.java (revision 11330) @@ -0,0 +1,57 @@ +/* + * 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.CacheManagerConfigEntityV2; +import net.sf.ehcache.management.sampled.CacheManagerSampler; + +import org.terracotta.management.resource.AgentEntityV2; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * @author brandony + */ +final class CacheManagerConfigurationEntityBuilderV2 { + private final List cmSamplers = new ArrayList(); + + static CacheManagerConfigurationEntityBuilderV2 createWith(CacheManagerSampler sampler) { + return new CacheManagerConfigurationEntityBuilderV2(sampler); + } + + private CacheManagerConfigurationEntityBuilderV2(CacheManagerSampler sampler) { + addSampler(sampler); + } + + CacheManagerConfigurationEntityBuilderV2 add(CacheManagerSampler sampler) { + addSampler(sampler); + return this; + } + + Collection build() { + Collection cmces = new ArrayList(cmSamplers.size()); + + for (CacheManagerSampler sampler : cmSamplers) { + CacheManagerConfigEntityV2 cmce = new CacheManagerConfigEntityV2(); + cmce.setCacheManagerName(sampler.getName()); + cmce.setAgentId(AgentEntityV2.EMBEDDED_AGENT_ID); + // cmce.setVersion(this.getClass().getPackage().getImplementationVersion()); + cmce.setXml(sampler.generateActiveConfigDeclaration()); + + cmces.add(cmce); + } + + return cmces; + } + + private void addSampler(CacheManagerSampler sampler) { + if (sampler == null) { + throw new IllegalArgumentException("sampler == null"); + } + cmSamplers.add(sampler); + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/AbstractWriteBehindAtomicityTestBase.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/AbstractWriteBehindAtomicityTestBase.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/AbstractWriteBehindAtomicityTestBase.java (revision 11330) @@ -0,0 +1,73 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.ehcache.tests; + +import org.terracotta.tests.base.AbstractClientBase; + +import com.tc.test.config.model.TestConfig; +import com.tc.util.Assert; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; + +public abstract class AbstractWriteBehindAtomicityTestBase extends AbstractCacheTestBase { + + public AbstractWriteBehindAtomicityTestBase(final String ehcacheConfigPath, TestConfig testConfig, + Class... c) { + super(ehcacheConfigPath, testConfig, c); + testConfig.getClientConfig().getBytemanConfig().setScript("/byteman/writeBehindAtomicity.btm"); + // disableTest(); + } + + // 1) Begin putWithWriter + // 2) lock() putWithWriter + // 3) Begin Transaction + // 4) Commit Transaction + // 5) unlock() putWithWriter + // 6) Done putWithWriter + @Override + protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable { + super.evaluateClientOutput(clientName, exitCode, output); + int txnCount = 0; + boolean underExplicitLock = false; + FileReader fr = null; + BufferedReader reader = null; + try { + fr = new FileReader(output); + reader = new BufferedReader(fr); + String st = ""; + while ((st = reader.readLine()) != null) { + // only check for main thread + if (st.contains("main")) { + if (st.contains("BEGINOPERATION")) { + Assert.assertEquals(false, underExplicitLock); + underExplicitLock = true; + } else if (st.contains("COMMITTRANSACTION") && underExplicitLock) { + txnCount++; + Assert.assertEquals(txnCount, 1); + } else if (st.contains("ENDOPERATION")) { + Assert.assertEquals(true, underExplicitLock); + underExplicitLock = false; + Assert.assertEquals(txnCount, 1); + txnCount = 0; + } + } + } + } catch (Exception e) { + throw new AssertionError(e); + } finally { + try { + fr.close(); + reader.close(); + } catch (Exception e) { + // + } + } + + Assert.assertEquals(false, underExplicitLock); + Assert.assertEquals(txnCount, 0); + } + +} \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/StrictlyBoundedPool.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/StrictlyBoundedPool.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/StrictlyBoundedPool.java (revision 11330) @@ -0,0 +1,52 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.pool.impl; + +import net.sf.ehcache.pool.PoolAccessor; +import net.sf.ehcache.pool.PoolEvictor; +import net.sf.ehcache.pool.PoolParticipant; +import net.sf.ehcache.pool.SizeOfEngine; + +/** + * A pool which strictly obeys to its bound: it will never allow the accessors to consume more bytes than what + * has been configured. + * + * @author Ludovic Orban + * @author Alex Snaps + */ +public class StrictlyBoundedPool extends AbstractPool { + + /** + * Create a StrictlyBoundedPool instance + * + * @param maximumPoolSize the maximum size of the pool, in bytes. + * @param evictor the pool evictor, for cross-store eviction. + * @param defaultSizeOfEngine the default SizeOf engine used by the accessors. + */ + public StrictlyBoundedPool(long maximumPoolSize, PoolEvictor evictor, SizeOfEngine defaultSizeOfEngine) { + super(maximumPoolSize, evictor, defaultSizeOfEngine); + } + + /** + * {@inheritDoc} + */ + public PoolAccessor createPoolAccessor(PoolParticipant participant, SizeOfEngine sizeOfEngine) { + LockedPoolAccessor accessor = new LockedPoolAccessor(this, participant, sizeOfEngine, 0); + registerPoolAccessor(accessor); + return accessor; + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/transaction/TransactionTimeoutException.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/transaction/TransactionTimeoutException.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/transaction/TransactionTimeoutException.java (revision 11330) @@ -0,0 +1,32 @@ +/** + * 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; + +/** + * This exception is thrown when a transactional operation times out + * + * @author Ludovic Orban + */ +public class TransactionTimeoutException extends TransactionException { + + /** + * Create a new TransactionTimeoutException + * @param message the error message + */ + public TransactionTimeoutException(String message) { + super(message); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/cluster/NoopCacheCluster.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/cluster/NoopCacheCluster.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/cluster/NoopCacheCluster.java (revision 11330) @@ -0,0 +1,98 @@ +/** + * 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.cluster; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * This is a dummy implementation of the CacheCluster (Null Object Pattern). It ignores + * all listeners and reports no nodes. + * + * @author Geert Bevin + * @since 2.0 + */ +public class NoopCacheCluster implements CacheCluster { + + /** + * A singleton instance you can use rather than constructing your own. + */ + public static final CacheCluster INSTANCE = new NoopCacheCluster(); + + /** + * {@inheritDoc} + */ + public Collection getNodes() { + return Collections.emptyList(); + } + + /** + * Always returns the ClusterScheme.NONE + * + * @return {@link ClusterScheme#NONE} + */ + public ClusterScheme getScheme() { + return ClusterScheme.NONE; + } + + /** + * {@inheritDoc} + */ + public boolean addTopologyListener(ClusterTopologyListener listener) { + return false; + } + + /** + * {@inheritDoc} + */ + public boolean removeTopologyListener(ClusterTopologyListener listener) { + return false; + } + + /** + * {@inheritDoc} + */ + public boolean isClusterOnline() { + return true; + } + + /** + * {@inheritDoc} + */ + public ClusterNode getCurrentNode() { + return null; + } + + /** + * {@inheritDoc} + */ + public ClusterNode waitUntilNodeJoinsCluster() { + return null; + } + + /** + * {@inheritDoc} + */ + public List getTopologyListeners() { + return Collections.emptyList(); + } + + @Override + public void removeAllListeners() { + // + } +} Index: rctags/ehcache-2.10.9.0.363/distribution/events/src/assemble/bin/start-jetty.bat =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/distribution/events/src/assemble/bin/start-jetty.bat (revision 0) +++ rctags/ehcache-2.10.9.0.363/distribution/events/src/assemble/bin/start-jetty.bat (revision 11330) @@ -0,0 +1,40 @@ +@echo off + +if not defined JAVA_HOME ( + echo JAVA_HOME is not defined + exit /b 1 +) + +setlocal + +set jetty_instance=%1 + +if "%jetty_instance%" == "" ( + echo Need to specify which instance of Jetty: 9081 or 9082 + exit /b 1 +) + +pushd "%~d0%~p0" +for /f "tokens=*" %%a in ('call relative-paths.bat tc_install_dir') do set tc_install_dir=%%a +pushd +cd %tc_install_dir% +set tc_install_dir=%CD% +set tc_install_dir="%tc_install_dir:"=%" +popd +popd + +set JAVA_HOME="%JAVA_HOME:"=%" +set root=%~d0%~p0.. +set root="%root:"=%" +set jetty_work_dir=%root%\jetty6.1\%jetty_instance% +set jetty_home=%tc_install_dir%\third-party\jetty-6.1.15 +set start_jar=%jetty_home%\start.jar +set /a stop_port=jetty_instance + 2 + +cd %jetty_work_dir% +mkdir logs +echo Starting Jetty %jetty_instance%... +start "Jetty %jetty_instance%" %JAVA_HOME%\bin\java -Dtc.install-root=%tc_install_dir% -Xmx256m -XX:MaxPermSize=128m -Dconfig.home=%jetty_work_dir% -Djetty.home=%jetty_home% -DSTOP.PORT=%stop_port% -DSTOP.KEY=secret -jar %start_jar% conf.xml +echo. + +endlocal Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/util/WeakIdentityConcurrentMapTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/util/WeakIdentityConcurrentMapTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/util/WeakIdentityConcurrentMapTest.java (revision 11330) @@ -0,0 +1,62 @@ +package net.sf.ehcache.util; + +import org.hamcrest.core.Is; +import org.junit.Test; + +import java.util.concurrent.Callable; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicLong; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.hamcrest.CoreMatchers.equalTo; +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; + +/** + * @author Alex Snaps + */ +public class WeakIdentityConcurrentMapTest { + + private Long someKey = 1024L; + + @Test + public void testReturnsValueAndCleanUpsProperly() { + + final ConcurrentMap cleanedUpValues = new ConcurrentHashMap(); + + final WeakIdentityConcurrentMap map = new WeakIdentityConcurrentMap(new WeakIdentityConcurrentMap.CleanUpTask() { + public void cleanUp(final String value) { + final AtomicLong previous = cleanedUpValues.putIfAbsent(value, new AtomicLong(1)); + if(previous != null) { + previous.incrementAndGet(); + } + } + }); + + final String value1 = "someValue for 1"; + final String value2 = "someValue for 1024"; + assertThat(map.putIfAbsent(1L, value1), nullValue()); + assertThat(map.putIfAbsent(someKey, value2), nullValue()); + assertThat(map.putIfAbsent(someKey, value2), equalTo(value2)); + assertThat(map.get(1L), equalTo(value1)); + assertThat(map.get(someKey), equalTo(value2)); + someKey = null; + + RetryAssert.assertBy(10, SECONDS, new Callable() { + public Integer call() throws Exception { + int i = 0; + while (i++ < 50) { + System.gc(); + assertThat(map.get(someKey), nullValue()); + } + return cleanedUpValues.size(); + } + }, Is.is(1)); + + assertThat(cleanedUpValues.get(value2), notNullValue()); + assertThat(cleanedUpValues.get(value2).get(), is(1L)); + } +} Index: rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncConfig.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncConfig.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/async/AsyncConfig.java (revision 11330) @@ -0,0 +1,78 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.async; + +import java.io.Serializable; + +public interface AsyncConfig extends Serializable { + /** + * Returns the minimum amount of time to wait between individual work cycles. + *

+ * This allows work to accumulate in the write behind queue and be processed more efficiently. + * + * @return the work delay that should be used, in milliseconds + */ + public long getWorkDelay(); + + /** + * The maximum amount of time that a queue is allowed to fall behind on the work that it's processing. + * + * @return the maximum of time that the queue is allowed to fall behind, in milliseconds + */ + public long getMaxAllowedFallBehind(); + + /** + * The number of items to include in each batch when batching is enabled. If there are less entries in the queue than + * the batch size, the queue length size is used. + * + * @return the amount of items to batch + */ + public int getBatchSize(); + + /** + * Indicates whether to batch items. If set to {@code true}, {@link ItemProcessor#process(java.util.Collection)} will + * be called rather than {@link ItemProcessor#process(Serializable)} being called for individual item. Resources such as + * databases can perform more efficiently if updates are batched, thus reducing load. + * + * @return {@code true} if items should be batched; {@code false} otherwise + */ + public boolean isBatchingEnabled(); + + /** + * Perform all writes to the Terracotta backend in a synchronous fashion, hence increasing reliability but decreasing + * performance. + * + * @return {@code true} to enable synchronous writes; or {@code false} to perform the write asynchronously + */ + public boolean isSynchronousWrite(); + + /** + * Retrieves the number of times the processing of an item is retried. + * + * @return the number of tries before this pass is considered failed + */ + public int getRetryAttempts(); + + /** + * Retrieves the number of milliseconds to wait before retrying a failed operation. + * + * @return the delay in between retries, in milliseconds + */ + public long getRetryAttemptDelay(); + + /** + * Sets the maximum number of operations to allow per second when {@link #isBatchingEnabled} is enabled. + * + * @return the rate limit + */ + public int getRateLimit(); + + /** + * The maximum size of items the Async coordinator can hold. + * + * @return + */ + public int getMaxQueueSize(); + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/store/disk/SegmentTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/store/disk/SegmentTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/store/disk/SegmentTest.java (revision 11330) @@ -0,0 +1,43 @@ +package net.sf.ehcache.store.disk; + +import net.sf.ehcache.CacheOperationOutcomes; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.event.CacheEventListener; +import net.sf.ehcache.event.RegisteredEventListeners; +import net.sf.ehcache.pool.PoolAccessor; + +import org.junit.Test; +import org.terracotta.statistics.observer.OperationObserver; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * SegmentTest + */ +public class SegmentTest { + + @Test + public void testInlineEvictionNotified() { + PoolAccessor onHeapAccessor = mock(PoolAccessor.class); + when(onHeapAccessor.add(eq("key"), any(DiskStorageFactory.DiskSubstitute.class), any(HashEntry.class), eq(false))).thenReturn(-1L); + RegisteredEventListeners cacheEventNotificationService = new RegisteredEventListeners(mock(Ehcache.class), null); + CacheEventListener listener = mock(CacheEventListener.class); + cacheEventNotificationService.registerListener(listener); + + OperationObserver evictionObserver = mock(OperationObserver.class); + DiskStorageFactory diskStorageFactory = mock(DiskStorageFactory.class); + + Segment segment = new Segment(10, .95f, diskStorageFactory, mock(CacheConfiguration.class), onHeapAccessor, mock(PoolAccessor.class), cacheEventNotificationService, evictionObserver); + Element element = new Element("key", "value"); + when(diskStorageFactory.create(element)).thenReturn(new DiskStorageFactory.DiskMarker(diskStorageFactory, 0L, 0, element)); + segment.put("key", 12, element, false, false); + verify(listener).notifyElementEvicted(any(Ehcache.class), eq(element)); + verify(evictionObserver).end(CacheOperationOutcomes.EvictionOutcome.SUCCESS); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/beans/AttributeProxy.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/beans/AttributeProxy.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/beans/AttributeProxy.java (revision 11330) @@ -0,0 +1,116 @@ +/** + * 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; + +/** + * The Class AttributeProxy, used to proxy operations from a dynamic mbean to a POJO object. + * Override get()/set() as needed. + * + * @param the return type/set type for the attribute + * + * @author cschanck + */ +public abstract class AttributeProxy { + private final String name; + private final Class clazz; + private final boolean isWrite; + private final boolean isRead; + private final String description; + + /** + * Instantiates a new attribute proxy. + * + * @param clazz the clazz of the return type + * @param name the name + * @param description the description + * @param isRead readable + * @param isWrite writable + */ + public AttributeProxy(Class clazz, String name, String description, boolean isRead, boolean isWrite) { + this.name = name; + this.description = description; + this.clazz = clazz; + this.isWrite = isWrite; + this.isRead = isRead; + } + + /** + * Gets the description. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Gets the type class. + * + * @return the type class + */ + public Class getTypeClass() { + return clazz; + } + + /** + * Gets the name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Gets the value. + * + * @param name the name + * @return the value + */ + public T get(String name) { + throw new UnsupportedOperationException(); + } + + /** + * Sets the value. + * + * @param name the name + * @param t the value + */ + public void set(String name, T t) { + throw new UnsupportedOperationException(); + } + + /** + * Checks if is readable. + * + * @return true, if is read + */ + public boolean isRead() { + return isRead; + } + + /** + * Checks if is writable. + * + * @return true, if is writable + */ + public boolean isWrite() { + return isWrite; + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache/src/main/resources/META-INF/terracotta/public-api-types =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache/src/main/resources/META-INF/terracotta/public-api-types (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache/src/main/resources/META-INF/terracotta/public-api-types (revision 11330) @@ -0,0 +1 @@ +# Don't remove this line -- if file is empty then everything will become an API type Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/BaseEmitterBean.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/BaseEmitterBean.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/BaseEmitterBean.java (revision 11330) @@ -0,0 +1,168 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.hibernate.management.impl; + +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicLong; + +import javax.management.ListenerNotFoundException; +import javax.management.MBeanNotificationInfo; +import javax.management.NotCompliantMBeanException; +import javax.management.Notification; +import javax.management.NotificationBroadcasterSupport; +import javax.management.NotificationEmitter; +import javax.management.NotificationFilter; +import javax.management.NotificationListener; +import javax.management.StandardMBean; + +/** + * @author gkeim + * + */ +public abstract class BaseEmitterBean extends StandardMBean implements NotificationEmitter { + /** + * emitter + */ + protected final Emitter emitter = new Emitter(); + + /** + * sequenceNumber + */ + protected final AtomicLong sequenceNumber = new AtomicLong(); + + + private final List notificationListeners = new CopyOnWriteArrayList(); + + /** + * BaseEmitterBean + * + * @param + * @param mbeanInterface + * @throws NotCompliantMBeanException + */ + protected BaseEmitterBean(Class mbeanInterface) throws NotCompliantMBeanException { + super(mbeanInterface); + } + + /** + * sendNotification + * + * @param eventType + */ + public void sendNotification(String eventType) { + sendNotification(eventType, null, null); + } + + /** + * sendNotification + * + * @param eventType + * @param data + */ + public void sendNotification(String eventType, Object data) { + sendNotification(eventType, data, null); + } + + /** + * sendNotification + * + * @param eventType + * @param data + * @param msg + */ + public void sendNotification(String eventType, Object data, String msg) { + Notification notif = new Notification(eventType, this, sequenceNumber.incrementAndGet(), System.currentTimeMillis(), msg); + if (data != null) { + notif.setUserData(data); + } + emitter.sendNotification(notif); + } + + /** + * Dispose of this SampledCacheManager and clean up held resources + */ + public final void dispose() { + doDispose(); + removeAllNotificationListeners(); + } + + /** + * Dispose callback of subclasses + */ + protected abstract void doDispose(); + + /** + * @author gkeim + */ + private class Emitter extends NotificationBroadcasterSupport { + /** + * @see javax.management.NotificationBroadcasterSupport#getNotificationInfo() + */ + @Override + public MBeanNotificationInfo[] getNotificationInfo() { + return BaseEmitterBean.this.getNotificationInfo(); + } + } + + /** + * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, + * javax.management.NotificationFilter, java.lang.Object) + */ + public void addNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) { + emitter.addNotificationListener(notif, filter, callBack); + notificationListeners.add(notif); + } + + /** + * remove all added notification listeners + */ + private void removeAllNotificationListeners() { + for (NotificationListener listener : notificationListeners) { + try { + emitter.removeNotificationListener(listener); + } catch (ListenerNotFoundException e) { + // ignore + } + } + notificationListeners.clear(); + } + + /** + * @see javax.management.NotificationBroadcaster#getNotificationInfo() + */ + public abstract MBeanNotificationInfo[] getNotificationInfo(); + + + /** + * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener) + */ + public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { + emitter.removeNotificationListener(listener); + notificationListeners.remove(listener); + } + + /** + * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, + * javax.management.NotificationFilter, java.lang.Object) + */ + public void removeNotificationListener(NotificationListener notif, NotificationFilter filter, Object callBack) + throws ListenerNotFoundException { + emitter.removeNotificationListener(notif, filter, callBack); + notificationListeners.remove(notif); + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/hibernate-config/nontransactional/domain/HolidayCalendar.hbm.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/hibernate-config/nontransactional/domain/HolidayCalendar.hbm.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/hibernate-config/nontransactional/domain/HolidayCalendar.hbm.xml (revision 11330) @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheEntityV2.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheEntityV2.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-v2/src/main/java/net/sf/ehcache/management/resource/CacheEntityV2.java (revision 11330) @@ -0,0 +1,23 @@ +/* All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.*/ + +package net.sf.ehcache.management.resource; + +import java.util.HashMap; +import java.util.Map; + + +/** + *

+ * An entity representing a cache resource from the management API. + *

+ * + * @author brandony + * + */ +public class CacheEntityV2 extends AbstractCacheEntityV2 { + private Map attributes = new HashMap(); + + public Map getAttributes() { + return attributes; + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/store/chm/SelectableConcurrentHashMap.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/store/chm/SelectableConcurrentHashMap.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/store/chm/SelectableConcurrentHashMap.java (revision 11330) @@ -0,0 +1,1259 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.ehcache.store.chm; + +import java.util.AbstractCollection; +import java.util.AbstractSet; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.NoSuchElementException; +import java.util.Random; +import java.util.Set; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +import net.sf.ehcache.CacheOperationOutcomes.EvictionOutcome; +import net.sf.ehcache.Element; +import net.sf.ehcache.event.RegisteredEventListeners; +import net.sf.ehcache.pool.PoolAccessor; +import org.terracotta.statistics.observer.OperationObserver; + +import static net.sf.ehcache.statistics.StatisticBuilder.operation; + +/** + * SelectableConcurrentHashMap subclasses a repackaged version of ConcurrentHashMap + * ito allow efficient random sampling of the map values. + *

+ * The random sampling technique involves randomly selecting a map Segment, and then + * selecting a number of random entry chains from that segment. + * + * @author Chris Dennis + */ +@SuppressWarnings("ForLoopReplaceableByForEach") +public class SelectableConcurrentHashMap { + + /** + * The default initial capacity for this table, + * used when not otherwise specified in a constructor. + */ + static final int DEFAULT_INITIAL_CAPACITY = 16; + + /** + * The default load factor for this table, used when not + * otherwise specified in a constructor. + */ + static final float DEFAULT_LOAD_FACTOR = 0.75f; + + /** + * The maximum capacity, used if a higher value is implicitly + * specified by either of the constructors with arguments. MUST + * be a power of two <= 1<<30 to ensure that entries are indexable + * using ints. + */ + private static final int MAXIMUM_CAPACITY = 1 << 30; + + /** + * The maximum number of segments to allow; used to bound + * constructor arguments. + */ + private static final int MAX_SEGMENTS = 1 << 16; // slightly conservative + + /** + * Number of unsynchronized retries in size and containsValue + * methods before resorting to locking. This is used to avoid + * unbounded retries if tables undergo continuous modification + * which would make it impossible to obtain an accurate result. + */ + private static final int RETRIES_BEFORE_LOCK = 2; + + /** + * Mask value for indexing into segments. The upper bits of a + * key's hash code are used to choose the segment. + */ + private final int segmentMask; + + /** + * Shift value for indexing within segments. + */ + private final int segmentShift; + + /** + * The segments, each of which is a specialized hash table + */ + private final Segment[] segments; + + private final Random rndm = new Random(); + private final PoolAccessor poolAccessor; + private volatile long maxSize; + private final RegisteredEventListeners cacheEventNotificationService; + + private Set keySet; + private Set> entrySet; + private Collection values; + + private final OperationObserver evictionObserver = operation(EvictionOutcome.class).named("eviction").of(this).build(); + + public SelectableConcurrentHashMap(PoolAccessor poolAccessor, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService) { + this(poolAccessor, DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, concurrency, maximumSize, cacheEventNotificationService); + } + + public SelectableConcurrentHashMap(PoolAccessor poolAccessor, int initialCapacity, float loadFactor, int concurrency, final long maximumSize, final RegisteredEventListeners cacheEventNotificationService) { + if (!(loadFactor > 0) || initialCapacity < 0 || concurrency <= 0) + throw new IllegalArgumentException(); + + if (concurrency > MAX_SEGMENTS) + concurrency = MAX_SEGMENTS; + + // Find power-of-two sizes best matching arguments + int sshift = 0; + int ssize = 1; + while (ssize < concurrency) { + ++sshift; + ssize <<= 1; + } + segmentShift = 32 - sshift; + segmentMask = ssize - 1; + this.segments = new Segment[ssize]; + + if (initialCapacity > MAXIMUM_CAPACITY) + initialCapacity = MAXIMUM_CAPACITY; + int c = initialCapacity / ssize; + if (c * ssize < initialCapacity) + ++c; + int cap = 1; + while (cap < c) + cap <<= 1; + + for (int i = 0; i < this.segments.length; ++i) + this.segments[i] = createSegment(cap, loadFactor); + + this.poolAccessor = poolAccessor; + this.maxSize = maximumSize; + this.cacheEventNotificationService = cacheEventNotificationService; + } + + public void setMaxSize(final long maxSize) { + this.maxSize = maxSize; + } + + public Element[] getRandomValues(final int size, Object keyHint) { + ArrayList sampled = new ArrayList(size * 2); + + // pick a random starting point in the map + int randomHash = rndm.nextInt(); + + final int segmentStart; + if (keyHint == null) { + segmentStart = (randomHash >>> segmentShift) & segmentMask; + } else { + segmentStart = (hash(keyHint.hashCode()) >>> segmentShift) & segmentMask; + } + + int segmentIndex = segmentStart; + do { + final HashEntry[] table = segments[segmentIndex].table; + final int tableStart = randomHash & (table.length - 1); + int tableIndex = tableStart; + do { + for (HashEntry e = table[tableIndex]; e != null; e = e.next) { + Element value = e.value; + if (value != null) { + sampled.add(value); + } + } + + if (sampled.size() >= size) { + return sampled.toArray(new Element[sampled.size()]); + } + + //move to next table slot + tableIndex = (tableIndex + 1) & (table.length - 1); + } while (tableIndex != tableStart); + + //move to next segment + segmentIndex = (segmentIndex + 1) & segmentMask; + } while (segmentIndex != segmentStart); + + return sampled.toArray(new Element[sampled.size()]); + } + + /** + * Return an object of the kind which will be stored when + * the element is going to be inserted + * @param e the element + * @return an object looking-alike the stored one + */ + public Object storedObject(Element e) { + return new HashEntry(null, 0, null, e, 0); + } + + /** + * Returns the number of key-value mappings in this map without locking anything. + * This may not give the exact element count as locking is avoided. + * If the map contains more than Integer.MAX_VALUE elements, returns + * Integer.MAX_VALUE. + * + * @return the number of key-value mappings in this map + */ + public int quickSize() { + final Segment[] segments = this.segments; + long sum = 0; + for (Segment seg : segments) { + sum += seg.count; + } + + if (sum > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } else { + return (int)sum; + } + } + + public boolean isEmpty() { + final Segment[] segments = this.segments; + /* + * We keep track of per-segment modCounts to avoid ABA + * problems in which an element in one segment was added and + * in another removed during traversal, in which case the + * table was never actually empty at any point. Note the + * similar use of modCounts in the size() and containsValue() + * methods, which are the only other methods also susceptible + * to ABA problems. + */ + int[] mc = new int[segments.length]; + int mcsum = 0; + for (int i = 0; i < segments.length; ++i) { + if (segments[i].count != 0) + return false; + else + mcsum += mc[i] = segments[i].modCount; + } + // If mcsum happens to be zero, then we know we got a snapshot + // before any modifications at all were made. This is + // probably common enough to bother tracking. + if (mcsum != 0) { + for (int i = 0; i < segments.length; ++i) { + if (segments[i].count != 0 || + mc[i] != segments[i].modCount) + return false; + } + } + return true; + } + + public int size() { + final Segment[] segments = this.segments; + + for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) { + int[] mc = new int[segments.length]; + long check = 0; + long sum = 0; + int mcsum = 0; + for (int i = 0; i < segments.length; ++i) { + sum += segments[i].count; + mcsum += mc[i] = segments[i].modCount; + } + if (mcsum != 0) { + for (int i = 0; i < segments.length; ++i) { + check += segments[i].count; + if (mc[i] != segments[i].modCount) { + check = -1; // force retry + break; + } + } + } + if (check == sum) { + if (sum > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } else { + return (int)sum; + } + } + } + + long sum = 0; + for (int i = 0; i < segments.length; ++i) { + segments[i].readLock().lock(); + } + try { + for (int i = 0; i < segments.length; ++i) { + sum += segments[i].count; + } + } finally { + for (int i = 0; i < segments.length; ++i) { + segments[i].readLock().unlock(); + } + } + + if (sum > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } else { + return (int)sum; + } + } + + public ReentrantReadWriteLock lockFor(Object key) { + int hash = hash(key.hashCode()); + return segmentFor(hash); + } + + public ReentrantReadWriteLock[] locks() { + return segments; + } + + public Element get(Object key) { + int hash = hash(key.hashCode()); + return segmentFor(hash).get(key, hash); + } + + public boolean containsKey(Object key) { + int hash = hash(key.hashCode()); + return segmentFor(hash).containsKey(key, hash); + } + + public boolean containsValue(Object value) { + if (value == null) + throw new NullPointerException(); + + // See explanation of modCount use above + + final Segment[] segments = this.segments; + int[] mc = new int[segments.length]; + + // Try a few times without locking + for (int k = 0; k < RETRIES_BEFORE_LOCK; ++k) { + int sum = 0; + int mcsum = 0; + for (int i = 0; i < segments.length; ++i) { + int c = segments[i].count; + mcsum += mc[i] = segments[i].modCount; + if (segments[i].containsValue(value)) + return true; + } + boolean cleanSweep = true; + if (mcsum != 0) { + for (int i = 0; i < segments.length; ++i) { + int c = segments[i].count; + if (mc[i] != segments[i].modCount) { + cleanSweep = false; + break; + } + } + } + if (cleanSweep) + return false; + } + + // Resort to locking all segments + for (int i = 0; i < segments.length; ++i) + segments[i].readLock().lock(); + try { + for (int i = 0; i < segments.length; ++i) { + if (segments[i].containsValue(value)) { + return true; + } + } + } finally { + for (int i = 0; i < segments.length; ++i) + segments[i].readLock().unlock(); + } + return false; + } + + public Element put(Object key, Element element, long sizeOf) { + int hash = hash(key.hashCode()); + return segmentFor(hash).put(key, hash, element, sizeOf, false, true); + } + + public Element putIfAbsent(Object key, Element element, long sizeOf) { + int hash = hash(key.hashCode()); + return segmentFor(hash).put(key, hash, element, sizeOf, true, true); + } + + public Element remove(Object key) { + int hash = hash(key.hashCode()); + return segmentFor(hash).remove(key, hash, null); + } + + public boolean remove(Object key, Object value) { + int hash = hash(key.hashCode()); + if (value == null) + return false; + return segmentFor(hash).remove(key, hash, value) != null; + } + + public void clear() { + for (int i = 0; i < segments.length; ++i) + segments[i].clear(); + } + + public Set keySet() { + Set ks = keySet; + return (ks != null) ? ks : (keySet = new KeySet()); + } + + public Collection values() { + Collection vs = values; + return (vs != null) ? vs : (values = new Values()); + } + + public Set> entrySet() { + Set> es = entrySet; + return (es != null) ? es : (entrySet = new EntrySet()); + } + + protected Segment createSegment(int initialCapacity, float lf) { + return new Segment(initialCapacity, lf); + } + + public boolean evict() { + return getRandomSegment().evict(); + } + + private Segment getRandomSegment() { + int randomHash = rndm.nextInt(); + return segments[((randomHash >>> segmentShift) & segmentMask)]; + } + + public void recalculateSize(Object key) { + int hash = hash(key.hashCode()); + segmentFor(hash).recalculateSize(key, hash); + } + + /** + * Returns the segment that should be used for key with given hash + * @param hash the hash code for the key + * @return the segment + */ + protected final Segment segmentFor(int hash) { + return segments[(hash >>> segmentShift) & segmentMask]; + } + + protected final List segments() { + return Collections.unmodifiableList(Arrays.asList(segments)); + } + + public class Segment extends ReentrantReadWriteLock { + + private static final int MAX_EVICTION = 5; + + /** + * The number of elements in this segment's region. + */ + protected volatile int count; + + /** + * Number of updates that alter the size of the table. This is + * used during bulk-read methods to make sure they see a + * consistent snapshot: If modCounts change during a traversal + * of segments computing size or checking containsValue, then + * we might have an inconsistent view of state so (usually) + * must retry. + */ + int modCount; + + /** + * The table is rehashed when its size exceeds this threshold. + * (The value of this field is always (int)(capacity * + * loadFactor).) + */ + int threshold; + + /** + * The per-segment table. + */ + protected volatile HashEntry[] table; + + /** + * The load factor for the hash table. Even though this value + * is same for all segments, it is replicated to avoid needing + * links to outer object. + * @serial + */ + final float loadFactor; + + private Iterator evictionIterator; + + protected Segment(int initialCapacity, float lf) { + loadFactor = lf; + setTable(new HashEntry[initialCapacity]); + } + + protected void preRemove(HashEntry e) { + + } + + protected void postInstall(Object key, Element value) { + + } + + /** + * Sets table to new HashEntry array. + * Call only while holding lock or in constructor. + */ + void setTable(HashEntry[] newTable) { + threshold = (int)(newTable.length * loadFactor); + table = newTable; + } + + /** + * Returns properly casted first entry of bin for given hash. + */ + protected HashEntry getFirst(int hash) { + HashEntry[] tab = table; + return tab[hash & (tab.length - 1)]; + } + + private HashEntry removeAndGetFirst(HashEntry e, HashEntry first) { + preRemove(e); + // All entries following removed node can stay + // in list, but all preceding ones need to be + // cloned. + HashEntry newFirst = e.next; + for (HashEntry p = first; p != e; p = p.next) + newFirst = relinkHashEntry(p, newFirst); + return newFirst; + } + + protected HashEntry createHashEntry(Object key, int hash, HashEntry next, Element value, long sizeOf) { + return new HashEntry(key, hash, next, value, sizeOf); + } + + protected HashEntry relinkHashEntry(HashEntry e, HashEntry next) { + return new HashEntry(e.key, e.hash, next, e.value, e.sizeOf); + } + + protected void clear() { + final WriteLock writeLock = writeLock(); + writeLock.lock(); + try { + if (count != 0) { + HashEntry[] tab = table; + for (int i = 0; i < tab.length ; i++) + tab[i] = null; + ++modCount; + count = 0; // write-volatile + } + evictionIterator = null; + } finally { + writeLock.unlock(); + } + } + + Element remove(Object key, int hash, Object value) { + final WriteLock writeLock = writeLock(); + writeLock.lock(); + try { + int c = count - 1; + HashEntry[] tab = table; + int index = hash & (tab.length - 1); + HashEntry first = tab[index]; + HashEntry e = first; + while (e != null && (e.hash != hash || !key.equals(e.key))) + e = e.next; + + Element oldValue = null; + if (e != null) { + Element v = e.value; + if (value == null || value.equals(v)) { + oldValue = v; + ++modCount; + tab[index] = removeAndGetFirst(e, first); + count = c; // write-volatile + if (cacheEventNotificationService != null) { + cacheEventNotificationService.notifyElementRemovedOrdered(oldValue); + } + poolAccessor.delete(e.sizeOf); + if(evictionIterator != null && ((SegmentIterator)evictionIterator).nextEntry == e) { + evictionIterator.next(); + } + } + } + return oldValue; + } finally { + writeLock.unlock(); + } + } + + public void recalculateSize(Object key, int hash) { + Element value = null; + long oldSize = 0; + final ReadLock readLock = readLock(); + readLock.lock(); + try { + HashEntry[] tab = table; + int index = hash & (tab.length - 1); + HashEntry first = tab[index]; + HashEntry e = first; + while (e != null && (e.hash != hash || !key.equals(e.key))) { + e = e.next; + } + if (e != null) { + key = e.key; + value = e.value; + oldSize = e.sizeOf; + } + } finally { + readLock.unlock(); + } + if (value != null) { + long delta = poolAccessor.replace(oldSize, key, value, storedObject(value), true); + final WriteLock writeLock = writeLock(); + writeLock.lock(); + try { + HashEntry e = getFirst(hash); + while (e != null && key != e.key) { + e = e.next; + } + + if (e != null && e.value == value && oldSize == e.sizeOf) { + e.sizeOf = oldSize + delta; + } else { + poolAccessor.delete(delta); + } + } finally { + writeLock.unlock(); + } + } + } + + protected Element put(Object key, int hash, Element value, long sizeOf, boolean onlyIfAbsent, boolean fire) { + Element[] evicted = new Element[MAX_EVICTION]; + final WriteLock writeLock = writeLock(); + writeLock.lock(); + try { + int c = count; + if (c++ > threshold) // ensure capacity + rehash(); + HashEntry[] tab = table; + int index = hash & (tab.length - 1); + HashEntry first = tab[index]; + HashEntry e = first; + while (e != null && (e.hash != hash || !key.equals(e.key))) + e = e.next; + + Element oldValue; + if (e != null) { + oldValue = e.value; + if (!onlyIfAbsent) { + poolAccessor.delete(e.sizeOf); + e.value = value; + e.sizeOf = sizeOf; + if (cacheEventNotificationService != null) { + cacheEventNotificationService.notifyElementUpdatedOrdered(oldValue, value); + } + if (fire) { + postInstall(key, value); + } + } + } else { + oldValue = null; + ++modCount; + tab[index] = createHashEntry(key, hash, first, value, sizeOf); + count = c; // write-volatile + if (cacheEventNotificationService != null) { + cacheEventNotificationService.notifyElementPutOrdered(value); + } + if (fire) { + postInstall(key, value); + } + } + + if((onlyIfAbsent && oldValue != null || !onlyIfAbsent)) { + if (SelectableConcurrentHashMap.this.maxSize > 0) { + int runs = Math.min(MAX_EVICTION, SelectableConcurrentHashMap.this.quickSize() - (int) SelectableConcurrentHashMap.this.maxSize); + while (runs-- > 0) { + evictionObserver.begin(); + Element evict = nextExpiredOrToEvict(value); + if (evict != null) { + Element removed; + while ((removed = remove(evict.getKey(), hash(evict.getKey().hashCode()), null)) == null) { + evict = nextExpiredOrToEvict(value); + if (evict == null) { + break; + } + } + evicted[runs] = removed; + } + evictionObserver.end(EvictionOutcome.SUCCESS); + } + } + } + return oldValue; + } finally { + writeLock.unlock(); + for (Element element : evicted) { + notifyEvictionOrExpiry(element); + } + } + } + + private void notifyEvictionOrExpiry(final Element element) { + if(element != null && cacheEventNotificationService != null) { + if (element.isExpired()) { + cacheEventNotificationService.notifyElementExpiry(element, false); + } else { + cacheEventNotificationService.notifyElementEvicted(element, false); + } + } + } + + Element get(final Object key, final int hash) { + final ReadLock readLock = readLock(); + readLock.lock(); + try { + if (count != 0) { // read-volatile + HashEntry e = getFirst(hash); + while (e != null) { + if (e.hash == hash && key.equals(e.key)) { + e.accessed = true; + return e.value; + } + e = e.next; + } + } + return null; + } finally { + readLock.unlock(); + } + } + + boolean containsKey(final Object key, final int hash) { + final ReadLock readLock = readLock(); + readLock.lock(); + try { + if (count != 0) { // read-volatile + HashEntry e = getFirst(hash); + while (e != null) { + if (e.hash == hash && key.equals(e.key)) + return true; + e = e.next; + } + } + return false; + } finally { + readLock.unlock(); + } + } + + boolean containsValue(Object value) { + final ReadLock readLock = readLock(); + readLock.lock(); + try { + if (count != 0) { // read-volatile + HashEntry[] tab = table; + int len = tab.length; + for (int i = 0 ; i < len; i++) { + for (HashEntry e = tab[i]; e != null; e = e.next) { + Element v = e.value; + if (value.equals(v)) + return true; + } + } + } + return false; + } finally { + readLock.unlock(); + } + } + + private Element nextExpiredOrToEvict(final Element justAdded) { + + Element lastUnpinned = null; + int i = 0; + + while (i++ < count) { + if (evictionIterator == null || !evictionIterator.hasNext()) { + evictionIterator = iterator(); + } + final HashEntry next = evictionIterator.next(); + if (!next.accessed || next.value.isExpired()) { + return next.value; + } else { + if (next.value != justAdded) { + lastUnpinned = next.value; + } + next.accessed = false; + } + } + + return lastUnpinned; + } + + protected Iterator iterator() { + return new SegmentIterator(this); + } + + boolean evict() { + Element remove = null; + final WriteLock writeLock = writeLock(); + writeLock.lock(); + try { + Element evict = nextExpiredOrToEvict(null); + if (evict != null) { + if (cacheEventNotificationService != null) { + evictionObserver.begin(); + remove = remove(evict.getKey(), hash(evict.getKey().hashCode()), null); + evictionObserver.end(EvictionOutcome.SUCCESS); + } else { + remove = remove(evict.getKey(), hash(evict.getKey().hashCode()), null); + } + } + } finally { + writeLock.unlock(); + } + notifyEvictionOrExpiry(remove); + return remove != null; + } + + void rehash() { + HashEntry[] oldTable = table; + int oldCapacity = oldTable.length; + if (oldCapacity >= MAXIMUM_CAPACITY) + return; + + /* + * Reclassify nodes in each list to new Map. Because we are + * using power-of-two expansion, the elements from each bin + * must either stay at same index, or move with a power of two + * offset. We eliminate unnecessary node creation by catching + * cases where old nodes can be reused because their next + * fields won't change. Statistically, at the default + * threshold, only about one-sixth of them need cloning when + * a table doubles. The nodes they replace will be garbage + * collectable as soon as they are no longer referenced by any + * reader thread that may be in the midst of traversing table + * right now. + */ + + HashEntry[] newTable = new HashEntry[oldCapacity << 1]; + threshold = (int)(newTable.length * loadFactor); + int sizeMask = newTable.length - 1; + for (int i = 0; i < oldCapacity ; i++) { + // We need to guarantee that any existing reads of old Map can + // proceed. So we cannot yet null out each bin. + HashEntry e = oldTable[i]; + + if (e != null) { + HashEntry next = e.next; + int idx = e.hash & sizeMask; + + // Single node on list + if (next == null) + newTable[idx] = e; + + else { + // Reuse trailing consecutive sequence at same slot + HashEntry lastRun = e; + int lastIdx = idx; + for (HashEntry last = next; + last != null; + last = last.next) { + int k = last.hash & sizeMask; + if (k != lastIdx) { + lastIdx = k; + lastRun = last; + } + } + newTable[lastIdx] = lastRun; + + // Clone all remaining nodes + for (HashEntry p = e; p != lastRun; p = p.next) { + int k = p.hash & sizeMask; + HashEntry n = newTable[k]; + newTable[k] = relinkHashEntry(p, n); + } + } + } + } + table = newTable; + if (evictionIterator != null) { + evictionIterator = iterator(); + } + } + + Iterator getEvictionIterator() { + return evictionIterator; + } + } + + public static class HashEntry { + public final Object key; + public final int hash; + public final HashEntry next; + + public volatile Element value; + + public volatile long sizeOf; + public volatile boolean accessed = true; + + protected HashEntry(Object key, int hash, HashEntry next, Element value, long sizeOf) { + this.key = key; + this.hash = hash; + this.next = next; + this.value = value; + this.sizeOf = sizeOf; + } + + } + + static class SegmentIterator implements Iterator { + + int nextTableIndex; + HashEntry[] currentTable; + HashEntry nextEntry; + private final Segment seg; + + private SegmentIterator(final Segment memoryStoreSegment) { + nextTableIndex = -1; + this.seg = memoryStoreSegment; + advance(); + } + + public boolean hasNext() { + return nextEntry != null; + } + + public HashEntry next() { + if (nextEntry == null) + return null; + HashEntry lastReturned = nextEntry; + advance(); + return lastReturned; + } + + public void remove() { + throw new UnsupportedOperationException("remove is not supported"); + } + + final void advance() { + if (nextEntry != null && (nextEntry = nextEntry.next) != null) + return; + while (nextTableIndex >= 0) { + if ( (nextEntry = currentTable[nextTableIndex--]) != null) + return; + } + if (seg.count != 0) { + currentTable = seg.table; + for (int j = currentTable.length - 1; j >= 0; --j) { + if ( (nextEntry = currentTable[j]) != null) { + nextTableIndex = j - 1; + return; + } + } + } + } + } + + final class KeySet extends AbstractSet { + + @Override + public Iterator iterator() { + return new KeyIterator(); + } + + @Override + public int size() { + return SelectableConcurrentHashMap.this.size(); + } + + @Override + public boolean isEmpty() { + return SelectableConcurrentHashMap.this.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return SelectableConcurrentHashMap.this.containsKey(o); + } + + @Override + public boolean remove(Object o) { + return SelectableConcurrentHashMap.this.remove(o) != null; + } + + @Override + public void clear() { + SelectableConcurrentHashMap.this.clear(); + } + + @Override + public Object[] toArray() { + Collection c = new ArrayList(); + for (Object object : this) + c.add(object); + return c.toArray(); + } + @Override + public T[] toArray(T[] a) { + Collection c = new ArrayList(); + for (Object object : this) + c.add(object); + return c.toArray(a); + } + } + + final class Values extends AbstractCollection { + + @Override + public Iterator iterator() { + return new ValueIterator(); + } + + @Override + public int size() { + return SelectableConcurrentHashMap.this.size(); + } + + @Override + public boolean isEmpty() { + return SelectableConcurrentHashMap.this.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return SelectableConcurrentHashMap.this.containsValue(o); + } + + @Override + public void clear() { + SelectableConcurrentHashMap.this.clear(); + } + + @Override + public Object[] toArray() { + Collection c = new ArrayList(); + for (Object object : this) + c.add(object); + return c.toArray(); + } + + @Override + public T[] toArray(T[] a) { + Collection c = new ArrayList(); + for (Object object : this) + c.add(object); + return c.toArray(a); + } + } + + final class EntrySet extends AbstractSet> { + + @Override + public Iterator> iterator() { + return new EntryIterator(); + } + + @Override + public int size() { + return SelectableConcurrentHashMap.this.size(); + } + + @Override + public boolean isEmpty() { + return SelectableConcurrentHashMap.this.isEmpty(); + } + + @Override + public boolean contains(Object o) { + if (!(o instanceof Entry)) + return false; + Entry e = (Entry)o; + Element v = SelectableConcurrentHashMap.this.get(e.getKey()); + return v != null && v.equals(e.getValue()); + } + + @Override + public boolean remove(Object o) { + if (!(o instanceof Entry)) + return false; + Entry e = (Entry)o; + return SelectableConcurrentHashMap.this.remove(e.getKey(), e.getValue()); + } + + @Override + public void clear() { + SelectableConcurrentHashMap.this.clear(); + } + + @Override + public Object[] toArray() { + Collection c = new ArrayList(); + for (Object object : this) + c.add(object); + return c.toArray(); + } + @Override + public T[] toArray(T[] a) { + Collection c = new ArrayList(); + for (Object object : this) + c.add(object); + return c.toArray(a); + } + } + + class KeyIterator extends HashEntryIterator implements Iterator { + + @Override + public Object next() { + return nextEntry().key; + } + } + + final class ValueIterator extends HashEntryIterator implements Iterator { + + @Override + public Element next() { + return nextEntry().value; + } + } + + final class EntryIterator extends HashEntryIterator implements Iterator> { + + @Override + public Entry next() { + HashEntry entry = nextEntry(); + final Object key = entry.key; + final Element value = entry.value; + return new Entry() { + + public Object getKey() { + return key; + } + + public Element getValue() { + return value; + } + + public Element setValue(Element value) { + throw new UnsupportedOperationException(); + } + }; + } + } + + abstract class HashEntryIterator extends HashIterator { + private HashEntry myNextEntry; + + public HashEntryIterator() { + myNextEntry = advanceToNextEntry(); + } + + @Override + public void remove() { + throw new UnsupportedOperationException("remove is not supported"); + } + + @Override + public HashEntry nextEntry() { + if (myNextEntry == null) { + throw new NoSuchElementException(); + } + HashEntry entry = myNextEntry; + myNextEntry = advanceToNextEntry(); + return entry; + } + + @Override + public boolean hasNext() { + return myNextEntry != null; + } + + private HashEntry advanceToNextEntry() { + HashEntry myEntry = null; + while (super.hasNext()) { + myEntry = super.nextEntry(); + if (myEntry != null) { + break; + } else { + myEntry = null; + } + } + return myEntry; + } + + } + + abstract class HashIterator { + int nextSegmentIndex; + int nextTableIndex; + HashEntry[] currentTable; + HashEntry nextEntry; + HashEntry lastReturned; + + HashIterator() { + nextSegmentIndex = segments.length - 1; + nextTableIndex = -1; + advance(); + } + + final void advance() { + if (nextEntry != null && (nextEntry = nextEntry.next) != null) + return; + + while (nextTableIndex >= 0) { + if ( (nextEntry = currentTable[nextTableIndex--]) != null) + return; + } + + while (nextSegmentIndex >= 0) { + Segment seg = segments[nextSegmentIndex--]; + if (seg.count != 0) { + currentTable = seg.table; + for (int j = currentTable.length - 1; j >= 0; --j) { + if ( (nextEntry = currentTable[j]) != null) { + nextTableIndex = j - 1; + return; + } + } + } + } + } + + public boolean hasNext() { return nextEntry != null; } + + HashEntry nextEntry() { + if (nextEntry == null) + throw new NoSuchElementException(); + lastReturned = nextEntry; + advance(); + return lastReturned; + } + + public void remove() { + if (lastReturned == null) + throw new IllegalStateException(); + SelectableConcurrentHashMap.this.remove(lastReturned.key); + lastReturned = null; + } + } + + protected static int hash(int h) { + // Spread bits to regularize both segment and index locations, + // using variant of single-word Wang/Jenkins hash. + h += (h << 15) ^ 0xffffcd7d; + h ^= (h >>> 10); + h += (h << 3); + h ^= (h >>> 6); + h += (h << 2) + (h << 14); + return h ^ (h >>> 16); + } +} Index: rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/SoftLockManagerProvider.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/SoftLockManagerProvider.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/transaction/SoftLockManagerProvider.java (revision 11330) @@ -0,0 +1,96 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.transaction; + +import net.sf.ehcache.CacheException; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.event.CacheEventListener; +import net.sf.ehcache.transaction.SoftLockManager; + +import org.terracotta.modules.ehcache.ToolkitInstanceFactory; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +public class SoftLockManagerProvider { + private final ConcurrentMap softLockFactories = new ConcurrentHashMap(); + private final ToolkitInstanceFactory toolkitInstanceFactory; + + public SoftLockManagerProvider( + ToolkitInstanceFactory toolkitInstanceFactory) { + this.toolkitInstanceFactory = toolkitInstanceFactory; + } + + public SoftLockManager getOrCreateClusteredSoftLockFactory(Ehcache cache) { + String name = toolkitInstanceFactory.getFullyQualifiedCacheName(cache); + SoftLockManager softLockFactory = softLockFactories.get(name); + if (softLockFactory == null) { + softLockFactory = new ReadCommittedClusteredSoftLockFactory(toolkitInstanceFactory, cache.getCacheManager() + .getName(), cache.getName()); + SoftLockManager old = softLockFactories.putIfAbsent(name, softLockFactory); + if (old == null) { + // Put successful add a Cache Event Listener. + cache.getCacheEventNotificationService().registerListener(new EventListener(name)); + } else { + softLockFactory = old; + } + } + return softLockFactory; + } + + private void disposeSoftLockFactory(String fullyQualifiedCacheName) { + softLockFactories.remove(fullyQualifiedCacheName); + } + + private class EventListener implements CacheEventListener { + private final String fullyQualifiedCacheName; + + private EventListener(String fullyQualifiedCacheName) { + this.fullyQualifiedCacheName = fullyQualifiedCacheName; + } + + @Override + public void dispose() { + disposeSoftLockFactory(fullyQualifiedCacheName); + } + + @Override + public void notifyElementRemoved(Ehcache cache, Element element) throws CacheException { + // DO Nothing + } + + @Override + public void notifyElementPut(Ehcache cache, Element element) throws CacheException { + // DO Nothing + } + + @Override + public void notifyElementUpdated(Ehcache cache, Element element) throws CacheException { + // DO Nothing + } + + @Override + public void notifyElementExpired(Ehcache cache, Element element) { + // DO Nothing + } + + @Override + public void notifyElementEvicted(Ehcache cache, Element element) { + // DO Nothing + } + + @Override + public void notifyRemoveAll(Ehcache cache) { + // DO Nothing + } + + @Override + public EventListener clone() throws CloneNotSupportedException { + return (EventListener) super.clone(); + } + + } + +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeBTMClient.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeBTMClient.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/txns/SuspendResumeBTMClient.java (revision 11330) @@ -0,0 +1,21 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.ehcache.tests.txns; + +import bitronix.tm.Configuration; +import bitronix.tm.TransactionManagerServices; + +public class SuspendResumeBTMClient extends SuspendResumeClient { + + public SuspendResumeBTMClient(String[] args) { + super(args); + Configuration config = TransactionManagerServices.getConfiguration(); + config.setServerId("suspendResumeTx-1-" + Math.random()); + config.setJournal("null"); + } + + public static void main(String[] args) { + new SuspendResumeBTMClient(args).run(); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/search/Person.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/search/Person.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/search/Person.java (revision 11330) @@ -0,0 +1,107 @@ +/** + * Copyright 2003-2010 Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.search; + +import java.io.Serializable; + +/** + * A domain object used for testing + * + * @author Greg Luck + */ +public class Person implements Serializable { + + private final String name; + private final int age; + private final Gender gender; + private final String dept; + + public Person(String name, int age, Gender gender) { + this(name, age, gender, "engg"); + } + + public Person(String name, int age, Gender gender, String dept) { + this.name = name; + this.age = age; + this.gender = gender; + this.dept = dept; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + age; + result = prime * result + ((dept == null) ? 0 : dept.hashCode()); + result = prime * result + ((gender == null) ? 0 : gender.hashCode()); + result = prime * result + ((name == null) ? 0 : name.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; + Person other = (Person) obj; + if (age != other.age) + return false; + if (dept == null) { + if (other.dept != null) + return false; + } else if (!dept.equals(other.dept)) + return false; + if (gender != other.gender) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } + + public String getName() { + return name; + } + + public int getAge() { + return age; + } + + public Gender getGender() { + return gender; + } + + public String getDepartment() { + return this.dept; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "(name:" + name + ", age:" + age + ", sex:" + gender.name().toLowerCase() + ", dept: " + dept + + ")"; + } + + public enum Gender { + MALE, FEMALE; + } + +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/jta.properties =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/jta.properties (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/jta.properties (revision 11330) @@ -0,0 +1,12 @@ +com.atomikos.icatch.service=com.atomikos.icatch.standalone.UserTransactionServiceFactory +com.atomikos.icatch.console_file_name = tm-dev.out +com.atomikos.icatch.log_base_name = tmlog-dev +com.atomikos.icatch.tm_unique_name = com.atomikos.spring.jdbc.tm-dev +com.atomikos.icatch.serial_jta_transactions=false +com.atomikos.icatch.automatic_resource_registration=true +com.atomikos.icatch.max_actives=15000 +com.atomikos.icatch.max_timeout=3600000 +com.atomikos.icatch.default_jta_timeout=60000 +com.atomikos.icatch.output_dir=atomikos-tmp/ +com.atomikos.icatch.log_base_dir=atomikos-tmp/ +com.atomikos.icatch.enable_logging=false Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/OsgiHibernateTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/OsgiHibernateTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/OsgiHibernateTest.java (revision 11330) @@ -0,0 +1,348 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package net.sf.ehcache.osgi; + +import static org.hamcrest.CoreMatchers.is; +import static org.hamcrest.CoreMatchers.notNullValue; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static org.ops4j.pax.exam.CoreOptions.bootDelegationPackages; +import static org.ops4j.pax.exam.CoreOptions.maven; +import static org.ops4j.pax.exam.CoreOptions.mavenBundle; +import static org.ops4j.pax.exam.CoreOptions.options; +import static org.ops4j.pax.exam.CoreOptions.systemProperty; +import static org.ops4j.pax.exam.CoreOptions.wrappedBundle; +import static org.terracotta.test.OsgiUtil.commonOptions; +import static org.terracotta.test.OsgiUtil.getMavenBundle; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Status; + +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.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.ops4j.pax.exam.Option; +import org.ops4j.pax.exam.ProbeBuilder; +import org.ops4j.pax.exam.TestProbeBuilder; +import org.ops4j.pax.exam.junit.PaxExam; +import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; +import org.ops4j.pax.exam.spi.reactors.PerMethod; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +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.Item; +import org.terracotta.ehcache.tests.container.hibernate.domain.Person; +import org.terracotta.ehcache.tests.container.hibernate.domain.PhoneNumber; +import org.terracotta.ehcache.tests.container.hibernate.domain.VersionedItem; +import org.terracotta.test.OsgiUtil; + +import java.lang.reflect.Method; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.inject.Inject; + +/** + * @author Chris Dennis + * @author hhuynh + */ +@RunWith(PaxExam.class) +@ExamReactorStrategy(PerMethod.class) +@Ignore +public class OsgiHibernateTest { + + private SessionFactory sessionFactory; + private Configuration config; + + /** + * Injected BundleContext + */ + @Inject + protected BundleContext bc; + + public OsgiHibernateTest() { + // + } + + public void testBundle() { + assertThat(bc, is(notNullValue())); + System.out.println(Arrays.asList(bc.getBundles())); + } + + @org.ops4j.pax.exam.Configuration + public Option[] config() { + return options(bootDelegationPackages("sun.*,jdk.*,javax.naming,javax.naming.spi,javax.naming.event,javax.management"), + commonOptions(), + wrappedBundle(maven("javax.transaction", "jta").versionAsInProject()) + .exports("javax.transaction;version=1.1"), + getMavenBundle("net.sf.ehcache", "ehcache-ee", "ehcache"), + getMavenBundle("net.sf.ehcache.test", "hibernate-ehcache-ee-bundle", "hibernate-ehcache-bundle").noStart(), + wrappedBundle(maven("org.apache.derby", "derby").versionAsInProject()), + systemProperty("derby.system.home").value("derby")); + } + + @ProbeBuilder + public TestProbeBuilder extendProbe(TestProbeBuilder builder) { + builder.setHeader(Constants.IMPORT_PACKAGE, + "javax.transaction;version=1.1,org.hibernate,org.osgi.framework,org.slf4j"); + builder.setHeader(Constants.DYNAMICIMPORT_PACKAGE, "*"); + return builder; + } + + public synchronized 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; + } + + private void printBundles() { + for (Bundle b : bc.getBundles()) { + System.out.println("XXX Bundle " + b.getSymbolicName() + ", " + b.getVersion() + ", state: " + b.getState()); + } + } + + @Before + public void setUp() throws Exception { + printBundles(); + + ClassLoader prev = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(OsgiHibernateTest.class.getClassLoader()); + config = new Configuration().configure(OsgiHibernateTest.class + .getResource("/net/sf/ehcache/osgi/hibernate.cfg.xml")); + + config.setProperty("hibernate.hbm2ddl.auto", "create-drop"); + getSessionFactory(); // call for side effect of initializing the session factory + } finally { + Thread.currentThread().setContextClassLoader(prev); + } + + getSessionFactory().getStatistics().setStatisticsEnabled(true); + removeCaches(); + } + + @After + public void tearDown() { + getSessionFactory().close(); + } + + private void removeCaches() { + 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() throws Exception { + 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.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/ConcurrencyProblemCachePerfTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/ConcurrencyProblemCachePerfTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/ConcurrencyProblemCachePerfTest.java (revision 11330) @@ -0,0 +1,88 @@ +package net.sf.ehcache; + +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import net.sf.ehcache.AbstractCacheTest.Executable; +import net.sf.ehcache.config.Configuration; +import static org.junit.Assert.assertTrue; + +/** + * @author Alex Snaps + */ +public class ConcurrencyProblemCachePerfTest { + + private static final Logger LOG = LoggerFactory.getLogger(ConcurrencyProblemCachePerfTest.class.getName()); + + @Test + public void testContinuousThrashProgrammatic() throws Exception { + CacheManager manager = new CacheManager(new Configuration().name("testContinuousThrashConfiguration")); + try { + Cache cache = new Cache("thrashcache", 5, false, false, 2, 5); + manager.addCache(cache); + for (int i = 0; i < 5; i++) { + thrashCache(cache, 1500L); + LOG.info("Finished run."); + + } + } finally { + manager.shutdown(); + } + } + + /** + * This method tries to get the cache to slow up. + * It creates 10 threads, does gets and puts. + */ + private long thrashCache(final Cache cache, final long retrievalTime) + throws Exception { + StopWatch stopWatch = new StopWatch(); + + // Create threads that do gets + final List executables = new ArrayList(); + for (int i = 0; i < 10; i++) { + final Executable executable = new Executable() { + public void execute() throws Exception { + for (int i = 0; i < 10; i++) { + final String key = "key" + i; + Object value = cache.get(key); + if (value == null) { + cache.put(new Element(key, "value" + i)); + } + //The key will be in. Now check we can get it quickly + checkRetrievalOnKnownKey(cache, retrievalTime, key); + } + } + }; + executables.add(executable); + } + + AbstractCacheTest.runThreads(executables); + cache.removeAll(); + return stopWatch.getElapsedTime(); + } + + + /** + * Checks that the liveness method returns in less than a given amount of time. + * liveness() is a method that simply returns a String. It should be very fast. It can be + * delayed because it is a synchronized method, and must acquire + * an object lock before continuing. The old blocking cache was taking up to several minutes in production + * + * @param cache a BlockingCache + */ + private void checkRetrievalOnKnownKey(Cache cache, long requiredRetrievalTime, Serializable key) { + StopWatch stopWatch = new StopWatch(); + cache.get(key); + long measuredRetrievalTime = stopWatch.getElapsedTime(); + assertTrue("Retrieval time on known key is " + measuredRetrievalTime + + " but should be less than " + requiredRetrievalTime + "ms", + measuredRetrievalTime < requiredRetrievalTime); + } +} + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/Event.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/Event.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/hibernate/domain/Event.java (revision 11330) @@ -0,0 +1,83 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.sf.ehcache.hibernate.domain; + +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +public class Event { + private Long id; + + private String title; + private Date date; + private Set participants = new HashSet(); + private Person organizer; + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public void setOrganizer(Person organizer) { + this.organizer = organizer; + } + + public Person getOrganizer() { + return organizer; + } + + public Set getParticipants() { + return participants; + } + + public void setParticipants(Set participants) { + this.participants = participants; + } + + public void addParticipant(Person person) { + participants.add(person); + person.getEvents().add(this); + } + + public void removeParticipant(Person person) { + participants.remove(person); + person.getEvents().remove(this); + } + + public String toString() { + return getTitle() + ": " + getDate(); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/management/sampled/CacheManagerSamplerImplTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/management/sampled/CacheManagerSamplerImplTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/management/sampled/CacheManagerSamplerImplTest.java (revision 11330) @@ -0,0 +1,44 @@ +package net.sf.ehcache.management.sampled; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.search.SearchException; +import net.sf.ehcache.search.query.QueryManagerBuilder; +import net.sf.ehcache.search.query.TestQueryManagerBuilder; +import org.junit.Test; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * @author Anthony Dahanne + */ +public class CacheManagerSamplerImplTest { + @Test(expected = SearchException.class) + public void testExecuteQuery__no_caches() throws Exception { + + CacheManager cacheManager = mock(CacheManager.class); + String[] emptyCacheNamesArray = new String[0]; + when(cacheManager.getCacheNames()).thenReturn(emptyCacheNamesArray); + CacheManagerSamplerImpl cacheManagerSampler = new CacheManagerSamplerImpl(cacheManager); + QueryManagerBuilder qmb = TestQueryManagerBuilder.getQueryManagerBuilder(); + cacheManagerSampler.executeQuery("bogus query", qmb); + } + + @Test(expected = SearchException.class) + public void testExecuteQuery__no_searchable_caches() throws Exception { + + CacheManager cacheManager = mock(CacheManager.class); + String[] emptyCacheNamesArray = new String[]{"pif"}; + when(cacheManager.getCacheNames()).thenReturn(emptyCacheNamesArray); + CacheConfiguration cacheConfiguration = new CacheConfiguration().name("pif"); + Ehcache cache = new Cache(cacheConfiguration); + when(cacheManager.getEhcache("pif")).thenReturn(cache); + + CacheManagerSamplerImpl cacheManagerSampler = new CacheManagerSamplerImpl(cacheManager); + QueryManagerBuilder qmb = TestQueryManagerBuilder.getQueryManagerBuilder(); + cacheManagerSampler.executeQuery("bogus query", qmb); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/CoreStatistics.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/CoreStatistics.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/CoreStatistics.java (revision 11330) @@ -0,0 +1,210 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.statistics; + +import net.sf.ehcache.CacheOperationOutcomes; +import net.sf.ehcache.store.StoreOperationOutcomes; +import net.sf.ehcache.transaction.xa.XaCommitOutcome; +import net.sf.ehcache.transaction.xa.XaRecoveryOutcome; +import net.sf.ehcache.transaction.xa.XaRollbackOutcome; + +/** + * The CoreStatistics interface. + * + * @author cschanck + */ +public interface CoreStatistics { + + /** + * The Interface CountOperation. + * + * @param the generic type + */ + public interface CountOperation { + + /** + * Value. + * + * @param result the result + * @return the long + */ + long value(T result); + + /** + * Value. + * + * @param results the results + * @return the long + */ + long value(T... results); + } + + /** + * Gets the. + * + * @return the count operation + */ + public CountOperation get(); + + /** + * Put. + * + * @return the count operation + */ + public CountOperation put(); + + /** + * Remove operation. + * + * @return the count operation + */ + public CountOperation remove(); + + /** + * The single arg replace operation. + * + * @return the count operation + */ + public CountOperation replaceOneArg(); + + /** + * The two arg replace operation. + * + * @return the count operation + */ + public CountOperation replaceTwoArg(); + + /** + * The put if absent operation. + * + * @return the count operation + */ + public CountOperation putIfAbsent(); + + /** + * The remove element operation. + * + * @return the count operation + */ + public CountOperation removeElement(); + + /** + * Local heap get. + * + * @return the count operation + */ + public CountOperation localHeapGet(); + + /** + * Local heap put. + * + * @return the count operation + */ + public CountOperation localHeapPut(); + + /** + * Local heap remove. + * + * @return the count operation + */ + public CountOperation localHeapRemove(); + + /** + * Local off heap get. + * + * @return the count operation + */ + public CountOperation localOffHeapGet(); + + /** + * Local off heap put. + * + * @return the count operation + */ + public CountOperation localOffHeapPut(); + + /** + * Local off heap remove. + * + * @return the count operation + */ + public CountOperation localOffHeapRemove(); + + /** + * Local disk get. + * + * @return the count operation + */ + public CountOperation localDiskGet(); + + /** + * Local disk put. + * + * @return the count operation + */ + public CountOperation localDiskPut(); + + /** + * Local disk remove. + * + * @return the count operation + */ + public CountOperation localDiskRemove(); + + /** + * Xa commit. + * + * @return the count operation + */ + public CountOperation xaCommit(); + + /** + * Xa recovery. + * + * @return the count operation + */ + public CountOperation xaRecovery(); + + /** + * Xa rollback. + * + * @return the count operation + */ + public CountOperation xaRollback(); + + /** + * Cache eviction. + * + * @return the count operation + */ + public CountOperation cacheEviction(); + + /** + * Cache expiration. + * + * @return the count operation + */ + public CountOperation cacheExpiration(); + + /** + * Cache cluster event. + * + * @return the count operation + */ + public CountOperation cacheClusterEvent(); + +} \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/nonstop/HibernateNonstopCacheExceptionHandler.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/nonstop/HibernateNonstopCacheExceptionHandler.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/nonstop/HibernateNonstopCacheExceptionHandler.java (revision 11330) @@ -0,0 +1,82 @@ +/** + * 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.nonstop; + +import net.sf.ehcache.constructs.nonstop.NonStopCacheException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * Class that takes care of {@link NonStopCacheException} that happens in hibernate module + * + * @author Abhishek Sanoujam + * + */ +public final class HibernateNonstopCacheExceptionHandler { + /** + * Property name which set as "true" will throw exceptions on timeout with hibernate + */ + public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "ehcache.hibernate.propagateNonStopCacheException"; + + /** + * Property name for logging the stack trace of the nonstop cache exception too. False by default + */ + public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "ehcache.hibernate.logNonStopCacheExceptionStackTrace"; + + private static final Logger LOGGER = LoggerFactory.getLogger(HibernateNonstopCacheExceptionHandler.class); + + private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler(); + + /** + * private constructor + */ + private HibernateNonstopCacheExceptionHandler() { + // private + } + + /** + * Returns the singleton instance + * + * @return the singleton instance + */ + public static HibernateNonstopCacheExceptionHandler getInstance() { + return INSTANCE; + } + + /** + * Handle {@link NonStopCacheException}. + * If {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY} system property is set to true, + * rethrows the {@link NonStopCacheException}, otherwise logs the exception. While logging, if + * {@link HibernateNonstopCacheExceptionHandler#HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY} is set to true, logs the exception stack + * trace too, otherwise logs the exception message only + * + * @param nonStopCacheException + */ + public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) { + if (Boolean.getBoolean(HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY)) { + throw nonStopCacheException; + } else { + if (Boolean.getBoolean(HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY)) { + LOGGER.debug("Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(), nonStopCacheException); + } else { + LOGGER.debug("Ignoring NonstopCacheException - " + nonStopCacheException.getMessage()); + } + } + } + +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/EvenCacheLoader.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/EvenCacheLoader.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/net/sf/ehcache/osgi/EvenCacheLoader.java (revision 11330) @@ -0,0 +1,12 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package net.sf.ehcache.osgi; + +public class EvenCacheLoader extends IncrementingCacheLoader { + + public EvenCacheLoader() { + super(true, 20000); + } + +} \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/coherence/RestartingL1ExpressClient.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/coherence/RestartingL1ExpressClient.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/coherence/RestartingL1ExpressClient.java (revision 11330) @@ -0,0 +1,111 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.ehcache.tests.coherence; + +import net.sf.ehcache.Cache; + +import org.terracotta.toolkit.Toolkit; +import org.terracotta.toolkit.concurrent.ToolkitBarrier; +import org.terracotta.ehcache.tests.ClientBase; + +import junit.framework.Assert; + +public class RestartingL1ExpressClient extends ClientBase { + + public static final String PASS_OUTPUT = "Restarting express client PASS output"; + private ToolkitBarrier barrier; + private boolean afterRestart = false; + private boolean shouldCrash = false; + + public RestartingL1ExpressClient(String[] args) { + super("test", args); + for (String arg : args) { + if (arg.equals(RestartingL1ExpressTest.SHOULD_CRASH)) { + this.shouldCrash = true; + } + + if (arg.equals(RestartingL1ExpressTest.AFTER_RESTART)) { + this.afterRestart = true; + } + } + } + + // n nodes start in coherent, then setCoherent(false) + // assert coherent=false in all n nodes + // n-1 nodes call setCoherent(true) + // 1 node exits without calling setCoherent(true) + // n-1 nodes assert coherent + // 1 node restarts, asserts cache coherent + @Override + protected void runTest(Cache cache, Toolkit toolkit) throws Throwable { + barrier = toolkit.getBarrier("CacheCoherenceExpressClient", RestartingL1ExpressTest.CLIENT_COUNT); + Assert.assertEquals(true, cache.isClusterCoherent()); + Assert.assertEquals(true, cache.isNodeCoherent()); + + if (!afterRestart) { + barrier.await(); + doInitialSteps(cache); + } else { + log("Running crashing client AFTER RESTART..."); + // barrier X + barrier.await(); + // barrier Z + barrier.await(); + // cache is coherent when it restarts + Assert.assertEquals(true, cache.isClusterCoherent()); + Assert.assertEquals(true, cache.isNodeCoherent()); + cache.setNodeCoherent(false); + Assert.assertEquals(false, cache.isClusterCoherent()); + Assert.assertEquals(false, cache.isNodeCoherent()); + cache.setNodeCoherent(true); + Assert.assertEquals(true, cache.isClusterCoherent()); + Assert.assertEquals(true, cache.isNodeCoherent()); + } + log(PASS_OUTPUT); + } + + private void doInitialSteps(Cache cache) throws Exception { + cache.setNodeCoherent(false); + Assert.assertEquals(false, cache.isNodeCoherent()); + Assert.assertEquals(false, cache.isClusterCoherent()); + barrier.await(); + if (shouldCrash) { + log("Running crashing client..."); + // let other nodes make cache coherent + Assert.assertEquals(false, cache.isClusterCoherent()); + Assert.assertEquals(false, cache.isNodeCoherent()); + log("Crashing client finishing without calling calling setNodeCoherent(true)"); + // barrier Y + barrier.await(); + // exit without calling setNodeCoherent(true) + } else { + log("Running normal client..."); + cache.setNodeCoherent(true); + Assert.assertEquals(true, cache.isNodeCoherent()); + Assert.assertEquals(false, cache.isClusterCoherent()); + log("Normal client before crasher exiting"); + // barrier Y + barrier.await(); + log("Crashing client has probably exited... waiting for it to come back..."); + // by this time 1 node has exited (or in process of exiting) + // the call below should return quite fast, as soon as the other node exits + cache.waitUntilClusterCoherent(); + + // wait for other node to come back after restart + // barrier X + barrier.await(); + log("Crashing client restarted."); + // other node has restarted now + Assert.assertEquals(true, cache.isClusterCoherent()); + Assert.assertEquals(true, cache.isNodeCoherent()); + // barrier Z + barrier.await(); + } + + } + + private static void log(String msg) { + System.out.println(msg); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/hibernate/HibernateAPIUsageTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/hibernate/HibernateAPIUsageTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/hibernate/HibernateAPIUsageTest.java (revision 11330) @@ -0,0 +1,654 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.hibernate; + +import net.sf.ehcache.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.Element; +import net.sf.ehcache.store.disk.DiskStoreHelper; + +import org.hamcrest.CoreMatchers; +import org.hibernate.cfg.Environment; +import org.junit.After; + +import static org.hamcrest.number.OrderingComparison.greaterThan; +import static org.hamcrest.number.OrderingComparison.lessThanOrEqualTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import org.junit.Before; +import org.junit.Test; +import org.junit.experimental.categories.Category; + +import java.io.IOException; +import java.io.Serializable; +import java.lang.reflect.Field; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ExecutionException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.terracotta.test.categories.CheckShorts; + + +/** + * Tests for a Cache + * + * @author Greg Luck, Claus Ibsen + * @version $Id: HibernateAPIUsageTest.java 10789 2018-04-26 02:08:13Z adahanne $ + */ +@Category(CheckShorts.class) +public class HibernateAPIUsageTest extends AbstractCacheTest { + private static final Logger LOG = LoggerFactory.getLogger(HibernateAPIUsageTest.class.getName()); + + /** + * teardown + */ + @Override + @After + public void tearDown() throws Exception { + super.tearDown(); + for (CacheManager cacheManager : CacheManager.ALL_CACHE_MANAGERS) { + cacheManager.shutdown(); + } + } + + @Override + @Before + public void setUp() { + // Do not setup a cachemanager here! + } + + + /** + * Make sure ehcache works with one of the main projects using it: Hibernate-2.1.8 + */ + @Test + public void testAPIAsUsedByHibernate2() throws Exception { + super.setUp(); + net.sf.hibernate.cache.EhCacheProvider provider = new net.sf.hibernate.cache.EhCacheProvider(); + provider.start(null); + net.sf.hibernate.cache.Cache cache = provider.buildCache("sampleCache1", null); + assertNotNull(manager.getCache("sampleCache1")); + + Serializable key = "key"; + Serializable value = "value"; + cache.put(key, value); + assertEquals(value, cache.get(key)); + + cache.remove(key); + assertEquals(null, cache.get(key)); + } + + + /** + * Make sure ehcache works with one of the main projects using it: Hibernate-3.1.3 and Hibernate 3.2 + * Note this test was updated to Hibernate3.2cr2 9 May 2006 + *

+ * Note that getElementCountInMemory() is broken. It reports the total cache size rather than the memory size. Fixed in Hibernate 3.2 + * getTimeout appears to be broken. It returns 4096 minutes! + */ + @Test + public void testAPIAsUsedByHibernate3() throws InterruptedException, ExecutionException { + + org.hibernate.cache.EhCacheProvider provider = new org.hibernate.cache.EhCacheProvider(); + provider.start(null); + final org.hibernate.cache.Cache cache = provider.buildCache("sampleCache1", null); + final Serializable key = "key"; + final Serializable value = "value"; + assertThat(cache.getSizeInMemory(), CoreMatchers.is(0L)); + cache.put(key, value); + final long EMPTY_ELEMENT_SIZE = cache.getSizeInMemory(); + cache.clear(); + + //Check created and name + assertNotNull(cache.getRegionName()); + assertEquals("sampleCache1", cache.getRegionName()); + + cache.put(key, value); + assertEquals(value, cache.get(key)); + assertEquals(value, cache.read(key)); + + cache.remove(key); + assertEquals(null, cache.get(key)); + + //Behaves like a put + cache.update(key, value); + assertEquals(value, cache.get(key)); + cache.remove(key); + + //Check counts and stats + for (int i = 0; i < 10010; i++) { + cache.put("" + i, value); + } + DiskStoreHelper.flushAllEntriesToDisk(getBackingCache((org.hibernate.cache.EhCache)cache)).get(); + //this is now fixed + assertThat(cache.getElementCountInMemory(), lessThanOrEqualTo(10000L)); + // TODO Lower tier will _never_ be smaller than higher ones now +// RetryAssert.assertBy(1, SECONDS, new Callable() { +// public Long call() throws Exception { +// return cache.getElementCountOnDisk(); +// } +// }, lessThan(1002L)); + assertThat(cache.getElementCountOnDisk(), greaterThan(999L)); + + //clear + cache.clear(); + assertEquals(0, cache.getElementCountInMemory()); + cache.put(key, value); + assertEquals(EMPTY_ELEMENT_SIZE, cache.getSizeInMemory()); + + //locks + //timeout. This seems strange + assertEquals(245760000, cache.getTimeout()); + cache.lock(key); + cache.unlock(key); + + //toMap + Map map = cache.toMap(); + assertEquals(1, map.size()); + assertEquals(value, map.get(key)); + + long time1 = cache.nextTimestamp(); + long time2 = cache.nextTimestamp(); + assertTrue(time2 > time1); + + cache.clear(); + + cache.destroy(); + try { + cache.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + provider.stop(); + + } + + private Cache getBackingCache(final org.hibernate.cache.EhCache cache) { + try { + final Field cacheField = cache.getClass().getDeclaredField("cache"); + cacheField.setAccessible(true); + return (Cache)cacheField.get(cache); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + + /** + * Test new features: + *

    + *
  1. Support for Object signatures + *
  2. support for multiple SessionFactory objects in Hibernate, which presumably mean multiple providers. + * We can have two caches of the same name in different providers and interact with both + *
+ */ + @Test + public void testNewHibernate32CacheAndProviderNewFeatures() { + + org.hibernate.cache.EhCacheProvider provider = new org.hibernate.cache.EhCacheProvider(); + provider.start(null); + org.hibernate.cache.Cache cache = provider.buildCache("sampleCache1", null); + + //start up second provider pointing to ehcache-failsage.xml because it is there + org.hibernate.cache.EhCacheProvider provider2 = new org.hibernate.cache.EhCacheProvider(); + + //Fire up a second provider, CacheManager and cache concurrently + Properties properties = new Properties(); + + properties.setProperty(Environment.CACHE_PROVIDER_CONFIG, "ehcache-2.xml"); + provider2.start(properties); + org.hibernate.cache.Cache cache2 = provider.buildCache("sampleCache1", null); + + //Check created and name + assertNotNull(cache.getRegionName()); + assertEquals("sampleCache1", cache.getRegionName()); + + //Test with Object rather than Serializable + Object key = new Object(); + Object value = new Object(); + + cache.put(key, value); + assertEquals(value, cache.get(key)); + assertEquals(value, cache.read(key)); + cache2.put(key, value); + assertEquals(value, cache2.get(key)); + assertEquals(value, cache2.read(key)); + + cache.remove(key); + assertEquals(null, cache.get(key)); + cache2.remove(key); + assertEquals(null, cache2.get(key)); + + //Behaves like a put + cache.update(key, value); + assertEquals(value, cache.get(key)); + cache.remove(key); + cache2.update(key, value); + assertEquals(value, cache2.get(key)); + cache2.remove(key); + + //Check counts and stats + for (int i = 0; i < 10010; i++) { + cache.put("" + i, value); + } + assertEquals(10000, cache.getElementCountInMemory()); + //objects don't overflow, only Serializable + assertEquals(0, cache.getElementCountOnDisk()); + + //clear + cache.clear(); + assertEquals(0, cache.getElementCountInMemory()); + cache.put(key, value); + + //locks + //timeout. This seems strange + assertEquals(245760000, cache.getTimeout()); + cache.lock(key); + cache.unlock(key); + + //toMap - broken in Hibernate 3.2 +// Map map = cache.toMap(); +// assertEquals(1, map.size()); +// assertEquals(value, map.get(key)); + + long time1 = cache.nextTimestamp(); + long time2 = cache.nextTimestamp(); + assertTrue(time2 > time1); + + cache.destroy(); + try { + cache.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + cache2.destroy(); + try { + cache2.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + provider.stop(); + provider2.stop(); + } + + + /** + * Test ehcache packaged provider and EhCache with Hibernate-3.1.3 + * Leave broken timeout until get clarification from Emmanuel + */ + @Test + public void testNewHibernateEhcacheAndProviderBackwardCompatible() { + + net.sf.ehcache.hibernate.EhCacheProvider provider = new net.sf.ehcache.hibernate.EhCacheProvider(); + + //Fire up a second provider, CacheManager and cache concurrently + Properties properties = new Properties(); + + properties.setProperty("net.sf.ehcache.configurationResourceName", "ehcache-2.xml"); + provider.start(properties); + final org.hibernate.cache.Cache cache = provider.buildCache("sampleCache1", null); + final Serializable key = "key"; + final Serializable value = "value"; + assertThat(cache.getSizeInMemory(), CoreMatchers.is(0L)); + cache.put(key, value); + final long EMPTY_ELEMENT_SIZE = cache.getSizeInMemory(); + cache.clear(); + + //Check created and name + assertNotNull(cache.getRegionName()); + assertEquals("sampleCache1", cache.getRegionName()); + + cache.put(key, value); + assertEquals(value, cache.get(key)); + assertEquals(value, cache.read(key)); + + cache.remove(key); + assertEquals(null, cache.get(key)); + + //Behaves like a put + cache.update(key, value); + assertEquals(value, cache.get(key)); + cache.remove(key); + + //Check counts and stats + for (int i = 0; i < 10010; i++) { + cache.put("" + i, value); + } + assertEquals(10010, cache.getElementCountInMemory()); + + //clear + cache.clear(); + assertEquals(0, cache.getElementCountInMemory()); + cache.put(key, value); + assertEquals(EMPTY_ELEMENT_SIZE, cache.getSizeInMemory()); + + //locks + //timeout. This seems strange + assertEquals(245760000, cache.getTimeout()); + cache.lock(key); + cache.unlock(key); + + //toMap + Map map = cache.toMap(); + assertEquals(1, map.size()); + assertEquals(value, map.get(key)); + + long time1 = cache.nextTimestamp(); + long time2 = cache.nextTimestamp(); + assertTrue(time2 > time1); + + cache.destroy(); + try { + cache.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + provider.stop(); + } + + + /** + * An integration test, at the CacheManager level, to make sure persistence works + */ + @Test + public void testPersistentStoreFromCacheManager() throws IOException, InterruptedException, CacheException, ExecutionException { + + //initialise + CacheManager manager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache.xml"); + Ehcache cache = manager.getCache("persistentLongExpiryIntervalCache"); + + cache.removeAll(); + DiskStoreHelper.flushAllEntriesToDisk((Cache)cache).get(); + for (int i = 0; i < 100; i++) { + byte[] data = new byte[1024]; + cache.put(new Element("key" + (i + 100), data)); + } + assertEquals(100, cache.getSize()); + + manager.shutdown(); + + net.sf.ehcache.hibernate.EhCacheProvider provider = new net.sf.ehcache.hibernate.EhCacheProvider(); + provider.start(null); + org.hibernate.cache.Cache hibernateCache = provider.buildCache("persistentLongExpiryIntervalCache", null); + + for (int i = 0; i < 100; i++) { + assertNotNull(hibernateCache.get("key" + (i + 100))); + } + + assertEquals(100, hibernateCache.getElementCountInMemory()); + + provider.stop(); + + + } + + + /** + * An integration test, at the CacheManager level, to make sure persistence works + */ + @Test + public void testPersistentStoreFromCacheManagerUsingHibernate321Provider() throws Exception { + + //initialise + CacheManager manager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache.xml"); + Ehcache cache = manager.getCache("persistentLongExpiryIntervalCache"); + cache.removeAll(); + + for (int i = 0; i < 100; i++) { + byte[] data = new byte[1024]; + cache.put(new Element("key" + (i + 100), data)); + } + assertEquals(100, cache.getSize()); + + manager.shutdown(); + + //Create hibernate using ehcache + org.hibernate.cache.EhCacheProvider provider = new org.hibernate.cache.EhCacheProvider(); + provider.start(null); + org.hibernate.cache.Cache hibernateCache = provider.buildCache("persistentLongExpiryIntervalCache", null); + + assertEquals(100, hibernateCache.getElementCountInMemory() + hibernateCache.getElementCountOnDisk()); + + provider.stop(); + + } + + /** + * Test ehcache packaged provider and EhCache with Hibernate-3.1.3 + * Leave broken timeout until get clarification from Emmanuel + *

+ * Test new features: + *

    + *
  1. Support for Object signatures + *
  2. support for multiple SessionFactory objects in Hibernate, which presumably mean multiple providers. + * We can have two caches of the same name in different providers and interact with both + *
+ */ + @Test + public void testNewHibernateEhcacheAndProviderNewFeatures() { + + net.sf.ehcache.hibernate.EhCacheProvider provider = new net.sf.ehcache.hibernate.EhCacheProvider(); + provider.start(null); + org.hibernate.cache.Cache cache = provider.buildCache("sampleCache1", null); + + //start up second provider pointing to ehcache-failsafe.xml because it is there + net.sf.ehcache.hibernate.EhCacheProvider provider2 = new net.sf.ehcache.hibernate.EhCacheProvider(); + + //Fire up a second provider, CacheManager and cache concurrently + Properties properties = new Properties(); + properties.setProperty(EhCacheProvider.NET_SF_EHCACHE_CONFIGURATION_RESOURCE_NAME, "ehcache-2.xml"); + provider2.start(properties); + org.hibernate.cache.Cache cache2 = provider.buildCache("sampleCache1", null); + + //Check created and name + assertNotNull(cache.getRegionName()); + assertEquals("sampleCache1", cache.getRegionName()); + + //Test with Object rather than Serializable + Object key = new Object(); + Object value = new Object(); + + cache.put(key, value); + assertEquals(value, cache.get(key)); + assertEquals(value, cache.read(key)); + cache2.put(key, value); + assertEquals(value, cache2.get(key)); + assertEquals(value, cache2.read(key)); + + cache.remove(key); + assertEquals(null, cache.get(key)); + cache2.remove(key); + assertEquals(null, cache2.get(key)); + + //Behaves like a put + cache.update(key, value); + assertEquals(value, cache.get(key)); + cache.remove(key); + cache2.update(key, value); + assertEquals(value, cache2.get(key)); + cache2.remove(key); + + //Check counts and stats + for (int i = 0; i < 10010; i++) { + cache.put("" + i, value); + } + assertEquals(10010, cache.getElementCountInMemory()); + + //clear + cache.clear(); + assertEquals(0, cache.getElementCountInMemory()); + cache.put(key, value); + // elements don't need to be serializable anymore to be measured + assertTrue(cache.getSizeInMemory() > 0); + + //locks + //timeout. This seems strange + assertEquals(245760000, cache.getTimeout()); + cache.lock(key); + cache.unlock(key); + + //toMap + Map map = cache.toMap(); + assertEquals(1, map.size()); + assertEquals(value, map.get(key)); + + long time1 = cache.nextTimestamp(); + long time2 = cache.nextTimestamp(); + assertTrue(time2 > time1); + + cache.destroy(); + try { + cache.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + cache2.destroy(); + try { + cache2.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + provider.stop(); + provider2.stop(); + } + + /** + * Test ehcache packaged provider and EhCache with Hibernate-3.1.3 + * Leave broken timeout until get clarification from Emmanuel + *

+ * Test new features: + *

    + *
  1. Support for Object signatures + *
+ */ + @Test + public void testNewHibernateSingletonEhcacheAndProviderNewFeatures() { + + net.sf.ehcache.hibernate.SingletonEhCacheProvider provider = new net.sf.ehcache.hibernate.SingletonEhCacheProvider(); + provider.start(null); + org.hibernate.cache.Cache cache = provider.buildCache("sampleCache1", null); + + net.sf.ehcache.hibernate.SingletonEhCacheProvider provider2 = new net.sf.ehcache.hibernate.SingletonEhCacheProvider(); + provider2.start(null); + org.hibernate.cache.Cache cache2 = provider.buildCache("sampleCache1", null); + + //Check created and name + assertNotNull(cache.getRegionName()); + assertEquals("sampleCache1", cache.getRegionName()); + + //Test with Object rather than Serializable + Object key = new Object(); + Object value = new Object(); + + cache.put(key, value); + assertEquals(value, cache2.get(key)); + assertEquals(value, cache.read(key)); + cache2.put(key, value); + assertEquals(value, cache.get(key)); + assertEquals(value, cache2.read(key)); + + cache.remove(key); + assertEquals(null, cache.get(key)); + cache2.remove(key); + assertEquals(null, cache2.get(key)); + + //Behaves like a put + cache.update(key, value); + assertEquals(value, cache.get(key)); + cache.remove(key); + cache2.update(key, value); + assertEquals(value, cache2.get(key)); + cache2.remove(key); + + //Check counts and stats + for (int i = 0; i < 10010; i++) { + cache.put("" + i, value); + } + assertEquals(10010, cache.getElementCountInMemory()); + + //clear + cache.clear(); + assertEquals(0, cache.getElementCountInMemory()); + cache.put(key, value); + // elements don't need to be serializable anymore to be measured + assertTrue(cache.getSizeInMemory() > 0); + + //locks + //timeout. This seems strange + assertEquals(245760000, cache.getTimeout()); + cache.lock(key); + cache.unlock(key); + + //toMap + Map map = cache.toMap(); + assertEquals(1, map.size()); + assertEquals(value, map.get(key)); + + long time1 = cache.nextTimestamp(); + long time2 = cache.nextTimestamp(); + assertTrue(time2 > time1); + + cache.destroy(); + try { + cache.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + cache2.destroy(); + //second destroy ok + cache2.destroy(); + + try { + cache2.get(key); + fail(); + } catch (IllegalStateException e) { + //expected + } + + + ((net.sf.ehcache.hibernate.EhCache) cache).getBackingCache().getCacheManager().shutdown(); + ((net.sf.ehcache.hibernate.EhCache) cache).getBackingCache().getCacheManager().shutdown(); + ((net.sf.ehcache.hibernate.EhCache) cache2).getBackingCache().getCacheManager().shutdown(); + + //Spring and Hibernate together can call destroy after the CacheManager has been shutdown + //See bug 1901094. We need to deal with this as "normal". + cache2.destroy(); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/loader/CacheLoaderTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/loader/CacheLoaderTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/loader/CacheLoaderTest.java (revision 11330) @@ -0,0 +1,193 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.loader; + + +import net.sf.ehcache.AbstractCacheTest; +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; +import net.sf.ehcache.Status; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.extension.TestCacheExtension; +import org.junit.After; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * @author Greg Luck + * @version $Id: CacheLoaderTest.java 5594 2012-05-07 16:04:31Z cdennis $ + */ +public class CacheLoaderTest { + + /** + * manager + */ + protected CacheManager manager; + + + /** + * {@inheritDoc} + * + * @throws Exception + */ + @Before + public void setUp() throws Exception { + manager = CacheManager.create(AbstractCacheTest.TEST_CONFIG_DIR + "ehcache-loaderinteractions.xml"); + } + + + /** + * {@inheritDoc} + * + * @throws Exception + */ + @After + public void tearDown() throws Exception { + if (!manager.getStatus().equals(Status.STATUS_SHUTDOWN)) { + manager.shutdown(); + } + } + + @Test + public void testWorksWithTransactionalCaches() { + Cache cache = new Cache(new CacheConfiguration("txLoaderCache", 100) + .transactionalMode(CacheConfiguration.TransactionalMode.LOCAL)); + manager.addCache(cache); + manager.getTransactionController().begin(); + final Element element = cache.getWithLoader(10, new CountingCacheLoader(), null); + assertThat((Integer) element.getValue(), equalTo(0)); + manager.getTransactionController().commit(); + } + + @Test + public void testGetAllWithLoaderExpiredKey() throws Exception { + Cache cache = manager.getCache("CCache"); + cache.put(new Element(1, "one")); + Thread.sleep(1100); // make Element 1 expire, see EHC-809 + cache.put(new Element(2, "two")); + cache.put(new Element(3, null)); + + Map cachedObjects = cache.getAllWithLoader(Arrays.asList(1, 2, 3), null); + + assertTrue(cachedObjects.get(1).toString().equals("C(1)")); + assertTrue(cachedObjects.get(2).toString().equals("two")); + assertNull(cachedObjects.get(3)); + assertTrue(cachedObjects.containsKey(3)); + } + + @Test + public void testLoaderChainNullFirst() { + Cache cache = manager.getCache("NullLoaderFirstCache"); + assertNotNull(cache.getWithLoader("key", null, null)); + NullCountingCacheLoader nullCountingCacheLoader = getNullCountingCacheLoader(cache); + assertEquals(1, nullCountingCacheLoader.getLoadCounter()); + CountingCacheLoader countingCacheLoader = getCountingCacheLoader(cache); + assertEquals(1, countingCacheLoader.getLoadCounter()); + } + + @Test + public void testLoaderChainNullLast() { + Cache cache = manager.getCache("NullLoaderLastCache"); + assertNotNull(cache.getWithLoader("key", null, null)); + CountingCacheLoader countingCacheLoader = getCountingCacheLoader(cache); + assertEquals(1, countingCacheLoader.getLoadCounter()); + NullCountingCacheLoader nullCountingCacheLoader = getNullCountingCacheLoader(cache); + assertEquals(0, nullCountingCacheLoader.getLoadCounter()); + } + + @Test + public void testLoaderChainNullBoth() { + Cache cache = manager.getCache("NullLoaderTwiceCache"); + Element element = cache.getWithLoader("key", null, null); + assertNull(element); + NullCountingCacheLoader nullCountingCacheLoader = getNullCountingCacheLoader(cache); + List list = cache.getRegisteredCacheLoaders(); + assertEquals(2, list.size()); + for (CacheLoader cacheLoader : list) { + if (cacheLoader instanceof NullCountingCacheLoader) { + nullCountingCacheLoader = (NullCountingCacheLoader) cacheLoader; + assertEquals(1, nullCountingCacheLoader.getLoadCounter()); + } + } + + } + + private CountingCacheLoader getCountingCacheLoader(Cache cache) { + List list = cache.getRegisteredCacheLoaders(); + for (CacheLoader cacheLoader : list) { + if (cacheLoader instanceof CountingCacheLoader) { + return (CountingCacheLoader) cacheLoader; + } + } + return null; + } + + private NullCountingCacheLoader getNullCountingCacheLoader(Cache cache) { + List list = cache.getRegisteredCacheLoaders(); + for (CacheLoader cacheLoader : list) { + if (cacheLoader instanceof NullCountingCacheLoader) { + return (NullCountingCacheLoader) cacheLoader; + } + } + return null; + } + + + /** + * Tests the put listener. + */ + @Test + public void testExtensionDirectly() { + + manager.addCache("test"); + TestCacheExtension testCacheExtension = new TestCacheExtension(manager.getCache("test"), "valueA"); + assertEquals(Status.STATUS_UNINITIALISED, testCacheExtension.getStatus()); + assertEquals("valueA", testCacheExtension.getPropertyA()); + + testCacheExtension.init(); + assertEquals(Status.STATUS_ALIVE, testCacheExtension.getStatus()); + + testCacheExtension.dispose(); + assertEquals(Status.STATUS_SHUTDOWN, testCacheExtension.getStatus()); + + } + + + /** + * We need to make sure that cloning a default cache results in a new cache with its own + * set of cache extensions. + */ + @Test + public void testClone() { + + //just test it does not blow up + manager.addCache("clonedCache"); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/FromLargestCachePoolEvictor.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/FromLargestCachePoolEvictor.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/impl/FromLargestCachePoolEvictor.java (revision 11330) @@ -0,0 +1,88 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.pool.impl; + +import net.sf.ehcache.pool.PoolAccessor; +import net.sf.ehcache.pool.PoolEvictor; +import net.sf.ehcache.pool.PoolParticipant; + +import java.util.ArrayList; +import java.util.Collection; + +/** + * Abstract pool evictor which always evicts from the store consuming the most resources. + * + * @author Ludovic Orban + * @author Alex Snaps + */ +public class FromLargestCachePoolEvictor implements PoolEvictor { + + /** + * {@inheritDoc} + */ + public boolean freeSpace(Collection> from, long bytes) { + if (from == null || from.isEmpty()) { + return false; + } + + long remainingSizeInBytes = bytes; + Collection> tried = new ArrayList>(); + + while (tried.size() != from.size()) { + PoolAccessor largestPoolAccessor = findUntriedLargestPoolableStore(from, tried); + + long beforeEvictionSize = largestPoolAccessor.getSize(); + if (!largestPoolAccessor.getParticipant().evict(1, bytes)) { + tried.add(largestPoolAccessor); + continue; + } + long afterEvictionSize = largestPoolAccessor.getSize(); + + remainingSizeInBytes -= (beforeEvictionSize - afterEvictionSize); + if (remainingSizeInBytes <= 0L) { + return true; + } + } + + return false; + } + + private PoolAccessor findUntriedLargestPoolableStore(Collection> from, + Collection> tried) { + PoolAccessor largestPoolAccessor = null; + for (PoolAccessor accessor : from) { + if (alreadyTried(tried, accessor)) { + continue; + } + + if (largestPoolAccessor == null || accessor.getSize() > largestPoolAccessor.getSize()) { + largestPoolAccessor = accessor; + } + } + return largestPoolAccessor; + } + + private boolean alreadyTried(Collection> tried, PoolAccessor from) { + for (PoolAccessor accessor : tried) { + if (accessor == from) { + return true; + } + } + return false; + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/SampledCounterConfig.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/SampledCounterConfig.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/util/counter/sampled/SampledCounterConfig.java (revision 11330) @@ -0,0 +1,95 @@ +/** + * 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 net.sf.ehcache.util.counter.Counter; +import net.sf.ehcache.util.counter.CounterConfig; + +/** + * Config for a {@link SampledCounter} + * + * @author Abhishek Sanoujam + * @since 1.7 + * + */ +public class SampledCounterConfig extends CounterConfig { + private final int intervalSecs; + private final int historySize; + private final boolean isReset; + + /** + * Make a new timed counter config (duh) + * + * @param intervalSecs + * the interval (in seconds) between sampling + * @param historySize + * number of counter samples that will be retained in memory + * @param isResetOnSample + * true if the counter should be reset to 0 upon each sample + * @param initialValue + * the initial value given to this counter + */ + public SampledCounterConfig(int intervalSecs, int historySize, boolean isResetOnSample, long initialValue) { + super(initialValue); + if (intervalSecs < 1) { + throw new IllegalArgumentException("Interval (" + intervalSecs + ") must be greater than or equal to 1"); + } + if (historySize < 1) { + throw new IllegalArgumentException("History size (" + historySize + ") must be greater than or equal to 1"); + } + + this.intervalSecs = intervalSecs; + this.historySize = historySize; + this.isReset = isResetOnSample; + } + + /** + * Returns the history size + * + * @return The history size + */ + public int getHistorySize() { + return historySize; + } + + /** + * Returns the interval time (seconds) + * + * @return Interval of the sampling thread in seconds + */ + public int getIntervalSecs() { + return intervalSecs; + } + + /** + * Returns true if counters created from this config will reset on each + * sample + * + * @return true if values are reset to the initial value after each sample + */ + public boolean isResetOnSample() { + return this.isReset; + } + + /** + * {@inheritDoc} + */ + @Override + public Counter createCounter() { + return new SampledCounterImpl(this); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/PoolAccessor.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/PoolAccessor.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/pool/PoolAccessor.java (revision 11330) @@ -0,0 +1,123 @@ +/** + * 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; + +/** + * PoolAccessors are used by stores to tell the pools about their resource consumption + * + * @param Type representing this "other" side of this accessor (i.e. a store), so the evictor can interact with it + * + * @author Ludovic Orban + * @author Alex Snaps + * + */ +public interface PoolAccessor { + + /** + * Add an element to the pool. + * + * @param key the key of the element + * @param value the value of the element + * @param container the element-container object + * @param force true if the pool should accept adding the element, even if it's out of resources + * @return how many bytes have been added to the pool or -1 if add failed. + */ + long add(Object key, Object value, Object container, boolean force); + + /** + * Check if there is enough room in the pool to add an element without provoking any eviction + * @param key the key of the element + * @param value the value of the element + * @param container the element-container object + * @return true if there is enough room left + */ + boolean canAddWithoutEvicting(Object key, Object value, Object container); + + /** + * Delete a fixed number of bytes from the pool. + * + * @param size number of bytes + * @return how many bytes have been freed from the pool. + * @throws IllegalArgumentException when sizeOf is negative + */ + long delete(long size) throws IllegalArgumentException; + + /** + * Delete a fixed number of bytes from the pool with the given objects. + * + * @param currentSize the size of the object(s) being replaced + * @param key the key of the element + * @param value the value of the element + * @param container the element-container object + * @param force true if the pool should accept replacing the element, even if it's out of resources + * @return the change in size of the pool, or {@link Long#MIN_VALUE} if replace failed. + */ + long replace(long currentSize, Object key, Object value, Object container, boolean force); + + /** + * Return how many bytes this accessor consumes from the pool. + * + * @return how many bytes this accessor consumes from the pool. + */ + long getSize(); + + /** + * unlink this PoolAccessor from its pool. + */ + void unlink(); + + /** + * Free resources used by this accessor. + */ + void clear(); + + /** + * Return the store that uses this accessor + * + * @return store using this accessor + */ + T getParticipant(); + + /** + * Sets the max size for this pool + * + * @param newValue the value in bytes + */ + void setMaxSize(long newValue); + + /** + * Returns the occupied size for this pool. + * + * @return occupied pool size + */ + long getPoolOccupancy(); + + /** + * Returns the size of this pool. + * + * @return pool size + */ + long getPoolSize(); + + /** + * Check if the store may contain elements which the SizeOf engine could not fully size. + * + * @return true if the store may contain partially sized objects + */ + boolean hasAbortedSizeOf(); + +} Index: rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/impl/ConstrainableEntityBuilderSupportV2.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/impl/ConstrainableEntityBuilderSupportV2.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/impl/ConstrainableEntityBuilderSupportV2.java (revision 11330) @@ -0,0 +1,136 @@ +/* + * 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 ConstrainableEntityBuilderSupportV2 { + + 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.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/distribution/ManualRMIPeerProviderIT.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/distribution/ManualRMIPeerProviderIT.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/distribution/ManualRMIPeerProviderIT.java (revision 11330) @@ -0,0 +1,89 @@ +/** + * 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.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; + +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.config.Configuration; +import net.sf.ehcache.config.FactoryConfiguration; + +import org.junit.Before; + +import static net.sf.ehcache.distribution.AbstractRMITest.createAsynchronousCache; + +/** + * @author Greg Luck + * @version $Id: ManualRMIPeerProviderIT.java 8870 2014-04-03 20:27:43Z cdennis $ + */ +public class ManualRMIPeerProviderIT extends MulticastRMIPeerProviderIT { + + /** + * {@inheritDoc} + */ + @Override + @Before + public void setUp() throws Exception { + List configurations = new ArrayList(); + configurations.add(new Configuration() + .cacheManagerPeerListenerFactory(new FactoryConfiguration() + .className("net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory") + .properties("hostName=localhost, port=5011, socketTimeoutMillis=2000")) + .cacheManagerPeerProviderFactory(new FactoryConfiguration() + .className("net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory") + .properties("peerDiscovery=manual,rmiUrls=//localhost:5012/asynchronousCache|//localhost:5013/asynchronousCache")) + .cache(createAsynchronousCache().name("asynchronousCache")) + .name("ManualRMIPeerProviderTest-1")); + + configurations.add(new Configuration() + .cacheManagerPeerListenerFactory(new FactoryConfiguration() + .className("net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory") + .properties("hostName=localhost, port=5012, socketTimeoutMillis=2000")) + .cacheManagerPeerProviderFactory(new FactoryConfiguration() + .className("net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory") + .properties("peerDiscovery=manual,rmiUrls=//localhost:5011/asynchronousCache|//localhost:5013/asynchronousCache")) + .cache(createAsynchronousCache().name("asynchronousCache")) + .name("ManualRMIPeerProviderTest-2")); + + configurations.add(new Configuration() + .cacheManagerPeerListenerFactory(new FactoryConfiguration() + .className("net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory") + .properties("hostName=localhost, port=5013, socketTimeoutMillis=2000")) + .cacheManagerPeerProviderFactory(new FactoryConfiguration() + .className("net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory") + .properties("peerDiscovery=manual")) + .cache(createAsynchronousCache().name("asynchronousCache")) + .name("ManualRMIPeerProviderTest-3")); + + List managers = startupManagers(configurations); + manager1 = managers.get(0); + manager2 = managers.get(1); + manager3 = managers.get(2); + + /* manager3 has an empty manual configuration, which is topped up by adding manual entries. + * The sampleCache1 from manager3 is added to the rmiUrls list for manager1 and manager2 + */ + CacheManagerPeerProvider peerProvider = manager3.getCacheManagerPeerProvider("RMI"); + peerProvider.registerPeer("//localhost:5011/asynchronousCache"); + peerProvider.registerPeer("//localhost:5012/asynchronousCache"); + + //Allow cluster setup + waitForClusterMembership(10, TimeUnit.SECONDS, manager1, manager2, manager3); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/SearchAttribute.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/SearchAttribute.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/SearchAttribute.java (revision 11330) @@ -0,0 +1,333 @@ +/** + * 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.Properties; +import java.util.Set; + +import net.sf.ehcache.config.generator.model.NodeElement; +import net.sf.ehcache.config.generator.model.SimpleNodeAttribute; +import net.sf.ehcache.config.generator.model.SimpleNodeElement; +import net.sf.ehcache.search.attribute.AttributeExtractor; +import net.sf.ehcache.search.attribute.AttributeType; +import net.sf.ehcache.search.attribute.JavaBeanAttributeExtractor; +import net.sf.ehcache.search.attribute.ReflectionAttributeExtractor; +import net.sf.ehcache.util.ClassLoaderUtil; +import net.sf.ehcache.util.PropertyUtil; + +/** + * A cache search attribute. Search attributes must have a name and optionally an expression or class set (if neither is set then this + * implies java bean style) + * + * @author teck + */ +public class SearchAttribute { + + private static final Class UNRESOLVED = UnresolvedType.class; + + private String name; + private String className; + private String expression; + private String properties; + private String propertySeparator; + private String typeName; + private Class type; + + /** + * Set the attribute name + * + * @param name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Set the extractor class for this attribute. This class must be available at runtime and must implement {@link AttributeExtractor} + * + * @param className + */ + public void setClass(String className) { + if (expression != null) { + throw new InvalidConfigurationException("Cannot set both class and expression for a search attribute"); + } + this.className = className; + } + + /** + * Set the attribute expression. See {@link ReflectionAttributeExtractor} for more information + * + * @param expression + */ + public void setExpression(String expression) { + if (className != null) { + throw new InvalidConfigurationException("Cannot set both class and expression for a search attribute"); + } + this.expression = expression; + } + + /** + * Set optional attribute type + * @param type + */ + public void setType(String type) { + this.type = UNRESOLVED; + this.typeName = type; + } + + /** + * Set optional attribute type + * @param type + */ + public void setType(Class type) { + this.typeName = validateType(type); + this.type = type; + } + + /** + * Get the extractor class name + */ + public String getClassName() { + return className; + } + + /** + * Get the attribute expression + */ + public String getExpression() { + return expression; + } + + /** + * Get the attribute name + */ + public String getName() { + return name; + } + + /** + * @return String representation of attribute type + */ + public String getTypeName() { + return typeName; + } + + + /** + * Get actual attribute type + * @return + */ + Class getType(ClassLoader loader) { + if (type == UNRESOLVED) { + type = validateType(this.typeName, loader); + } + + + return type; + } + + /** + * Construct the extractor for this attribute configuration + */ + public AttributeExtractor constructExtractor(ClassLoader loader) { + if (name == null) { + throw new InvalidConfigurationException("search attribute has no name"); + } + + if (expression != null) { + return new ReflectionAttributeExtractor(expression); + } else if (className != null) { + if (properties != null) { + return (AttributeExtractor) ClassLoaderUtil.createNewInstance(loader, className, new Class[] {Properties.class}, + new Object[] {PropertyUtil.parseProperties(properties, propertySeparator)}); + } else { + return (AttributeExtractor) ClassLoaderUtil.createNewInstance(loader, className); + } + } else { + return new JavaBeanAttributeExtractor(name); + } + } + + /** + * Set the attribute name + * + * @param name + * @return this + */ + public SearchAttribute name(String name) { + setName(name); + return this; + } + + /** + * Set the attribute extractor class name + * + * @param className + * attribute extractor class + * @return this + */ + public SearchAttribute className(String className) { + setClass(className); + return this; + } + + /** + * Set the attribute expression + * + * @param expression + * attribute expression + * @return this + */ + public SearchAttribute expression(String expression) { + setExpression(expression); + return this; + } + + /** + * Set optional attribute type + * @param type + * @return this + */ + public SearchAttribute type(String type) { + setType(type); + return this; + } + + /** + * Set optional attribute type + * @param type + * @return this + */ + public SearchAttribute type(Class type) { + setType(type); + return this; + } + + /** + * Set the extractor properties + * + * @param props + */ + public void setProperties(String props) { + this.properties = props; + } + + /** + * Set the extractor properties separator + * + * @param sep + */ + public void setPropertySeparator(String sep) { + this.propertySeparator = sep; + } + + /** + * Set the extractor properties separator + * + * @param sep + * @return this + */ + public SearchAttribute propertySeparator(String sep) { + setPropertySeparator(sep); + return this; + } + + /** + * Set the extractor properties + * + * @param props + * @return this + */ + public SearchAttribute properties(String props) { + setProperties(props); + return this; + } + + /** + * Create a generated config element node for this search attribute definition + * + * @param parent the enclosing parent config element + * @return generated config element for this search attribute + */ + public NodeElement asConfigElement(NodeElement parent) { + SimpleNodeElement rv = new SimpleNodeElement(parent, "searchAttribute"); + + rv.addAttribute(new SimpleNodeAttribute("name", name)); + + if (expression != null) { + rv.addAttribute(new SimpleNodeAttribute("expression", expression)); + } else if (className != null) { + rv.addAttribute(new SimpleNodeAttribute("class", className)); + if (properties != null) { + rv.addAttribute(new SimpleNodeAttribute("properties", properties)); + } + if (propertySeparator != null) { + rv.addAttribute(new SimpleNodeAttribute("propertySeparator", propertySeparator)); + } + } + if (typeName != null) { + rv.addAttribute(new SimpleNodeAttribute("type", typeName)); + } + + return rv; + } + + private Class validateType(String attrType, ClassLoader loader) { + Class realType = null; + for (Class c : AttributeType.getSupportedJavaTypes()) { + if (attrType.equals(c.getName())) { + realType = c; + break; + } + String[] groups = c.getName().split("\\."); + if (attrType.equals(groups[groups.length - 1])) { + if (realType != null) { throw new InvalidConfigurationException("Ambiguous attribute type " + attrType); } + realType = c; + } + } + + if (realType == null) { + // Attempt to load then validate that it's enum + try { + realType = loader.loadClass(attrType); + } catch (ClassNotFoundException e) { + throw new InvalidConfigurationException(String.format("Unable to load class specified as type of attribute %s: %s", + name, e.getMessage())); + } + if (!realType.isEnum()) { + throw new InvalidConfigurationException(String.format("Unsupported attribute type specified %s for search attribute %s", + attrType, name)); + } + } + + return realType; + } + + private String validateType(Class attrType) { + Set> knownTypes = AttributeType.getSupportedJavaTypes(); + String t = attrType.getName(); + if (!knownTypes.contains(attrType) && !attrType.isEnum()) { + throw new InvalidConfigurationException(String.format("Unsupported attribute type specified %s for search attribute %s", t, name)); + } + return t; + } + + private static class UnresolvedType { + // + } + +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsGenericSanityTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsGenericSanityTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/bulkops/BulkOpsGenericSanityTest.java (revision 11330) @@ -0,0 +1,133 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.bulkops; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Element; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration.Consistency; + +import org.junit.Assert; +import org.terracotta.ehcache.tests.AbstractCacheTestBase; +import org.terracotta.ehcache.tests.ClientBase; +import org.terracotta.toolkit.Toolkit; +import org.terracotta.toolkit.concurrent.ToolkitBarrier; + +import com.tc.test.config.model.TestConfig; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.BrokenBarrierException; + +public class BulkOpsGenericSanityTest extends AbstractCacheTestBase { + private static final int NODE_COUNT = 2; + + public BulkOpsGenericSanityTest(TestConfig testConfig) { + super(testConfig, BulkOpsGenericSanityTestClient.class, BulkOpsGenericSanityTestClient.class); + } + + public static class BulkOpsGenericSanityTestClient extends ClientBase { + private ToolkitBarrier barrier; + + public BulkOpsGenericSanityTestClient(String[] args) { + super(args); + } + + public static void main(String[] args) { + new BulkOpsGenericSanityTestClient(args).run(); + } + + @Override + protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { + this.barrier = clusteringToolkit.getBarrier("test-barrier", NODE_COUNT); + + Cache dcv2StrongIdentity = createCache("dcv2StrongIdentity", cacheManager, Consistency.STRONG); + testBulkOpsSanity(dcv2StrongIdentity); + } + + private void testBulkOpsSanity(Cache cache) throws InterruptedException, BrokenBarrierException { + int index = barrier.await(); + int numOfElements = 10; + Set elements = new HashSet(); + for (int i = 0; i < numOfElements; i++) { + elements.add(new Element("key" + i, "val" + i, i)); + } + if (index == 0) { + cache.putAll(elements); + } + + barrier.await(); + while (cache.getSize() != numOfElements) { + Thread.sleep(1000); + } + Assert.assertEquals(numOfElements, cache.getSize()); + + Map rv = cache.getAll(Arrays.asList("key0", "key1", "key2", "key3", "key4", "key5", "key6", + "key7", "key8", "key9")); + Assert.assertEquals(numOfElements, rv.size()); + + for (Element element : rv.values()) { + Assert.assertTrue(elements.contains(element)); + } + + Collection values = rv.values(); + for (Element element : elements) { + Assert.assertTrue(values.contains(element)); + } + + rv = cache.getAll(Arrays.asList("key0", "key2", "key4", "key6", "key8")); + Assert.assertEquals(5, rv.size()); + + for (Element element : rv.values()) { + Assert.assertTrue(elements.contains(element)); + } + + System.out.println("verified by client now waiting for others..."); + barrier.await(); + + if (index != 0) { + cache.removeAll(Arrays.asList("key0", "key2", "key4", "key6", "key8")); + System.out.println("removed 5 keys from " + cache.getName() + ". Now waiting for others..."); + } + barrier.await(); + while (cache.getSize() != numOfElements - 5) { + Thread.sleep(1000); + } + + Assert.assertEquals(numOfElements - 5, cache.getSize()); + System.out.println("now checking removed in " + cache.getName() + " by client"); + + for (int i = 0; i < numOfElements; i++) { + if (i % 2 == 0) { + Assert.assertNull(cache.get("key" + i)); + } else { + Assert.assertNotNull("key" + i); + } + } + System.out.println("client, I am done with " + cache.getName()); + } + + private Cache createCache(String cacheName, CacheManager cm, Consistency consistency) { + CacheConfiguration cacheConfiguration = new CacheConfiguration(); + cacheConfiguration.setName(cacheName); + cacheConfiguration.setMaxElementsInMemory(100000); + cacheConfiguration.setEternal(false); + cacheConfiguration.setTimeToLiveSeconds(100000); + cacheConfiguration.setTimeToIdleSeconds(200000); + + TerracottaConfiguration tcConfiguration = new TerracottaConfiguration(); + tcConfiguration.setConsistency(consistency); + cacheConfiguration.addTerracotta(tcConfiguration); + + Cache cache = new Cache(cacheConfiguration); + cm.addCache(cache); + return cache; + } + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/RecalculateSizeTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/RecalculateSizeTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/RecalculateSizeTest.java (revision 11330) @@ -0,0 +1,346 @@ +/** + * 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.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; + +import junit.framework.Assert; +import junit.framework.TestCase; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.Configuration; +import net.sf.ehcache.config.MemoryUnit; +import net.sf.ehcache.pool.SizeOfEngine; +import net.sf.ehcache.pool.impl.DefaultSizeOfEngine; + +public class RecalculateSizeTest extends TestCase { + private static final Random random; + + static { + final long seed = System.currentTimeMillis(); + System.out.println("*** RANDOM SEEDED WITH " + seed + " ***"); + random = new Random(seed); + } + + private final SizeOfEngine engine = new DefaultSizeOfEngine(1000, true); + + public void testCustomValue() { + DynamicSizedValue value = new DynamicSizedValue('A'); + + value.shrinkSize(); + long shrinkedSize = engine.sizeOf(value, null, null).getCalculated(); + + value.expandSize(); + long expandedSize = engine.sizeOf(value, null, null).getCalculated(); + + System.out.println("Shrinked size: " + shrinkedSize + ", expanded size: " + expandedSize); + + Assert.assertTrue(expandedSize > shrinkedSize); + // consumes 6mb, assert diff is at least 5mb + Assert.assertTrue(expandedSize - shrinkedSize > MemoryUnit.MEGABYTES.toBytes(5)); + + value.shrinkSize(); + long shrinkedSize2 = engine.sizeOf(value, null, null).getCalculated(); + + value.expandSize(); + long expandedSize2 = engine.sizeOf(value, null, null).getCalculated(); + System.out.println("Shrinked size2: " + shrinkedSize2 + ", expanded size2: " + expandedSize2); + + Assert.assertEquals(shrinkedSize, shrinkedSize2); + Assert.assertEquals(expandedSize, expandedSize2); + + value.shrinkSize(); + value = null; + } + + public void testRecalculateSizeGrowing() { + CacheManager cm = createCacheManager(); + cm.addCache(createCache("test-cache-growing")); + + Cache cache = cm.getCache("test-cache-growing"); + Assert.assertEquals(0, cache.getStatistics().getLocalHeapSizeInBytes()); + + DynamicSizedValue value = new DynamicSizedValue('A'); + value.shrinkSize(); + long valueShrinkedSize = engine.sizeOf(value, null, null).getCalculated(); + value.expandSize(); + long valueExpandedSize = engine.sizeOf(value, null, null).getCalculated(); + long valueSizeDiff = valueExpandedSize - valueShrinkedSize; + + value.shrinkSize(); + cache.put(new Element("key", value)); + long shrinkedSize = cache.getStatistics().getLocalHeapSizeInBytes(); + + value.expandSize(); + long expandedSizeBeforeRecalculate = cache.getStatistics().getLocalHeapSizeInBytes(); + + cache.recalculateSize("key"); + long expandedSize = cache.getStatistics().getLocalHeapSizeInBytes(); + + long expectedExpandedSize = shrinkedSize + valueSizeDiff; + + System.out.println("Shrinked size: " + shrinkedSize + ", expandedSizeBeforeRecalculate: " + expandedSizeBeforeRecalculate + + ", expandedSize: " + expandedSize + ", expectedExpandedSize: " + expectedExpandedSize + ", valueShrinkedSize: " + + valueShrinkedSize + ", valueExpandedSize: " + valueExpandedSize); + Assert.assertEquals(shrinkedSize, expandedSizeBeforeRecalculate); + Assert.assertTrue(expandedSize > shrinkedSize); + Assert.assertEquals(valueSizeDiff, expandedSize - expandedSizeBeforeRecalculate); + Assert.assertEquals(expectedExpandedSize, expandedSize); + + cache.remove("key"); + cm.shutdown(); + } + + public void testRecalculateSizeShrinking() { + CacheManager cm = createCacheManager(); + cm.addCache(createCache("test-cache-shrinking")); + + Cache cache = cm.getCache("test-cache-shrinking"); + Assert.assertEquals(0, cache.getStatistics().getLocalHeapSizeInBytes()); + + DynamicSizedValue value = new DynamicSizedValue('A'); + value.shrinkSize(); + long valueShrinkedSize = engine.sizeOf(value, null, null).getCalculated(); + value.expandSize(); + long valueExpandedSize = engine.sizeOf(value, null, null).getCalculated(); + long valueSizeDiff = valueExpandedSize - valueShrinkedSize; + + value.expandSize(); + cache.put(new Element("key", value)); + long expandedSize = cache.getStatistics().getLocalHeapSizeInBytes(); + + value.shrinkSize(); + long shrinkedSizeBeforeRecalculate = cache.getStatistics().getLocalHeapSizeInBytes(); + + cache.recalculateSize("key"); + long shrinkedSize = cache.getStatistics().getLocalHeapSizeInBytes(); + + long expectedShrinkedSize = expandedSize - valueSizeDiff; + + System.out.println("Shrinked size: " + shrinkedSize + ", shrinkedSizeBeforeRecalculate: " + shrinkedSizeBeforeRecalculate + + ", expandedSize: " + expandedSize + ", expectedShrinkedSize: " + expectedShrinkedSize + ", valueShrinkedSize: " + + valueShrinkedSize + ", valueExpandedSize: " + valueExpandedSize); + Assert.assertEquals(expandedSize, shrinkedSizeBeforeRecalculate); + Assert.assertTrue(expandedSize > shrinkedSize); + Assert.assertEquals(valueSizeDiff, expandedSize - shrinkedSize); + Assert.assertEquals(expectedShrinkedSize, shrinkedSize); + + cache.remove("key"); + cm.shutdown(); + } + + private Cache createCache(String name) { + return new Cache(new CacheConfiguration().name(name)); + } + + private CacheManager createCacheManager() { + return CacheManager.create(new Configuration().name("test-cm").maxBytesLocalHeap(40, MemoryUnit.MEGABYTES)); + } + + public void testMultipleRecalculates() throws Exception { + System.out.println("Testing multiple recalculates..."); + final CacheManager cacheManager = createCacheManager(); + cacheManager.addCache(createCache("test-cache")); + final Cache cache = cacheManager.getCache("test-cache"); + final AtomicBoolean stop = new AtomicBoolean(false); + final AtomicReference error = new AtomicReference(); + final AtomicLong numRecalculates = new AtomicLong(); + + final String key = "the-key"; + DynamicSizedValue value = new DynamicSizedValue('A'); + value.setSize(random.nextInt(100000) + 100000); + cache.put(new Element(key, value)); + long initialInMemorySizeBytes = cache.getStatistics().getLocalHeapSizeInBytes(); + System.out.println("Initial: inMemorySizeBytes: " + initialInMemorySizeBytes); + + final int numThreads = 50; + final Thread[] threads = new Thread[numThreads]; + for (int i = 0; i < numThreads; i++) { + threads[i] = new Thread(new Runnable() { + + public void run() { + try { + while (!stop.get()) { + cache.recalculateSize(key); + numRecalculates.incrementAndGet(); + } + } catch (Throwable e) { + error.set(e); + stop.set(true); + } + } + + }, "Test thread - " + i); + + threads[i].setDaemon(true); + threads[i].start(); + } + + for (int i = 0; i < 10; i++) { + cache.recalculateSize(key); + long inMemorySizeBytes = cache.getStatistics().getLocalHeapSizeInBytes(); + System.out.println("initialInMemorySizeBytes: " + initialInMemorySizeBytes + ", calculatedInMemorySizeBytes: " + + inMemorySizeBytes + ", numRecalculates: " + numRecalculates.get()); + Assert.assertEquals(initialInMemorySizeBytes, cache.getStatistics().getLocalHeapSizeInBytes()); + Thread.sleep(1000); + } + + stop.set(true); + for (Thread t : threads) { + t.join(); + } + + Assert.assertEquals(initialInMemorySizeBytes, cache.getStatistics().getLocalHeapSizeInBytes()); + + cacheManager.shutdown(); + } + + public void testMultipleRecalculatesAndMutates() throws Exception { + System.out.println("Testing multiple recalculates with mutation..."); + final CacheManager cacheManager = createCacheManager(); + cacheManager.addCache(createCache("test-cache")); + final Cache cache = cacheManager.getCache("test-cache"); + final AtomicBoolean stop = new AtomicBoolean(false); + final AtomicReference error = new AtomicReference(); + final AtomicLong numRecalculates = new AtomicLong(); + + final String key = "the-key"; + DynamicSizedValue value = new DynamicSizedValue('A'); + value.setSize(random.nextInt(100000)); + cache.put(new Element(key, value)); + + final int numThreads = 50; + final Thread[] threads = new Thread[numThreads]; + for (int i = 0; i < numThreads; i++) { + threads[i] = new Thread(new Runnable() { + + public void run() { + try { + while (!stop.get()) { + cache.recalculateSize(key); + numRecalculates.incrementAndGet(); + } + } catch (Throwable e) { + error.set(e); + stop.set(true); + } + } + + }, "Test thread - " + i); + + threads[i].setDaemon(true); + threads[i].start(); + } + int numChanges = 1; + final int maxNumChanges = 100; + int lastValueSize = 0; + List valueSizeToCalculatedSizeList = new ArrayList(); + while (numChanges <= maxNumChanges && !stop.get()) { + lastValueSize = random.nextInt((int) MemoryUnit.KILOBYTES.toBytes(30)); + value = new DynamicSizedValue('A'); + value.setSize(lastValueSize); + cache.put(new Element(key, value)); + long calculatedInMemorySizeBytes = cache.getStatistics().getLocalHeapSizeInBytes(); + if (numChanges % 10 == 0) { + System.out.println("numChanges: " + numChanges + ", numRecalculates: " + numRecalculates.get() + ", InMemorySizeBytes: " + + calculatedInMemorySizeBytes + ", lastValueSize: " + lastValueSize); + } + valueSizeToCalculatedSizeList.add(new ValueSizeToCalculatedSizeTuple(lastValueSize, calculatedInMemorySizeBytes)); + numChanges++; + } + + for (int i = 0; i < 3; i++) { + cache.recalculateSize(key); + long calculatedMemorySizeBytes = cache.getStatistics().getLocalHeapSizeInBytes(); + System.out.println("calculatedMemorySizeBytes: " + calculatedMemorySizeBytes + ", lastValueSize: " + lastValueSize + + ", numRecalculates: " + numRecalculates.get()); + valueSizeToCalculatedSizeList.add(new ValueSizeToCalculatedSizeTuple(lastValueSize, calculatedMemorySizeBytes)); + Thread.sleep(1000); + } + + System.out.println("Done with changing size randomly. Waiting for all test threads to finish"); + + stop.set(true); + for (Thread t : threads) { + t.join(); + } + + cache.remove(key); + long sizeAfterRemove = cache.getStatistics().getLocalHeapSizeInBytes(); + Assert.assertEquals(0, sizeAfterRemove); + + for (ValueSizeToCalculatedSizeTuple tuple : valueSizeToCalculatedSizeList) { + int valueSize = tuple.valueSize; + long calculatedMemorySizeBytes = tuple.calculatedInMemorySizeBytes; + + Assert.assertEquals(0, cache.getStatistics().getLocalHeapSizeInBytes()); + DynamicSizedValue v = new DynamicSizedValue('A'); + v.setSize(valueSize); + cache.put(new Element(key, v)); + long actualCaculatedInMemorySize = cache.getStatistics().getLocalHeapSizeInBytes(); + System.out.println("valueSize: " + valueSize + ", expectedCalculatedMemorySizeBytes: " + calculatedMemorySizeBytes + + ", actual: " + actualCaculatedInMemorySize); + Assert.assertEquals(calculatedMemorySizeBytes, actualCaculatedInMemorySize); + + cache.remove(key); + } + + cacheManager.shutdown(); + } + + private static class ValueSizeToCalculatedSizeTuple { + final int valueSize; + final long calculatedInMemorySizeBytes; + + public ValueSizeToCalculatedSizeTuple(int valueSize, long calculatedInMemorySizeBytes) { + this.valueSize = valueSize; + this.calculatedInMemorySizeBytes = calculatedInMemorySizeBytes; + } + + } + + public static class DynamicSizedValue { + private volatile char[] chars; + private final char singleChar; + + public DynamicSizedValue(char singleChar) { + this.singleChar = singleChar; + } + + public void shrinkSize() { + this.chars = null; + } + + public void expandSize() { + setSize((int) MemoryUnit.MEGABYTES.toBytes(3)); + } + + private void setSize(int bytes) { + this.chars = null; + this.chars = new char[bytes]; + for (int i = 0; i < chars.length; i++) { + chars[i] = singleChar; + } + } + + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshRAMJobStoreFactory.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshRAMJobStoreFactory.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/src/main/java/net/sf/ehcache/constructs/scheduledrefresh/ScheduledRefreshRAMJobStoreFactory.java (revision 11330) @@ -0,0 +1,43 @@ +/** + * 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; +import org.quartz.simpl.RAMJobStore; + +/** + * A factory for creating RAM job stores. + * + * @author cschanck + */ +public class ScheduledRefreshRAMJobStoreFactory implements ScheduledRefreshJobStorePropertiesFactory { + + /** + * Return the necessary job store proprties to initialize a RAM job store in + * Quartz. + */ + @Override + public Properties jobStoreProperties(Ehcache underlyingCache, ScheduledRefreshConfiguration config) { + Properties p = new Properties(); + p.put(StdSchedulerFactory.PROP_JOB_STORE_CLASS, RAMJobStore.class.getName()); + return p; + } + +} Index: rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/CacheStatisticSamplesResourceServiceImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/CacheStatisticSamplesResourceServiceImpl.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/services/CacheStatisticSamplesResourceServiceImpl.java (revision 11330) @@ -0,0 +1,75 @@ +/* + * 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.resource.CacheStatisticSampleEntity; +import net.sf.ehcache.management.service.EntityResourceFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.terracotta.management.ServiceExecutionException; +import org.terracotta.management.ServiceLocator; +import org.terracotta.management.resource.exceptions.ResourceRuntimeException; +import org.terracotta.management.resource.services.validator.RequestValidator; + +import javax.ws.rs.GET; +import javax.ws.rs.Path; +import javax.ws.rs.Produces; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.UriInfo; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +/** + * @author brandony + */ +@Path("/agents/cacheManagers/caches/statistics/samples") +public final class CacheStatisticSamplesResourceServiceImpl { + private static final Logger LOG = LoggerFactory.getLogger(CacheStatisticSamplesResourceServiceImpl.class); + private final EntityResourceFactory entityResourceFactory; + + private final RequestValidator validator; + + public CacheStatisticSamplesResourceServiceImpl() { + this.entityResourceFactory = ServiceLocator.locate(EntityResourceFactory.class); + this.validator = ServiceLocator.locate(RequestValidator.class); + } + + /** + * + * @param info + * @return + */ + @GET + @Produces(MediaType.APPLICATION_JSON) + public Collection getCacheStatisticSamples(@Context UriInfo info) { + LOG.debug(String.format("Invoking CacheStatisticSamplesResourceServiceImpl.getCacheStatisticSamples: %s", + info.getRequestUri())); + + validator.validateSafe(info); + + String cacheManagerNames = info.getPathSegments().get(1).getMatrixParameters().getFirst("names"); + Set cmNames = cacheManagerNames == null ? null : new HashSet( + Arrays.asList(cacheManagerNames.split(","))); + + String cacheNames = info.getPathSegments().get(2).getMatrixParameters().getFirst("names"); + Set cNames = cacheNames == null ? null : new HashSet(Arrays.asList(cacheNames.split(","))); + + String sampleNames = info.getPathSegments().get(4).getMatrixParameters().getFirst("names"); + Set sNames = sampleNames == null ? null : new HashSet(Arrays.asList(sampleNames.split(","))); + + try { + return entityResourceFactory.createCacheStatisticSampleEntity(cmNames, cNames, sNames); + } catch (ServiceExecutionException e) { + throw new ResourceRuntimeException("Failed to get cache statistics sample", e, + Response.Status.BAD_REQUEST.getStatusCode()); + } + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/config/ConfigurationTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/config/ConfigurationTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/config/ConfigurationTest.java (revision 11330) @@ -0,0 +1,83 @@ +/* + * 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.CacheManager; +import net.sf.ehcache.ObjectExistsException; +import net.sf.ehcache.Status; + +import org.junit.Test; + +import static org.hamcrest.Matchers.containsString; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * ConfigurationTest + */ +public class ConfigurationTest { + + @Test + public void testConfigurationCannotBeSharedAcrossRunningCacheManagers() { + Configuration configuration = new Configuration(); + configuration.setupFor(mock(CacheManager.class), "one"); + + try { + configuration.setupFor(mock(CacheManager.class), "two"); + } catch (IllegalStateException e) { + assertThat(e.getMessage(), containsString("share a Configuration")); + } + } + + @Test + public void testNullingTerracottaConfiguration() { + Configuration config = new Configuration(); + config.addTerracottaConfig(new TerracottaClientConfiguration()); + + try { + config.addTerracottaConfig(new TerracottaClientConfiguration()); + throw new AssertionError(); + } catch (ObjectExistsException oee) { + // expected + } + + config.addTerracottaConfig(null); + config.addTerracottaConfig(new TerracottaClientConfiguration()); + } + + @Test + public void testConfigurationCanBeReusedAfterCacheManagerShutdown() { + Configuration configuration = new Configuration(); + CacheManager mock = mock(CacheManager.class); + when(mock.getStatus()).thenReturn(Status.STATUS_SHUTDOWN); + configuration.setupFor(mock, "one"); + + configuration.setupFor(mock(CacheManager.class), "two"); + } + + @Test + public void testCleanup() throws Exception { + Configuration configuration = new Configuration(); + CacheManager cacheManager = mock(CacheManager.class); + Configuration.RuntimeCfg runtimeCfg1 = configuration.setupFor(cacheManager, "initial CacheManager"); + configuration.cleanup(); + Configuration.RuntimeCfg runtimeCfg2 = configuration.setupFor(cacheManager, "expecting CacheManager name in RuntimeCfg to be this value"); + assertTrue(runtimeCfg2.getCacheManagerName().equals("expecting CacheManager name in RuntimeCfg to be this value")); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/AggregateCacheRegionStats.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/AggregateCacheRegionStats.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/AggregateCacheRegionStats.java (revision 11330) @@ -0,0 +1,62 @@ +/** + * 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; + +/** + * @author gkeim + * + */ +public class AggregateCacheRegionStats extends CacheRegionStats { + private int nodeCount; + + /** + * @param region + */ + public AggregateCacheRegionStats(String region) { + super(region); + } + + /** + * @param stats + */ + public void aggregate(CacheRegionStats stats) { + nodeCount++; + hitCount += stats.getHitCount(); + missCount += stats.getMissCount(); + putCount += stats.getPutCount(); + hitRatio = determineHitRatio(); + + // just add the in memory count together, an average will be returned when the getter is used + elementCountInMemory += stats.getElementCountInMemory(); + + // the largest element count on disk is the one that is the most correct + if (stats.getElementCountOnDisk() > elementCountOnDisk) { + elementCountOnDisk = stats.getElementCountOnDisk(); + } + // elementCountTotal is the same for each node, since it's the total count in the cluster + // no real aggregation is needed, just use the same total count + elementCountTotal = stats.getElementCountTotal(); + } + + /** + * @see net.sf.ehcache.hibernate.management.impl.CacheRegionStats#getElementCountInMemory() + */ + @Override + public long getElementCountInMemory() { + return elementCountInMemory / nodeCount; + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/HibernateUtil.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/HibernateUtil.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/container/hibernate/nontransactional/HibernateUtil.java (revision 11330) @@ -0,0 +1,70 @@ +/* + * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright + * notice. All rights reserved. + */ + +package org.terracotta.ehcache.tests.container.hibernate.nontransactional; + +import org.hibernate.HibernateException; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; + +public class HibernateUtil { + public static final String DB_PORT_VARIABLE = "__PORT__"; + public static final String DB_PORT_SYSPROP = "HibernateUtil.DB_PORT"; + + private static final String defaultConfig = "/hibernate-config/hibernate.cfg.xml"; + private static SessionFactory sessionFactory; + private static Configuration config; + + public synchronized static void configure(String configResource) { + config = makeConfig(configResource); + } + + public synchronized static SessionFactory getSessionFactory() { + if (sessionFactory == null) { + try { + sessionFactory = getConfig().buildSessionFactory(); + } catch (HibernateException ex) { + System.err.println("Initial SessionFactory creation failed." + ex); + throw new ExceptionInInitializerError(ex); + } + } + return sessionFactory; + } + + public synchronized static void dropAndCreateDatabaseSchema() { + getConfig().setProperty("hibernate.hbm2ddl.auto", "create"); + } + + private synchronized static Configuration getConfig() { + if (config == null) { + config = makeConfig(defaultConfig); + } + return config; + } + + private static Configuration makeConfig(String resource) { + String dbPort = System.getProperty(DB_PORT_SYSPROP, null); + if (dbPort == null) { throw new AssertionError("System property (" + DB_PORT_SYSPROP + ") not set"); } + dbPort = dbPort.trim(); + + Configuration cfg = new Configuration().configure(resource); + + String[] keys = new String[] { "connection.url", "hibernate.connection.url" }; + for (String key : keys) { + String value = cfg.getProperty(key); + value = value.replace(DB_PORT_VARIABLE, dbPort); + cfg.setProperty(key, value); + } + + return cfg; + } + + public synchronized static void closeSessionFactory() { + if (sessionFactory != null) { + sessionFactory.close(); + sessionFactory = null; + } + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/AttributeExtractor.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/AttributeExtractor.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/AttributeExtractor.java (revision 11330) @@ -0,0 +1,59 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.search.attribute; + +import java.io.Serializable; + +import net.sf.ehcache.Element; + +/** + * Used to extract a search attribute value for a given cache element.
+ *
+ * Instances must be {@link Serializable} in order to ensure identical + * extractors are used in distributed caches + * + * @author teck + */ +public interface AttributeExtractor extends Serializable { + + /** + * Extract the attribute value. The instance returned from this method must + * be one of: + *
    + *
  • java.lang.Boolean + *
  • java.lang.Byte + *
  • java.lang.Character + *
  • java.lang.Double + *
  • java.lang.Float + *
  • java.lang.Integer + *
  • java.lang.Long + *
  • java.lang.Short + *
  • java.lang.String + *
  • java.util.Date + *
  • java.sql.Date + *
  • java.lang.Enum + *
+ *

+ * NOTE: null is a legal return here as well indicating that this attribute will not be available for the given element + * + * @param element the cache element to inspect + * @param attributeName the name of the requested attribute + * @return the attribute value + * @throws AttributeExtractorException if the attribute cannot be found or extracted + */ + Object attributeFor(Element element, String attributeName) throws AttributeExtractorException; +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/CacheSamplerImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/CacheSamplerImpl.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/management/sampled/CacheSamplerImpl.java (revision 11330) @@ -0,0 +1,2134 @@ +/** + * 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 net.sf.ehcache.Cache; +import net.sf.ehcache.CacheOperationOutcomes; +import net.sf.ehcache.CacheOperationOutcomes.ClusterEventOutcomes; +import net.sf.ehcache.CacheOperationOutcomes.NonStopOperationOutcomes; +import net.sf.ehcache.CacheStoreHelper; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.CacheConfigurationListener; +import net.sf.ehcache.config.PersistenceConfiguration; +import net.sf.ehcache.config.PinningConfiguration; +import net.sf.ehcache.config.SearchAttribute; +import net.sf.ehcache.config.TerracottaConfiguration.Consistency; +import net.sf.ehcache.search.Attribute; +import net.sf.ehcache.store.Store; +import net.sf.ehcache.store.TerracottaStore; +import net.sf.ehcache.util.CacheTransactionHelper; +import net.sf.ehcache.util.counter.sampled.SampledCounter; +import net.sf.ehcache.util.counter.sampled.SampledRateCounter; +import net.sf.ehcache.util.counter.sampled.TimeStampedCounterValue; +import net.sf.ehcache.writer.writebehind.WriteBehindManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.terracotta.statistics.archive.Timestamped; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; + +/** + * An implementation of {@link CacheSampler} + * + * @author Abhishek Sanoujam + * @author byoukste + * + * There is stupid here -- *Sample() is the same as *Rate() + */ +public class CacheSamplerImpl implements CacheSampler, CacheConfigurationListener { + private static final double ONE_HUNDRED = 100.0d; + + private static final int PERCENTAGE_DIVISOR = 100; + + private static final Logger LOG = LoggerFactory.getLogger(CacheSamplerImpl.class); + + private final Ehcache cache; + + /** + * Constructor accepting the backing {@link Ehcache} + * + * @param cache the cache object to use in initializing this sampled representation + */ + public CacheSamplerImpl(Ehcache cache) { + this.cache = cache; + cache.getCacheConfiguration().addConfigurationListener(this); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isEnabled() { + return !cache.isDisabled(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setEnabled(boolean enabled) { + try { + cache.setDisabled(!enabled); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isClusterBulkLoadEnabled() { + try { + return cache.isClusterBulkLoadEnabled(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isNodeBulkLoadEnabled() { + return cache.getCacheConfiguration().isTerracottaClustered() && cache.isNodeBulkLoadEnabled(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setNodeBulkLoadEnabled(boolean bulkLoadEnabled) { + if (bulkLoadEnabled && getTransactional()) { + LOG.warn("a transactional cache cannot be put into bulk-load mode"); + return; + } + cache.setNodeBulkLoadEnabled(bulkLoadEnabled); + } + + /** + * {@inheritDoc} + */ + @Override + public void flush() { + try { + cache.flush(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getCacheName() { + return cache.getName(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getStatus() { + return cache.getStatus().toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeAll() { + if (cache instanceof Cache) { + Store store = new CacheStoreHelper((Cache)cache).getStore(); + if (store instanceof TerracottaStore) { + ((TerracottaStore)store).quickClear(); + cache.getCacheEventNotificationService().notifyRemoveAll(false); + PinningConfiguration pinningConfiguration = cache.getCacheConfiguration().getPinningConfiguration(); + if (pinningConfiguration != null && PinningConfiguration.Store.INCACHE.equals(pinningConfiguration.getStore())) { + LOG.warn("Data availability impacted:\n" + + "****************************************************************************************\n" + + "************************** removeAll called on a pinned cache **************************\n" + + "****************************************************************************************"); + } + return; + } + } + + CacheTransactionHelper.beginTransactionIfNeeded(cache); + try { + cache.removeAll(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } finally { + try { + CacheTransactionHelper.commitTransactionIfNeeded(cache); + } catch (RuntimeException e2) { + throw Utils.newPlainException(e2); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getAverageGetTimeNanosMostRecentSample() { + return getAverageGetTimeNanos(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheEvictionRate() { + return cache.getStatistics().cacheEvictionOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheElementEvictedMostRecentSample() { + return getCacheEvictionRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheExpirationRate() { + return cache.getStatistics().cacheExpiredOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheElementExpiredMostRecentSample() { + return getCacheExpirationRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCachePutRate() { + return cache.getStatistics().cachePutOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheElementPutMostRecentSample() { + return getCachePutRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheRemoveRate() { + return cache.getStatistics().cacheRemoveOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheElementRemovedMostRecentSample() { + return getCacheRemoveRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheUpdateRate() { + return cache.getStatistics().cachePutReplacedOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheElementUpdatedMostRecentSample() { + return getCacheUpdateRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheInMemoryHitRate() { + return cache.getStatistics().localHeapHitOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheHitInMemoryMostRecentSample() { + return getCacheInMemoryHitRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheOffHeapHitRate() { + return cache.getStatistics().localOffHeapHitOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheHitOffHeapMostRecentSample() { + return getCacheOffHeapHitRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheHitRate() { + return cache.getStatistics().cacheHitOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheHitMostRecentSample() { + return getCacheHitRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheOnDiskHitRate() { + return cache.getStatistics().localDiskHitOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheHitOnDiskMostRecentSample() { + return getCacheOnDiskHitRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissExpiredMostRecentSample() { + return cache.getStatistics().cacheMissExpiredOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissRate() { + return cache.getStatistics().cacheMissOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissMostRecentSample() { + return getCacheMissRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheInMemoryMissRate() { + return cache.getStatistics().localHeapMissOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissInMemoryMostRecentSample() { + return getCacheInMemoryMissRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheOffHeapMissRate() { + return cache.getStatistics().localOffHeapMissOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissOffHeapMostRecentSample() { + return getCacheOffHeapMissRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheOnDiskMissRate() { + return cache.getStatistics().localDiskMissOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissOnDiskMostRecentSample() { + return getCacheOnDiskMissRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissNotFoundMostRecentSample() { + return cache.getStatistics().cacheMissNotFoundOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public void dispose() { + cache.getCacheConfiguration().removeConfigurationListener(this); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isTerracottaClustered() { + return this.cache.getCacheConfiguration().isTerracottaClustered(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getTerracottaConsistency() { + Consistency consistency = this.cache.getCacheConfiguration().getTerracottaConsistency(); + return consistency != null ? consistency.name() : "na"; + } + + /** + * {@inheritDoc} + */ + @Override + public long getAverageGetTime() { + try { + return cache.getStatistics().cacheGetOperation().latency().average().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Long getMaxGetTimeNanos() { + try { + return (Long)cache.getStatistics().cacheGetOperation().latency().maximum().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Long getMinGetTimeNanos() { + try { + return (Long)cache.getStatistics().cacheGetOperation().latency().minimum().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getXaCommitCount() { + try { + return cache.getStatistics().xaCommitCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getXaRollbackCount() { + try { + return cache.getStatistics().xaRollbackCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getXaRecoveredCount() { + try { + return cache.getStatistics().xaRecoveryCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean getHasWriteBehindWriter() { + return cache.getWriterManager() instanceof WriteBehindManager && cache.getRegisteredCacheWriter() != null; + } + + /** + * {@inheritDoc} + */ + @Override + public long getWriterQueueLength() { + try { + return cache.getStatistics().getWriterQueueLength(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public int getWriterMaxQueueSize() { + return cache.getCacheConfiguration().getCacheWriterConfiguration().getWriteBehindMaxQueueSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public int getWriterConcurrency() { + return cache.getCacheConfiguration().getCacheWriterConfiguration().getWriteBehindConcurrency(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheHitCount() { + try { + return cache.getStatistics().cacheHitCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissCount() { + try { + return cache.getStatistics().cacheMissCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getInMemoryMissCount() { + try { + return cache.getStatistics().localHeapMissCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getOffHeapMissCount() { + try { + return cache.getStatistics().localOffHeapMissCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getOnDiskMissCount() { + try { + return cache.getStatistics().localDiskMissCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheMissCountExpired() { + try { + return cache.getStatistics().cacheMissExpiredCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getDiskExpiryThreadIntervalSeconds() { + return cache.getCacheConfiguration().getDiskExpiryThreadIntervalSeconds(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setDiskExpiryThreadIntervalSeconds(long seconds) { + if (getDiskExpiryThreadIntervalSeconds() != seconds) { + try { + cache.getCacheConfiguration().setDiskExpiryThreadIntervalSeconds(seconds); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getMaxEntriesLocalHeap() { + return cache.getCacheConfiguration().getMaxEntriesLocalHeap(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxEntriesLocalHeap(long maxEntries) { + if (getMaxEntriesLocalHeap() != maxEntries) { + try { + cache.getCacheConfiguration().setMaxEntriesLocalHeap(maxEntries); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getMaxBytesLocalHeap() { + return cache.getCacheConfiguration().getMaxBytesLocalHeap(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxBytesLocalHeap(long maxBytes) { + try { + if (cache.getCacheManager().getConfiguration().isMaxBytesLocalHeapSet()) { + long heapPoolSize = cache.getCacheManager().getConfiguration().getMaxBytesLocalHeap(); + if (maxBytes > heapPoolSize) { + throw new IllegalArgumentException("Requested maxBytesLocalHeap (" + maxBytes + + ") greater than available CacheManager heap pool size (" + heapPoolSize + ")"); + } + } + cache.getCacheConfiguration().setMaxBytesLocalHeap(maxBytes); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxBytesLocalHeapAsString(String maxBytes) { + try { + cache.getCacheConfiguration().setMaxBytesLocalHeap(maxBytes); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + + if (cache.getCacheConfiguration().isMaxBytesLocalHeapPercentageSet()) { + long cacheAssignedMem = cache.getCacheManager().getConfiguration().getMaxBytesLocalHeap() + * cache.getCacheConfiguration().getMaxBytesLocalHeapPercentage() / PERCENTAGE_DIVISOR; + setMaxBytesLocalHeap(cacheAssignedMem); + } + + } + + /** + * {@inheritDoc} + */ + @Override + public String getMaxBytesLocalHeapAsString() { + return cache.getCacheConfiguration().getMaxBytesLocalHeapAsString(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getMaxEntriesLocalDisk() { + return cache.getCacheConfiguration().getMaxEntriesLocalDisk(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxEntriesLocalDisk(long maxEntries) { + if (getMaxEntriesLocalDisk() != maxEntries) { + try { + cache.getCacheConfiguration().setMaxEntriesLocalDisk(maxEntries); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxBytesLocalDisk(long maxBytes) { + try { + if (cache.getCacheManager().getConfiguration().isMaxBytesLocalDiskSet()) { + long diskPoolSize = cache.getCacheManager().getConfiguration().getMaxBytesLocalDisk(); + if (maxBytes > diskPoolSize) { + throw new IllegalArgumentException("Requested maxBytesLocalDisk (" + maxBytes + + ") greater than available CacheManager disk pool size (" + diskPoolSize + ")"); + } + } + cache.getCacheConfiguration().setMaxBytesLocalDisk(maxBytes); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxBytesLocalDiskAsString(String maxBytes) { + try { + cache.getCacheConfiguration().setMaxBytesLocalDisk(maxBytes); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + + if (cache.getCacheConfiguration().isMaxBytesLocalDiskPercentageSet()) { + long cacheAssignedMem = cache.getCacheManager().getConfiguration().getMaxBytesLocalDisk() + * cache.getCacheConfiguration().getMaxBytesLocalDiskPercentage() / PERCENTAGE_DIVISOR; + setMaxBytesLocalDisk(cacheAssignedMem); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getMaxBytesLocalDiskAsString() { + return cache.getCacheConfiguration().getMaxBytesLocalDiskAsString(); + } + + /** + * {@inheritDoc} + */ + @Override + public int getMaxElementsOnDisk() { + return cache.getCacheConfiguration().getMaxElementsOnDisk(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getMaxEntriesInCache() { + return cache.getCacheConfiguration().getMaxEntriesInCache(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxElementsOnDisk(int maxElements) { + if (getMaxElementsOnDisk() != maxElements) { + try { + cache.getCacheConfiguration().setMaxElementsOnDisk(maxElements); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public void setMaxEntriesInCache(long maxEntries) { + if (getMaxEntriesInCache() != maxEntries) { + try { + cache.getCacheConfiguration().setMaxEntriesInCache(maxEntries); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getMaxBytesLocalDisk() { + return cache.getCacheConfiguration().getMaxBytesLocalDisk(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getMaxBytesLocalOffHeap() { + return cache.getCacheConfiguration().getMaxBytesLocalOffHeap(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getMaxBytesLocalOffHeapAsString() { + return cache.getCacheConfiguration().getMaxBytesLocalOffHeapAsString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getMemoryStoreEvictionPolicy() { + return cache.getCacheConfiguration().getMemoryStoreEvictionPolicy().toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setMemoryStoreEvictionPolicy(String evictionPolicy) { + if (!getMemoryStoreEvictionPolicy().equals(evictionPolicy)) { + try { + cache.getCacheConfiguration().setMemoryStoreEvictionPolicy(evictionPolicy); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getTimeToIdleSeconds() { + return cache.getCacheConfiguration().getTimeToIdleSeconds(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setTimeToIdleSeconds(long tti) { + if (getTimeToIdleSeconds() != tti) { + try { + cache.getCacheConfiguration().setTimeToIdleSeconds(tti); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getTimeToLiveSeconds() { + return cache.getCacheConfiguration().getTimeToLiveSeconds(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setTimeToLiveSeconds(long ttl) { + if (getTimeToLiveSeconds() != ttl) { + try { + cache.getCacheConfiguration().setTimeToLiveSeconds(ttl); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isDiskPersistent() { + return cache.getCacheConfiguration().isDiskPersistent(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getPersistenceStrategy() { + PersistenceConfiguration pc = cache.getCacheConfiguration().getPersistenceConfiguration(); + return pc != null ? pc.getStrategy().name() : ""; + } + + /** + * {@inheritDoc} + */ + @Override + public void setDiskPersistent(boolean diskPersistent) { + if (isDiskPersistent() != diskPersistent) { + try { + cache.getCacheConfiguration().setDiskPersistent(diskPersistent); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isOverflowToOffHeap() { + return cache.getCacheConfiguration().isOverflowToOffHeap(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isEternal() { + return cache.getCacheConfiguration().isEternal(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setEternal(boolean eternal) { + if (isEternal() != eternal) { + try { + cache.getCacheConfiguration().setEternal(eternal); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isOverflowToDisk() { + return cache.getCacheConfiguration().isOverflowToDisk(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setOverflowToDisk(boolean overflowToDisk) { + if (isOverflowToDisk() != overflowToDisk) { + try { + cache.getCacheConfiguration().setOverflowToDisk(overflowToDisk); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isLoggingEnabled() { + return cache.getCacheConfiguration().getLogging(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setLoggingEnabled(boolean enabled) { + if (isLoggingEnabled() != enabled) { + try { + cache.getCacheConfiguration().setLogging(enabled); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isPinned() { + return cache.getCacheConfiguration().getPinningConfiguration() != null; + } + + /** + * {@inheritDoc} + */ + @Override + public String getPinnedToStore() { + PinningConfiguration pinningConfig = cache.getCacheConfiguration().getPinningConfiguration(); + return pinningConfig != null ? pinningConfig.getStore().name() : "na"; + } + + /** + * {@inheritDoc} + */ + @Override + public long getEvictedCount() { + try { + return cache.getStatistics().cacheEvictedCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getExpiredCount() { + try { + return cache.getStatistics().cacheExpiredCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getInMemoryHitCount() { + try { + return cache.getStatistics().localHeapHitCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getOffHeapHitCount() { + try { + return cache.getStatistics().localOffHeapHitCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + * + * @deprecated use {@link #getLocalOffHeapSize()} + */ + @Deprecated + @Override + public long getOffHeapSize() { + return getLocalOffHeapSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getOnDiskHitCount() { + try { + return cache.getStatistics().localDiskHitCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + * + * @deprecated use {@link #getLocalDiskSize()} + */ + @Deprecated + @Override + public long getOnDiskSize() { + return getLocalDiskSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getLocalDiskSize() { + try { + return cache.getStatistics().getLocalDiskSize(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getLocalHeapSize() { + try { + return cache.getStatistics().getLocalHeapSize(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getLocalOffHeapSize() { + try { + return cache.getStatistics().getLocalOffHeapSize(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getLocalDiskSizeInBytes() { + try { + return cache.getStatistics().getLocalDiskSizeInBytes(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getLocalHeapSizeInBytes() { + try { + return cache.getStatistics().getLocalHeapSizeInBytes(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getLocalOffHeapSizeInBytes() { + try { + return cache.getStatistics().getLocalOffHeapSizeInBytes(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getPutCount() { + try { + return cache.getStatistics().cachePutCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getRemovedCount() { + try { + return cache.getStatistics().cacheRemoveCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getSize() { + if (cache.getCacheConfiguration().isTerracottaClustered()) { + return getRemoteSizeSample().getMostRecentSample().getCounterValue(); + } + CacheTransactionHelper.beginTransactionIfNeeded(cache); + try { + return cache.getStatistics().getSize(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } finally { + try { + CacheTransactionHelper.commitTransactionIfNeeded(cache); + } catch (RuntimeException re) { + throw Utils.newPlainException(re); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getInMemorySize() { + return getLocalHeapSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getUpdateCount() { + try { + return cache.getStatistics().cachePutUpdatedCount(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceOneArgSuccessCount() { + try { + return cache.getStatistics().getExtended().replaceOneArg().component(CacheOperationOutcomes.ReplaceOneArgOutcome.SUCCESS).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceOneArgSuccessRate() { + try { + return cache.getStatistics().getExtended().replaceOneArg().component(CacheOperationOutcomes.ReplaceOneArgOutcome.SUCCESS).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceOneArgMissCount() { + try { + return cache.getStatistics().getExtended().replaceOneArg().component(CacheOperationOutcomes.ReplaceOneArgOutcome.FAILURE).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceOneArgMissRate() { + try { + return cache.getStatistics().getExtended().replaceOneArg().component(CacheOperationOutcomes.ReplaceOneArgOutcome.FAILURE).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceTwoArgSuccessCount() { + try { + return cache.getStatistics().getExtended().replaceTwoArg().component(CacheOperationOutcomes.ReplaceTwoArgOutcome.SUCCESS).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceTwoArgSuccessRate() { + try { + return cache.getStatistics().getExtended().replaceTwoArg().component(CacheOperationOutcomes.ReplaceTwoArgOutcome.SUCCESS).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceTwoArgMissCount() { + try { + return cache.getStatistics().getExtended().replaceTwoArg().component(CacheOperationOutcomes.ReplaceTwoArgOutcome.SUCCESS).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getReplaceTwoArgMissRate() { + try { + return cache.getStatistics().getExtended().replaceTwoArg().component(CacheOperationOutcomes.ReplaceTwoArgOutcome.FAILURE).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getPutIfAbsentSuccessCount() { + try { + return cache.getStatistics().getExtended().putIfAbsent().component(CacheOperationOutcomes.PutIfAbsentOutcome.SUCCESS).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getPutIfAbsentSuccessRate() { + try { + return cache.getStatistics().getExtended().putIfAbsent().component(CacheOperationOutcomes.PutIfAbsentOutcome.SUCCESS).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getPutIfAbsentMissCount() { + try { + return cache.getStatistics().getExtended().putIfAbsent().component( + CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getPutIfAbsentMissRate() { + try { + return cache.getStatistics().getExtended().putIfAbsent().component(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getRemoveElementSuccessCount() { + try { + return cache.getStatistics().getExtended().removeElement().component( + CacheOperationOutcomes.RemoveElementOutcome.SUCCESS).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getRemoveElementSuccessRate() { + try { + return cache.getStatistics().getExtended().removeElement().component(CacheOperationOutcomes.RemoveElementOutcome.SUCCESS).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getRemoveElementMissCount() { + try { + return cache.getStatistics().getExtended().removeElement().component( + CacheOperationOutcomes.RemoveElementOutcome.FAILURE).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getRemoveElementMissRate() { + try { + return cache.getStatistics().getExtended().removeElement().component(CacheOperationOutcomes.RemoveElementOutcome.FAILURE).rate().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void deregistered(CacheConfiguration config) { + /**/ + } + + /** + * {@inheritDoc} + */ + @Override + public void maxBytesLocalHeapChanged(final long oldValue, final long newValue) { + if (oldValue != newValue) { + setMaxBytesLocalHeap(newValue); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void maxBytesLocalDiskChanged(final long oldValue, final long newValue) { + if (oldValue != newValue) { + setMaxBytesLocalDisk(newValue); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void diskCapacityChanged(int oldCapacity, int newCapacity) { + if (oldCapacity != newCapacity) { + setMaxElementsOnDisk(newCapacity); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void maxEntriesInCacheChanged(long oldCapacity, long newCapacity) { + if (oldCapacity != newCapacity) { + setMaxEntriesInCache(newCapacity); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void loggingChanged(boolean oldValue, boolean newValue) { + if (oldValue != newValue) { + setLoggingEnabled(newValue); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void memoryCapacityChanged(int oldCapacity, int newCapacity) { + if (oldCapacity != newCapacity) { + setMaxEntriesLocalHeap(newCapacity); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void registered(CacheConfiguration config) { + /**/ + } + + /** + * {@inheritDoc} + */ + @Override + public void timeToIdleChanged(long oldTimeToIdle, long newTimeToIdle) { + if (oldTimeToIdle != newTimeToIdle) { + setTimeToIdleSeconds(newTimeToIdle); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void timeToLiveChanged(long oldTimeToLive, long newTimeToLive) { + if (oldTimeToLive != newTimeToLive) { + setTimeToLiveSeconds(newTimeToLive); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getAverageSearchTime() { + return cache.getStatistics().cacheSearchOperation().latency().average().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getSearchesPerSecond() { + return getCacheSearchRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean getTransactional() { + return cache.getCacheConfiguration().getTransactionalMode().isTransactional(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean getSearchable() { + return cache.getCacheConfiguration().getSearchable() != null; + } + + @Override + public Map getSearchAttributes() { + Map result = new HashMap(); + + if (cache != null && cache.getCacheConfiguration().getSearchable() != null) { + Map attrMap = new HashMap(); + + for (Attribute attr : cache.getSearchAttributes()) { + attrMap.put(attr.getAttributeName(), attr); + } + + for (SearchAttribute sa : cache.getCacheConfiguration().getSearchAttributes().values()) { + String saName = sa.getName(); + String typeName = sa.getTypeName(); + + if (attrMap.containsKey(saName) && typeName != null) { + result.put(saName, typeName); + } + } + } + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheSearchRate() { + return cache.getStatistics().cacheSearchOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getTransactionCommitRate() { + return cache.getStatistics().xaRecoveryOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheXaCommitsMostRecentSample() { + return getTransactionCommitRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getTransactionRollbackRate() { + return cache.getStatistics().xaRollbackOperation().rate().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getCacheXaRollbacksMostRecentSample() { + return getTransactionRollbackRate(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isLocalHeapCountBased() { + return cache.getCacheConfiguration() + .getMaxBytesLocalHeap() <= 0 && !(cache.getCacheManager() != null && cache.getCacheManager() + .getConfiguration() + .isMaxBytesLocalHeapSet()); + } + + /** + * A package friendly method to allow dependants access to the underlying {@link Ehcache} object. This is available + * in order to allow {@link SampledCache} objects to continue to provide deprecated methods on the {@link SampledCacheMBean} interface, + * rather than burdening {@link CacheSampler} with these now irrelevant methods. This helper method + * should be removed if we are ever able to discontinue support for the deprecated methods on dependant interfaces. + * + * @return the underlying {@code Ehcache} object + */ + Ehcache getCache() { + return cache; + } + + /** + * {@inheritDoc} + */ + @Override + public int getCacheHitRatio() { + return (int) (cache.getStatistics().getExtended().cacheHitRatio().value().doubleValue() * ONE_HUNDRED); + } + + /** + * {@inheritDoc} + */ + @Override + public int getCacheHitRatioMostRecentSample() { + return getCacheHitRatio(); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheHitRatioSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().cacheHitRatio()) { + + @Override + public TimeStampedCounterValue getMostRecentSample() { + return new TimeStampedCounterValue(System.currentTimeMillis(), getValue()); + } + + @Override + public TimeStampedCounterValue[] getAllSampleValues() { + ArrayList arr = new ArrayList(); + for (Timestamped ts : rate.history()) { + arr.add(new TimeStampedCounterValue(ts.getTimestamp(), (int) (ts.getSample().doubleValue() * ONE_HUNDRED))); + } + return sortAndPresent(arr); + } + + @Override + public long getValue() { + return (long) (rate.value().doubleValue() * ONE_HUNDRED); + } + + }; + } + + @Override + public long getAverageGetTimeNanos() { + return cache.getStatistics().cacheGetOperation().latency().average().value().longValue(); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheHitSample() { + return new SampledCounterProxy(cache.getStatistics().cacheHitOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheHitInMemorySample() { + return new SampledCounterProxy(cache.getStatistics().localHeapHitOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheHitOffHeapSample() { + return new SampledCounterProxy(cache.getStatistics().localOffHeapHitOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheHitOnDiskSample() { + return new SampledCounterProxy(cache.getStatistics().localDiskHitOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheMissSample() { + return new SampledCounterProxy(cache.getStatistics().cacheMissOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheMissInMemorySample() { + return new SampledCounterProxy(cache.getStatistics().localHeapMissOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheMissOffHeapSample() { + return new SampledCounterProxy(cache.getStatistics().localOffHeapMissOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheMissOnDiskSample() { + return new SampledCounterProxy(cache.getStatistics().localDiskMissOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheMissExpiredSample() { + return new SampledCounterProxy(cache.getStatistics().cacheMissExpiredOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheMissNotFoundSample() { + return new SampledCounterProxy(cache.getStatistics().cacheMissNotFoundOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheElementEvictedSample() { + return new SampledCounterProxy(cache.getStatistics().cacheEvictionOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheElementRemovedSample() { + return new SampledCounterProxy(cache.getStatistics().cacheRemoveOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheElementExpiredSample() { + return new SampledCounterProxy(cache.getStatistics().cacheExpiredOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheElementPutSample() { + return new SampledCounterProxy(cache.getStatistics().cachePutOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheElementUpdatedSample() { + return new SampledCounterProxy(cache.getStatistics().cachePutReplacedOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledRateCounter getAverageGetTimeSample() { + return new SampledRateCounterProxy(cache.getStatistics().cacheGetOperation().latency().average()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledRateCounter getAverageSearchTimeSample() { + return new SampledRateCounterProxy(cache.getStatistics().cacheSearchOperation().latency().average()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getSearchesPerSecondSample() { + return new SampledRateCounterProxy(cache.getStatistics().cacheSearchOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheXaCommitsSample() { + return new SampledRateCounterProxy(cache.getStatistics().xaCommitSuccessOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getCacheXaRollbacksSample() { + return new SampledRateCounterProxy(cache.getStatistics().xaRollbackOperation().rate()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getSizeSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().size()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getLocalHeapSizeSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().localHeapSize()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getLocalHeapSizeInBytesSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().localHeapSizeInBytes()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getLocalOffHeapSizeSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().localOffHeapSize()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getLocalOffHeapSizeInBytesSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().localOffHeapSizeInBytes()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getLocalDiskSizeSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().localDiskSize()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getLocalDiskSizeInBytesSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().localDiskSizeInBytes()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getRemoteSizeSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().remoteSize()); + } + + /** + * {@inheritDoc} + */ + @Override + public SampledCounter getWriterQueueLengthSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().writerQueueLength()); + } + + @Override + public long getAverageSearchTimeNanos() { + return getAverageSearchTime(); + } + + @Override + public long getCacheClusterOfflineCount() { + try { + return cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.OFFLINE).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getCacheClusterRejoinCount() { + try { + return cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.REJOINED).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getCacheClusterOnlineCount() { + try { + return cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.ONLINE).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getCacheClusterOfflineMostRecentSample() { + return cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.OFFLINE).rate().value().longValue(); + } + + @Override + public long getCacheClusterRejoinMostRecentSample() { + return cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.REJOINED).rate().value().longValue(); + } + + @Override + public long getCacheClusterOnlineMostRecentSample() { + return cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.ONLINE).rate().value().longValue(); + } + + @Override + public SampledCounter getCacheClusterOfflineSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.OFFLINE).rate()); + } + + @Override + public SampledCounter getCacheClusterOnlineSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.ONLINE).rate()); + } + + @Override + public SampledCounter getCacheClusterRejoinSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().clusterEvent().component(ClusterEventOutcomes.REJOINED).rate()); + } + + @Override + public long getMostRecentRejoinTimeStampMillis() { + try { + return cache.getStatistics().getExtended().mostRecentRejoinTimeStampMillis().value().longValue(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public SampledCounter getMostRecentRejoinTimestampMillisSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().mostRecentRejoinTimeStampMillis()); + } + + @Override + public long getNonStopSuccessCount() { + try { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.SUCCESS).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getNonStopFailureCount() { + try { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.FAILURE).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getNonStopRejoinTimeoutCount() { + try { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.REJOIN_TIMEOUT).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getNonStopTimeoutCount() { + try { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.TIMEOUT).count().value(); + } catch (RuntimeException e) { + throw Utils.newPlainException(e); + } + } + + @Override + public long getNonStopSuccessMostRecentSample() { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.SUCCESS).rate().value().longValue(); + } + + @Override + public long getNonStopFailureMostRecentSample() { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.FAILURE).rate().value().longValue(); + } + + @Override + public long getNonStopRejoinTimeoutMostRecentSample() { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.REJOIN_TIMEOUT).rate().value().longValue(); + } + + @Override + public long getNonStopTimeoutMostRecentSample() { + return cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.TIMEOUT).rate().value().longValue(); + } + + @Override + public SampledCounter getNonStopSuccessSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.SUCCESS).rate()); + } + + @Override + public SampledCounter getNonStopFailureSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.FAILURE).rate()); + } + + @Override + public SampledCounter getNonStopRejoinTimeoutSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.REJOIN_TIMEOUT).rate()); + } + + @Override + public SampledCounter getNonStopTimeoutSample() { + return new SampledRateCounterProxy(cache.getStatistics().getExtended().nonstop().component(NonStopOperationOutcomes.TIMEOUT).rate()); + } + + @Override + public long getNonStopSuccessRate() { + return getNonStopSuccessMostRecentSample(); + } + + @Override + public long getNonStopFailureRate() { + return getNonStopFailureMostRecentSample(); + } + + @Override + public long getNonStopRejoinTimeoutRate() { + return getNonStopRejoinTimeoutMostRecentSample(); + } + + @Override + public long getNonStopTimeoutRate() { + return getNonStopTimeoutMostRecentSample(); + } + + @Override + public SampledCounter getReplaceOneArgSuccessSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().replaceOneArg().component( + CacheOperationOutcomes.ReplaceOneArgOutcome.SUCCESS).rate()); + } + + @Override + public SampledCounter getReplaceOneArgMissSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().replaceOneArg().component( + CacheOperationOutcomes.ReplaceOneArgOutcome.FAILURE).rate()); + } + + @Override + public SampledCounter getReplaceTwoArgSuccessSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().replaceTwoArg().component( + CacheOperationOutcomes.ReplaceTwoArgOutcome.SUCCESS).rate()); + } + + @Override + public SampledCounter getReplaceTwoArgMissSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().replaceTwoArg().component( + CacheOperationOutcomes.ReplaceTwoArgOutcome.FAILURE).rate()); + } + + @Override + public SampledCounter getPutIfAbsentSuccessSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().putIfAbsent().component( + CacheOperationOutcomes.PutIfAbsentOutcome.SUCCESS).rate()); + } + + @Override + public SampledCounter getPutIfAbsentMissSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().putIfAbsent().component( + CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE).rate()); + } + + @Override + public SampledCounter getRemoveElementSuccessSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().removeElement().component( + CacheOperationOutcomes.RemoveElementOutcome.SUCCESS).rate()); + } + + @Override + public SampledCounter getRemoveElementMissSample() { + return new SampledCounterProxy(cache.getStatistics().getExtended().removeElement().component( + CacheOperationOutcomes.RemoveElementOutcome.FAILURE).rate()); + } + + @Override + public int getNonstopTimeoutRatio() { + return (int) (cache.getStatistics().getExtended().nonstopTimeoutRatio().value().doubleValue() * ONE_HUNDRED); + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/management/ManagementServerLoader.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/management/ManagementServerLoader.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/management/ManagementServerLoader.java (revision 11330) @@ -0,0 +1,263 @@ +/** + * 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; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.config.ManagementRESTServiceConfiguration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.net.URL; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.ServiceLoader; + +/** + * ManagementServerLoader is a facility class to access the rest management interface + * One would use it from EhCache or QuartzScheduler to start or stop a new rest management interface + * or to simply register a cache or a scheduler to an already started management interface. + *

+ * It uses internally a ResourceClassLoader to load classes from a rest agent jar. + * + * @author Anthony Dahanne + */ +public class ManagementServerLoader { + + static final Map MGMT_SVR_BY_BIND = new HashMap(); + + private static final String PRIVATE_CLASSPATH = "rest-management-private-classpath"; + private static final Class MANAGEMENT_SERVER_CLASS; + + private static final ClassLoader RESOURCE_CLASS_LOADER; + private static final Logger LOG = LoggerFactory.getLogger(ManagementServerLoader.class); + + static { + URL depsResource = DevModeClassLoader.devModeResource(); + if (depsResource != null) { + RESOURCE_CLASS_LOADER = new DevModeClassLoader(depsResource, CacheManager.class.getClassLoader()); + } else { + RESOURCE_CLASS_LOADER = new ResourceClassLoader(PRIVATE_CLASSPATH, CacheManager.class.getClassLoader()); + } + LOG.info("XXX: using classloader: " + RESOURCE_CLASS_LOADER); + + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + Class managementServerClass = null; + try { + // because some code in Jersey is using the TCCL to resolve some classes + Thread.currentThread().setContextClassLoader(RESOURCE_CLASS_LOADER); + managementServerClass = RESOURCE_CLASS_LOADER.loadClass("net.sf.ehcache.management.ManagementServer"); + } catch (Exception e) { + managementServerClass = null; + if (e.getCause() instanceof ClassNotFoundException) { + LOG.warn("Failed to initialize the ManagementRESTService - Did you include ehcache-rest-agent on the classpath?", e); + } else { + LOG.warn("Failed to load ManagementServer class. Management agent will not be available.", e); + } + } finally { + // setting back the appClassLoader as the TCCL + Thread.currentThread().setContextClassLoader(contextClassLoader); + MANAGEMENT_SERVER_CLASS = managementServerClass; + } + } + + /** + * Check if the ehcache-rest-agent jar is on the classpath + * + * @return true if ehcache-rest-agent is available, false otherwise. + */ + public static boolean isManagementAvailable() { + try { + ServiceLoader loader = ServiceLoader.load(ManagementServer.class, RESOURCE_CLASS_LOADER); + Iterator loaderIterator = loader.iterator(); + if (loaderIterator.hasNext()) { + return true; + } + } catch (Exception e) { + LOG.warn("Unable to load META-INF/services/net.sf.ehcache.management.ManagementServer ; the management" + + " agent won't be available"); + } + return false; + } + + /** + * Register a cacheManager to management rest server. + * If the server does not exist, starts it. + * + * @param cacheManager the cacheManager to register + * @param clientUUID the client UUID + * @param managementRESTServiceConfiguration the management configuration + */ + public static void register(CacheManager cacheManager, String clientUUID, + ManagementRESTServiceConfiguration managementRESTServiceConfiguration) { + ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); + try { + // because some code in Jersey is using the TCCL to resolve some classes + Thread.currentThread().setContextClassLoader(RESOURCE_CLASS_LOADER); + if (!MGMT_SVR_BY_BIND.containsKey(managementRESTServiceConfiguration.getBind())) { + if (!MGMT_SVR_BY_BIND.isEmpty()) { + String alreadyBound = MGMT_SVR_BY_BIND.keySet().iterator().next(); + managementRESTServiceConfiguration.setBind(alreadyBound); + LOG.warn("You cannot have several Ehcache management rest agents running in the same ClassLoader; CacheManager " + + cacheManager.getName() + + " will be registered to the already running Ehcache management rest agent " + + (ManagementRESTServiceConfiguration.NO_BIND.equals(managementRESTServiceConfiguration.getBind()) ? + "reachable through the TSA agent" : "listening on port " + alreadyBound) + + ", the configuration will not be changed for " + cacheManager.getName()); + } else { + new ManagementServerHolder(loadOSorEEManagementServer()).start(managementRESTServiceConfiguration); + } + } else { + LOG.warn("Another CacheManager already instantiated the Ehcache Management rest agent" + + (ManagementRESTServiceConfiguration.NO_BIND.equals(managementRESTServiceConfiguration.getBind()) ? + ", reachable through the TSA agent" : ", on port " + managementRESTServiceConfiguration.getBind()) + + ", the configuration will not be changed for " + cacheManager.getName()); + } + ManagementServerHolder managementServerHolder = MGMT_SVR_BY_BIND.get(managementRESTServiceConfiguration.getBind()); + managementServerHolder.register(cacheManager, clientUUID); + } catch (Exception e) { + if (e.getCause() instanceof ClassNotFoundException) { + throw new RuntimeException( + "Failed to initialize the ManagementRESTService - Did you include ehcache-rest-agent on the classpath?", e); + } else { + throw new CacheException("Failed to instantiate ManagementServer.", e); + } + } finally { + // setting back the appClassLoader as the TCCL + Thread.currentThread().setContextClassLoader(contextClassLoader); + } + } + + /** + * This method instantiates the ManagementServer implementation found in + * META-INF/services/net.sf.ehcache.management.ManagementServer + * + * @return a {@link ManagementServer} instance + */ + private static Object loadOSorEEManagementServer() throws Exception { + Object managementServerImpl; + ServiceLoader loader = ServiceLoader.load(ManagementServer.class, RESOURCE_CLASS_LOADER); + + Iterator loaderIterator = loader.iterator(); + if (!loaderIterator.hasNext()) { + LOG.info("Could not find any META-INF/services/net.sf.ehcache.management.ManagementServer using the " + + "ResourceClassLoader; choosing the default OS implementation : " + + "net.sf.ehcache.management.ManagementServerImpl"); + Class managementServerImplClass = RESOURCE_CLASS_LOADER + .loadClass("net.sf.ehcache.management.ManagementServerImpl"); + Constructor managementServerImplClassConstructor = managementServerImplClass.getConstructor(); + managementServerImpl = managementServerImplClassConstructor.newInstance(); + } else { + managementServerImpl = loaderIterator.next(); + // more than one file found ? is it even possible ? well across multiple jars, why not.. + if (loaderIterator.hasNext()) { + throw new RuntimeException("Several META-INF/services/net.sf.ehcache.management.ManagementServer " + + "found in the classpath, aborting agent start up"); + } + LOG.info("The ManagementServer implementation that is going to be used is {} .", + managementServerImpl.getClass().toString()); + } + return managementServerImpl; + } + + /** + * Unregister a cache manager from a management rest server + * If it is the last cache manager bound to this server, stops the server too. + * + * @param registeredMgmtSvrBind the bind identifying what to un-register from + * @param cacheManager the cacheManager to un-register + */ + public static void unregister(String registeredMgmtSvrBind, CacheManager cacheManager) { + ManagementServerHolder managementServerHolder = MGMT_SVR_BY_BIND.get(registeredMgmtSvrBind); + + try { + managementServerHolder.unregister(cacheManager); + + // there are no more cacheManagers registered to the rest agent, we can now stop it + if (!managementServerHolder.hasRegistered()) { + managementServerHolder.stop(registeredMgmtSvrBind); + } + + } catch (Exception e) { + LOG.warn("Failed to shutdown the ManagementRESTService", e); + } + } + + + static final class ManagementServerHolder { + private Object managementServer; + private final Map clientUUIDs = new HashMap(); + + ManagementServerHolder(Object managementServer) { + this.managementServer = managementServer; + } + + void start(ManagementRESTServiceConfiguration managementRESTServiceConfiguration) throws Exception { + Method initializeMethod = MANAGEMENT_SERVER_CLASS.getMethod("initialize", ManagementRESTServiceConfiguration.class); + initializeMethod.invoke(managementServer, managementRESTServiceConfiguration); + + Method startMethod = MANAGEMENT_SERVER_CLASS.getMethod("start"); + startMethod.invoke(managementServer); + + MGMT_SVR_BY_BIND.put(managementRESTServiceConfiguration.getBind(), this); + } + + void register(CacheManager cacheManager, String clientUUID) throws Exception { + Method registerMethod = MANAGEMENT_SERVER_CLASS.getMethod("register", CacheManager.class); + registerMethod.invoke(managementServer, cacheManager); + + if (clientUUID != null) { + Method registerClusterRemoteEndpoint = MANAGEMENT_SERVER_CLASS.getMethod("registerClusterRemoteEndpoint", String.class); + registerClusterRemoteEndpoint.invoke(managementServer, clientUUID); + clientUUIDs.put(cacheManager.getName(), clientUUID); + } + } + + void unregister(CacheManager cacheManager) throws Exception { + Method unregisterMethod = MANAGEMENT_SERVER_CLASS.getMethod("unregister", CacheManager.class); + unregisterMethod.invoke(managementServer, cacheManager); + + String unregisteredClientUUID = clientUUIDs.remove(cacheManager.getName()); + if (unregisteredClientUUID != null) { + Method unregisterClusterRemoteEndpoint = MANAGEMENT_SERVER_CLASS.getMethod("unregisterClusterRemoteEndpoint", String.class); + unregisterClusterRemoteEndpoint.invoke(managementServer, unregisteredClientUUID); + } + } + + boolean hasRegistered() throws Exception { + Method hasRegisteredMethod = MANAGEMENT_SERVER_CLASS.getMethod("hasRegistered"); + return (Boolean)hasRegisteredMethod.invoke(managementServer); + } + + void stop(String bind) throws Exception { + try { + Method stopMethod = MANAGEMENT_SERVER_CLASS.getMethod("stop"); + stopMethod.invoke(managementServer); + } finally { + MGMT_SVR_BY_BIND.remove(bind); + } + } + + public Object getManagementServer() { + return managementServer; + } + } + +} Index: rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/service/impl/RemoteAgentEndpointImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/service/impl/RemoteAgentEndpointImpl.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-common/src/main/java/net/sf/ehcache/management/service/impl/RemoteAgentEndpointImpl.java (revision 11330) @@ -0,0 +1,102 @@ +/* + * 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.util.concurrent.ConcurrentHashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.terracotta.management.l1bridge.AbstractRemoteAgentEndpointImpl; + +import javax.management.MBeanException; +import javax.management.MBeanServer; +import javax.management.ObjectName; +import javax.management.ReflectionException; +import javax.management.StandardMBean; +import java.lang.management.ManagementFactory; +import java.util.Map; + + +public class RemoteAgentEndpointImpl extends AbstractRemoteAgentEndpointImpl implements RemoteAgentEndpointImplMBean { + private static final Logger LOG = LoggerFactory.getLogger(RemoteAgentEndpointImpl.class); + + public static final String AGENCY = "Ehcache"; + public static final String MBEAN_NAME_PREFIX = "net.sf.ehcache:type=" + IDENTIFIER + ",agency=" + AGENCY; + + private final ThreadLocal requestClusterUUID = new ThreadLocal(); + + private final Map objectNames = new ConcurrentHashMap(); + + public RemoteAgentEndpointImpl() { + } + + protected boolean isTsaSecured() { + return false; + } + + public String getRequestClusterUUID() { + return requestClusterUUID.get(); + } + + public boolean isTsaBridged() { + return getRequestClusterUUID() != null; + } + + public void registerMBean(final String clientUUID) { + if (clientUUID == null) { + throw new NullPointerException("clientUUID cannot be null"); + } + + ObjectName objectName; + try { + objectName = new ObjectName(MBEAN_NAME_PREFIX + ",node=" + clientUUID); + MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); + platformMBeanServer.registerMBean(new StandardMBean(this, RemoteAgentEndpointImplMBean.class) { + @Override + public Object invoke(String actionName, Object[] params, String[] signature) throws MBeanException, ReflectionException { + try { + requestClusterUUID.set(clientUUID); + return super.invoke(actionName, params, signature); + } finally { + requestClusterUUID.remove(); + } + } + }, objectName); + } catch (Exception e) { + LOG.warn("Error registering RemoteAgentEndpointImpl MBean with UUID: " + clientUUID, e); + objectName = null; + } + this.objectNames.put(clientUUID, objectName); + } + + public void unregisterMBean(String clientUUID) { + ObjectName objectName = objectNames.remove(clientUUID); + if (objectName == null) { + return; + } + try { + MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); + platformMBeanServer.unregisterMBean(objectName); + } catch (Exception e) { + LOG.warn("Error unregistering RemoteAgentEndpointImpl MBean : " + objectName, e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public String getVersion() { + return this.getClass().getPackage().getImplementationVersion(); + } + + /** + * {@inheritDoc} + */ + @Override + public String getAgency() { + return AGENCY; + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/src/test/java/net/sf/ehcache/constructs/scheduledrefresh/EvenCacheLoader.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/src/test/java/net/sf/ehcache/constructs/scheduledrefresh/EvenCacheLoader.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-scheduled-refresh/src/test/java/net/sf/ehcache/constructs/scheduledrefresh/EvenCacheLoader.java (revision 11330) @@ -0,0 +1,9 @@ +package net.sf.ehcache.constructs.scheduledrefresh; + +public class EvenCacheLoader extends IncrementingCacheLoader { + + public EvenCacheLoader() { + super(true, 20000); + } + +} \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/pool/impl/RoundRobinOnHeapPoolEvictor.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/pool/impl/RoundRobinOnHeapPoolEvictor.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/pool/impl/RoundRobinOnHeapPoolEvictor.java (revision 11330) @@ -0,0 +1,47 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.pool.impl; + +import net.sf.ehcache.pool.PoolAccessor; +import net.sf.ehcache.pool.PoolEvictor; +import net.sf.ehcache.pool.PoolParticipant; + +import java.util.Collection; + +/** + * @author Ludovic Orban + */ +public class RoundRobinOnHeapPoolEvictor implements PoolEvictor { + public boolean freeSpace(Collection> from, long bytes) { + long remaining = bytes; + + while (true) { + for (PoolAccessor accessor : from) { + long beforeEvictionSize = accessor.getSize(); + if (!accessor.getParticipant().evict(1, bytes)) { + return false; + } + long afterEvictionSize = accessor.getSize(); + + remaining -= (beforeEvictionSize - afterEvictionSize); + if (remaining <= 0L) { + return true; + } + } + } + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/package.html =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/package.html (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/attribute/package.html (revision 11330) @@ -0,0 +1,7 @@ + + + + +This package contains classes for ehcache search attributes + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/ObjectExistsException.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/ObjectExistsException.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/ObjectExistsException.java (revision 11330) @@ -0,0 +1,45 @@ +/** + * 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; + +/** + * Thrown when a duplicate cache is attemtpted to be created + * + * @author Greg Luck, Claus Ibsen + * @version $Id: ObjectExistsException.java 5594 2012-05-07 16:04:31Z cdennis $ + */ +public final class ObjectExistsException extends CacheException { + + /** + * Constructor for the ObjectExistsException object. + */ + public ObjectExistsException() { + super(); + } + + + /** + * Constructor for the ObjectExistsException object. + * + * @param message + */ + public ObjectExistsException(String message) { + super(message); + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/store/ElementIdAssigningStore.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/store/ElementIdAssigningStore.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/store/ElementIdAssigningStore.java (revision 11330) @@ -0,0 +1,477 @@ +/** + * 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.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import net.sf.ehcache.CacheException; +import net.sf.ehcache.Element; +import net.sf.ehcache.ElementIdHelper; +import net.sf.ehcache.Status; +import net.sf.ehcache.search.Attribute; +import net.sf.ehcache.search.Results; +import net.sf.ehcache.search.SearchException; +import net.sf.ehcache.search.attribute.AttributeExtractor; +import net.sf.ehcache.terracotta.TerracottaNotRunningException; +import net.sf.ehcache.util.LongSequence; +import net.sf.ehcache.writer.CacheWriterManager; +import org.terracotta.context.annotations.ContextChild; + +/** + * Store wrapper that assigns sequential IDs to elements as they are added to the underlying store + * + * @author teck + */ +public class ElementIdAssigningStore implements Store { + + @ContextChild + private final Store delegate; + private final LongSequence elementIdSequence; + + /** + * Constructor + * + * @param delegate underlying Store + * @param sequence id sequence + */ + public ElementIdAssigningStore(Store delegate, LongSequence sequence) { + this.delegate = delegate; + this.elementIdSequence = sequence; + } + + private void setId(Element element) { + long id = elementIdSequence.next(); + if (id <= 0) { + throw new CacheException("Element ID must be > 0"); + } + + ElementIdHelper.setId(element, id); + } + + /** + * {@inheritDoc} + */ + @Override + public void addStoreListener(StoreListener listener) { + delegate.addStoreListener(listener); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeStoreListener(StoreListener listener) { + delegate.removeStoreListener(listener); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean put(Element element) throws CacheException { + setId(element); + return delegate.put(element); + } + + /** + * {@inheritDoc} + */ + @Override + public void putAll(Collection elements) throws CacheException { + for (Element e : elements) { + setId(e); + } + delegate.putAll(elements); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean putWithWriter(Element element, CacheWriterManager writerManager) throws CacheException { + setId(element); + return delegate.putWithWriter(element, writerManager); + } + + /** + * {@inheritDoc} + */ + @Override + public Element get(Object key) { + return delegate.get(key); + } + + /** + * {@inheritDoc} + */ + @Override + public Element getQuiet(Object key) { + return delegate.getQuiet(key); + } + + /** + * {@inheritDoc} + */ + @Override + public List getKeys() { + return delegate.getKeys(); + } + + /** + * {@inheritDoc} + */ + @Override + public Element remove(Object key) { + return delegate.remove(key); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeAll(Collection keys) { + delegate.removeAll(keys); + } + + /** + * {@inheritDoc} + */ + @Override + public Element removeWithWriter(Object key, CacheWriterManager writerManager) throws CacheException { + return delegate.removeWithWriter(key, writerManager); + } + + /** + * {@inheritDoc} + */ + @Override + public void removeAll() throws CacheException { + delegate.removeAll(); + } + + /** + * {@inheritDoc} + */ + @Override + public Element putIfAbsent(Element element) throws NullPointerException { + setId(element); + return delegate.putIfAbsent(element); + } + + /** + * {@inheritDoc} + */ + @Override + public Element removeElement(Element element, ElementValueComparator comparator) throws NullPointerException { + return delegate.removeElement(element, comparator); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean replace(Element old, Element element, ElementValueComparator comparator) throws NullPointerException, + IllegalArgumentException { + setId(element); + return delegate.replace(old, element, comparator); + } + + /** + * {@inheritDoc} + */ + @Override + public Element replace(Element element) throws NullPointerException { + setId(element); + return delegate.replace(element); + } + + /** + * {@inheritDoc} + */ + @Override + public void dispose() { + delegate.dispose(); + } + + /** + * {@inheritDoc} + */ + @Override + public int getSize() { + return delegate.getSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public int getInMemorySize() { + return delegate.getInMemorySize(); + } + + /** + * {@inheritDoc} + */ + @Override + public int getOffHeapSize() { + return delegate.getOffHeapSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public int getOnDiskSize() { + return delegate.getOnDiskSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public int getTerracottaClusteredSize() { + return delegate.getTerracottaClusteredSize(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getInMemorySizeInBytes() { + return delegate.getInMemorySizeInBytes(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getOffHeapSizeInBytes() { + return delegate.getOffHeapSizeInBytes(); + } + + /** + * {@inheritDoc} + */ + @Override + public long getOnDiskSizeInBytes() { + return delegate.getOnDiskSizeInBytes(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean hasAbortedSizeOf() { + return delegate.hasAbortedSizeOf(); + } + + /** + * {@inheritDoc} + */ + @Override + public Status getStatus() { + return delegate.getStatus(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsKey(Object key) { + return delegate.containsKey(key); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsKeyOnDisk(Object key) { + return delegate.containsKeyOnDisk(key); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsKeyOffHeap(Object key) { + return delegate.containsKeyOffHeap(key); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsKeyInMemory(Object key) { + return delegate.containsKeyInMemory(key); + } + + /** + * {@inheritDoc} + */ + @Override + public void expireElements() { + delegate.expireElements(); + } + + /** + * {@inheritDoc} + */ + @Override + public void flush() throws IOException { + delegate.flush(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean bufferFull() { + return delegate.bufferFull(); + } + + /** + * {@inheritDoc} + */ + @Override + public Policy getInMemoryEvictionPolicy() { + return delegate.getInMemoryEvictionPolicy(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setInMemoryEvictionPolicy(Policy policy) { + delegate.setInMemoryEvictionPolicy(policy); + } + + /** + * {@inheritDoc} + */ + @Override + public Object getInternalContext() { + return delegate.getInternalContext(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isCacheCoherent() { + return delegate.isCacheCoherent(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isClusterCoherent() throws TerracottaNotRunningException { + return delegate.isClusterCoherent(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean isNodeCoherent() throws TerracottaNotRunningException { + return delegate.isNodeCoherent(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setNodeCoherent(boolean coherent) throws UnsupportedOperationException, TerracottaNotRunningException { + delegate.setNodeCoherent(coherent); + } + + /** + * {@inheritDoc} + */ + @Override + public void waitUntilClusterCoherent() throws UnsupportedOperationException, TerracottaNotRunningException, InterruptedException { + delegate.waitUntilClusterCoherent(); + } + + /** + * {@inheritDoc} + */ + @Override + public Object getMBean() { + return delegate.getMBean(); + } + + /** + * {@inheritDoc} + */ + @Override + public void setAttributeExtractors(Map extractors) { + delegate.setAttributeExtractors(extractors); + } + + /** + * {@inheritDoc} + */ + @Override + public Results executeQuery(StoreQuery query) throws SearchException { + return delegate.executeQuery(query); + } + + /** + * {@inheritDoc} + */ + @Override + public Attribute getSearchAttribute(String attributeName) { + return delegate.getSearchAttribute(attributeName); + } + + /** + * {@inheritDoc} + */ + @Override + public Set getSearchAttributes() { + return delegate.getSearchAttributes(); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getAllQuiet(Collection keys) { + return delegate.getAllQuiet(keys); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getAll(Collection keys) { + return delegate.getAll(keys); + } + + /** + * {@inheritDoc} + */ + @Override + public void recalculateSize(Object key) { + delegate.recalculateSize(key); + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/TerracottaClientConfiguration.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/TerracottaClientConfiguration.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/TerracottaClientConfiguration.java (revision 11330) @@ -0,0 +1,213 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.config; + +import net.sf.ehcache.CacheException; + +/** + * Holds the Terracotta configuration for a particular client + * + * @author amiller@terracotta.org + * @author Abhishek Sanoujam + */ +public class TerracottaClientConfiguration implements Cloneable { + + /** + * Default value of rejoin attribute + */ + public static final boolean DEFAULT_REJOIN_VALUE = false; + + /** + * Default value for whether WAN replication enabled or not + */ + public static final boolean DEFAULT_WAN_ENABLED_TSA_VALUE = false; + + private static final String TC_CONFIG_HEADER = ""; + private static final String TC_CONFIG_FOOTER = ""; + + private String url; + private String embeddedConfig; + private boolean rejoin = DEFAULT_REJOIN_VALUE; + private boolean wanEnabledTSA = DEFAULT_WAN_ENABLED_TSA_VALUE; + private volatile boolean configFrozen; + + /** + * Clones this object, following the usual contract. + * + * @return a copy, which independent other than configurations than cannot change. + * @throws CloneNotSupportedException + */ + @Override + public TerracottaClientConfiguration clone() throws CloneNotSupportedException { + return (TerracottaClientConfiguration) super.clone(); + } + + /** + * Builder method to set the URL. + * + * @param url + * the URL to set + * @return this configuration instance + */ + public final TerracottaClientConfiguration url(String url) { + setUrl(url); + return this; + } + + /** + * Builder method to set the URL for a host and a port. + * + * @param host + * the host where to get the Terracotta configuration from + * @param port + * the port on that host + * @return this configuration instance + */ + public final TerracottaClientConfiguration url(String host, String port) { + if (host.contains(":")) { + host = "[" + host + "]"; + } + setUrl(host + ":" + port); + return this; + } + + /** + * Set url + */ + public final void setUrl(String url) { + this.url = url; + validateConfiguration(); + } + + /** + * Get url string + */ + public final String getUrl() { + return this.url; + } + + /** + * Tell the BeanHandler to extract the entire subtree xml as text at element{@code }. Expects + * to receive the contents of the{@code } tag and will wrap it in a proper tc-config header / footer. + */ + public final void extractTcconfig(String text) { + this.embeddedConfig = text; + validateConfiguration(); + } + + /** + * Get the embedded config read as {@code } + */ + public final String getEmbeddedConfig() { + return TC_CONFIG_HEADER + embeddedConfig + TC_CONFIG_FOOTER; + } + + /** + * Get the original embedded config + * + * @return original embedded config + */ + public final String getOriginalEmbeddedConfig() { + return embeddedConfig; + } + + /** + * Helper to check whether this is url config or embedded config + */ + public final boolean isUrlConfig() { + return this.url != null; + } + + private void validateConfiguration() { + if (this.url != null && this.embeddedConfig != null) { + throw new InvalidConfigurationException("It is invalid to specify both a config url and " + + "an embedded config in the element."); + } + } + + /** + * Returns true if rejoin is enabled + * + * @return the rejoin + */ + public boolean isRejoin() { + return rejoin; + } + + /** + * Set rejoin value + * + * @param rejoin the rejoin to set + */ + public void setRejoin(boolean rejoin) { + if (configFrozen) { + throw new CacheException("Cannot enable/disable rejoin once config has been frozen"); + } + this.rejoin = rejoin; + } + + /** + * Builder method to set rejoin + * + * @param rejoin + * @return this instance + */ + public TerracottaClientConfiguration rejoin(boolean rejoin) { + this.setRejoin(rejoin); + return this; + } + + /** + * Returns true if it is a WAN enabled TSA + * + * @return wanEnabledTSA + */ + public boolean isWanEnabledTSA() { + return wanEnabledTSA; + } + + /** + * Set wanEnabledTSA value + * + * @param wanEnabledTSA + */ + public void setWanEnabledTSA(boolean wanEnabledTSA) { + if (configFrozen) { + throw new CacheException("Cannot set wanEnabledTSA once config has been frozen"); + } + this.wanEnabledTSA = wanEnabledTSA; + } + + /** + * Builder method to set wanEnabledTSA + * + * @param wanEnabledTSA + * @return this instance + */ + public TerracottaClientConfiguration wanEnabledTSA(boolean wanEnabledTSA) { + this.setWanEnabledTSA(wanEnabledTSA); + return this; + } + + /** + * Freezes the config + */ + public void freezeConfig() { + configFrozen = true; + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/terracotta/ClusteredInstanceFactoryWrapper.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/terracotta/ClusteredInstanceFactoryWrapper.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/terracotta/ClusteredInstanceFactoryWrapper.java (revision 11330) @@ -0,0 +1,165 @@ +/** + * 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.Ehcache; +import net.sf.ehcache.cluster.CacheCluster; +import net.sf.ehcache.config.Configuration; +import net.sf.ehcache.event.CacheEventListener; +import net.sf.ehcache.management.event.ManagementEventSink; +import net.sf.ehcache.store.Store; +import net.sf.ehcache.store.TerracottaStore; +import net.sf.ehcache.transaction.SoftLockManager; +import net.sf.ehcache.transaction.TransactionIDFactory; +import net.sf.ehcache.writer.writebehind.WriteBehind; + +import java.util.concurrent.Callable; + +/** + * A {@link ClusteredInstanceFactory} implementation that delegates all operations to an underlying delegate except for the following + * operations: + *

    + *
  • {@link #getTopology()} : Delegates to the {@link TerracottaClient#getCacheCluster()}
  • + *
+ * + * @author Abhishek Sanoujam + * + */ +public class ClusteredInstanceFactoryWrapper implements ClusteredInstanceFactory { + + private final TerracottaClient client; + private final ClusteredInstanceFactory delegate; + + /** + * Constructor accepting the TerracottaClient and the actual factory + * + * @param client + * @param delegate + */ + public ClusteredInstanceFactoryWrapper(TerracottaClient client, ClusteredInstanceFactory delegate) { + this.client = client; + this.delegate = delegate; + + } + + /** + * Returns the actual underlying factory + * + * @return the actual underlying factory + */ + protected ClusteredInstanceFactory getActualFactory() { + return delegate; + } + + /** + * {@inheritDoc} + */ + public CacheCluster getTopology() { + return client.getCacheCluster(); + } + + // all methods below delegate to the real factory + + /** + * {@inheritDoc} + */ + public String getUUID() { + return delegate.getUUID(); + } + + /** + * {@inheritDoc} + */ + @Override + public void enableNonStopForCurrentThread(boolean enable) { + delegate.enableNonStopForCurrentThread(enable); + } + + /** + * {@inheritDoc} + */ + public CacheEventListener createEventReplicator(Ehcache cache) { + return delegate.createEventReplicator(cache); + } + + /** + * {@inheritDoc} + */ + public Store createStore(Ehcache cache) { + return delegate.createStore(cache); + } + + /** + * {@inheritDoc} + */ + public TransactionIDFactory createTransactionIDFactory(String uuid, String cacheManagerName) { + return delegate.createTransactionIDFactory(uuid, cacheManagerName); + } + + /** + * {@inheritDoc} + */ + public WriteBehind createWriteBehind(Ehcache cache) { + return delegate.createWriteBehind(cache); + } + + /** + * {@inheritDoc} + */ + public SoftLockManager getOrCreateSoftLockManager(Ehcache cache) { + return delegate.getOrCreateSoftLockManager(cache); + } + + /** + * {@inheritDoc} + */ + public void shutdown() { + delegate.shutdown(); + } + + @Override + public TerracottaStore createNonStopStore(Callable store, Ehcache cache) { + return delegate.createNonStopStore(store, cache); + } + + @Override + public boolean destroyCache(final String cacheManagerName, final String cacheName) { + return delegate.destroyCache(cacheManagerName, cacheName); + } + + @Override + public void linkClusteredCacheManager(String cacheManagerName, Configuration configuration) { + delegate.linkClusteredCacheManager(cacheManagerName, configuration); + } + + @Override + public void unlinkCache(String cacheName) { + delegate.unlinkCache(cacheName); + } + + @Override + public ManagementEventSink createEventSink() { + return delegate.createEventSink(); + } + + /** + * {@inheritDoc} + */ + public void waitForOrchestrator(String cacheManagerName) { + delegate.waitForOrchestrator(cacheManagerName); + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/strong-cache-invalidation-test.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/strong-cache-invalidation-test.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/resources/strong-cache-invalidation-test.xml (revision 11330) @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + + + + + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/writer/CoalesceKeysFilterTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/writer/CoalesceKeysFilterTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/writer/CoalesceKeysFilterTest.java (revision 11330) @@ -0,0 +1,87 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.writer; + +import net.sf.ehcache.CacheEntry; +import net.sf.ehcache.Element; +import net.sf.ehcache.writer.writebehind.CastingOperationConverter; +import net.sf.ehcache.writer.writebehind.CoalesceKeysFilter; +import net.sf.ehcache.writer.writebehind.operations.DeleteOperation; +import net.sf.ehcache.writer.writebehind.operations.KeyBasedOperation; +import net.sf.ehcache.writer.writebehind.operations.WriteOperation; + +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.terracotta.test.categories.CheckShorts; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +/** + * Tests for a key-based operations coalescing + * + * @author Geert Bevin + * @version $Id: CoalesceKeysFilterTest.java 8024 2013-08-22 10:33:13Z ljacomet $ + */ +@Category(CheckShorts.class) +public class CoalesceKeysFilterTest { + + @Test + public void testFilter() { + List operations = new ArrayList(); + operations.add(new WriteOperation(new Element("key1", "value1"), 10)); + operations.add(new WriteOperation(new Element("key2", "value2"), 10)); + operations.add(new WriteOperation(new Element("key1", "value3"), 30)); + operations.add(new WriteOperation(new Element("key1", "value4"), 20)); + operations.add(new DeleteOperation(new CacheEntry("key3", new Element("key3", "value5")), 30)); + operations.add(new WriteOperation(new Element("key4", "value6"), 40)); + operations.add(new DeleteOperation(new CacheEntry("key2", new Element("key2", "value7")), 20)); + operations.add(new DeleteOperation(new CacheEntry("key4", new Element("key4", "value8")), 30)); + operations.add(new WriteOperation(new Element("key4", "value9"), 20)); + operations.add(new WriteOperation(new Element("key5", "value10"), 50)); + + // key1 - W 10, W 30, W 20 = 3 + // key2 - W 10, D 20 = 2 + // key3 - D 30 = 1 + // key4 - W 40, D 30, W 20 = 3 + // key5 - W 50 = 1 + // operations = k1, k2, k1, k2, k4, k1, k3, k4, k4, k5 = 10 (create time order) + // operations = k1 10, k2 10, k1 30, k1 20, k3 30, k4 40, k2 20, k4 30, k4 20, k5 50 = 10 (add order) + // operations = k1 30, k3 30, k4 40, k2 20, k5 50 = 5 + + new CoalesceKeysFilter().filter(operations, CastingOperationConverter.getInstance()); + + assertEquals(5, operations.size()); + assertEquals("key1", operations.get(0).getKey()); + assertEquals("value3", ((WriteOperation) operations.get(0)).getElement().getValue()); + + assertTrue(operations.get(1) instanceof DeleteOperation); + assertEquals("key3", operations.get(1).getKey()); + + assertEquals("key4", operations.get(2).getKey()); + assertEquals("value6", ((WriteOperation) operations.get(2)).getElement().getValue()); + + assertTrue(operations.get(3) instanceof DeleteOperation); + assertEquals("key2", operations.get(3).getKey()); + + assertEquals("key5", operations.get(4).getKey()); + assertEquals("value10", ((WriteOperation) operations.get(4)).getElement().getValue()); + } +} \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/package-info.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/package-info.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-search-parser/src/main/java/net/sf/ehcache/search/parser/package-info.java (revision 11330) @@ -0,0 +1,5 @@ +/** + * Provides parser for ehcache search. + * + */ +package net.sf.ehcache.search.parser; \ No newline at end of file Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/CompoundOperationImpl.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/CompoundOperationImpl.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/statistics/extended/CompoundOperationImpl.java (revision 11330) @@ -0,0 +1,285 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.statistics.extended; + +import java.util.Arrays; +import java.util.EnumMap; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +import net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation; +import net.sf.ehcache.statistics.extended.ExtendedStatistics.Result; +import net.sf.ehcache.statistics.extended.ExtendedStatistics.Statistic; + +import org.terracotta.statistics.OperationStatistic; +import org.terracotta.statistics.ValueStatistic; + +/** + * The Class CompoundOperationImpl. + * + * @param the generic type + * @author cdennis + */ +class CompoundOperationImpl> implements Operation { + + private final OperationStatistic source; + + private final Class type; + private final Map> operations; + private final ConcurrentMap, OperationImpl> compounds = new ConcurrentHashMap, OperationImpl>(); + private final ConcurrentMap>, ExpiringStatistic> ratios = new ConcurrentHashMap>, ExpiringStatistic>(); + + private final ScheduledExecutorService executor; + + private volatile long averageNanos; + private volatile int historySize; + private volatile long historyNanos; + + private volatile boolean alwaysOn = false; + + /** + * Instantiates a new compound operation impl. + * + * @param source the source + * @param type the type + * @param averagePeriod the average period + * @param averageUnit the average unit + * @param executor the executor + * @param historySize the history size + * @param historyPeriod the history period + * @param historyUnit the history unit + */ + public CompoundOperationImpl(OperationStatistic source, Class type, long averagePeriod, TimeUnit averageUnit, + ScheduledExecutorService executor, int historySize, long historyPeriod, TimeUnit historyUnit) { + this.type = type; + this.source = source; + + this.averageNanos = averageUnit.toNanos(averagePeriod); + this.executor = executor; + this.historySize = historySize; + this.historyNanos = historyUnit.toNanos(historyPeriod); + + this.operations = new EnumMap(type); + for (T result : type.getEnumConstants()) { + operations.put(result, new OperationImpl(source, EnumSet.of(result), averageNanos, executor, historySize, historyNanos)); + } + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#type() + */ + @Override + public Class type() { + return type; + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#component(java.lang.Enum) + */ + @Override + public Result component(T result) { + return operations.get(result); + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#compound(java.util.Set) + */ + @Override + public Result compound(Set results) { + if (results.size() == 1) { + return component(results.iterator().next()); + } else { + Set key = EnumSet.copyOf(results); + OperationImpl existing = compounds.get(key); + if (existing == null) { + OperationImpl created = new OperationImpl(source, key, averageNanos, executor, historySize, historyNanos); + OperationImpl racer = compounds.putIfAbsent(key, created); + if (racer == null) { + return created; + } else { + return racer; + } + } else { + return existing; + } + } + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#ratioOf(java.util.Set, java.util.Set) + */ + @Override + public Statistic ratioOf(Set numerator, Set denominator) { + List> key = Arrays.> asList(EnumSet.copyOf(numerator), EnumSet.copyOf(denominator)); + ExpiringStatistic existing = ratios.get(key); + if (existing == null) { + final Statistic numeratorRate = compound(numerator).rate(); + final Statistic denominatorRate = compound(denominator).rate(); + ExpiringStatistic created = new ExpiringStatistic(new ValueStatistic() { + @Override + public Double value() { + return numeratorRate.value() / denominatorRate.value(); + } + }, executor, historySize, historyNanos); + ExpiringStatistic racer = ratios.putIfAbsent(key, created); + if (racer == null) { + return created; + } else { + return racer; + } + } else { + return existing; + } + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#setAlwaysOn(boolean) + */ + @Override + public void setAlwaysOn(boolean enable) { + alwaysOn = enable; + if (enable) { + for (OperationImpl op : operations.values()) { + op.start(); + } + for (OperationImpl op : compounds.values()) { + op.start(); + } + for (ExpiringStatistic ratio : ratios.values()) { + ratio.start(); + } + } + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#isAlwaysOn() + */ + @Override + public boolean isAlwaysOn() { + return alwaysOn; + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#setWindow(long, java.util.concurrent.TimeUnit) + */ + @Override + public void setWindow(long time, TimeUnit unit) { + averageNanos = unit.toNanos(time); + for (OperationImpl op : operations.values()) { + op.setWindow(averageNanos); + } + for (OperationImpl op : compounds.values()) { + op.setWindow(averageNanos); + } + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#setHistory(int, long, java.util.concurrent.TimeUnit) + */ + @Override + public void setHistory(int samples, long time, TimeUnit unit) { + historySize = samples; + historyNanos = unit.toNanos(time); + for (OperationImpl op : operations.values()) { + op.setHistory(historySize, historyNanos); + } + for (OperationImpl op : compounds.values()) { + op.setHistory(historySize, historyNanos); + } + for (ExpiringStatistic ratio : ratios.values()) { + ratio.setHistory(historySize, historyNanos); + } + } + + /* + * (non-Javadoc) + * + * @see net.sf.ehcache.statistics.extended.ExtendedStatistics.Operation#getWindowSize(java.util.concurrent.TimeUnit) + */ + @Override + public long getWindowSize(TimeUnit unit) { + return unit.convert(averageNanos, TimeUnit.NANOSECONDS); + } + + /** + * Get the history sample size. + */ + @Override + public int getHistorySampleSize() { + return historySize; + } + + /** + * Get the history sample time. + */ + @Override + public long getHistorySampleTime(TimeUnit unit) { + return unit.convert(historySize, TimeUnit.NANOSECONDS); + } + + /** + * Expire. + * + * @param expiryTime the expiry time + * @return true, if successful + */ + boolean expire(long expiryTime) { + if (alwaysOn) { + return false; + } else { + boolean expired = true; + for (OperationImpl o : operations.values()) { + expired &= o.expire(expiryTime); + } + for (Iterator> it = compounds.values().iterator(); it.hasNext();) { + if (it.next().expire(expiryTime)) { + it.remove(); + } + } + for (Iterator> it = ratios.values().iterator(); it.hasNext();) { + if (it.next().expire(expiryTime)) { + it.remove(); + } + } + return expired & compounds.isEmpty() & ratios.isEmpty(); + } + } + +} Index: rctags/ehcache-2.10.9.0.363/distribution/colorcache/src/assemble/jetty6.1/9081/conf.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/distribution/colorcache/src/assemble/jetty6.1/9081/conf.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/distribution/colorcache/src/assemble/jetty6.1/9081/conf.xml (revision 11330) @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /webapps + false + true + false + + + + + + + + ./logs/console.yyyy_mm_dd.log + false + 90 + GMT + + + + + + Redirecting stderr/stdout to + + + + Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/constructs/nonstop/MockCacheWriterFactory.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/constructs/nonstop/MockCacheWriterFactory.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/test/java/net/sf/ehcache/constructs/nonstop/MockCacheWriterFactory.java (revision 11330) @@ -0,0 +1,76 @@ +/** + * 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.nonstop; + +import java.util.Collection; +import java.util.Properties; + +import net.sf.ehcache.CacheEntry; +import net.sf.ehcache.CacheException; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.writer.CacheWriter; +import net.sf.ehcache.writer.CacheWriterFactory; +import net.sf.ehcache.writer.writebehind.operations.SingleOperationType; + +public class MockCacheWriterFactory extends CacheWriterFactory { + + @Override + public CacheWriter createCacheWriter(Ehcache cache, Properties properties) { + return new CacheWriter() { + + public void writeAll(Collection elements) throws CacheException { + // no-op + } + + public void write(Element element) throws CacheException { + // no-op + + } + + public void init() { + // no-op + + } + + public void dispose() throws CacheException { + // no-op + + } + + public void deleteAll(Collection entries) throws CacheException { + // no-op + + } + + public void throwAway(final Element element, final SingleOperationType operationType, final RuntimeException e) { + // no-op + } + + public void delete(CacheEntry entry) throws CacheException { + // no-op + + } + + public CacheWriter clone(Ehcache cache) throws CloneNotSupportedException { + // no-op + return null; + } + }; + } + +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/expression/LessThanOrEqual.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/expression/LessThanOrEqual.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/search/expression/LessThanOrEqual.java (revision 11330) @@ -0,0 +1,64 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.search.expression; + +/** + * Less than or equal criteria + * + * @author teck + */ +public class LessThanOrEqual extends ComparableValue { + + private final Comparable comparableValue; + + /** + * Constructor + * + * @param attributeName attribute name + * @param value + */ + public LessThanOrEqual(String attributeName, Object value) { + super(attributeName, value); + this.comparableValue = (Comparable) value; + } + + /** + * {@inheritDoc} + */ + @Override + protected boolean executeComparable(Comparable attributeValue) { + return attributeValue.compareTo(comparableValue) <= 0; + } + + /** + * {@inheritDoc} + */ + @Override + protected boolean executeComparableString(Comparable attributeValue) { + return luceneStringCompare(attributeValue.toString(), comparableValue.toString()) <= 0; + } + + /** + * Comparable value. + * + * @return value + */ + public Comparable getComparableValue() { + return comparableValue; + } + +} Index: rctags/ehcache-2.10.9.0.363/distribution/colorcache/src/assemble/jetty6.1/9082/conf.xml =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/distribution/colorcache/src/assemble/jetty6.1/9082/conf.xml (revision 0) +++ rctags/ehcache-2.10.9.0.363/distribution/colorcache/src/assemble/jetty6.1/9082/conf.xml (revision 11330) @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + /webapps + false + true + false + + + + + + + + ./logs/console.yyyy_mm_dd.log + false + 90 + GMT + + + + + + Redirecting stderr/stdout to + + + + Index: rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/RealObjectKeySet.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/RealObjectKeySet.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/RealObjectKeySet.java (revision 11330) @@ -0,0 +1,87 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ + +package org.terracotta.modules.ehcache.store; + +import java.io.IOException; +import java.util.AbstractSet; +import java.util.Collection; +import java.util.Iterator; +import java.util.NoSuchElementException; + +/** + * @author cdennis + */ +class RealObjectKeySet extends AbstractSet { + + private final ValueModeHandler mode; + private final Collection keys; + + public RealObjectKeySet(ValueModeHandler mode, Collection keys) { + this.mode = mode; + this.keys = keys; + } + + @Override + public int size() { + return keys.size(); + } + + @Override + public boolean contains(Object o) { + try { + return keys.contains(mode.createPortableKey(o)); + } catch (IOException e) { + return false; + } + } + + @Override + public Iterator iterator() { + return new KeyIterator(mode, keys.iterator()); + } + + static class KeyIterator implements Iterator { + + private static final Object NO_OBJECT = new Object(); + + private final Iterator keysIterator; + private final ValueModeHandler mode; + private Object next; + + private KeyIterator(ValueModeHandler mode, Iterator iterator) { + this.mode = mode; + this.keysIterator = iterator; + advance(); + } + + private void advance() { + if (keysIterator.hasNext()) { + final Object real; + real = mode.getRealKeyObject((String) keysIterator.next()); + next = real; + } else { + next = NO_OBJECT; + } + } + + @Override + public boolean hasNext() { + return next != NO_OBJECT; + } + + @Override + public Object next() { + Object rv = next; + if (rv == NO_OBJECT) { throw new NoSuchElementException(); } + advance(); + return rv; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + } +} Index: rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/TerracottaStoreInitializationService.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/TerracottaStoreInitializationService.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/main/java/org/terracotta/modules/ehcache/store/TerracottaStoreInitializationService.java (revision 11330) @@ -0,0 +1,101 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.store; + +import net.sf.ehcache.config.NonstopConfiguration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.terracotta.toolkit.cluster.ClusterInfo; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicInteger; + +public class TerracottaStoreInitializationService { + private static final Logger LOGGER = LoggerFactory.getLogger(TerracottaStoreInitializationService.class); + private final ExecutorService threadPool; + private final ClusterInfo clusterInfo; + + + public TerracottaStoreInitializationService(ClusterInfo clusterInfo) { + this.clusterInfo = clusterInfo; + this.threadPool = getThreadPool(); + } + + /** + * This method should be called when the associated CacheManager is shutdown. Once shutdowm, the initialization + * service cannot be started again. + */ + public void shutdown() { + threadPool.shutdownNow(); + } + + public void initialize(Runnable runnable, NonstopConfiguration nonStopConfiguration) { + + // Submit the Thread for execution + Future future = threadPool.submit(runnable); + + // wait for initialization to complete (until operations are enabled) + waitForInitialization(future, nonStopConfiguration.getTimeoutMillis()); + } + + /** + * This method holds the calling thread until the given Future returns the result or the Cluster operations get/are + * disabled. In case the Cluster operations get disabled while waiting, the method call returns honoring the nonstop + * timeout. + * + */ + private void waitForInitialization(Future future, long nonStopTimeOutInMillis) { + boolean interrupted = false; + boolean initializationCompleted = false; + try { + do { + try { + future.get(nonStopTimeOutInMillis, TimeUnit.MILLISECONDS); + initializationCompleted = true; + } catch (InterruptedException e) { + interrupted = true; + } catch (ExecutionException e) { + throw new RuntimeException(e.getCause()); + } catch (TimeoutException e) { + // Retry if operations are enabled + } + } while (!initializationCompleted && areOperationsEnabled()); + + } finally { + if (interrupted) Thread.currentThread().interrupt(); + } + + if (!initializationCompleted) { + LOGGER.debug("Returning without completing TerracottaStore initialization. Operations Enabled = {}", + areOperationsEnabled()); + } + } + + private boolean areOperationsEnabled() { + return clusterInfo.areOperationsEnabled(); + } + + private ExecutorService getThreadPool() { + ThreadFactory daemonThreadFactory = new ThreadFactory() { + private final AtomicInteger threadID = new AtomicInteger(); + + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "TerracottaStoreInitializationThread_" + threadID.incrementAndGet()); + thread.setDaemon(true); + return thread; + } + }; + + return Executors.newCachedThreadPool(daemonThreadFactory); + } + +} Index: rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-impl-v1/src/main/java/net/sf/ehcache/management/service/impl/CacheManagerEntityBuilder.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-impl-v1/src/main/java/net/sf/ehcache/management/service/impl/CacheManagerEntityBuilder.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-impl/management-ehcache-impl-v1/src/main/java/net/sf/ehcache/management/service/impl/CacheManagerEntityBuilder.java (revision 11330) @@ -0,0 +1,85 @@ +/* + * 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.CacheManagerEntity; +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.AgentEntity; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +/** + * @author brandony + */ +final class CacheManagerEntityBuilder extends ConstrainableEntityBuilderSupport { + private static final Logger LOG = LoggerFactory.getLogger(CacheManagerEntityBuilder.class); + + private static final String CM_NAME_ACCESSOR = AccessorPrefix.get + "Name"; + + private final List cmSamplers = new ArrayList(); + + static CacheManagerEntityBuilder createWith(CacheManagerSampler sampler) { + return new CacheManagerEntityBuilder(sampler); + } + + CacheManagerEntityBuilder(CacheManagerSampler sampler) { + addSampler(sampler); + } + + CacheManagerEntityBuilder add(CacheManagerSampler sampler) { + addSampler(sampler); + return this; + } + + CacheManagerEntityBuilder add(Set constraintAttributes) { + addConstraints(constraintAttributes); + return this; + } + + Collection build() { + Collection cmes = new ArrayList(cmSamplers.size()); + + for (CacheManagerSampler cms : cmSamplers) { + CacheManagerEntity cme = new CacheManagerEntity(); + cme.setName(cms.getName()); + cme.setAgentId(AgentEntity.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; + } + + 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.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/ConfigurationElement.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/ConfigurationElement.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/elements/ConfigurationElement.java (revision 11330) @@ -0,0 +1,197 @@ +/** + * 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 java.util.List; + +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.Configuration; +import net.sf.ehcache.config.DiskStoreConfiguration; +import net.sf.ehcache.config.FactoryConfiguration; +import net.sf.ehcache.config.ManagementRESTServiceConfiguration; +import net.sf.ehcache.config.SizeOfPolicyConfiguration; +import net.sf.ehcache.config.TerracottaClientConfiguration; +import net.sf.ehcache.config.generator.model.SimpleNodeAttribute; +import net.sf.ehcache.config.generator.model.SimpleNodeElement; + +/** + * Element representing the {@link Configuration}. This element does not have a parent and is always null. + * + * @author Abhishek Sanoujam + * + */ +public class ConfigurationElement extends SimpleNodeElement { + + private final CacheManager cacheManager; + private final Configuration configuration; + + /** + * Constructor accepting the {@link Configuration}. This element does not have a parent and is always null. + * + * @param configuration + */ + public ConfigurationElement(Configuration configuration) { + super(null, "ehcache"); + this.cacheManager = null; + this.configuration = configuration; + init(); + } + + /** + * Constructor accepting the {@link CacheManager}. This element does not have a parent and is always null. + * + * @param cacheManager + */ + public ConfigurationElement(CacheManager cacheManager) { + super(null, "ehcache"); + this.cacheManager = cacheManager; + this.configuration = cacheManager.getConfiguration(); + init(); + } + + private void init() { + if (configuration == null) { + return; + } + // add the attributes + addAttribute(new SimpleNodeAttribute("name", configuration.getName()).optional(true)); + addAttribute(new SimpleNodeAttribute("monitoring", configuration.getMonitoring()).optional(true).defaultValue( + Configuration.DEFAULT_MONITORING.name().toLowerCase())); + addAttribute(new SimpleNodeAttribute("dynamicConfig", configuration.getDynamicConfig()).optional(true).defaultValue( + String.valueOf(Configuration.DEFAULT_DYNAMIC_CONFIG))); + addAttribute(new SimpleNodeAttribute("defaultTransactionTimeoutInSeconds", configuration.getDefaultTransactionTimeoutInSeconds()) + .optional(true).defaultValue(String.valueOf(Configuration.DEFAULT_TRANSACTION_TIMEOUT))); + testAddMaxBytesLocalHeapAttribute(); + testAddMaxBytesLocalOffHeapAttribute(); + testAddMaxBytesLocalDiskAttribute(); + + // add the child elements + testAddDiskStoreElement(); + testAddSizeOfPolicyElement(); + testAddTransactionManagerLookupElement(); + testAddManagementRESTService(); + testAddCacheManagerEventListenerFactoryElement(); + testAddCacheManagerPeerProviderFactoryElement(); + testAddCacheManagerPeerListenerFactoryElement(); + + addChildElement(new DefaultCacheConfigurationElement(this, configuration, configuration.getDefaultCacheConfiguration())); + + if (cacheManager != null) { + for (String cacheName : cacheManager.getCacheNames()) { + boolean decoratedCache = false; + Ehcache cache = cacheManager.getCache(cacheName); + if (cache == null) { + cache = cacheManager.getEhcache(cacheName); + decoratedCache = true; + } + CacheConfiguration config = decoratedCache ? cache.getCacheConfiguration().clone().name(cacheName) : cache.getCacheConfiguration(); + addChildElement(new CacheConfigurationElement(this, configuration, config)); + } + } else { + for (CacheConfiguration cacheConfiguration : configuration.getCacheConfigurations().values()) { + addChildElement(new CacheConfigurationElement(this, configuration, cacheConfiguration)); + } + } + + testAddTerracottaElement(); + } + + private void testAddMaxBytesLocalHeapAttribute() { + if (configuration.getMaxBytesLocalHeap() > 0) { + addAttribute(new SimpleNodeAttribute("maxBytesLocalHeap", configuration.getMaxBytesLocalHeapAsString()) + .optional(true).defaultValue(String.valueOf(Configuration.DEFAULT_MAX_BYTES_ON_HEAP))); + } + } + + private void testAddMaxBytesLocalOffHeapAttribute() { + if (configuration.getMaxBytesLocalOffHeap() > 0) { + addAttribute(new SimpleNodeAttribute("maxBytesLocalOffHeap", configuration.getMaxBytesLocalOffHeapAsString()) + .optional(true).defaultValue(String.valueOf(Configuration.DEFAULT_MAX_BYTES_OFF_HEAP))); + } + } + + private void testAddMaxBytesLocalDiskAttribute() { + if (configuration.getMaxBytesLocalDisk() > 0) { + addAttribute(new SimpleNodeAttribute("maxBytesLocalDisk", configuration.getMaxBytesLocalDiskAsString()) + .optional(true).defaultValue(String.valueOf(Configuration.DEFAULT_MAX_BYTES_ON_DISK))); + } + } + + private void testAddDiskStoreElement() { + DiskStoreConfiguration diskStoreConfiguration = configuration.getDiskStoreConfiguration(); + if (diskStoreConfiguration != null) { + addChildElement(new DiskStoreConfigurationElement(this, diskStoreConfiguration)); + } + } + + private void testAddSizeOfPolicyElement() { + SizeOfPolicyConfiguration sizeOfPolicyConfiguration = configuration.getSizeOfPolicyConfiguration(); + if (sizeOfPolicyConfiguration != null && + !Configuration.DEFAULT_SIZEOF_POLICY_CONFIGURATION.equals(sizeOfPolicyConfiguration)) { + addChildElement(new SizeOfPolicyConfigurationElement(this, sizeOfPolicyConfiguration)); + } + } + + private void testAddTransactionManagerLookupElement() { + FactoryConfiguration transactionManagerLookupConfiguration = configuration.getTransactionManagerLookupConfiguration(); + if (transactionManagerLookupConfiguration != null + && !transactionManagerLookupConfiguration.equals(Configuration.DEFAULT_TRANSACTION_MANAGER_LOOKUP_CONFIG)) { + addChildElement(new FactoryConfigurationElement(this, "transactionManagerLookup", transactionManagerLookupConfiguration)); + } + } + + private void testAddManagementRESTService() { + ManagementRESTServiceConfiguration managementRESTServiceConfiguration = configuration.getManagementRESTService(); + if (managementRESTServiceConfiguration != null) { + addChildElement(new ManagementRESTServiceConfigurationElement(this, managementRESTServiceConfiguration)); + } + } + + private void testAddCacheManagerEventListenerFactoryElement() { + FactoryConfiguration cacheManagerEventListenerFactoryConfiguration = configuration + .getCacheManagerEventListenerFactoryConfiguration(); + if (cacheManagerEventListenerFactoryConfiguration != null) { + addChildElement(new FactoryConfigurationElement(this, "cacheManagerEventListenerFactory", + cacheManagerEventListenerFactoryConfiguration)); + } + } + + private void testAddCacheManagerPeerProviderFactoryElement() { + List cacheManagerPeerProviderFactoryConfiguration = configuration + .getCacheManagerPeerProviderFactoryConfiguration(); + if (cacheManagerPeerProviderFactoryConfiguration != null) { + addAllFactoryConfigsAsChildElements(this, "cacheManagerPeerProviderFactory", cacheManagerPeerProviderFactoryConfiguration); + } + } + + private void testAddCacheManagerPeerListenerFactoryElement() { + List cacheManagerPeerListenerFactoryConfigurations = configuration + .getCacheManagerPeerListenerFactoryConfigurations(); + if (cacheManagerPeerListenerFactoryConfigurations != null && !cacheManagerPeerListenerFactoryConfigurations.isEmpty()) { + addAllFactoryConfigsAsChildElements(this, "cacheManagerPeerListenerFactory", cacheManagerPeerListenerFactoryConfigurations); + } + } + + private void testAddTerracottaElement() { + TerracottaClientConfiguration terracottaConfiguration = configuration.getTerracottaConfiguration(); + if (terracottaConfiguration != null) { + addChildElement(new TerracottaConfigConfigurationElement(this, terracottaConfiguration)); + } + } +} Index: rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/ElementEntity.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/ElementEntity.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/management-ehcache-v1/src/main/java/net/sf/ehcache/management/resource/ElementEntity.java (revision 11330) @@ -0,0 +1,35 @@ +/* + * All content copyright (c) 2003-2012 Terracotta, Inc., except as may otherwise be noted in a separate copyright + * notice. All rights reserved. + */ + +package net.sf.ehcache.management.resource; + +import org.terracotta.management.resource.VersionedEntity; + +/** + * @author brandony + */ +public class ElementEntity extends VersionedEntity { + private String agentId; + + private String cacheName; + + @Override + public String getAgentId() { + return agentId; + } + + @Override + public void setAgentId(String agentId) { + this.agentId = agentId; + } + + public String getCacheName() { + return cacheName; + } + + public void setCacheName(String cacheName) { + this.cacheName = cacheName; + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/l1bm/L1BMCacheManagerRecreateTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/l1bm/L1BMCacheManagerRecreateTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/l1bm/L1BMCacheManagerRecreateTest.java (revision 11330) @@ -0,0 +1,55 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.l1bm; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.Element; + +import org.junit.Assert; +import org.terracotta.toolkit.Toolkit; +import org.terracotta.ehcache.tests.AbstractCacheTestBase; +import org.terracotta.ehcache.tests.ClientBase; + +import com.tc.test.config.model.TestConfig; + +public class L1BMCacheManagerRecreateTest extends AbstractCacheTestBase { + + public L1BMCacheManagerRecreateTest(TestConfig testConfig) { + super(testConfig, App.class); + } + + public static class App extends ClientBase { + private Cache cache; + + public App(String[] args) { + super(args); + } + + @Override + protected void runTest(Cache testcache, Toolkit clusteringToolkit) throws Throwable { + cache = testcache; + for (int i = 0; i < 100; i++) { + cache.put(new Element("key" + i, "value" + i)); + } + cleanup(); + + setup(); + for (int i = 0; i < 100; i++) { + Element e = cache.get("key" + i); + Assert.assertNotNull(e); + Assert.assertEquals("value" + i, e.getObjectValue()); + } + cleanup(); + } + + private void setup() { + setupCacheManager(); + cache = getCache(); + } + + private void cleanup() { + getCacheManager().shutdown(); + } + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/DoubleConfigStandaloneCacheTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/DoubleConfigStandaloneCacheTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/ehcache/tests/DoubleConfigStandaloneCacheTest.java (revision 11330) @@ -0,0 +1,45 @@ +/* + * All content copyright (c) 2003-2008 Terracotta, Inc., except as may otherwise be noted in a separate copyright + * notice. All rights reserved. + */ +package org.terracotta.ehcache.tests; + +import com.tc.test.config.model.TestConfig; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; + +/** + * @author cdennis + */ +public class DoubleConfigStandaloneCacheTest extends AbstractCacheTestBase { + + public DoubleConfigStandaloneCacheTest(TestConfig testConfig) { + super("double-config-cache-test.xml", testConfig); + } + + @Override + protected void evaluateClientOutput(String clientName, int exitCode, File output) throws Throwable { + if ((exitCode == 0)) { throw new AssertionError("Client " + clientName + " exited with exit code: " + exitCode); } + + FileReader fr = null; + try { + fr = new FileReader(output); + BufferedReader reader = new BufferedReader(fr); + String st = ""; + while ((st = reader.readLine()) != null) { + if (st.contains("InvalidConfigurationException")) return; + } + throw new AssertionError("Client " + clientName + " did not pass"); + } catch (Exception e) { + throw new AssertionError(e); + } finally { + try { + fr.close(); + } catch (Exception e) { + // + } + } + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/event/ClusteredEventsSerializationTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/event/ClusteredEventsSerializationTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/event/ClusteredEventsSerializationTest.java (revision 11330) @@ -0,0 +1,142 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.event; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.Element; +import net.sf.ehcache.event.CacheEventListener; + +import org.terracotta.ehcache.tests.AbstractCacheTestBase; +import org.terracotta.ehcache.tests.ClientBase; +import org.terracotta.toolkit.Toolkit; +import org.terracotta.toolkit.concurrent.ToolkitBarrier; + +import com.tc.test.config.model.TestConfig; + +import java.io.Serializable; +import java.util.Set; + +import junit.framework.Assert; + +public class ClusteredEventsSerializationTest extends AbstractCacheTestBase { + + private static final int NODE_COUNT = 5; + + public ClusteredEventsSerializationTest(TestConfig testConfig) { + super("clustered-events-test.xml", testConfig, App.class, App.class, App.class, App.class, App.class); + testConfig.getClientConfig().addExtraClientJvmArg("-Dcom.tc.ehcache.clusteredStore.checkContainsKeyOnPut=true"); + } + + public static class App extends ClientBase { + private final ToolkitBarrier barrier; + + public App(String[] args) { + super("testSerialization", args); + this.barrier = getClusteringToolkit().getBarrier("test-barrier", NODE_COUNT); + } + + @Override + protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { + final int index = barrier.await(); + + Assert.assertEquals(0, cache.getSize()); + + barrier.await(); + + NonPortable key = new NonPortable("key" + index); + NonPortable valuePut = new NonPortable("value" + index); + NonPortable valueUpdate = new NonPortable("valueUpdated" + index); + cache.put(new Element(key, valuePut)); + cache.put(new Element(key, valueUpdate)); + cache.remove(key); + + barrier.await(); + + cache.removeAll(); + + barrier.await(); + + Thread.sleep(10000); + + EhcacheTerracottaEventListener listener = null; + Set listeners = cache.getCacheEventNotificationService().getCacheEventListeners(); + for (CacheEventListener l : listeners) { + if (l instanceof EhcacheTerracottaEventListener) { + listener = (EhcacheTerracottaEventListener) l; + break; + } + } + + Assert.assertNotNull(listener); + + Assert.assertEquals(NODE_COUNT, listener.getPut().size()); + Assert.assertEquals(NODE_COUNT, listener.getUpdate().size()); + Assert.assertEquals(NODE_COUNT, listener.getRemove().size()); + Assert.assertEquals(NODE_COUNT, listener.getRemoveAll()); + + boolean foundPutKey = false; + for (Element element : listener.getPut()) { + if (element.getObjectKey().equals(key)) { + foundPutKey = true; + Assert.assertEquals(valuePut, element.getObjectValue()); + } else { + Assert.assertEquals("value" + element.getObjectKey().toString().substring("key".length()), element + .getObjectValue().toString()); + } + } + Assert.assertTrue(foundPutKey); + + boolean foundUpdateKey = false; + for (Element element : listener.getUpdate()) { + if (element.getObjectKey().equals(key)) { + foundUpdateKey = true; + Assert.assertEquals(valueUpdate, element.getObjectValue()); + } else { + Assert.assertEquals("valueUpdated" + element.getObjectKey().toString().substring("key".length()), element + .getObjectValue().toString()); + } + } + Assert.assertTrue(foundUpdateKey); + + boolean foundRemoveKey = false; + for (Element element : listener.getRemove()) { + if (element.getObjectKey().equals(key)) { + foundRemoveKey = true; + } + } + Assert.assertTrue(foundRemoveKey); + } + + } + + public static class NonPortable implements Serializable { + private final String value; + + public NonPortable(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + NonPortable that = (NonPortable) o; + + if (value != null ? !value.equals(that.value) : that.value != null) return false; + + return true; + } + + @Override + public int hashCode() { + return value != null ? value.hashCode() : 0; + } + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EhcacheHibernateMbeanNames.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EhcacheHibernateMbeanNames.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/hibernate/management/impl/EhcacheHibernateMbeanNames.java (revision 11330) @@ -0,0 +1,77 @@ +/** + * 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 javax.management.MalformedObjectNameException; +import javax.management.ObjectName; + +/** + * Utility class used for getting {@link ObjectName}'s for ehcache hibernate MBeans + * + *

+ * + * @author Abhishek Sanoujam + * @since 1.7 + * + */ +public abstract class EhcacheHibernateMbeanNames { + + /** + * Group id for all sampled mbeans registered + */ + public static final String GROUP_ID = "net.sf.ehcache.hibernate"; + + /** + * Type for the ehcache backed hibernate second level cache statistics mbean + */ + public static final String EHCACHE_HIBERNATE_TYPE = "EhcacheHibernateStats"; + + /** + * Filter out invalid ObjectName characters from s. + * + * @param s + * @return A valid JMX ObjectName attribute value. + */ + public static String mbeanSafe(String s) { + return s == null ? "" : s.replaceAll(",|:|=|\n", "."); + } + + /** + * Returns an ObjectName for the passed name + * + * @param name + * @return An {@link ObjectName} using the input name of cache manager + * @throws MalformedObjectNameException + */ + public static ObjectName getCacheManagerObjectName(String cacheManagerClusterUUID, String name) throws MalformedObjectNameException { + ObjectName objectName = new ObjectName(GROUP_ID + ":type=" + EHCACHE_HIBERNATE_TYPE + ",name=" + mbeanSafe(name) + + getBeanNameSuffix(cacheManagerClusterUUID)); + return objectName; + } + + private static String getBeanNameSuffix(String cacheManagerClusterUUID) { + String suffix = ""; + if (!isBlank(cacheManagerClusterUUID)) { + suffix = ",node=" + cacheManagerClusterUUID; + } + return suffix; + } + + private static boolean isBlank(String param) { + return param == null || "".equals(param.trim()); + } +} Index: rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/ClusteredStoreTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/ClusteredStoreTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/terracotta/bootstrap/src/test/java/org/terracotta/modules/ehcache/store/ClusteredStoreTest.java (revision 11330) @@ -0,0 +1,173 @@ +/** + * Copyright Terracotta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions and limitations under the + * License. + */ +package org.terracotta.modules.ehcache.store; + +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.CacheStoreHelper; +import net.sf.ehcache.Ehcache; +import net.sf.ehcache.Element; +import net.sf.ehcache.NonEternalElementData; +import net.sf.ehcache.Status; +import net.sf.ehcache.cluster.CacheCluster; +import net.sf.ehcache.cluster.ClusterNode; +import net.sf.ehcache.cluster.ClusterTopologyListener; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.Configuration; +import net.sf.ehcache.config.TerracottaClientConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration; +import net.sf.ehcache.event.CacheEventListener; +import net.sf.ehcache.event.CacheEventListenerAdapter; +import net.sf.ehcache.event.RegisteredEventListeners; +import net.sf.ehcache.store.DefaultElementValueComparator; + +import org.junit.Before; +import org.junit.Test; +import org.terracotta.modules.ehcache.ToolkitInstanceFactory; +import org.terracotta.toolkit.cache.ToolkitCacheListener; +import org.terracotta.toolkit.collections.ToolkitMap; +import org.terracotta.toolkit.concurrent.locks.ToolkitLock; +import org.terracotta.toolkit.events.ToolkitNotifier; +import org.terracotta.toolkit.internal.ToolkitInternal; +import org.terracotta.toolkit.internal.ToolkitProperties; +import org.terracotta.toolkit.internal.cache.ToolkitCacheInternal; +import org.terracotta.toolkit.internal.cache.ToolkitValueComparator; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Test that asserts quickSize is not called when {@link Ehcache} sizing methods are called. + * + * @author Ludovic Orban + */ +public class ClusteredStoreTest { + + private Ehcache cache = mock(Ehcache.class); + private CacheConfiguration cacheConfiguration = new CacheConfiguration().terracotta(new TerracottaConfiguration().clustered(true).consistency(TerracottaConfiguration.Consistency.EVENTUAL)); + private Configuration configuration = new Configuration().name("ClusteredStoreTest-cm").terracotta(new TerracottaClientConfiguration()); + private ToolkitCacheInternal toolkitCacheInternal = mock(ToolkitCacheInternal.class); + private ClusteredStore clusteredStore; + private ToolkitInstanceFactory toolkitInstanceFactory = mock(ToolkitInstanceFactory.class); + private CacheCluster cacheCluster = mockCacheCluster("abc"); + private CacheManager cacheManager = when(mock(CacheManager.class).getConfiguration()).thenReturn(configuration).getMock(); + private ToolkitMap configMap = mock(ToolkitMap.class); + private ToolkitInternal toolkitInternal = mock(ToolkitInternal.class); + private ToolkitProperties toolkitProperties = mock(ToolkitProperties.class); + private org.terracotta.toolkit.config.Configuration toolkitCacheConfiguration = mock(org.terracotta.toolkit.config.Configuration.class); + private ToolkitNotifier toolkitNotifier = mock(ToolkitNotifier.class); + private CacheStoreHelper cacheStoreHelper = mock(CacheStoreHelper.class); + private ToolkitLock toolkitLock = mock(ToolkitLock.class); + + @Before + public void setUpClusteredStore() { + when(cache.getCacheConfiguration()).thenReturn(cacheConfiguration); + when(cache.getCacheManager()).thenReturn(cacheManager); + when(cache.getName()).thenReturn("ClusteredStoreTest-cache"); + when(cache.getStatus()).thenReturn(Status.STATUS_ALIVE); + when(cache.getCacheEventNotificationService()).thenReturn(new RegisteredEventListeners(cache, cacheStoreHelper)); + when(cacheManager.getName()).thenReturn("ClusteredStoreTest-cm"); + when(toolkitInstanceFactory.getOrCreateClusteredStoreConfigMap(eq("ClusteredStoreTest-cm"), eq("ClusteredStoreTest-cache"))).thenReturn(configMap); + when(toolkitInstanceFactory.getToolkit()).thenReturn(toolkitInternal); + when(toolkitInstanceFactory.getLockForCache(any(Ehcache.class), anyString())).thenReturn(toolkitLock); + when(toolkitInternal.getProperties()).thenReturn(toolkitProperties); + when(toolkitProperties.getBoolean(anyString())).thenReturn(false); + when(toolkitInstanceFactory.getOrCreateToolkitCache(cache)).thenReturn(toolkitCacheInternal); + when(toolkitCacheInternal.getConfiguration()).thenReturn(toolkitCacheConfiguration); + when(toolkitCacheConfiguration.getInt(anyString())).thenReturn(1); + when(toolkitInstanceFactory.getOrCreateConfigChangeNotifier(eq(cache))).thenReturn(toolkitNotifier); + clusteredStore = new ClusteredStore(toolkitInstanceFactory, cache, cacheCluster) { + @Override + void setUpWanConfig() { + // Do Nothing + } + }; + when(cacheStoreHelper.getStore()).thenReturn(clusteredStore); + } + + private static CacheCluster mockCacheCluster(String thisNode) { + CacheCluster cacheCluster = mock(CacheCluster.class); + ClusterNode node = when(mock(ClusterNode.class).getId()).thenReturn(thisNode).getMock(); + when(cacheCluster.getCurrentNode()).thenReturn(node); + return cacheCluster; + } + + @Test + public void clusteredStore_getSize_calls_size_not_quickSize() throws Exception { + clusteredStore.getSize(); + verify(toolkitCacheInternal, times(1)).size(); + verify(toolkitCacheInternal, times(0)).quickSize(); + } + + @Test + public void clusteredStore_getTerracottaClusteredSize_calls_size_not_quickSize() throws Exception { + clusteredStore.getTerracottaClusteredSize(); + verify(toolkitCacheInternal, times(1)).size(); + verify(toolkitCacheInternal, times(0)).quickSize(); + } + + @Test + public void clusteredStore_putIfAbsent_enabled_in_eventual_consistency() { + clusteredStore.putIfAbsent(new Element("key", "value")); + verify(toolkitCacheInternal).putIfAbsent(eq("key"), any(NonEternalElementData.class)); + } + + @Test + public void clusteredStore_replace_1_arg_enabled_in_eventual_consistency() { + clusteredStore.replace(new Element("key", "value")); + verify(toolkitCacheInternal).replace(any(), any()); + } + + @Test + public void clusteredStore_replace_2_args_enabled_in_eventual_consistency() { + clusteredStore.replace(new Element("key", "value"), new Element("key", "other"), new DefaultElementValueComparator(cacheConfiguration)); + verify(toolkitCacheInternal).replace(any(), any(), any(), any(ToolkitValueComparator.class)); + } + + @Test + public void clusteredStore_removeElement_enabled_in_eventual_consistency() { + clusteredStore.removeElement(new Element("key", "value"), new DefaultElementValueComparator(cacheConfiguration)); + verify(toolkitCacheInternal).remove(any(), any(), any(ToolkitValueComparator.class)); + } + + @Test + public void testDispose() throws Exception { + clusteredStore.dispose(); + verify(toolkitCacheInternal).disposeLocally(); + verify(cacheCluster).removeTopologyListener(any(ClusterTopologyListener.class)); + verify(toolkitCacheInternal).removeListener(any(ToolkitCacheListener.class)); + } + + @Test + public void testRegisterToolkitCacheEventListener() throws Exception { + verify(toolkitCacheInternal, never()).addListener(any(ToolkitCacheListener.class)); + cache.getCacheEventNotificationService().registerListener(new CacheEventListenerAdapter()); + cache.getCacheEventNotificationService().registerListener(new CacheEventListenerAdapter()); + verify(toolkitCacheInternal, times(1)).addListener(any(ToolkitCacheListener.class)); + } + + @Test + public void testUnregisterToolkitCacheEventListener() throws Exception { + String thisNodeId = cacheCluster.getCurrentNode().getId(); + when(configMap.get(ClusteredStore.LEADER_NODE_ID)).thenReturn(thisNodeId); // make this node the leader + verify(toolkitCacheInternal, never()).addListener(any(ToolkitCacheListener.class)); + CacheEventListener listener = new CacheEventListenerAdapter(); + cache.getCacheEventNotificationService().registerListener(listener); + cache.getCacheEventNotificationService().registerListener(listener); + cache.getCacheEventNotificationService().unregisterListener(listener); + cache.getCacheEventNotificationService().unregisterListener(listener); + verify(toolkitCacheInternal, times(1)).removeListener(any(ToolkitCacheListener.class)); + verify(configMap).remove(ClusteredStore.LEADER_NODE_ID); // make sure we drop leader status + } +} Index: rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/store/StorageStrategyNotSupportedTest.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/store/StorageStrategyNotSupportedTest.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/src/test/java/org/terracotta/modules/ehcache/store/StorageStrategyNotSupportedTest.java (revision 11330) @@ -0,0 +1,69 @@ +/* + * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. + */ +package org.terracotta.modules.ehcache.store; + +import net.sf.ehcache.Cache; +import net.sf.ehcache.CacheException; +import net.sf.ehcache.CacheManager; +import net.sf.ehcache.config.CacheConfiguration; +import net.sf.ehcache.config.TerracottaConfiguration; + +import org.terracotta.ehcache.tests.AbstractCacheTestBase; +import org.terracotta.ehcache.tests.ClientBase; +import org.terracotta.toolkit.Toolkit; + +import com.tc.test.config.model.TestConfig; + +import junit.framework.Assert; + +public class StorageStrategyNotSupportedTest extends AbstractCacheTestBase { + + public StorageStrategyNotSupportedTest(TestConfig testConfig) { + super("ehcache-not-supported.xml", testConfig, App.class); + } + + public static class App extends ClientBase { + + public App(String[] args) { + super(args); + } + + public static void main(String[] args) { + new App(args).run(); + } + + @Override + protected void runTest(Cache cache, Toolkit clusteringToolkit) throws Throwable { + + CacheManager cm = getCacheManager(); + + try { + Assert.assertEquals(1, cm.getCacheNames().length); + Assert.assertTrue(cm.getCacheNames()[0].equals("test")); + } catch (CacheException e) { + fail("Using storageStrategy=dcv2 should work even without ee"); + } + + // test programmatic way + cm.shutdown(); + setupCacheManager(); + cm = getCacheManager(); + CacheConfiguration cacheConfiguration = new CacheConfiguration("testCache", 100); + TerracottaConfiguration tc = new TerracottaConfiguration().clustered(true); + cacheConfiguration.addTerracotta(tc); + cache = new Cache(cacheConfiguration); + + cm.removeCache("test"); + + try { + cm.addCache(cache); + Assert.assertEquals(1, cm.getCacheNames().length); + Assert.assertTrue(cm.getCacheNames()[0].equals("testCache")); + } catch (CacheException e) { + e.printStackTrace(); + fail("Using storageStrategy=dcv2 should work even without ee"); + } + } + } +} Index: rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/SimpleNodeAttribute.java =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/SimpleNodeAttribute.java (revision 0) +++ rctags/ehcache-2.10.9.0.363/ehcache-core/src/main/java/net/sf/ehcache/config/generator/model/SimpleNodeAttribute.java (revision 11330) @@ -0,0 +1,256 @@ +/** + * Copyright Terracotta, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package net.sf.ehcache.config.generator.model; + +/** + * Implementation of the {@link NodeAttribute} interface + * + * @author Abhishek Sanoujam + * + */ +public class SimpleNodeAttribute implements NodeAttribute { + + private final String name; + private String value; + private String defaultValue; + private boolean optional = true; + + /** + * Constructor accepting the name of the attribute + * + * @param name + * the name of the attribute + */ + public SimpleNodeAttribute(String name) { + this(name, (String) null); + } + + /** + * Constructor accepting name and Enum value of the attribute + * + * @param name + * the name of the attribute + * @param value + * the Enum value of the attribute + */ + public SimpleNodeAttribute(String name, Enum value) { + this(name, value.name().toLowerCase()); + } + + /** + * Constructor accepting name and int value of the attribute + * + * @param name + * the name of the attribute + * @param value + * the int value of the attribute + */ + public SimpleNodeAttribute(String name, int value) { + this(name, String.valueOf(value)); + } + + /** + * Constructor accepting name and long value of the attribute + * + * @param name + * the name of the attribute + * @param value + * the long value of the attribute + */ + public SimpleNodeAttribute(String name, long value) { + this(name, String.valueOf(value)); + } + + /** + * Constructor accepting name and boolean value of the attribute + * + * @param name + * the name of the attribute + * @param value + * the boolean value of the attribute + */ + public SimpleNodeAttribute(String name, boolean value) { + this(name, String.valueOf(value)); + } + + /** + * Constructor accepting name and String value of the attribute + * + * @param name + * the name of the attribute + * @param value + * the String value of the attribute + */ + public SimpleNodeAttribute(String name, String value) { + this.name = name; + this.value = value; + } + + /** + * {@inheritDoc} + */ + public String getName() { + return name; + } + + /** + * {@inheritDoc} + */ + public String getValue() { + return value; + } + + /** + * {@inheritDoc} + */ + public boolean isOptional() { + return optional; + } + + /** + * {@inheritDoc} + */ + public void setOptional(boolean optional) { + this.optional = optional; + } + + /** + * {@inheritDoc} + */ + public String getDefaultValue() { + return defaultValue; + } + + /** + * {@inheritDoc} + */ + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + /** + * {@inheritDoc} + */ + public void setValue(String value) { + this.value = value; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof NodeAttribute)) { + return false; + } + NodeAttribute other = (NodeAttribute) obj; + if (name == null) { + if (other.getName() != null) { + return false; + } + } else if (!name.equals(other.getName())) { + return false; + } + return true; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "SimpleAttribute [name=" + name + "]"; + } + + /** + * {@inheritDoc} + */ + public SimpleNodeAttribute optional(boolean optional) { + this.optional = optional; + return this; + } + + /** + * {@inheritDoc} + */ + public SimpleNodeAttribute defaultValue(String defaultValue) { + this.defaultValue = defaultValue; + return this; + } + + /** + * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue) + * + * @param defaultValue + * the default value + * @return the same instance + */ + public SimpleNodeAttribute defaultValue(boolean defaultValue) { + return this.defaultValue(String.valueOf(defaultValue)); + } + + /** + * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue) + * + * @param defaultValue + * the default value + * @return the same instance + */ + public SimpleNodeAttribute defaultValue(int defaultValue) { + return this.defaultValue(String.valueOf(defaultValue)); + } + + /** + * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue) + * + * @param defaultValue + * the default value + * @return the same instance + */ + public SimpleNodeAttribute defaultValue(Enum defaultValue) { + return this.defaultValue(defaultValue.name().toLowerCase()); + } + + /** + * Same as {@link #defaultValue(String)} using String.valueOf(defaultValue) + * + * @param defaultValue + * the default value + * @return the same instance + */ + public SimpleNodeAttribute defaultValue(long defaultValue) { + return this.defaultValue(String.valueOf(defaultValue)); + } + +} Index: rctags/ehcache-2.10.9.0.363/system-tests/.settings/org.eclipse.jdt.ui.prefs =================================================================== diff -u -N --- rctags/ehcache-2.10.9.0.363/system-tests/.settings/org.eclipse.jdt.ui.prefs (revision 0) +++ rctags/ehcache-2.10.9.0.363/system-tests/.settings/org.eclipse.jdt.ui.prefs (revision 11330) @@ -0,0 +1,72 @@ +eclipse.preferences.version=1 +editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=false +formatter_profile=_Terracotta profile +formatter_settings_version=11 +org.eclipse.jdt.ui.exception.name=e +org.eclipse.jdt.ui.gettersetter.use.is=true +org.eclipse.jdt.ui.ignorelowercasenames=true +org.eclipse.jdt.ui.importorder=org;com;java;javax; +org.eclipse.jdt.ui.javadoc=false +org.eclipse.jdt.ui.keywordthis=false +org.eclipse.jdt.ui.ondemandthreshold=99 +org.eclipse.jdt.ui.overrideannotation=true +org.eclipse.jdt.ui.staticondemandthreshold=99 +org.eclipse.jdt.ui.text.custom_code_templates=