Repository: jsr107/jsr107spec Branch: master Commit: 763de4830fbc Files: 74 Total size: 322.4 KB Directory structure: gitextract_8lerwxfn/ ├── .gitignore ├── LICENSE.txt ├── README.md ├── bnd.bnd ├── checkstyle/ │ ├── ClassHeader.txt │ ├── checkstyle.xml │ └── suppressions.xml ├── findbugs/ │ └── findbugs-exclude.xml ├── pom.xml └── src/ └── main/ └── java/ └── javax/ └── cache/ ├── Cache.java ├── CacheException.java ├── CacheManager.java ├── Caching.java ├── annotation/ │ ├── CacheDefaults.java │ ├── CacheInvocationContext.java │ ├── CacheInvocationParameter.java │ ├── CacheKey.java │ ├── CacheKeyGenerator.java │ ├── CacheKeyInvocationContext.java │ ├── CacheMethodDetails.java │ ├── CachePut.java │ ├── CacheRemove.java │ ├── CacheRemoveAll.java │ ├── CacheResolver.java │ ├── CacheResolverFactory.java │ ├── CacheResult.java │ ├── CacheValue.java │ ├── GeneratedCacheKey.java │ └── package-info.java ├── configuration/ │ ├── CacheEntryListenerConfiguration.java │ ├── CompleteConfiguration.java │ ├── Configuration.java │ ├── Factory.java │ ├── FactoryBuilder.java │ ├── MutableCacheEntryListenerConfiguration.java │ ├── MutableConfiguration.java │ ├── OptionalFeature.java │ └── package-info.java ├── event/ │ ├── CacheEntryCreatedListener.java │ ├── CacheEntryEvent.java │ ├── CacheEntryEventFilter.java │ ├── CacheEntryExpiredListener.java │ ├── CacheEntryListener.java │ ├── CacheEntryListenerException.java │ ├── CacheEntryRemovedListener.java │ ├── CacheEntryUpdatedListener.java │ ├── EventType.java │ └── package-info.java ├── expiry/ │ ├── AccessedExpiryPolicy.java │ ├── CreatedExpiryPolicy.java │ ├── Duration.java │ ├── EternalExpiryPolicy.java │ ├── ExpiryPolicy.java │ ├── ModifiedExpiryPolicy.java │ ├── TouchedExpiryPolicy.java │ └── package-info.java ├── integration/ │ ├── CacheLoader.java │ ├── CacheLoaderException.java │ ├── CacheWriter.java │ ├── CacheWriterException.java │ ├── CompletionListener.java │ ├── CompletionListenerFuture.java │ └── package-info.java ├── management/ │ ├── CacheMXBean.java │ ├── CacheStatisticsMXBean.java │ └── package-info.java ├── package-info.java ├── processor/ │ ├── EntryProcessor.java │ ├── EntryProcessorException.java │ ├── EntryProcessorResult.java │ ├── MutableEntry.java │ └── package-info.java └── spi/ ├── CachingProvider.java └── package-info.java ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.iml *.ipr *.iws .idea target /.settings /.project /.classpath /.checkstyle ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. ================================================ FILE: README.md ================================================ JSR107 (JCache) =============== About ----- *JCache* is the Java caching API. It was defined by JSR107. It defines a standard Java Caching API for use by developers and a standard SPI ("Service Provider Interface") for use by implementers. ## Releases * 10 May 2019: 1.1.1 Maintenance Release. * 16 December 2017: 1.1.0 Maintenance Release. * 18 March 2014: 1.0.0. Final Release. Unchanged from 1.0.0-RC1. * 16 December 2013: 1.0.0-RC1. This is the version matching the final specification and is what is up on https://jcp.org/aboutJava/communityprocess/final/jsr107/index.html. * 21 October 2013: 1.0.0-PFD for the cache-api and 0.11 for other artifacts.Proposed Final Draft * 26 August 2013: 0.10 Third Public Review Draft * 25 June 2013: 0.9 Second Public Review Draft * 25 June 2013: 0.8 Public Review Draft * 17 April 2013 0.7 * 12 February 2013 0.6 * 13 March 2012: 0.5 Early Draft Submission uses this release. * December 2011: 0.4 * 12 October 2011: 0.3 * 16 August 2011: 0.2 Initial release Maven snippet: javax.cache cache-api 1.0.0 Maven Central Releases ---------------------- Releases of jars for binaries, source and javadoc are available on Maven central. Download the cache-api from or use the following Maven snippet: javax.cache cache-api 1.1.1 Javadoc ------- The JavaDoc is available as a jar with the releases. You can also find the JavaDoc [online](http://www.javadoc.io/doc/javax.cache/cache-api/1.1.1). Specification ------------- The specification is available online as a [Google Doc](https://docs.google.com/document/d/1ijduF_tmHvBaUS7VBBU2ZN8_eEBiFaXXg9OI0_ZxCrA/edit?usp=sharing). Reference Implementation ------------------------ The reference implementation ("RI") source is available on [GitHub](https://github.com/jsr107/RI). This implementation is not meant for production use. For that we would refer you to one of the many high quality open source and commercial implementations of JCache. See the [official list of compatible implementions](https://jcp.org/aboutJava/communityprocess/implementations/jsr107/index.html), and also the community maintained [JSR107 Test Zoo](https://github.com/cruftex/jsr107-test-zoo/blob/master/report.md). The RI is there to ensure that the specification and API works as its only purpose. For example, some things that we leave out: - tiered storage. A simple on-heap store is used. - replicated or distributed caching Why did we do this? Because a much greater engineering effort, which gets put into the open source and commercial caches which implement this API, is required to accomplish these things. Having said that, the RI is Apache 2 and is a correct implementation of the spec. It can be used to create new cache implementations. Building From Source -------------------- Building uses Maven in all modules. Maven 3.3.9 - 3.5.4 have been tested. JCache is compatible with Java 6 to Java 11. We have tested building from Java 8 and Java 11. See each module's README.md for build instructions. Please add the following to your settings.xml to enable the CDI RI to be sucked down from JBoss. jboss-public-repository jboss-public-repository-group JBoss Public Maven Repository Group https://repository.jboss.org/nexus/content/groups/public-jboss/ default true never true never jboss-public-repository-group JBoss Public Maven Repository Group https://repository.jboss.org/nexus/content/groups/public-jboss/ default true never true never Testing Implementions of JSR107 ------------------------------- See the [TCK User Guide](https://docs.google.com/document/d/1w3Ugj_oEqjMlhpCkGQOZkd9iPf955ZWHAVdZzEwYYdU/edit?usp=sharing) for instructions on how to use this TCK. Mailing list ------------ Please join the mailing list if you're interested in using or developing the software: Issue tracker ------------- Please log issues to: User Questions -------------- Some of the expert group monitor the tags "jcache" and "jsr107" on [stackoverflow](http://stackoverflow.com). Contributing ------------ Admission to the Expert Group is closed, but please feel free to post to the mailing list. License ------- The API is available under the Apache 2.0 license. The TCK is available under a restricted Standalone TCK (SATCK) license and must be licensed from Oracle as is the usual case with JSRs. The reference implementation is available under an Apache 2.0 license. For details please read the license in each source code file. Contributors ------------ This free, open source software was made possible by the JSR107 Expert Group who put many hours of hard work into it. Copyright --------- Copyright (c) JSR107 Expert Group ================================================ FILE: bnd.bnd ================================================ Export-Package: javax.cache;\ javax.cache.annotation;\ javax.cache.configuration;\ javax.cache.event;\ javax.cache.expiry;\ javax.cache.integration;\ javax.cache.management;\ javax.cache.processor;\ javax.cache.spi;\ Bundle-SymbolicName: javax.cache Bundle-Version: ${project.version} ================================================ FILE: checkstyle/ClassHeader.txt ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ ================================================ FILE: checkstyle/checkstyle.xml ================================================ ================================================ FILE: checkstyle/suppressions.xml ================================================ ================================================ FILE: findbugs/findbugs-exclude.xml ================================================ ================================================ FILE: pom.xml ================================================ 4.0.0 org.sonatype.oss oss-parent 7 javax.cache cache-api 1.1.2-SNAPSHOT jar JSR107 API and SPI https://github.com/jsr107/jsr107spec Apache License, Version 2.0 https://www.apache.org/licenses/LICENSE-2.0.txt repo A business-friendly OSS license UTF-8 UTF-8 javax.enterprise cdi-api 1.0-SP4 provided true jsr250-api javax.annotation jboss-interceptors-api_1.1_spec org.jboss.spec.javax.interceptor javax.inject javax.inject junit junit 4.11 test maven-compiler-plugin 3.7.0 1.6 1.6 org.apache.maven.plugins maven-source-plugin 3.0.1 attach-sources package jar org.apache.maven.plugins maven-javadoc-plugin 3.0.1 attach-javadocs jar false org.apache.maven.plugins maven-checkstyle-plugin 2.12 install checkstyle ${basedir}/checkstyle/checkstyle.xml ${basedir}/checkstyle/suppressions.xml ${basedir}/checkstyle/ClassHeader.txt false true true true true false true maven-jar-plugin 3.0.2 ${project.build.outputDirectory}/META-INF/MANIFEST.MF org.apache.felix maven-bundle-plugin 2.3.7 true <_include>bnd.bnd {maven-resources} bundle-manifest process-classes manifest org.apache.maven.plugins maven-site-plugin 3.6 com.atlassian.maven.plugins maven-clover2-plugin 3.2.0 ${java.io.tmpdir}/clover/clover.db true insert license here method false release org.apache.maven.plugins maven-gpg-plugin 1.5 sign-artifacts verify sign doclint-java8-all-but-missing [1.8,) org.apache.maven.plugins maven-javadoc-plugin 3.1.0 all -missing scm:git:git@github.com:juven/git-demo.git scm:git:git@github.com:juven/git-demo.git git@github.com:juven/git-demo.git sourceforge-releases Sourceforge Release Repository http://oss.sonatype.org/service/local/staging/deploy/maven2 sourceforge-snapshots Sourceforge Snapshot Repository http://oss.sonatype.org/content/repositories/sourceforge-snapshots org.apache.maven.plugins maven-project-info-reports-plugin 2.6 org.codehaus.mojo findbugs-maven-plugin 3.0.5 Max Low ${basedir}/findbugs/findbugs-exclude.xml org.apache.maven.plugins maven-jxr-plugin 2.5 ================================================ FILE: src/main/java/javax/cache/Cache.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache; import javax.cache.configuration.CacheEntryListenerConfiguration; import javax.cache.configuration.Configuration; import javax.cache.event.CacheEntryListener; import javax.cache.event.CacheEntryRemovedListener; import javax.cache.expiry.ExpiryPolicy; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheWriter; import javax.cache.integration.CompletionListener; import javax.cache.processor.EntryProcessor; import javax.cache.processor.EntryProcessorException; import javax.cache.processor.EntryProcessorResult; import java.io.Closeable; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * A {@link Cache} is a Map-like data structure that provides temporary storage * of application data. *

* Like {@link Map}s, {@link Cache}s *

    *
  1. store key-value pairs, each referred to as an {@link Entry}
  2. *
  3. allow use of Java Generics to improve application type-safety
  4. *
  5. are {@link Iterable}
  6. *
*

* Unlike {@link Map}s, {@link Cache}s *

    *
  1. do not allow null keys or values. Attempts to use null * will result in a {@link NullPointerException}
  2. *
  3. provide the ability to read values from a * {@link CacheLoader} (read-through-caching) * when a value being requested is not in a cache
  4. *
  5. provide the ability to write values to a * {@link CacheWriter} (write-through-caching) * when a value being created/updated/removed from a cache
  6. *
  7. provide the ability to observe cache entry changes
  8. *
  9. may capture and measure operational statistics
  10. *
*

* A simple example of how to use a cache is: *


 * String cacheName = "sampleCache";
 * CachingProvider provider = Caching.getCachingProvider();
 * CacheManager manager = provider.getCacheManager();
 * Cache<Integer, Date> cache = manager.getCache(cacheName, Integer.class,
 *                                                     Date.class);
 * Date value1 = new Date();
 * Integer key = 1;
 * cache.put(key, value1);
 * Date value2 = cache.get(key);
 * 
* * @param the type of key * @param the type of value * @author Greg Luck * @author Yannis Cosmadopoulos * @author Brian Oliver * @since 1.0 */ public interface Cache extends Iterable>, Closeable { /** * Gets an entry from the cache. *

* If the cache is configured to use read-through, and get would return null * because the entry is missing from the cache, the Cache's {@link CacheLoader} * is called in an attempt to load the entry. * * @param key the key whose associated value is to be returned * @return the element, or null, if it does not exist. * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws NullPointerException if the key is null * @throws CacheException if there is a problem fetching the value * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} */ V get(K key); /** * Gets a collection of entries from the {@link Cache}, returning them as * {@link Map} of the values associated with the set of keys requested. *

* If the cache is configured read-through, and a get for a key would * return null because an entry is missing from the cache, the Cache's * {@link CacheLoader} is called in an attempt to load the entry. If an * entry cannot be loaded for a given key, the key will not be present in * the returned Map. * * @param keys The keys whose associated values are to be returned. * @return A map of entries that were found for the given keys. Keys not found * in the cache are not in the returned map. * @throws NullPointerException if keys is null or if keys contains a null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem fetching the values * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} */ Map getAll(Set keys); /** * Determines if the {@link Cache} contains an entry for the specified key. *

* More formally, returns true if and only if this cache contains a * mapping for a key k such that key.equals(k). * (There can be at most one such mapping.)

*

* If the cache is configured read-through the associated {@link CacheLoader} * is not called. Only the cache is checked. *

* @param key key whose presence in this cache is to be tested. * @return true if this map contains a mapping for the specified key * @throws NullPointerException if key is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException it there is a problem checking the mapping * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see java.util.Map#containsKey(Object) */ boolean containsKey(K key); /** * Asynchronously loads the specified entries into the cache using the * configured {@link CacheLoader} for the given keys. *

* If an entry for a key already exists in the Cache, a value will be loaded * if and only if replaceExistingValues is true. If no loader * is configured for the cache, no objects will be loaded. If a problem is * encountered during the retrieving or loading of the objects, * an exception is provided to the {@link CompletionListener}. Once the * operation has completed, the specified CompletionListener is notified. *

* Implementations may choose to load multiple keys from the provided * {@link Set} in parallel. Iteration however must not occur in parallel, * thus allow for non-thread-safe {@link Set}s to be used. *

* The thread on which the completion listener is called is implementation * dependent. An implementation may also choose to serialize calls to * different CompletionListeners rather than use a thread per * CompletionListener. * * @param keys the keys to load * @param replaceExistingValues when true existing values in the Cache will * be replaced by those loaded from a CacheLoader * @param completionListener the CompletionListener (may be null) * @throws NullPointerException if keys is null or if keys contains a null. * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException thrown if there is a problem performing the * load. This may also be thrown on calling if * there are insufficient threads available to * perform the load. * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} */ void loadAll(Set keys, boolean replaceExistingValues, CompletionListener completionListener); /** * Associates the specified value with the specified key in the cache. *

* If the {@link Cache} previously contained a mapping for the key, the old * value is replaced by the specified value. (A cache c is said to * contain a mapping for a key k if and only if {@link * #containsKey(Object) c.containsKey(k)} would return true.) *

* If the cache is configured write-through the * {@link CacheWriter#write(Cache.Entry)} method will be called. *

* * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @throws NullPointerException if key is null or if value is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem doing the put * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see java.util.Map#put(Object, Object) * @see #getAndPut(Object, Object) * @see #getAndReplace(Object, Object) * @see CacheWriter#write */ void put(K key, V value); /** * Associates the specified value with the specified key in this cache, * returning an existing value if one existed. *

* If the cache previously contained a mapping for * the key, the old value is replaced by the specified value. (A cache * c is said to contain a mapping for a key k if and only * if {@link #containsKey(Object) c.containsKey(k)} would return * true.) *

* The previous value is returned, or null if there was no value associated * with the key previously.

*

* If the cache is configured write-through the associated * {@link CacheWriter#write(Cache.Entry)} method will be called. *

* * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the value associated with the key at the start of the operation or * null if none was associated * @throws NullPointerException if key is null or if value is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem doing the put * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see #put(Object, Object) * @see #getAndReplace(Object, Object) * @see CacheWriter#write(Cache.Entry) */ V getAndPut(K key, V value); /** * Copies all of the entries from the specified map to the {@link Cache}. *

* The effect of this call is equivalent to that of calling * {@link #put(Object, Object) put(k, v)} on this cache once for each mapping * from key k to value v in the specified map. *

* The order in which the individual puts occur is undefined. *

* The behavior of this operation is undefined if entries in the cache * corresponding to entries in the map are modified or removed while this * operation is in progress. or if map is modified while the operation is in * progress. *

* In Default Consistency mode, individual puts occur atomically but not * the entire putAll. Listeners may observe individual updates. *

* If the cache is configured write-through the associated * {@link CacheWriter#writeAll} method will be called. *

* * @param map mappings to be stored in this cache * @throws NullPointerException if map is null or if map contains null keys * or values. * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem doing the put. * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see CacheWriter#writeAll */ void putAll(java.util.Map map); /** * Atomically associates the specified key with the given value if it is * not already associated with a value. *

* This is equivalent to: *


     * if (!cache.containsKey(key)) {}
     *   cache.put(key, value);
     *   return true;
     * } else {
     *   return false;
     * }
     * 
* except that the action is performed atomically. *

* If the cache is configured write-through, and this method returns true, * the associated {@link CacheWriter#write(Cache.Entry)} method will be called. *

* @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return true if a value was set. * @throws NullPointerException if key is null or value is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem doing the put * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see CacheWriter#write */ boolean putIfAbsent(K key, V value); /** * Removes the mapping for a key from this cache if it is present. *

* More formally, if this cache contains a mapping from key k to * value v such that * (key==null ? k==null : key.equals(k)), that mapping is removed. * (The cache can contain at most one such mapping.) * *

Returns true if this cache previously associated the key, * or false if the cache contained no mapping for the key. *

* The cache will not contain a mapping for the specified key once the * call returns. *

* If the cache is configured write-through the associated * {@link CacheWriter#delete(Object)} method will be called. *

* @param key key whose mapping is to be removed from the cache * @return returns false if there was no matching key * @throws NullPointerException if key is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem doing the remove * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see CacheWriter#delete */ boolean remove(K key); /** * Atomically removes the mapping for a key only if currently mapped to the * given value. *

* This is equivalent to: *


     * if (cache.containsKey(key) && equals(cache.get(key), oldValue) {
     *   cache.remove(key);
     *   return true;
     * } else {
     *   return false;
     * }
     * 
* except that the action is performed atomically. *

* If the cache is configured write-through, and this method returns true, * the associated {@link CacheWriter#delete(Object)} method will be called. *

* @param key key whose mapping is to be removed from the cache * @param oldValue value expected to be associated with the specified key * @return returns false if there was no matching key * @throws NullPointerException if key is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem doing the remove * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see CacheWriter#delete */ boolean remove(K key, V oldValue); /** * Atomically removes the entry for a key only if currently mapped to some * value. *

* This is equivalent to: *


     * if (cache.containsKey(key)) {
     *   V oldValue = cache.get(key);
     *   cache.remove(key);
     *   return oldValue;
     * } else {
     *   return null;
     * }
     * 
* except that the action is performed atomically. *

* If the cache is configured write-through the associated * {@link CacheWriter#delete(Object)} method will be called. *

* * @param key key with which the specified value is associated * @return the value if one existed or null if no mapping existed for this key * @throws NullPointerException if the specified key or value is null. * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem during the remove * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see CacheWriter#delete */ V getAndRemove(K key); /** * Atomically replaces the entry for a key only if currently mapped to a * given value. *

* This is equivalent to: *


     * if (cache.containsKey(key) && equals(cache.get(key), oldValue)) {
     *  cache.put(key, newValue);
     * return true;
     * } else {
     *  return false;
     * }
     * 
* except that the action is performed atomically. *

* If the cache is configured write-through, and this method returns true, * the associated {@link CacheWriter#write(Cache.Entry)} method will be called. *

* @param key key with which the specified value is associated * @param oldValue value expected to be associated with the specified key * @param newValue value to be associated with the specified key * @return true if the value was replaced * @throws NullPointerException if key is null or if the values are null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem during the replace * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see CacheWriter#write */ boolean replace(K key, V oldValue, V newValue); /** * Atomically replaces the entry for a key only if currently mapped to some * value. *

* This is equivalent to *


     * if (cache.containsKey(key)) {
     *   cache.put(key, value);
     *   return true;
     * } else {
     *   return false;
     * }
* except that the action is performed atomically. *

* If the cache is configured write-through, and this method returns true, * the associated {@link CacheWriter#write(Cache.Entry)} method will be called. *

* @param key the key with which the specified value is associated * @param value the value to be associated with the specified key * @return true if the value was replaced * @throws NullPointerException if key is null or if value is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem during the replace * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see #getAndReplace(Object, Object) * @see CacheWriter#write */ boolean replace(K key, V value); /** * Atomically replaces the value for a given key if and only if there is a * value currently mapped by the key. *

* This is equivalent to *


     * if (cache.containsKey(key)) {
     *   V oldValue = cache.get(key);
     *   cache.put(key, value);
     *   return oldValue;
     * } else {
     *   return null;
     * }
     * 
* except that the action is performed atomically. *

* If the cache is configured write-through, and this method returns true, * the associated {@link CacheWriter#write(Cache.Entry)} method will be called. *

* @param key key with which the specified value is associated * @param value value to be associated with the specified key * @return the previous value associated with the specified key, or * null if there was no mapping for the key. * @throws NullPointerException if key is null or if value is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem during the replace * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see java.util.concurrent.ConcurrentMap#replace(Object, Object) * @see CacheWriter#write */ V getAndReplace(K key, V value); /** * Removes entries for the specified keys. *

* The order in which the individual entries are removed is undefined. *

* For every entry in the key set, the following are called: *

    *
  • any registered {@link CacheEntryRemovedListener}s
  • *
  • if the cache is a write-through cache, the {@link CacheWriter}
  • *
* * @param keys the keys to remove * @throws NullPointerException if keys is null or if it contains a null key * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem during the remove * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see CacheWriter#deleteAll */ void removeAll(Set keys); /** * Removes all of the mappings from this cache. *

* The order that the individual entries are removed is undefined. *

* For every mapping that exists the following are called: *

    *
  • any registered {@link CacheEntryRemovedListener}s
  • *
  • if the cache is a write-through cache, the {@link CacheWriter}
  • *
* If the cache is empty, the {@link CacheWriter} is not called. *

* This is potentially an expensive operation as listeners are invoked. * Use {@link #clear()} to avoid this. * * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem during the remove * @see #clear() * @see CacheWriter#deleteAll */ void removeAll(); /** * Clears the contents of the cache, without notifying listeners or * {@link CacheWriter}s. * * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws CacheException if there is a problem during the clear */ void clear(); /** * Provides a standard way to access the configuration of a cache using * JCache configuration or additional proprietary configuration. *

* The returned value must be immutable. *

* If the provider's implementation does not support the specified class, * the {@link IllegalArgumentException} is thrown. * * @param the type of the Configuration * @param clazz the configuration interface or class to return. This includes * {@link Configuration}.class and * {@link javax.cache.configuration.CompleteConfiguration}s. * @return the requested implementation of {@link Configuration} * @throws IllegalArgumentException if the caching provider doesn't support * the specified class. */ > C getConfiguration(Class clazz); /** * Invokes an {@link EntryProcessor} against the {@link Entry} specified by * the provided key. * * @param the type of the return value * @param key the key to the entry * @param entryProcessor the {@link EntryProcessor} to invoke * @param arguments additional arguments to pass to the * {@link EntryProcessor} * @return the result of the processing, if any, defined by the * {@link EntryProcessor} implementation * @throws NullPointerException if key or {@link EntryProcessor} is null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @throws EntryProcessorException if an exception is thrown by the {@link * EntryProcessor}, a Caching Implementation * must wrap any {@link Exception} thrown * wrapped in an {@link EntryProcessorException}. * @see EntryProcessor */ T invoke(K key, EntryProcessor entryProcessor, Object... arguments) throws EntryProcessorException; /** * Invokes an {@link EntryProcessor} against the set of {@link Entry}s * specified by the set of keys. *

* The order that the entries for the keys are processed is undefined. * Implementations may choose to process the entries in any order, including * concurrently. Furthermore there is no guarantee implementations will * use the same {@link EntryProcessor} instance to process each entry, as * the case may be in a non-local cache topology. *

* The result of executing the {@link EntryProcessor} is returned as a * {@link Map} of {@link EntryProcessorResult}s, one result per key. Should the * {@link EntryProcessor} or Caching implementation throw an exception, the * exception is wrapped and re-thrown when a call to * {@link javax.cache.processor.EntryProcessorResult#get()} is made. * * @param the type of the return value * @param keys the set of keys for entries to process * @param entryProcessor the {@link EntryProcessor} to invoke * @param arguments additional arguments to pass to the * {@link EntryProcessor} * @return the map of {@link EntryProcessorResult}s of the processing per key, * if any, defined by the {@link EntryProcessor} implementation. No mappings * will be returned for {@link EntryProcessor}s that return a * null value for a key. * @throws NullPointerException if keys or {@link EntryProcessor} are null * @throws IllegalStateException if the cache is {@link #isClosed()} * @throws ClassCastException if the implementation is configured to perform * runtime-type-checking, and the key or value * types are incompatible with those that have been * configured for the {@link Cache} * @see EntryProcessor */ Map> invokeAll(Set keys, EntryProcessor entryProcessor, Object... arguments); /** * Return the name of the cache. * * @return the name of the cache. */ String getName(); /** * Gets the {@link CacheManager} that owns and manages the {@link Cache}. * * @return the manager or null if the {@link Cache} is not * managed */ CacheManager getCacheManager(); /** * Closing a {@link Cache} signals to the {@link CacheManager} that produced or * owns the {@link Cache} that it should no longer be managed. At this * point in time the {@link CacheManager}: *

    *
  • must close and release all resources being coordinated on behalf of the * Cache by the {@link CacheManager}. This includes calling the close * method on configured {@link CacheLoader}, * {@link CacheWriter}, registered {@link CacheEntryListener}s and * {@link ExpiryPolicy} instances that implement the java.io.Closeable * interface. *
  • prevent events being delivered to configured {@link CacheEntryListener}s * registered on the {@link Cache} *
  • *
  • not return the name of the Cache when the CacheManager getCacheNames() * method is called
  • *
* Once closed any attempt to use an operational method on a Cache will throw an * {@link IllegalStateException}. *

* Closing a Cache does not necessarily destroy the contents of a Cache. * It simply signals to the owning CacheManager that the Cache is no longer * required by the application and that future uses of a specific Cache instance * should not be permitted. *

* Depending on the implementation and Cache topology, * (e.g. a storage-backed or distributed cache), the contents of a closed Cache * may still be available and accessible by other applications, or, in fact, via * the Cache Manager that previously owned the Cache, if an application calls * getCache at some point in the future. * * @throws SecurityException when the operation could not be performed * due to the current security settings */ void close(); /** * Determines whether this Cache instance has been closed. A Cache is * considered closed if; *

    *
  1. the {@link #close()} method has been called
  2. *
  3. the associated {@link #getCacheManager()} has been closed, or
  4. *
  5. the Cache has been removed from the associated * {@link #getCacheManager()}
  6. *
*

* This method generally cannot be called to determine whether a Cache instance * is valid or invalid. A typical client can determine that a Cache is invalid * by catching any exceptions that might be thrown when an operation is * attempted. * * @return true if this Cache instance is closed; false if it is still open */ boolean isClosed(); /** * Provides a standard way to access the underlying concrete caching * implementation to provide access to further, proprietary features. *

* If the provider's implementation does not support the specified class, * the {@link IllegalArgumentException} is thrown. * * @param the type of the underlying {@link Cache} implementation * @param clazz the proprietary class or interface of the underlying concrete * cache. It is this type that is returned. * @return an instance of the underlying concrete cache * @throws IllegalArgumentException if the caching provider doesn't support * the specified class. * @throws SecurityException when the operation could not be performed * due to the current security settings */ T unwrap(java.lang.Class clazz); /** * Registers a {@link CacheEntryListener}. The supplied * {@link CacheEntryListenerConfiguration} is used to instantiate a listener * and apply it to those events specified in the configuration. * * @param cacheEntryListenerConfiguration * a factory and related configuration * for creating the listener * @throws IllegalArgumentException is the same CacheEntryListenerConfiguration * is used more than once * @throws IllegalStateException if the cache is {@link #isClosed()} * @see CacheEntryListener */ void registerCacheEntryListener( CacheEntryListenerConfiguration cacheEntryListenerConfiguration); /** * Deregisters a listener, using the * {@link CacheEntryListenerConfiguration} that was used to register it. *

* Both listeners registered at configuration time, * and those created at runtime with {@link #registerCacheEntryListener} can * be deregistered. * * @param cacheEntryListenerConfiguration * the factory and related configuration * that was used to create the * listener * @throws IllegalStateException if the cache is {@link #isClosed()} */ void deregisterCacheEntryListener(CacheEntryListenerConfiguration cacheEntryListenerConfiguration); /** * {@inheritDoc} *

* The ordering of iteration over entries is undefined. *

* During iteration, any entries that are removed will have their appropriate * CacheEntryRemovedListeners notified. *

* When iterating over a cache it must be assumed that the underlying * cache may be changing, with entries being added, removed, evicted * and expiring. {@link java.util.Iterator#next()} may therefore return * null. * * @throws IllegalStateException if the cache is {@link #isClosed()} */ Iterator> iterator(); /** * A cache entry (key-value pair). */ interface Entry { /** * Returns the key corresponding to this entry. * * @return the key corresponding to this entry */ K getKey(); /** * Returns the value stored in the cache when this entry was created. * * @return the value corresponding to this entry */ V getValue(); /** * Provides a standard way to access the underlying concrete cache entry * implementation in order to provide access to further, proprietary features. *

* If the provider's implementation does not support the specified class, * the {@link IllegalArgumentException} is thrown. * * @param the type of the underlying {@link Entry} implementation * @param clazz the proprietary class or interface of the underlying * concrete cache. It is this type that is returned. * @return an instance of the underlying concrete cache * @throws IllegalArgumentException if the caching provider doesn't support * the specified class. */ T unwrap(Class clazz); } } ================================================ FILE: src/main/java/javax/cache/CacheException.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache; /** * Thrown to indicate an exception has occurred in the Cache. *

* This is the base class for all cache exceptions. * * @author Greg Luck * @since 1.0 */ public class CacheException extends RuntimeException { private static final long serialVersionUID = 1L; /** * Constructs a new CacheException. * * @since 1.0 */ public CacheException() { super(); } /** * Constructs a new CacheException with a message string. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @since 1.0 */ public CacheException(String message) { super(message); } /** * Constructs a CacheException with a message string, and * a base exception * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new CacheException with the specified cause and a * detail message of (cause==null ? null : cause.toString()) * (that typically contains the class and detail message of * cause). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheException(Throwable cause) { super(cause); } } ================================================ FILE: src/main/java/javax/cache/CacheManager.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache; import javax.cache.configuration.Configuration; import javax.cache.management.CacheMXBean; import javax.cache.spi.CachingProvider; import java.io.Closeable; import java.lang.management.ManagementFactory; import java.net.URI; import java.util.Properties; /** * A {@link CacheManager} provides a means of establishing, configuring, * acquiring, closing and destroying uniquely named {@link Cache}s. *

* {@link Cache}s produced and owned by a {@link CacheManager} typically share * common infrastructure, for example, a common {@link ClassLoader} and * implementation specific {@link Properties}. *

* Implementations of {@link CacheManager} may additionally provide and share * external resources between the {@link Cache}s being managed, for example, * the content of the managed {@link Cache}s may be stored in the same cluster. *

* By default {@link CacheManager} instances are typically acquired through the * use of a {@link CachingProvider}. Implementations however may additionally * provide other mechanisms to create, acquire, manage and configure * {@link CacheManager}s, including: *

    *
  • making use of {@link java.util.ServiceLoader}s,
  • *
  • permitting the use of the new operator to create a * concrete implementation,
  • *
  • providing the construction through the use of one or more * builders, and
  • *
  • through the use of dependency injection.
  • *
*

* The default {@link CacheManager} however can always be acquired using the * default configured {@link CachingProvider} obtained by the {@link Caching} * class. For example: *


 * CachingProvider provider = Caching.getCachingProvider();
 * CacheManager manager = provider.getCacheManager();
 * 
*

* Within a Java process {@link CacheManager}s and the {@link Cache}s they * manage are scoped and uniquely identified by a {@link URI}, the meaning of * which is implementation specific. To obtain the default {@link URI}, * {@link ClassLoader} and {@link Properties} for an implementation, consult the * {@link CachingProvider} class. * * * @author Greg Luck * @author Yannis Cosmadopoulos * @author Brian Oliver * @see Caching * @see CachingProvider * @see Cache * @since 1.0 * */ public interface CacheManager extends Closeable { /** * Get the {@link CachingProvider} that created and is responsible for * the {@link CacheManager}. * * @return the CachingProvider or null if the {@link CacheManager} * was created without using a {@link CachingProvider} */ CachingProvider getCachingProvider(); /** * Get the URI of the {@link CacheManager}. * * @return the URI of the {@link CacheManager} */ URI getURI(); /** * Get the {@link ClassLoader} used by the {@link CacheManager}. * * @return the {@link ClassLoader} used by the {@link CacheManager} */ ClassLoader getClassLoader(); /** * Get the {@link Properties} that were used to create this * {@link CacheManager}. *

* Implementations are not required to re-configure the * {@link CacheManager} should modifications to the returned * {@link Properties} be made. * * @return the Properties used to create the {@link CacheManager} */ Properties getProperties(); /** * Creates a named {@link Cache} at runtime. *

* If a {@link Cache} with the specified name is known to the {@link * CacheManager}, a CacheException is thrown. *

* If a {@link Cache} with the specified name is unknown the {@link * CacheManager}, one is created according to the provided {@link Configuration} * after which it becomes managed by the {@link CacheManager}. *

* Prior to a {@link Cache} being created, the provided {@link Configuration}s is * validated within the context of the {@link CacheManager} properties and * implementation. *

* Implementers should be aware that the {@link Configuration} may be used to * configure other {@link Cache}s. *

* There's no requirement on the part of a developer to call this method for * each {@link Cache} an application may use. Implementations may support * the use of declarative mechanisms to pre-configure {@link Cache}s, thus * removing the requirement to configure them in an application. In such * circumstances a developer may simply call either the * {@link #getCache(String)} or {@link #getCache(String, Class, Class)} * methods to acquire a previously established or pre-configured {@link Cache}. * * @param the type of key * @param the type of value * @param the type of the Configuration * @param cacheName the name of the {@link Cache}. Names should not use * forward slashes(/) or colons(:), or start with * java. or javax. These prefixes are reserved. * @param configuration a {@link Configuration} for the {@link Cache} * @throws IllegalStateException if the {@link CacheManager} * {@link #isClosed()} * @throws CacheException if there was an error configuring the * {@link Cache}, which includes trying * to create a cache that already exists. * @throws IllegalArgumentException if the configuration is invalid * @throws UnsupportedOperationException if the configuration specifies * an unsupported feature * @throws NullPointerException if the cache configuration or name * is null * @throws SecurityException when the operation could not be performed * due to the current security settings */ > Cache createCache(String cacheName, C configuration) throws IllegalArgumentException; /** * Looks up a managed {@link Cache} given its name. *

* Use this method to check runtime key and value types. *

* Use {@link #getCache(String)} where this check is not required. *

* Implementations must ensure that the key and value types are the same as * those configured for the {@link Cache} prior to returning from this method. *

* Implementations may further perform type checking on mutative cache operations * and throw a {@link ClassCastException} if these checks fail. *

* Implementations that support declarative mechanisms for pre-configuring * {@link Cache}s may return a pre-configured {@link Cache} instead of * null. * * @param the type of key * @param the type of value * @param cacheName the name of the managed {@link Cache} to acquire * @param keyType the expected {@link Class} of the key * @param valueType the expected {@link Class} of the value * @return the Cache or null if it does exist or can't be pre-configured * @throws IllegalStateException if the {@link CacheManager} * is {@link #isClosed()} * @throws ClassCastException if the specified key and/or value types are * incompatible with the configured cache. * @throws NullPointerException if either keyType or classType is null. * @throws SecurityException when the operation could not be performed * due to the current security settings */ Cache getCache(String cacheName, Class keyType, Class valueType); /** * Looks up a managed {@link Cache} given its name. *

* This method may only be used to acquire {@link Cache}s that were * configured without runtime key and value types, or were configured * to use Object.class key and value types. *

* Use the {@link #getCache(String, Class, Class)} method to acquire * {@link Cache}s with a check that the supplied key and value type parameters * match the runtime types. *

* Implementations that support declarative mechanisms for pre-configuring * {@link Cache}s may return a pre-configured {@link Cache} instead of * null. * * @param the type of key * @param the type of value * @param cacheName the name of the cache to look for * @return the Cache or null if it does exist or can't be pre-configured * @throws IllegalStateException if the CacheManager is {@link #isClosed()} * @throws SecurityException when the operation could not be performed * due to the current security settings * @see #getCache(String, Class, Class) */ Cache getCache(String cacheName); /** * Obtains an {@link Iterable} over the names of {@link Cache}s managed by the * {@link CacheManager}. *

* {@link java.util.Iterator}s returned by the {@link Iterable} are immutable. * If the {@link Cache}s managed by the {@link CacheManager} change, * the {@link Iterable} and associated {@link java.util.Iterator}s are not * affected. *

* {@link java.util.Iterator}s returned by the {@link Iterable} may not provide * all of the {@link Cache}s managed by the {@link CacheManager}. For example: * Internally defined or platform specific {@link Cache}s that may be accessible * by a call to {@link #getCache(String)} or {@link #getCache(String, Class, * Class)} may not be present in an iteration. * * @return an {@link Iterable} over the names of managed {@link Cache}s. * @throws IllegalStateException if the {@link CacheManager} * is {@link #isClosed()} * @throws SecurityException when the operation could not be performed * due to the current security settings */ Iterable getCacheNames(); /** * Destroys a specifically named and managed {@link Cache}. Once destroyed * a new {@link Cache} of the same name but with a different {@link * Configuration} may be configured. *

* This is equivalent to the following sequence of method calls: *

    *
  1. {@link Cache#clear()}
  2. *
  3. {@link Cache#close()}
  4. *
* followed by allowing the name of the {@link Cache} to be used for other * {@link Cache} configurations. *

* From the time this method is called, the specified {@link Cache} is not * available for operational use. An attempt to call an operational method on * the {@link Cache} will throw an {@link IllegalStateException}. * * @param cacheName the cache to destroy * @throws IllegalStateException if the {@link CacheManager} * {@link #isClosed()} * @throws NullPointerException if cacheName is null * @throws SecurityException when the operation could not be performed * due to the current security settings */ void destroyCache(String cacheName); /** * Controls whether management is enabled. If enabled the {@link CacheMXBean} * for each cache is registered in the platform MBean server. The platform * MBeanServer is obtained using * {@link ManagementFactory#getPlatformMBeanServer()}. *

* Management information includes the name and configuration information for * the cache. *

* Each cache's management object must be registered with an ObjectName that * is unique and has the following type and attributes: *

* Type: * javax.cache:type=CacheConfiguration *

* Required Attributes: *

    *
  • CacheManager the URI of the CacheManager *
  • Cache the name of the Cache *
* * @param cacheName the name of the cache to register * @param enabled true to enable management, false to disable. * @throws IllegalStateException if the {@link CacheManager} or * {@link Cache} {@link #isClosed()} * @throws SecurityException when the operation could not be performed * due to the current security settings */ void enableManagement(String cacheName, boolean enabled); /** * Enables or disables statistics gathering for a managed {@link Cache} at * runtime. *

* Each cache's statistics object must be registered with an ObjectName that * is unique and has the following type and attributes: *

* Type: * javax.cache:type=CacheStatistics *

* Required Attributes: *

    *
  • CacheManager the URI of the CacheManager *
  • Cache the name of the Cache *
* * @param cacheName the name of the cache to register * @param enabled true to enable statistics, false to disable. * @throws IllegalStateException if the {@link CacheManager} or * {@link Cache} {@link #isClosed()} * @throws NullPointerException if cacheName is null * @throws SecurityException when the operation could not be performed * due to the current security settings */ void enableStatistics(String cacheName, boolean enabled); /** * Closes the {@link CacheManager}. *

* For each {@link Cache} managed by the {@link CacheManager}, the * {@link Cache#close()} method will be invoked, in no guaranteed order. *

* If a {@link Cache#close()} call throws an exception, the exception will be * ignored. *

* After executing this method, the {@link #isClosed()} method will return * true. *

* All attempts to close a previously closed {@link CacheManager} will be * ignored. * * Closing a CacheManager does not necessarily destroy the contents of the * Caches in the CacheManager. *

* It simply signals that the CacheManager is no longer required by the application * and that future uses of a specific CacheManager instance should not be permitted. *

* Depending on the implementation and Cache topology, * (e.g. a storage-backed or distributed cache), the contents of closed Caches * previously referenced by the CacheManager, may still be available and accessible * by other applications. * * @throws SecurityException when the operation could not be performed due to the * current security settings */ void close(); /** * Determines whether the {@link CacheManager} instance has been closed. A * {@link CacheManager} is considered closed if; *

    *
  1. the {@link #close()} method has been called
  2. *
  3. the associated {@link #getCachingProvider()} has been closed, or
  4. *
  5. the {@link CacheManager} has been closed using the associated * {@link #getCachingProvider()}
  6. *
*

* This method generally cannot be called to determine whether the * {@link CacheManager} is valid or invalid. A typical client can determine * that a {@link CacheManager} is invalid by catching any exceptions that * might be thrown when an operation is attempted. * * @return true if this {@link CacheManager} instance is closed; false if it * is still open */ boolean isClosed(); /** * Provides a standard mechanism to access the underlying concrete caching * implementation to provide access to further, proprietary features. *

* If the provider's implementation does not support the specified class, * the {@link IllegalArgumentException} is thrown. * * @param the type of the underlying {@link CacheManager} * @param clazz the proprietary class or interface of the underlying concrete * {@link CacheManager}. It is this type that is returned. * @return an instance of the underlying concrete {@link CacheManager} * @throws IllegalArgumentException if the caching provider doesn't support the * specified class. * @throws SecurityException when the operation could not be performed * due to the current security settings */ T unwrap(java.lang.Class clazz); } ================================================ FILE: src/main/java/javax/cache/Caching.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache; import javax.cache.spi.CachingProvider; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.ServiceLoader; import java.util.WeakHashMap; /** * The {@link Caching} class provides a convenient means for an application to * acquire an appropriate {@link CachingProvider} implementation. *

* While defined as part of the specification, its use is not required. * Applications and/or containers may instead choose to directly instantiate a * {@link CachingProvider} implementation based on implementation specific * instructions. *

* When using the {@link Caching} class, {@link CachingProvider} implementations * are automatically discovered when they follow the conventions outlined by the * Java Development Kit {@link ServiceLoader} class. *

* Although automatically discovered, applications that choose to use this class * should not make assumptions regarding the order in which implementations are * returned by the {@link #getCachingProviders()} or * {@link #getCachingProviders(ClassLoader)} methods. *

* For a {@link CachingProvider} to be automatically discoverable by the * {@link Caching} class, the fully qualified class name of the * {@link CachingProvider} implementation must be declared in the following * file: *

 *   META-INF/services/javax.cache.spi.CachingProvider
 * 
* This file must be resolvable via the class path. *

* For example, in the reference implementation the contents of this file are: * org.jsr107.ri.RICachingProvider *

* Alternatively when the fully qualified class name of a * {@link CachingProvider} implementation is specified using the system property * javax.cache.spi.cachingprovider, that implementation will be used * as the default {@link CachingProvider}. *

* All {@link CachingProvider}s that are automatically detected or explicitly * declared and loaded by the {@link Caching} class are maintained in an * internal registry. Consequently when a previously loaded * {@link CachingProvider} is requested, it will be simply returned from the * internal registry, without reloading and/or instantiating the said * implementation again. *

* As required by some applications and containers, multiple co-existing * {@link CachingProvider}s implementations, from the same or different * implementors are permitted at runtime. *

* To iterate through those that are currently registered a developer may use * the following methods: *

    *
  1. {@link #getCachingProviders()}
  2. *
  3. {@link #getCachingProviders(ClassLoader)}
  4. *
* To request a specific {@link CachingProvider} implementation, a developer * should use either the {@link #getCachingProvider(String)} or * {@link #getCachingProvider(String, ClassLoader)} method. *

* Where multiple {@link CachingProvider}s are present, the * {@link CachingProvider} returned by getters {@link #getCachingProvider()} and * {@link #getCachingProvider(ClassLoader)} is undefined and as a result a * {@link CacheException} will be thrown when attempted. * * @author Brian Oliver * @author Greg Luck * @author Yannis Cosmadopoulos * @since 1.0 * @see ServiceLoader * @see CachingProvider */ public final class Caching { /** * The javax.cache.spi.cachingprovider constant. */ public static final String JAVAX_CACHE_CACHING_PROVIDER = "javax.cache" + ".spi.CachingProvider"; /** * The {@link CachingProviderRegistry} that tracks the {@link CachingProvider}s. */ private static final CachingProviderRegistry CACHING_PROVIDERS = new CachingProviderRegistry(); /** * No public constructor as all methods are static. */ private Caching() { } /** * Obtains the {@link ClassLoader} to use for API methods that don't * explicitly require a {@link ClassLoader} but internally require one. *

* By default this is the {@link Thread#getContextClassLoader()}. * * @return the default {@link ClassLoader} */ public static ClassLoader getDefaultClassLoader() { return CACHING_PROVIDERS.getDefaultClassLoader(); } /** * Set the {@link ClassLoader} to use for API methods that don't explicitly * require a {@link ClassLoader}, but internally use one. * * @param classLoader the {@link ClassLoader} or null if the * calling {@link Thread#getContextClassLoader()} should * be used */ public static void setDefaultClassLoader(ClassLoader classLoader) { CACHING_PROVIDERS.setDefaultClassLoader(classLoader); } /** * Obtains the default {@link CachingProvider} available via the * {@link #getDefaultClassLoader()}. * * @return the {@link CachingProvider} * @throws CacheException should zero, or more than one * {@link CachingProvider} be available on the * classpath, or it could not be loaded * @throws SecurityException when the operation could not be performed * due to the current security settings */ public static CachingProvider getCachingProvider() { return CACHING_PROVIDERS.getCachingProvider(); } /** * Obtains the single {@link CachingProvider} visible to the specified * {@link ClassLoader}. * * @param classLoader the {@link ClassLoader} to use for loading the * {@link CachingProvider} * @return the {@link CachingProvider} * @throws CacheException should zero, or more than one * {@link CachingProvider} be available on the * classpath, or it could not be loaded * @throws SecurityException when the operation could not be performed * due to the current security settings * @see #getCachingProviders(ClassLoader) */ public static CachingProvider getCachingProvider(ClassLoader classLoader) { return CACHING_PROVIDERS.getCachingProvider(classLoader); } /** * Obtains the {@link CachingProvider}s that are available via the * {@link #getDefaultClassLoader()}. *

* If a javax.cache.spi.cachingprovider system property is defined, * only that {@link CachingProvider} specified by that property is returned. * Otherwise all {@link CachingProvider}s that are available via a * {@link ServiceLoader} for {@link CachingProvider}s using the default * {@link ClassLoader} (including those previously requested via * {@link #getCachingProvider(String)}) are returned. * * @return an {@link Iterable} of {@link CachingProvider}s loaded by the * specified {@link ClassLoader} */ public static Iterable getCachingProviders() { return CACHING_PROVIDERS.getCachingProviders(); } /** * Obtains the {@link CachingProvider}s that are available via the specified * {@link ClassLoader}. *

* If a javax.cache.spi.cachingprovider system property is defined, * only that {@link CachingProvider} specified by that property is returned. * Otherwise all {@link CachingProvider}s that are available via a * {@link ServiceLoader} for {@link CachingProvider}s using the specified * {@link ClassLoader} (including those previously requested via * {@link #getCachingProvider(String, ClassLoader)}) are returned. * * @param classLoader the {@link ClassLoader} of the returned * {@link CachingProvider}s * @return an {@link Iterable} of {@link CachingProvider}s loaded by the * specified {@link ClassLoader} */ public static Iterable getCachingProviders( ClassLoader classLoader) { return CACHING_PROVIDERS.getCachingProviders(classLoader); } /** * Obtain the {@link CachingProvider} that is implemented by the specified * fully qualified class name using the {@link #getDefaultClassLoader()}. * Should this {@link CachingProvider} already be loaded it is simply returned, * otherwise an attempt will be made to load and instantiate the specified * class (using a no-args constructor). * * @param fullyQualifiedClassName the fully qualified class name of the * {@link CachingProvider} * @return the {@link CachingProvider} * @throws CacheException if the {@link CachingProvider} cannot be created * @throws SecurityException when the operation could not be performed * due to the current security settings */ public static CachingProvider getCachingProvider(String fullyQualifiedClassName) { return CACHING_PROVIDERS.getCachingProvider(fullyQualifiedClassName); } /** * Obtain the {@link CachingProvider} that is implemented by the specified * fully qualified class name using the provided {@link ClassLoader}. * Should this {@link CachingProvider} already be loaded it is returned, * otherwise an attempt will be made to load and instantiate the specified * class (using a no-args constructor). * * @param fullyQualifiedClassName the fully qualified class name of the * {@link CachingProvider} * @param classLoader the {@link ClassLoader} to load the * {@link CachingProvider} * @return the {@link CachingProvider} * @throws CacheException if the {@link CachingProvider} cannot be created * @throws SecurityException when the operation could not be performed * due to the current security settings */ public static CachingProvider getCachingProvider(String fullyQualifiedClassName, ClassLoader classLoader) { return CACHING_PROVIDERS.getCachingProvider(fullyQualifiedClassName, classLoader); } /** * A convenience that method that looks up a managed {@link Cache} given its * name. using the default CachingProvider and CacheManager * . For the full range of Cache look up methods see * {@link CacheManager}. *

* This method must be used for {@link Cache}s that were configured with * runtime key and value types. Use {@link CacheManager#getCache(String)} for * {@link Cache}s where these were not specified. *

* Implementations must ensure that the key and value types are the same as * those configured for the {@link Cache} prior to returning from this method. *

* Implementations may further perform type checking on mutative cache operations * and throw a {@link ClassCastException} if these checks fail. *

* Implementations that support declarative mechanisms for pre-configuring * {@link Cache}s may return a pre-configured {@link Cache} instead of * null. * @param the type of key * @param the type of value * @param cacheName the name of the managed {@link Cache} to acquire * @param keyType the expected {@link Class} of the key * @param valueType the expected {@link Class} of the value * @return the Cache or null if it does exist or can't be pre-configured * @throws IllegalStateException if the CacheManager is * {@link CacheManager#isClosed()} * @throws IllegalArgumentException if the specified key and/or value types are * incompatible with the configured cache. * @throws SecurityException when the operation could not be performed * due to the current security settings * @see CacheManager#getCache(String, Class, Class) * @see CacheManager#getCache(String) */ public static Cache getCache(String cacheName, Class keyType, Class valueType) { return getCachingProvider().getCacheManager().getCache(cacheName, keyType, valueType); } /** * Maintains a registry of loaded {@link CachingProvider}s scoped by * {@link ClassLoader}. */ private static class CachingProviderRegistry { /** * The {@link CachingProvider}s by Class Name organized by the * {@link ClassLoader} was used to load them. */ private WeakHashMap> cachingProviders; /** * The default {@link ClassLoader}. When null the * {@link Thread#getContextClassLoader()} will be used. */ private volatile ClassLoader classLoader; /** * Constructs a CachingProviderManager. */ public CachingProviderRegistry() { this.cachingProviders = new WeakHashMap>(); this.classLoader = null; } /** * Obtains the {@link ClassLoader} to use for API methods that don't * explicitly require a {@link ClassLoader} but internally require one. *

* By default this is the {@link Thread#getContextClassLoader()}. *

* @return the default {@link ClassLoader} */ public ClassLoader getDefaultClassLoader() { ClassLoader loader = classLoader; return loader == null ? Thread.currentThread().getContextClassLoader() : loader; } /** * Set the {@link ClassLoader} to use for API methods that don't explicitly * require a {@link ClassLoader}, but internally use one. * * @param classLoader the {@link ClassLoader} or null if the * calling {@link Thread#getContextClassLoader()} should * be used */ public void setDefaultClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Obtains the only {@link CachingProvider} defined by the * {@link #getDefaultClassLoader()}. *

* Should zero or more than one {@link CachingProvider}s be available, a * CacheException is thrown. *

* @return the {@link CachingProvider} * @throws CacheException should zero or more than one * {@link CachingProvider} be available * or a {@link CachingProvider} could not be loaded * @see #getCachingProvider(ClassLoader) * @see #getCachingProviders(ClassLoader) */ public CachingProvider getCachingProvider() { return getCachingProvider(getDefaultClassLoader()); } /** * Obtains the only {@link CachingProvider} defined by the specified * {@link ClassLoader}. *

* Should zero or more than one {@link CachingProvider}s be available, a * CacheException is thrown. *

* @param classLoader the {@link ClassLoader} to use for loading the * {@link CachingProvider} * @return the {@link CachingProvider} * @throws CacheException should zero or more than one * {@link CachingProvider} be available * or a {@link CachingProvider} could not be loaded * @see #getCachingProviders(ClassLoader) */ public CachingProvider getCachingProvider(ClassLoader classLoader) { Iterator iterator = getCachingProviders(classLoader).iterator(); if (iterator.hasNext()) { CachingProvider provider = iterator.next(); if (iterator.hasNext()) { throw new CacheException("Multiple CachingProviders have been configured when only a single CachingProvider is expected"); } else { return provider; } } else { throw new CacheException("No CachingProviders have been configured"); } } /** * Obtain the {@link CachingProvider}s that are available via the * {@link #getDefaultClassLoader()}. *

* If a javax.cache.spi.cachingprovider system property is defined, * only that {@link CachingProvider} specified by that property is returned. * Otherwise all {@link CachingProvider}s that are available via a * {@link ServiceLoader} for {@link CachingProvider}s using the default * {@link ClassLoader} (and those explicitly requested via * {@link #getCachingProvider(String)}) are returned. *

* @return an {@link Iterable} of {@link CachingProvider}s loaded by the * default {@link ClassLoader} */ public Iterable getCachingProviders() { return getCachingProviders(getDefaultClassLoader()); } /** * Obtain the {@link CachingProvider}s that are available via the specified * {@link ClassLoader}. *

* If a javax.cache.spi.cachingprovider system property is defined, * only that {@link CachingProvider} specified by that property is returned. * Otherwise all {@link CachingProvider}s that are available via a * {@link ServiceLoader} for {@link CachingProvider}s using the specified * {@link ClassLoader} (and those explicitly requested via * {@link #getCachingProvider(String, ClassLoader)}) are returned. *

* @param classLoader the {@link ClassLoader} of the returned * {@link CachingProvider}s * @return an {@link Iterable} of {@link CachingProvider}s loaded by the * specified {@link ClassLoader} */ public synchronized Iterable getCachingProviders(ClassLoader classLoader) { final ClassLoader serviceClassLoader = classLoader == null ? getDefaultClassLoader() : classLoader; LinkedHashMap providers = cachingProviders.get(serviceClassLoader); if (providers == null) { String className = System.getProperty(JAVAX_CACHE_CACHING_PROVIDER); if (className != null) { providers = new LinkedHashMap(); providers.put(className, loadCachingProvider(className, serviceClassLoader)); } else { providers = AccessController.doPrivileged(new PrivilegedAction>() { @Override public LinkedHashMap run() { LinkedHashMap result = new LinkedHashMap(); ServiceLoader serviceLoader = ServiceLoader.load(CachingProvider.class, serviceClassLoader); for (CachingProvider provider : serviceLoader) { result.put(provider.getClass().getName(), provider); } return result; } }); } cachingProviders.put(serviceClassLoader, providers); } return providers.values(); } /** * Obtain the {@link CachingProvider} that is implemented by the specified * fully qualified class name using the {@link #getDefaultClassLoader()}. * Should this {@link CachingProvider} already be loaded it is simply * returned, otherwise an attempt will be made to load and instantiate the * specified class name (using a no-args constructor). * * @param fullyQualifiedClassName the fully qualified class name of the * {@link CachingProvider} * @return the {@link CachingProvider} * @throws CacheException when the {@link CachingProvider} can't be created */ public CachingProvider getCachingProvider(String fullyQualifiedClassName) { return getCachingProvider(fullyQualifiedClassName, getDefaultClassLoader()); } /** * Load and instantiate the {@link CachingProvider} with the specified * fully qualified class name using the provided {@link ClassLoader} * * @param fullyQualifiedClassName the name of the {@link CachingProvider} * class * @param classLoader the {@link ClassLoader} to use * @return a new {@link CachingProvider} instance * @throws CacheException if the specified {@link CachingProvider} could not be * loaded * or the specified class is not a {@link * CachingProvider} */ protected CachingProvider loadCachingProvider(String fullyQualifiedClassName, ClassLoader classLoader) throws CacheException { synchronized (classLoader) { try { Class clazz = classLoader.loadClass(fullyQualifiedClassName); if (CachingProvider.class.isAssignableFrom(clazz)) { return ((Class) clazz).newInstance(); } else { throw new CacheException("The specified class [" + fullyQualifiedClassName + "] is not a CachingProvider"); } } catch (Exception e) { throw new CacheException("Failed to load the CachingProvider [" + fullyQualifiedClassName + "]", e); } } } /** * Obtain the {@link CachingProvider} that is implemented by the specified * fully qualified class name using the provided {@link ClassLoader}. * Should this {@link CachingProvider} already be loaded it is returned, * otherwise an attempt will be made to load and instantiate the specified * class (using a no-args constructor). * * @param fullyQualifiedClassName the fully qualified class name of the * {@link CachingProvider} * @param classLoader the {@link ClassLoader} to load the * {@link CachingProvider} * @return the {@link CachingProvider} * @throws CacheException when the {@link CachingProvider} can't be created */ public synchronized CachingProvider getCachingProvider(String fullyQualifiedClassName, ClassLoader classLoader) { ClassLoader serviceClassLoader = classLoader == null ? getDefaultClassLoader() : classLoader; LinkedHashMap providers = cachingProviders.get(serviceClassLoader); if (providers == null) { // first load the CachingProviders for the {@link ClassLoader} // this may automatically load the CachingProvider we desire getCachingProviders(serviceClassLoader); providers = cachingProviders.get(serviceClassLoader); } CachingProvider provider = providers.get(fullyQualifiedClassName); if (provider == null) { provider = loadCachingProvider(fullyQualifiedClassName, serviceClassLoader); providers.put(fullyQualifiedClassName, provider); } return provider; } } } ================================================ FILE: src/main/java/javax/cache/annotation/CacheDefaults.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import javax.cache.CacheManager; import javax.enterprise.util.Nonbinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Arrays; /** * Allows the configuration of defaults for {@link CacheResult}, {@link CachePut}, * {@link CacheRemove}, and {@link CacheRemoveAll} at the class level. Without * the method level annotations this annotation has no effect. *

* Following is an example of specifying a default cache name that is used by * the annotations on the getDomain and deleteDomain methods. The annotation for * getAllDomains would use the "allDomains" cache name specified in the method * level annotation. *


 * package my.app;
 * 
 * @CacheDefaults(cacheName="domainCache")
 * public class DomainDao {
 *   @CacheResult
 *   public Domain getDomain(String domainId, int index) {
 *     ...
 *   }
 * 
 *   @CacheRemove
 *   public void deleteDomain(String domainId, int index) {
 *     ...
 *   }
 * 
 *   @CacheResult(cacheName="allDomains")
 *   public List<Domain> getAllDomains() {
 *     ...
 *   }
 * }
 * 
* * @author Rick Hightower * @since 1.0 */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface CacheDefaults { /** * The default name of the cache for the annotated class *

* If not specified defaults to: * package.name.ClassName.methodName(package.ParameterType,package.ParameterType) *

* Applicable for {@link CacheResult}, {@link CachePut}, {@link CacheRemove}, * and {@link CacheRemoveAll} */ @Nonbinding String cacheName() default ""; /** * The {@link CacheResolverFactory} used to find the {@link CacheResolver} to * use at runtime. *

* The default resolver pair will resolve the cache by name from the default * {@link CacheManager} *

* Applicable for {@link CacheResult}, {@link CachePut}, {@link CacheRemove}, * and {@link CacheRemoveAll} */ @Nonbinding Class cacheResolverFactory() default CacheResolverFactory.class; /** * The {@link CacheKeyGenerator} to use to generate the * {@link GeneratedCacheKey} for interacting with the specified Cache. *

* Defaults to a key generator that uses {@link Arrays#deepHashCode(Object[])} * and {@link Arrays#deepEquals(Object[], Object[])} with the array returned by * {@link CacheKeyInvocationContext#getKeyParameters()} *

* Applicable for {@link CacheResult}, {@link CachePut}, and {@link CacheRemove} * * @see CacheKey */ @Nonbinding Class cacheKeyGenerator() default CacheKeyGenerator.class; } ================================================ FILE: src/main/java/javax/cache/annotation/CacheInvocationContext.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.lang.annotation.Annotation; /** * Runtime information about an intercepted method invocation for a method * annotated with {@link CacheResult}, {@link CachePut}, {@link CacheRemove}, * or {@link CacheRemoveAll} *

* Used with {@link CacheResolver#resolveCache(CacheInvocationContext)} to * determine the {@link javax.cache.Cache} to use at runtime for the method * invocation. * * @param The type of annotation this context information is for. One of * {@link CacheResult}, {@link CachePut}, {@link CacheRemove}, or {@link * CacheRemoveAll}. * @author Eric Dalquist * @see CacheResolver */ public interface CacheInvocationContext extends CacheMethodDetails { /** * @return The object the intercepted method was invoked on. */ Object getTarget(); /** * Returns a clone of the array of all method parameters. * * @return An array of all parameters for the annotated method */ CacheInvocationParameter[] getAllParameters(); /** * Return an object of the specified type to allow access to the * provider-specific API. If the provider's * implementation does not support the specified class, the {@link * IllegalArgumentException} is thrown. * * @param The type of the expected underlying {@link javax.cache.Cache} implementation. * @param cls the class of the object to be returned. This is normally either the * underlying implementation class or an interface that it implements. * @return an instance of the specified class * @throws IllegalArgumentException if the provider doesn't support the specified * class. */ T unwrap(java.lang.Class cls); } ================================================ FILE: src/main/java/javax/cache/annotation/CacheInvocationParameter.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.lang.annotation.Annotation; import java.util.Set; /** * A parameter to an intercepted method invocation. Contains the parameter value * as well static type and annotation information about the parameter. * * @author Eric Dalquist */ public interface CacheInvocationParameter { /** * The parameter type as declared on the method. */ Class getRawType(); /** * @return The parameter value */ Object getValue(); /** * @return An immutable Set of all Annotations on this method parameter, never * null. */ Set getAnnotations(); /** * The index of the parameter in the original parameter array as returned by * {@link CacheInvocationContext#getAllParameters()} * * @return The index of the parameter in the original parameter array. */ int getParameterPosition(); } ================================================ FILE: src/main/java/javax/cache/annotation/CacheKey.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks a method argument as part of the cache key. * If no arguments are marked all arguments are used. The exception is * for a method annotated with {@link CachePut} where the {@link CacheValue} * parameter is never included in the key * * @author Rick Hightower * @see CacheResult * @see CachePut * @see CacheRemove * @see CacheKeyInvocationContext#getKeyParameters() * @since 1.0 */ @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface CacheKey { } ================================================ FILE: src/main/java/javax/cache/annotation/CacheKeyGenerator.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.lang.annotation.Annotation; /** * Generates a {@link GeneratedCacheKey} based on * a {@link CacheKeyInvocationContext}. *

* Implementations must be thread-safe. * * @author Eric Dalquist * @since 1.0 */ public interface CacheKeyGenerator { /** * Called for each intercepted method invocation to generate a suitable * cache key (as a {@link GeneratedCacheKey}) from the * {@link CacheKeyInvocationContext} data. * * @param cacheKeyInvocationContext Information about the intercepted method invocation * @return A non-null cache key for the invocation. */ GeneratedCacheKey generateCacheKey(CacheKeyInvocationContext cacheKeyInvocationContext); } ================================================ FILE: src/main/java/javax/cache/annotation/CacheKeyInvocationContext.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.lang.annotation.Annotation; /** * Runtime information about an intercepted method invocation for a method * annotated with {@link CacheResult}, {@link CachePut}, or * {@link CacheRemove}. *

* Used with {@link CacheKeyGenerator#generateCacheKey(CacheKeyInvocationContext)} * to generate a {@link GeneratedCacheKey} for the invocation. * * @param The type of annotation this context information is for. One of * {@link CacheResult}, {@link CachePut}, or {@link CacheRemove}. * @author Eric Dalquist * @see CacheKeyGenerator */ public interface CacheKeyInvocationContext extends CacheInvocationContext { /** * Returns a clone of the array of all method parameters to be used by the * {@link * CacheKeyGenerator} in creating a {@link GeneratedCacheKey}. The returned array * may be the same as or a subset of the array returned by * {@link #getAllParameters()} *

* Parameters in this array are selected by the following rules: *

* * @return An array of all parameters to be used in cache key generation */ CacheInvocationParameter[] getKeyParameters(); /** * When a method is annotated with {@link CachePut} this is the parameter * annotated with {@link CacheValue} * * @return The parameter to cache, will never be null for methods annotated with * {@link CachePut}, will be null for methods not annotated with {@link * CachePut} */ CacheInvocationParameter getValueParameter(); } ================================================ FILE: src/main/java/javax/cache/annotation/CacheMethodDetails.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Set; /** * Static information about a method annotated with one of: * {@link CacheResult}, {@link CachePut}, {@link CacheRemove}, or {@link * CacheRemoveAll} *

* Used with {@link CacheResolverFactory#getCacheResolver(CacheMethodDetails)} to * determine the {@link CacheResolver} to use with the method. * * @param The type of annotation this context information is for. One of * {@link CacheResult}, {@link CachePut}, {@link CacheRemove}, or * {@link CacheRemoveAll}. * @author Eric Dalquist * @see CacheResolverFactory */ public interface CacheMethodDetails { /** * The annotated method * * @return The annotated method */ Method getMethod(); /** * An immutable Set of all Annotations on this method * * @return An immutable Set of all Annotations on this method */ Set getAnnotations(); /** * The caching related annotation on the method. * One of: {@link CacheResult}, {@link CachePut}, {@link CacheRemove}, or * {@link CacheRemoveAll} * * @return The caching related annotation on the method. */ A getCacheAnnotation(); /** * The cache name resolved by the implementation. *

* The cache name is determined by first looking at the cacheName attribute of * the method level annotation. If that attribute is not set then the class * level {@link CacheDefaults} annotation is checked. If that annotation does * not exist or does not have its cacheName attribute set then the following * cache name generation rules are followed: *

* "fully qualified class name"."method name"("fully qualified parameter class * names") *

* For example: *


   * package my.app;
   * 
   * public class DomainDao {
   *   @CacheResult
   *   public Domain getDomain(String domainId, int index) {
   *     ...
   *   }
   * }
   * 
*

* Results in the cache name: "my.app.DomainDao.getDomain(java.lang.String,int)" * * @return The fully resolved cache name */ String getCacheName(); } ================================================ FILE: src/main/java/javax/cache/annotation/CachePut.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import javax.cache.Cache; import javax.cache.CacheManager; import javax.enterprise.util.Nonbinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Arrays; /** * When a method annotated with {@link CachePut} is invoked a {@link * GeneratedCacheKey} will be generated and {@link Cache#put(Object, * Object)} will be invoked on the specified cache storing the value marked with * {@link CacheValue}. *

* The default behavior is to call {@link Cache#put(Object, Object)} * after the annotated method is invoked, this behavior can be changed by setting * {@link #afterInvocation()} to false in which case * {@link Cache#put(Object, Object)} will be called before the annotated method is * invoked. *

* Example of caching the Domain object with a key generated from the String and * int parameters. The {@link CacheValue} annotation is used to designate which * parameter should be stored in the "domainDao" cache. *


 * package my.app;
 * 
 * public class DomainDao {
 *   @CachePut(cacheName="domainCache")
 *   public void updateDomain(String domainId, int index, @CacheValue Domain
 * domain) {
 *     ...
 *   }
 * }
 * 
*

* Exception Handling, only used if {@link #afterInvocation()} is true. *

    *
  1. If {@link #cacheFor()} and {@link #noCacheFor()} are both empty then all * exceptions prevent the put
  2. *
  3. If {@link #cacheFor()} is specified and {@link #noCacheFor()} is not * specified then only exceptions that pass an instanceof check against the * cacheFor list result in a put
  4. *
  5. If {@link #noCacheFor()} is specified and {@link #cacheFor()} is not * specified then all exceptions that do not pass an instanceof check against the * noCacheFor result in a put
  6. *
  7. If {@link #cacheFor()} and {@link #noCacheFor()} are both specified then * exceptions that pass an instanceof check against the cacheFor list but do not * pass an instanceof check against the noCacheFor list result in a put
  8. *
* * @author Eric Dalquist * @author Rick Hightower * @see CacheValue * @see CacheKey * @since 1.0 */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface CachePut { /** * The name of the cache. *

* If not specified defaults first to {@link CacheDefaults#cacheName()} and if * that is not set it defaults to: * package.name.ClassName.methodName(package.ParameterType,package.ParameterType) */ @Nonbinding String cacheName() default ""; /** * When {@link Cache#put(Object, Object)} should be called. If true it is called * after the annotated method invocation completes successfully. If false it is * called before the annotated method is invoked. *

* Defaults to true. *

* If true and the annotated method throws an exception the rules governing * {@link #cacheFor()} and {@link #noCacheFor()} will be followed. */ @Nonbinding boolean afterInvocation() default true; /** * The {@link CacheResolverFactory} used to find the {@link CacheResolver} to * use at runtime. *

* The default resolver pair will resolve the cache by name from the default * {@link CacheManager} */ @Nonbinding Class cacheResolverFactory() default CacheResolverFactory.class; /** * The {@link CacheKeyGenerator} to use to generate the {@link * GeneratedCacheKey} for interacting with the specified Cache. *

* Defaults to a key generator that uses {@link Arrays#deepHashCode(Object[])} * and {@link Arrays#deepEquals(Object[], Object[])} with the array * returned by {@link CacheKeyInvocationContext#getKeyParameters()} * * @see CacheKey */ @Nonbinding Class cacheKeyGenerator() default CacheKeyGenerator.class; /** * Defines zero (0) or more exception {@link Class classes}, that must be a * subclass of {@link Throwable}, indicating the exception types that must * cause the parameter to be cached. Only used if {@link #afterInvocation()} is * true. */ @Nonbinding Class[] cacheFor() default {}; /** * Defines zero (0) or more exception {@link Class Classes}, which must be a * subclass of {@link Throwable}, indicating which exception types must * not cause the parameter to be cached. Only used if * {@link #afterInvocation()} is true. */ @Nonbinding Class[] noCacheFor() default {}; } ================================================ FILE: src/main/java/javax/cache/annotation/CacheRemove.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import javax.cache.Cache; import javax.cache.CacheManager; import javax.enterprise.util.Nonbinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * When a method annotated with {@link CacheRemove} is invoked a {@link * GeneratedCacheKey} will be generated and {@link Cache#remove(Object)} will be * invoked on the specified cache. *

* The default behavior is to call {@link Cache#remove(Object)} after * the annotated method is invoked, this behavior can be changed by setting * {@link #afterInvocation()} to false in which case * {@link Cache#remove(Object)} will be called before the annotated * method is invoked. *

* Example of removing a specific Domain object from the "domainCache". A {@link * GeneratedCacheKey} will be generated from the String and int parameters and * used to call {@link Cache#remove(Object)} after the deleteDomain * method completes successfully. *


 * package my.app;
 * 
 * public class DomainDao {
 *   @CacheRemove(cacheName="domainCache")
 *   public void deleteDomain(String domainId, int index) {
 *     ...
 *   }
 * }
 * 
*

* Exception Handling, only used if {@link #afterInvocation()} is true. *

    *
  1. If {@link #evictFor()} and {@link #noEvictFor()} are both empty then all * exceptions prevent the remove
  2. *
  3. If {@link #evictFor()} is specified and {@link #noEvictFor()} is not * specified then only exceptions that pass an instanceof check against the * evictFor list result in a remove
  4. *
  5. If {@link #noEvictFor()} is specified and {@link #evictFor()} is not * specified then all exceptions that do not pass an instanceof check against the * noEvictFor result in a remove
  6. *
  7. If {@link #evictFor()} and {@link #noEvictFor()} are both specified then * exceptions that pass an instanceof check against the evictFor list but do not * pass an instanceof check against the noEvictFor list result in a remove
  8. *
* * @author Eric Dalquist * @author Rick Hightower * @author Greg Luck * @see CacheKey * @since 1.0 */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface CacheRemove { /** * The name of the cache. *

* If not specified defaults first to {@link CacheDefaults#cacheName()}, * and if that is not set then to: * package.name.ClassName.methodName(package.ParameterType,package.ParameterType) */ @Nonbinding String cacheName() default ""; /** * When {@link Cache#remove(Object)} should be called. If true it is called * after the annotated method invocation completes successfully. If false it is * called before the annotated method is invoked. *

* Defaults to true. *

* If true and the annotated method throws an exception the remove will not be * executed. */ @Nonbinding boolean afterInvocation() default true; /** * The {@link CacheResolverFactory} used to find the {@link CacheResolver} to * use at runtime. *

* The default resolver pair will resolve the cache by name from the default * {@link CacheManager} */ @Nonbinding Class cacheResolverFactory() default CacheResolverFactory.class; /** * The {@link CacheKeyGenerator} to use to generate the {@link * GeneratedCacheKey} for interacting with the specified Cache. *

* Defaults to a key generator that uses * {@link java.util.Arrays#deepHashCode(Object[])} * and {@link java.util.Arrays#deepEquals(Object[], Object[])} with the array * returned by {@link CacheKeyInvocationContext#getKeyParameters()} * * @see CacheKey */ @Nonbinding Class cacheKeyGenerator() default CacheKeyGenerator.class; /** * Defines zero (0) or more exception {@link Class classes}, that must be a * subclass of {@link Throwable}, indicating the exception types that must cause * a cache eviction. Only used if {@link #afterInvocation()} is true. */ @Nonbinding Class[] evictFor() default {}; /** * Defines zero (0) or more exception {@link Class Classes}, that must be a * subclass of {@link Throwable}, indicating the exception types that must * not cause a cache eviction. Only used if {@link #afterInvocation()} is * true. */ @Nonbinding Class[] noEvictFor() default {}; } ================================================ FILE: src/main/java/javax/cache/annotation/CacheRemoveAll.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import javax.cache.Cache; import javax.cache.CacheManager; import javax.enterprise.util.Nonbinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * When a method annotated with {@link CacheRemoveAll} is invoked all elements in * the specified cache will be removed via the * {@link Cache#removeAll()} method *

* The default behavior is to call {@link Cache#removeAll()} after the * annotated method is invoked, this behavior can be changed by setting {@link * #afterInvocation()} to false in which case {@link Cache#removeAll()} * will be called before the annotated method is invoked. *

* Example of removing all Domain objects from the "domainCache". {@link * Cache#removeAll()} will be called after deleteAllDomains() returns * successfully. *


 * package my.app;
 * 
 * public class DomainDao {
 *   @CacheRemoveAll(cacheName="domainCache")
 *   public void deleteAllDomains() {
 *     ...
 *   }
 * }
 * 
*

* Exception Handling, only used if {@link #afterInvocation()} is true. *

    *
  1. If {@link #evictFor()} and {@link #noEvictFor()} are both empty then all * exceptions prevent the removeAll
  2. *
  3. If {@link #evictFor()} is specified and {@link #noEvictFor()} is not * specified then only exceptions that pass an instanceof check against the * evictFor list result in a removeAll
  4. *
  5. If {@link #noEvictFor()} is specified and {@link #evictFor()} is not * specified then all exceptions that do not pass an instanceof check against the * noEvictFor result in a removeAll
  6. *
  7. If {@link #evictFor()} and {@link #noEvictFor()} are both specified then * exceptions that pass an instanceof check against the evictFor list but do not * pass an instanceof check against the noEvictFor list result in a removeAll
  8. *
* * @author Eric Dalquist * @author Rick Hightower * @since 1.0 */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface CacheRemoveAll { /** * /** * The name of the cache. *

* If not specified defaults first to {@link CacheDefaults#cacheName()} and if * that is not set it defaults to: * package.name.ClassName.methodName(package.ParameterType,package.ParameterType) */ @Nonbinding String cacheName() default ""; /** * When {@link Cache#removeAll()} should be called. If true it is called after * the annotated method invocation completes successfully. If false it is called * before the annotated method is invoked. *

* Defaults to true. *

* If true and the annotated method throws an exception the removeAll will not be * executed. */ @Nonbinding boolean afterInvocation() default true; /** * The {@link CacheResolverFactory} used to find the {@link CacheResolver} to * use at runtime. *

* The default resolver pair will resolve the cache by name from the default * {@link CacheManager} */ @Nonbinding Class cacheResolverFactory() default CacheResolverFactory.class; /** * Defines zero (0) or more exception {@link Class classes}, that must be a * subclass of {@link Throwable}, indicating the exception types that must * cause a cache eviction. Only used if {@link #afterInvocation()} is true. */ @Nonbinding Class[] evictFor() default {}; /** * Defines zero (0) or more exception {@link Class Classes}, that must be a * subclass of {@link Throwable}, indicating the exception types that must * not cause a cache eviction. Only used if {@link #afterInvocation()} is * true. */ @Nonbinding Class[] noEvictFor() default {}; } ================================================ FILE: src/main/java/javax/cache/annotation/CacheResolver.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import javax.cache.Cache; import java.lang.annotation.Annotation; /** * Determines the {@link Cache} to use for an intercepted method invocation. *

* Implementations MUST be thread-safe. * * @author Eric Dalquist * @see CacheResolverFactory * @since 1.0 */ public interface CacheResolver { /** * Resolve the {@link Cache} to use for the {@link CacheInvocationContext}. * * @param the type of key * @param the type of value * @param cacheInvocationContext The context data for the intercepted method * invocation * @return The {@link Cache} instance to be used by the interceptor */ Cache resolveCache(CacheInvocationContext cacheInvocationContext); } ================================================ FILE: src/main/java/javax/cache/annotation/CacheResolverFactory.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import javax.cache.Cache; import java.lang.annotation.Annotation; /** * Determines the {@link CacheResolver} to use for an annotated method. The * {@link CacheResolver} will be retrieved once per annotated method. *

* Implementations MUST be thread-safe. * * @author Eric Dalquist * @since 1.0 */ public interface CacheResolverFactory { /** * Get the {@link CacheResolver} used at runtime for resolution of the * {@link Cache} for the {@link CacheResult}, {@link CachePut}, * {@link CacheRemove}, or {@link CacheRemoveAll} annotation. * * @param cacheMethodDetails The details of the annotated method to get the * {@link CacheResolver} for. @return The {@link * CacheResolver} instance to be * used by the interceptor. */ CacheResolver getCacheResolver(CacheMethodDetails cacheMethodDetails); /** * Get the {@link CacheResolver} used at runtime for resolution of the {@link * Cache} for the {@link CacheResult} annotation to cache exceptions. *

* Will only be called if {@link CacheResult#exceptionCacheName()} is not empty. * * @param cacheMethodDetails The details of the annotated method to get the * {@link CacheResolver} for. * @return The {@link CacheResolver} instance to be used by the interceptor. */ CacheResolver getExceptionCacheResolver(CacheMethodDetails cacheMethodDetails); } ================================================ FILE: src/main/java/javax/cache/annotation/CacheResult.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import javax.cache.Cache; import javax.cache.CacheManager; import javax.enterprise.util.Nonbinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * When a method annotated with {@link CacheResult} is invoked a * {@link GeneratedCacheKey} will be generated and {@link Cache#get(Object)} is * called before the annotated method actually executes. If a value is found in the * cache it is returned and the annotated method is never actually executed. If no * value is found the annotated method is invoked and the returned value is stored * in the cache with the generated key. *

* Exceptions are not cached by default. Caching of exceptions can be enabled by * specifying an {@link #exceptionCacheName()}. If an exception cache is specified * it is checked before invoking the annotated method and if a cached exception is * found it is re-thrown. *

* The {@link #cachedExceptions()} and {@link #nonCachedExceptions()} properties * can be used to control the exceptions are cached and those that are not. *

* To always invoke the annotated method and still cache the result set * {@link #skipGet()} to true. This will disable the pre-invocation * {@link Cache#get(Object)} call. If {@link #exceptionCacheName()} is * specified the pre-invocation exception check is also disabled. This feature is * useful for methods that create or update objects to be cached. *

* Example of caching the Domain object with a key generated from the * String and int parameters. *

* With no {@link #cacheName()} specified a cache name of * "my.app.DomainDao.getDomain(java.lang.String,int)" will be generated. *

*

 * package my.app;
 * 
 * public class DomainDao {
 *   @CacheResult
 *   public Domain getDomain(String domainId, int index) {
 *     ...
 *   }
 * }
 * 
*

* Example using the {@link GeneratedCacheKey} annotation so that only the domainId * parameter is used in key generation: *


 * package my.app;
 * 
 * public class DomainDao {
 *   @CacheResult
 *   public Domain getDomain(@CacheKey String domainId, Monitor mon) {
 *     ...
 *   }
 * }
 * 
*

* If exception caching is enabled via specification of * {@link #exceptionCacheName()} the following rules are used to determine if a * thrown exception is cached: *

    *
  1. If {@link #cachedExceptions()} and {@link #nonCachedExceptions()} are both * empty then all exceptions are cached
  2. *
  3. If {@link #cachedExceptions()} is specified and * {@link #nonCachedExceptions()} is not specified then only exceptions * that pass an instanceof check against the cachedExceptions list are cached
  4. *
  5. If {@link #nonCachedExceptions()} is specified and * {@link #cachedExceptions()} is not specified then all exceptions * that do not pass an instanceof check against the nonCachedExceptions list are * cached
  6. *
  7. If {@link #cachedExceptions()} and {@link #nonCachedExceptions()} are both * specified then exceptions that pass an instanceof check against the * cachedExceptions list but do not pass an instanceof check against the * nonCachedExceptions list are cached
  8. *
* * @author Eric Dalquist * @author Rick Hightower * @see CacheKey * @since 1.0 */ @Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface CacheResult { /** *

* The name of the cache. *

* If not specified defaults first to {@link CacheDefaults#cacheName()} and if * that is not set it defaults to: * package.name.ClassName.methodName(package.ParameterType,package.ParameterType) */ @Nonbinding String cacheName() default ""; /** * If set to true the pre-invocation {@link Cache#get(Object)} is * skipped and the annotated method is always executed with the returned value * being cached as normal. This is useful for create or update methods that * should always be executed and have their returned value placed in the cache. *

* If true and an {@link #exceptionCacheName()} is specified the pre-invocation * check for a thrown exception is also skipped. If an exception is thrown during * invocation it will be cached following the standard exception caching rules. *

* Defaults to false. * * @see CachePut */ @Nonbinding boolean skipGet() default false; /** * The {@link CacheResolverFactory} used to find the {@link CacheResolver} to * use at runtime. *

* The default resolver pair will resolve the cache by name from the default * {@link CacheManager} */ @Nonbinding Class cacheResolverFactory() default CacheResolverFactory.class; /** * The {@link CacheKeyGenerator} to use to generate the {@link GeneratedCacheKey} * for interacting with the specified Cache. *

* Defaults to a key generator that uses * {@link java.util.Arrays#deepHashCode(Object[])} and * {@link java.util.Arrays#deepEquals(Object[], Object[])} with the array * returned by {@link CacheKeyInvocationContext#getKeyParameters()} * * @see CacheKey */ @Nonbinding Class cacheKeyGenerator() default CacheKeyGenerator.class; /** * The name of the cache to cache exceptions. *

* If not specified no exception caching is done. */ @Nonbinding String exceptionCacheName() default ""; /** * Defines zero (0) or more exception {@link Class classes}, that must be a * subclass of {@link Throwable}, indicating the exception types that * must be cached. Only consulted if {@link #exceptionCacheName()} is * specified. */ @Nonbinding Class[] cachedExceptions() default {}; /** * Defines zero (0) or more exception {@link Class Classes}, that must be a * subclass of {@link Throwable}, indicating the exception types that * must not be cached. Only consulted if {@link #exceptionCacheName()} * is specified. */ @Nonbinding Class[] nonCachedExceptions() default {}; } ================================================ FILE: src/main/java/javax/cache/annotation/CacheValue.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks the parameter to be cached for a method annotated with {@link CachePut}. * * @author Eric Dalquist * @author Rick Hightower * @see CachePut * @since 1.0 */ @Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) public @interface CacheValue { } ================================================ FILE: src/main/java/javax/cache/annotation/GeneratedCacheKey.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.annotation; import java.io.Serializable; /** * A {@link Serializable}, immutable, thread-safe object that is used as a key, * automatically generated by a {@link CacheKeyGenerator}. *

* The implementation MUST follow the Java contract for {@link Object#hashCode()} * and {@link Object#equals(Object)} to ensure correct behavior. *

* It is recommended that implementations also override {@link Object#toString()} * and provide a human-readable string representation of the key. * * @author Eric Dalquist * @see CacheKeyGenerator * @since 1.0 */ public interface GeneratedCacheKey extends Serializable { /** * The immutable hash code of the cache key. * * @return The hash code of the object * @see Object#hashCode() */ @Override int hashCode(); /** * Compare this {@link GeneratedCacheKey} with another. If the two objects * are equal their {@link #hashCode()} values MUST be equal as well. * * @param object The other object to compare to. * @return true if the objects are equal * @see Object#equals(Object) */ @Override boolean equals(Object object); } ================================================ FILE: src/main/java/javax/cache/annotation/package-info.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ /** * The annotations in this package provide method interceptors for user supplied * classes. *

* In the case of a the {@link javax.cache.annotation.CacheResult} annotation, * if the cache can satisfy the request a result is returned by the method from * cache, not from method execution. For the mutative annotations such as * {@link javax.cache.annotation.CacheResult} the annotation allows the cached * value to be mutated so that it will be correct the next time * {@link javax.cache.annotation.CacheResult} is used. *

* Any operations against a cache via an annotation will have the same behaviour * as if the {@link javax.cache.annotation.CacheResult} methods were used. So * if the same underlying cache is used for an annotation and a direct API call, * the same data would be returned. Annotations therefore provide an additional * API for interacting with caches. *

* To use these annotations you'll need a library or framework that processes * these annotations and intercepts calls to your application objects * to provide the caching behaviour. This would commonly be provided by a * dependency injection framework such as defined by CDI in Java EE. * * @author Eric Dalquist * @author Greg Luck * @since 1.0 */ package javax.cache.annotation; ================================================ FILE: src/main/java/javax/cache/configuration/CacheEntryListenerConfiguration.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; import javax.cache.event.CacheEntryEventFilter; import javax.cache.event.CacheEntryListener; import java.io.Serializable; /** * Defines the configuration requirements for a * {@link CacheEntryListener} and a {@link Factory} for its * creation. * * @param the type of keys * @param the type of values * @author Brian Oliver * @author Greg Luck * @since 1.0 */ public interface CacheEntryListenerConfiguration extends Serializable { /** * Obtains the {@link Factory} for the * {@link CacheEntryListener}. * * @return the {@link Factory} for the * {@link CacheEntryListener} */ Factory> getCacheEntryListenerFactory(); /** * Determines if the old value should be provided to the * {@link CacheEntryListener}. * * @return true if the old value is required by the * {@link CacheEntryListener} */ boolean isOldValueRequired(); /** * Obtains the {@link Factory} for the {@link CacheEntryEventFilter} that should be * applied prior to notifying the {@link CacheEntryListener}. *

* When null no filtering is applied and all appropriate events * are notified. * * @return the {@link Factory} for the * {@link CacheEntryEventFilter} or null * if no filtering is required */ Factory> getCacheEntryEventFilterFactory(); /** * Determines if the thread that caused an event to be created should be * blocked (not return from the operation causing the event) until the * {@link CacheEntryListener} has been notified. * * @return true if the thread that created the event should block */ boolean isSynchronous(); } ================================================ FILE: src/main/java/javax/cache/configuration/CompleteConfiguration.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; import javax.cache.expiry.ExpiryPolicy; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheWriter; import java.io.Serializable; /** * A read-only representation of the complete JCache {@link javax.cache.Cache} * configuration. *

* The properties provided by instances of this interface are used by * {@link javax.cache.CacheManager}s to configure {@link javax.cache.Cache}s. *

* Implementations of this interface must override {@link Object#hashCode()} and * {@link Object#equals(Object)} as * {@link javax.cache.configuration.CompleteConfiguration}s are often compared at * runtime. * * @param the type of keys maintained the cache * @param the type of cached values * @author Greg Luck * @author Yannis Cosmadopoulos * @author Brian Oliver * @since 1.0 */ public interface CompleteConfiguration extends Configuration, Serializable { /** * Determines if a {@link javax.cache.Cache} should operate in read-through mode. *

* When in "read-through" mode, cache misses that occur due to cache entries * not existing as a result of performing a "get" will appropriately * cause the configured {@link javax.cache.integration.CacheLoader} to be * invoked. *

* The default value is false. * * @return true when a {@link javax.cache.Cache} is in * "read-through" mode. * @see #getCacheLoaderFactory() */ boolean isReadThrough(); /** * Determines if a {@link javax.cache.Cache} should operate in write-through * mode. *

* When in "write-through" mode, cache updates that occur as a result of * performing "put" operations called via one of * {@link javax.cache.Cache#put(Object, Object)}, * {@link javax.cache.Cache#getAndRemove(Object)}, * {@link javax.cache.Cache#removeAll()}, * {@link javax.cache.Cache#getAndPut(Object, Object)} * {@link javax.cache.Cache#getAndRemove(Object)}, * {@link javax.cache.Cache#getAndReplace(Object, * Object)}, {@link javax.cache.Cache#invoke(Object, * javax.cache.processor.EntryProcessor, * Object...)}, {@link javax.cache.Cache#invokeAll(java.util.Set, * javax.cache.processor.EntryProcessor, Object...)} will appropriately cause * the configured {@link javax.cache.integration.CacheWriter} to be invoked. *

* The default value is false. * * @return true when a {@link javax.cache.Cache} is in * "write-through" mode. * @see #getCacheWriterFactory() */ boolean isWriteThrough(); /** * Checks whether statistics collection is enabled in this cache. *

* The default value is false. * * @return true if statistics collection is enabled */ boolean isStatisticsEnabled(); /** * Checks whether management is enabled on this cache. *

* The default value is false. * * @return true if management is enabled */ boolean isManagementEnabled(); /** * Obtains the {@link javax.cache.configuration.CacheEntryListenerConfiguration}s * for {@link javax.cache.event.CacheEntryListener}s to be configured on a * {@link javax.cache.Cache}. * * @return an {@link Iterable} over the * {@link javax.cache.configuration.CacheEntryListenerConfiguration}s */ Iterable> getCacheEntryListenerConfigurations(); /** * Gets the {@link javax.cache.configuration.Factory} for the * {@link javax.cache.integration.CacheLoader}, if any. *

* A CacheLoader should be configured for "Read Through" caches to load values * when a cache miss occurs using either the * {@link javax.cache.Cache#get(Object)} and/or * {@link javax.cache.Cache#getAll(java.util.Set)} methods. *

* The default value is null. * * @return the {@link javax.cache.configuration.Factory} for the * {@link javax.cache.integration.CacheLoader} or null if none has been set. */ Factory> getCacheLoaderFactory(); /** * Gets the {@link javax.cache.configuration.Factory} for the * {@link javax.cache.integration.CacheWriter}, if any. *

* The default value is null. * * @return the {@link javax.cache.configuration.Factory} for the * {@link javax.cache.integration.CacheWriter} or null if none has been set. */ Factory> getCacheWriterFactory(); /** * Gets the {@link javax.cache.configuration.Factory} for the * {@link javax.cache.expiry.ExpiryPolicy} to be used for caches. *

* The default value is a {@link javax.cache.configuration.Factory} that will * produce a {@link javax.cache.expiry.EternalExpiryPolicy} instance. * * @return the {@link javax.cache.configuration.Factory} for * {@link javax.cache.expiry.ExpiryPolicy} (must not be null) */ Factory getExpiryPolicyFactory(); } ================================================ FILE: src/main/java/javax/cache/configuration/Configuration.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; import javax.cache.Cache; import javax.cache.CacheManager; import java.io.Serializable; /** * A basic read-only representation of a {@link Cache} configuration. *

* The properties provided by instances of this interface are used by * {@link CacheManager}s to configure {@link Cache}s. *

* Implementations of this interface must override {@link Object#hashCode()} and * {@link Object#equals(Object)} as {@link Configuration}s are often compared at * runtime. * * @param the type of keys maintained the cache * @param the type of cached values * @author Greg Luck * @author Brian Oliver * @since 1.0 */ public interface Configuration extends Serializable { /** * Determines the required type of keys for {@link Cache}s configured * with this {@link Configuration}. * * @return the key type or Object.class if the type is undefined */ Class getKeyType(); /** * Determines the required type of values for {@link Cache}s configured * with this {@link Configuration}. * * @return the value type or Object.class if the type is undefined */ Class getValueType(); /** * Whether storeByValue (true) or storeByReference (false). * When true, both keys and values are stored by value. *

* When false, both keys and values are stored by reference. * Caches stored by reference are capable of mutation by any threads holding * the reference. The effects are: *

    *
  • if the key is mutated, then the key may not be retrievable or * removable
  • *
  • if the value is mutated, then all threads in the JVM can potentially * observe those mutations, subject to the normal Java Memory Model rules.
  • *
* Storage by reference only applies to the local heap. If an entry is moved off * heap it will need to be transformed into a representation. Any mutations that * occur after transformation may not be reflected in the cache. *

* When a cache is storeByValue, any mutation to the key or value does not * affect the key of value stored in the cache. *

* The default value is true. * * @return true if the cache is store by value */ boolean isStoreByValue(); } ================================================ FILE: src/main/java/javax/cache/configuration/Factory.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; import java.io.Serializable; /** * Constructs and returns a fully configured instance of a specific factory type. *

* Implementations may choose not to construct a new instance, but instead * return a previously created instance. *

* Implementations must correctly implement {@link Object#equals(Object)} and * {@link Object#hashCode()} as {@link Factory}s are often compared with each * other for equivalence. * * @param the type of factory constructed * @author Brian Oliver * @since 1.0 */ public interface Factory extends Serializable { /** * Constructs and returns a fully configured instance of T. * * @return an instance of T. */ T create(); } ================================================ FILE: src/main/java/javax/cache/configuration/FactoryBuilder.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; import java.io.Serializable; /** * A convenience class that defines generically typed static methods to aid in * the building of {@link Factory} instances. *

* {@link Factory} is used by {@link MutableConfiguration} to avoid adding * non-Serializable instances that would assume usage in the local JVM. *

* Two styles of builder are available: *

    *
  • those taking a Class or className. A new instance will be created by * the {@link Factory} *
  • *
  • those taking a Serializable instance. That instance will be created * by the {@link Factory}. As the instance is Serializable it no assumption of * usage in the local JVM is implied. *
  • *
* * Factory instances can also be created in other ways. * * @author Brian Oliver * @author Greg Luck * @since 1.0 */ public final class FactoryBuilder { /** * A private constructor to prevent instantiation. */ private FactoryBuilder() { //deliberately empty - no instances allowed! } /** * Constructs a {@link Factory} that will produce factory instances of the * specified class. *

* The specified class must have a no-args constructor. * * @param clazz the class of instances to be produced by the returned * {@link Factory} * @param the type of the instances produced by the {@link Factory} * @return a {@link Factory} for the specified clazz */ public static Factory factoryOf(Class clazz) { return new ClassFactory(clazz); } /** * Constructs a {@link Factory} that will produce factory instances of the * specified class. *

* The specified class must have a no-args constructor. * * @param className the class of instances to be produced by the returned * {@link Factory} * @param the type of the instances produced by the {@link Factory} * @return a {@link Factory} for the specified clazz */ public static Factory factoryOf(String className) { return new ClassFactory(className); } /** * Constructs a {@link Factory} that will return the specified factory * Serializable instance. *

* If T is not Serializable use {@link #factoryOf(Class)} or * {@link #factoryOf(String)}. * * @param instance the Serializable instance the {@link Factory} will return * @param the type of the instances returned * @return a {@link Factory} for the instance */ public static Factory factoryOf(T instance) { return new SingletonFactory(instance); } /** * A {@link Factory} that instantiates a specific Class. * * @param the type of the instance produced by the {@link Factory} */ public static class ClassFactory implements Factory, Serializable { /** * The serialVersionUID required for {@link Serializable}. */ public static final long serialVersionUID = 201305101626L; /** * The name of the Class. */ private String className; /** * Constructor for the {@link ClassFactory}. * * @param clazz the Class to instantiate */ public ClassFactory(Class clazz) { this.className = clazz.getName(); } /** * Constructor for the {@link ClassFactory}. * * @param className the name of the Class to instantiate */ public ClassFactory(String className) { this.className = className; } @Override public T create() { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class clazz = loader.loadClass(className); return (T) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException("Failed to create an instance of " + className, e); } } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ClassFactory that = (ClassFactory) other; if (!className.equals(that.className)) return false; return true; } @Override public int hashCode() { return className.hashCode(); } } /** * A {@link Factory} that always returns a specific instance. ie: the * factory returns a singleton, regardless of the number of times * {@link Factory#create()} is called. * * @param the type of the instance produced by the {@link Factory} */ public static class SingletonFactory implements Factory, Serializable { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201305101634L; /** * The singleton instance. */ private T instance; /** * Constructor for the {@link SingletonFactory}. * * @param instance the instance to return */ public SingletonFactory(T instance) { this.instance = instance; } @Override public T create() { return instance; } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; SingletonFactory that = (SingletonFactory) other; if (!instance.equals(that.instance)) return false; return true; } @Override public int hashCode() { return instance.hashCode(); } } } ================================================ FILE: src/main/java/javax/cache/configuration/MutableCacheEntryListenerConfiguration.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; import javax.cache.event.CacheEntryEventFilter; import javax.cache.event.CacheEntryListener; /** * A convenience class providing a mutable, serializable implementation of a * {@link CacheEntryListenerConfiguration}. * * @param the type of keys maintained the cache * @param the type of cached values * @author Brian Oliver * @since 1.0 */ public class MutableCacheEntryListenerConfiguration implements CacheEntryListenerConfiguration { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201306200822L; /** * The {@link Factory} to be used to create the {@link CacheEntryListener}. */ private Factory> listenerFactory; /** * The {@link Factory} to be used to create the {@link CacheEntryEventFilter}. * (may be null if no filtering is required) */ private Factory> filterFactory; /** * Is the old value required to be provide to the {@link CacheEntryListener}? */ private boolean isOldValueRequired; /** * Should the {@link CacheEntryListener} be notified as part of an operation * or is asynchronous delivery acceptable? */ private boolean isSynchronous; /** * Constructs a {@link MutableCacheEntryListenerConfiguration} based on * another {@link CacheEntryListenerConfiguration}. * * @param configuration the {@link CacheEntryListenerConfiguration} */ public MutableCacheEntryListenerConfiguration(CacheEntryListenerConfiguration configuration) { this.listenerFactory = configuration.getCacheEntryListenerFactory(); this.filterFactory = configuration.getCacheEntryEventFilterFactory(); this.isOldValueRequired = configuration.isOldValueRequired(); this.isSynchronous = configuration.isSynchronous(); } /** * Constructs a {@link MutableCacheEntryListenerConfiguration}. * * @param listenerFactory the {@link CacheEntryListener} {@link Factory} * @param filterFactory the optional {@link CacheEntryEventFilter} {@link Factory} * @param isOldValueRequired if the old value is required for events with this listenerFactory * @param isSynchronous if the listenerFactory should block the thread causing the event */ public MutableCacheEntryListenerConfiguration(Factory> listenerFactory, Factory> filterFactory, boolean isOldValueRequired, boolean isSynchronous) { this.listenerFactory = (Factory>) listenerFactory; this.filterFactory = (Factory>) filterFactory; this.isOldValueRequired = isOldValueRequired; this.isSynchronous = isSynchronous; } /** * {@inheritDoc} */ @Override public Factory> getCacheEntryListenerFactory() { return listenerFactory; } /** * Sets the {@link Factory} to be used to create a {@link CacheEntryListener}. * * @param listenerFactory the {@link Factory} * @return the {@link MutableCacheEntryListenerConfiguration} to permit * fluent-style method calls */ public MutableCacheEntryListenerConfiguration setCacheEntryListenerFactory( Factory> listenerFactory) { this.listenerFactory = (Factory>) listenerFactory; return this; } /** * {@inheritDoc} */ @Override public Factory> getCacheEntryEventFilterFactory() { return filterFactory; } /** * Sets the {@link Factory} to be used to create a {@link CacheEntryEventFilter}. * * @param filterFactory the {@link Factory}, or null if event * filtering is not requried * @return the {@link MutableCacheEntryListenerConfiguration} to permit * fluent-style method calls */ public MutableCacheEntryListenerConfiguration setCacheEntryEventFilterFactory( Factory> filterFactory) { this.filterFactory = (Factory>) filterFactory; return this; } /** * {@inheritDoc} */ @Override public boolean isOldValueRequired() { return isOldValueRequired; } /** * Sets if the old value should be provided to the {@link CacheEntryListener}. * * @param isOldValueRequired true if the old value is required * @return the {@link MutableCacheEntryListenerConfiguration} to permit * fluent-style method calls */ public MutableCacheEntryListenerConfiguration setOldValueRequired( boolean isOldValueRequired) { this.isOldValueRequired = isOldValueRequired; return this; } /** * {@inheritDoc} */ @Override public boolean isSynchronous() { return isSynchronous; } /** * Sets if the thread that causes an event should be blocked * (not return from the operation causing the event) until the * {@link CacheEntryListener} has been notified. * * @param isSynchronous true means block until notified * @return the {@link MutableCacheEntryListenerConfiguration} to permit * fluent-style method calls */ public MutableCacheEntryListenerConfiguration setSynchronous( boolean isSynchronous) { this.isSynchronous = isSynchronous; return this; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((filterFactory == null) ? 0 : filterFactory.hashCode()); result = prime * result + (isOldValueRequired ? 1231 : 1237); result = prime * result + (isSynchronous ? 1231 : 1237); result = prime * result + ((listenerFactory == null) ? 0 : listenerFactory.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!(object instanceof MutableCacheEntryListenerConfiguration)) { return false; } MutableCacheEntryListenerConfiguration other = (MutableCacheEntryListenerConfiguration) object; if (filterFactory == null) { if (other.filterFactory != null) { return false; } } else if (!filterFactory.equals(other.filterFactory)) { return false; } if (isOldValueRequired != other.isOldValueRequired) { return false; } if (isSynchronous != other.isSynchronous) { return false; } if (listenerFactory == null) { if (other.listenerFactory != null) { return false; } } else if (!listenerFactory.equals(other.listenerFactory)) { return false; } return true; } } ================================================ FILE: src/main/java/javax/cache/configuration/MutableConfiguration.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.event.CacheEntryListener; import javax.cache.expiry.EternalExpiryPolicy; import javax.cache.expiry.ExpiryPolicy; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheWriter; import java.util.HashSet; /** * A simple mutable implementation of a {@link Configuration}. * * @param the type of keys maintained the cache * @param the type of cached values * @author Brian Oliver * @author Greg Luck * @since 1.0 */ public class MutableConfiguration implements CompleteConfiguration { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201306200821L; /** * The type of keys for {@link Cache}s configured with this * {@link Configuration}. */ protected Class keyType; /** * The type of values for {@link Cache}s configured with this * {@link Configuration}. */ protected Class valueType; /** * The {@link CacheEntryListenerConfiguration}s for the {@link Configuration}. */ protected HashSet> listenerConfigurations; /** * The {@link Factory} for the {@link CacheLoader}. */ protected Factory> cacheLoaderFactory; /** * The {@link Factory} for the {@link CacheWriter}. */ protected Factory> cacheWriterFactory; /** * The {@link Factory} for the {@link ExpiryPolicy}. */ protected Factory expiryPolicyFactory; /** * A flag indicating if "read-through" mode is required. */ protected boolean isReadThrough; /** * A flag indicating if "write-through" mode is required. */ protected boolean isWriteThrough; /** * A flag indicating if statistics gathering is enabled. */ protected boolean isStatisticsEnabled; /** * A flag indicating if the cache will be store-by-value or store-by-reference. */ protected boolean isStoreByValue; /** * Whether management is enabled */ protected boolean isManagementEnabled; /** * Default JavaBean constructor. *

* Creates a default configuration. Default configurations have no * runtime type checking and are set for eternal expiry. *

* To enable runtime type enforcement, if supported by the implementation, call * {@link #setTypes} after construction. *

* After construction set any other configuration parameters in the * fluent style. e.g. *

*
{@code
   * CacheConfiguration = new MutableConfiguration()
   *             .setTypes(Integer.class, String.class)
   *             .setReadThrough(true)
   *             . . .
   * }
* @see #setTypes(Class, Class) */ public MutableConfiguration() { //Due to erasure in generics the type will always be Object.class. i.e. cast is ignored this.keyType = (Class)Object.class; //Due to erasure in generics the type will always be Object.class. i.e. cast is ignored this.valueType = (Class)Object.class; this.listenerConfigurations = new HashSet>(); this.cacheLoaderFactory = null; this.cacheWriterFactory = null; this.expiryPolicyFactory = EternalExpiryPolicy.factoryOf(); this.isReadThrough = false; this.isWriteThrough = false; this.isStatisticsEnabled = false; this.isStoreByValue = true; this.isManagementEnabled = false; } /** * Constructs a {@link MutableConfiguration} based on another * {@link CompleteConfiguration}. * * @param configuration the {@link CompleteConfiguration} */ public MutableConfiguration(CompleteConfiguration configuration) { this.keyType = configuration.getKeyType(); this.valueType = configuration.getValueType(); listenerConfigurations = new HashSet>(); for (CacheEntryListenerConfiguration definition : configuration .getCacheEntryListenerConfigurations()) { addCacheEntryListenerConfiguration(definition); } this.cacheLoaderFactory = configuration.getCacheLoaderFactory(); this.cacheWriterFactory = configuration.getCacheWriterFactory(); if (configuration.getExpiryPolicyFactory() == null) { this.expiryPolicyFactory = EternalExpiryPolicy.factoryOf(); } else { this.expiryPolicyFactory = configuration.getExpiryPolicyFactory(); } this.isReadThrough = configuration.isReadThrough(); this.isWriteThrough = configuration.isWriteThrough(); this.isStatisticsEnabled = configuration.isStatisticsEnabled(); this.isStoreByValue = configuration.isStoreByValue(); this.isManagementEnabled = configuration.isManagementEnabled(); } /** * {@inheritDoc} */ @Override public Class getKeyType() { return keyType; } /** * {@inheritDoc} */ @Override public Class getValueType() { return valueType; } /** * Sets the expected type of keys and values for a {@link Cache} * configured with this {@link Configuration}. Setting both to * Object.class means type-safety checks are not required. *

* This is used by {@link CacheManager} to ensure that the key and value * types are the same as those configured for the {@link Cache} prior to * returning a requested cache from this method. *

* Implementations may further perform type checking on mutative cache operations * and throw a {@link ClassCastException} if these checks fail. * * @param keyType the expected key type * @param valueType the expected value type * @return the {@link MutableConfiguration} to permit fluent-style method calls * @throws NullPointerException should the key or value type be null * @see CacheManager#getCache(String, Class, Class) */ public MutableConfiguration setTypes(Class keyType, Class valueType) { if (keyType == null || valueType == null) { throw new NullPointerException("keyType and/or valueType can't be null"); } else { this.keyType = keyType; this.valueType = valueType; return this; } } /** * {@inheritDoc} */ @Override public Iterable> getCacheEntryListenerConfigurations() { return listenerConfigurations; } /** * Add a configuration for a {@link CacheEntryListener}. * * @param cacheEntryListenerConfiguration the * {@link CacheEntryListenerConfiguration} * @return the {@link MutableConfiguration} to permit fluent-style method calls * @throws IllegalArgumentException is the same CacheEntryListenerConfiguration * is used more than once */ public MutableConfiguration addCacheEntryListenerConfiguration( CacheEntryListenerConfiguration cacheEntryListenerConfiguration) { if (cacheEntryListenerConfiguration == null) { throw new NullPointerException("CacheEntryListenerConfiguration can't be null"); } boolean alreadyExists = false; for (CacheEntryListenerConfiguration c : listenerConfigurations) { if (c.equals(cacheEntryListenerConfiguration)) { alreadyExists = true; } } if (!alreadyExists) { this.listenerConfigurations.add(cacheEntryListenerConfiguration); } else { throw new IllegalArgumentException("A CacheEntryListenerConfiguration can " + "be registered only once"); } return this; } /** * Remove a configuration for a {@link CacheEntryListener}. * * @param cacheEntryListenerConfiguration the * {@link CacheEntryListenerConfiguration} to remove * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration removeCacheEntryListenerConfiguration( CacheEntryListenerConfiguration cacheEntryListenerConfiguration) { if (cacheEntryListenerConfiguration == null) { throw new NullPointerException("CacheEntryListenerConfiguration can't be null"); } listenerConfigurations.remove(cacheEntryListenerConfiguration); return this; } /** * {@inheritDoc} */ @Override public Factory> getCacheLoaderFactory() { return this.cacheLoaderFactory; } /** * Set the {@link CacheLoader} factory. * * @param factory the {@link CacheLoader} {@link Factory} * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setCacheLoaderFactory(Factory> factory) { this.cacheLoaderFactory = (Factory>) factory; return this; } /** * {@inheritDoc} */ @Override public Factory> getCacheWriterFactory() { return this.cacheWriterFactory; } /** * Set the {@link CacheWriter} factory. * * @param factory the {@link CacheWriter} {@link Factory} * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setCacheWriterFactory(Factory> factory) { this.cacheWriterFactory = (Factory>) factory; return this; } /** * {@inheritDoc} */ public Factory getExpiryPolicyFactory() { return this.expiryPolicyFactory; } /** * Set the {@link Factory} for the {@link ExpiryPolicy}. If null * is specified the default {@link ExpiryPolicy} is used. *

* Only one expiry policy can be set for a cache. The last policy applied * before cache construction will be the one used. * @param factory the {@link ExpiryPolicy} {@link Factory} * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setExpiryPolicyFactory(Factory factory) { if (factory == null) { this.expiryPolicyFactory = EternalExpiryPolicy.factoryOf(); } else { this.expiryPolicyFactory = (Factory) factory; } return this; } /** * {@inheritDoc} */ @Override public boolean isReadThrough() { return this.isReadThrough; } /** * Set if read-through caching should be used. *

* It is an invalid configuration to set this to true without specifying a * {@link CacheLoader} {@link Factory}. * * @param isReadThrough true if read-through is required * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setReadThrough(boolean isReadThrough) { this.isReadThrough = isReadThrough; return this; } /** * {@inheritDoc} */ @Override public boolean isWriteThrough() { return this.isWriteThrough; } /** * Set if write-through caching should be used. *

* It is an invalid configuration to set this to true without specifying a * {@link CacheWriter} {@link Factory}. * * @param isWriteThrough true if write-through is required * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setWriteThrough(boolean isWriteThrough) { this.isWriteThrough = isWriteThrough; return this; } /** * {@inheritDoc} */ @Override public boolean isStoreByValue() { return this.isStoreByValue; } /** * Set if a configured cache should use store-by-value or store-by-reference * semantics. * * @param isStoreByValue true if store-by-value is required, * false for store-by-reference * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setStoreByValue(boolean isStoreByValue) { this.isStoreByValue = isStoreByValue; return this; } /** * {@inheritDoc} */ @Override public boolean isStatisticsEnabled() { return this.isStatisticsEnabled; } /** * Sets whether statistics gathering is enabled on a cache. *

* Statistics may be enabled or disabled at runtime via * {@link CacheManager#enableStatistics(String, boolean)}. * * @param enabled true to enable statistics, false to disable. * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setStatisticsEnabled(boolean enabled) { this.isStatisticsEnabled = enabled; return this; } /** * {@inheritDoc} */ @Override public boolean isManagementEnabled() { return this.isManagementEnabled; } /** * Sets whether management is enabled on a cache. *

* Management may be enabled or disabled at runtime via * {@link CacheManager#enableManagement(String, boolean)}. * * @param enabled true to enable statistics, false to disable. * @return the {@link MutableConfiguration} to permit fluent-style method calls */ public MutableConfiguration setManagementEnabled(boolean enabled) { this.isManagementEnabled = enabled; return this; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + keyType.hashCode(); result = prime * result + valueType.hashCode(); result = prime * result + ((listenerConfigurations == null) ? 0 : listenerConfigurations .hashCode()); result = prime * result + ((cacheLoaderFactory == null) ? 0 : cacheLoaderFactory.hashCode()); result = prime * result + ((cacheWriterFactory == null) ? 0 : cacheWriterFactory.hashCode()); result = prime * result + ((expiryPolicyFactory == null) ? 0 : expiryPolicyFactory.hashCode()); result = prime * result + (isReadThrough ? 1231 : 1237); result = prime * result + (isStatisticsEnabled ? 1231 : 1237); result = prime * result + (isStoreByValue ? 1231 : 1237); result = prime * result + (isWriteThrough ? 1231 : 1237); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!(object instanceof MutableConfiguration)) { return false; } MutableConfiguration other = (MutableConfiguration) object; if (!keyType.equals(other.keyType)) { return false; } if (!valueType.equals(other.valueType)) { return false; } if (!listenerConfigurations.equals(other.listenerConfigurations)) { return false; } if (cacheLoaderFactory == null) { if (other.cacheLoaderFactory != null) { return false; } } else if (!cacheLoaderFactory.equals(other.cacheLoaderFactory)) { return false; } if (cacheWriterFactory == null) { if (other.cacheWriterFactory != null) { return false; } } else if (!cacheWriterFactory.equals(other.cacheWriterFactory)) { return false; } if (expiryPolicyFactory == null) { if (other.expiryPolicyFactory != null) { return false; } } else if (!expiryPolicyFactory.equals(other.expiryPolicyFactory)) { return false; } if (isReadThrough != other.isReadThrough) { return false; } if (isStatisticsEnabled != other.isStatisticsEnabled) { return false; } if (isStoreByValue != other.isStoreByValue) { return false; } if (isWriteThrough != other.isWriteThrough) { return false; } return true; } } ================================================ FILE: src/main/java/javax/cache/configuration/OptionalFeature.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.configuration; /** * Optional features that may be present in an implementation. * * @author Yannis Cosmadopoulos * @author Greg Luck * @since 1.0 */ public enum OptionalFeature { /** * Implementation supports store by reference */ STORE_BY_REFERENCE } ================================================ FILE: src/main/java/javax/cache/configuration/package-info.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ /** * This package contains configuration classes and interfaces. *

* Rather than configuration accepting user instances of interfaces for maximum * portability factories are configured instead, so that instances can be * instantiated where needed. To aid in this, FactoryBuilder can build factories * of the required type as shown in the following example. *


 *  MutableConfiguration<String, Integer> config = new MutableConfiguration<String, Integer>();
 *
 *  config.setTypes(String.class, Integer.class)
 *        .setStoreByValue(false)
 *        .setStatisticsEnabled(true)
 *        .setExpiryPolicyFactory(FactoryBuilder.factoryOf(
 *            new AccessedExpiryPolicy<String>(new Duration(TimeUnit.HOURS, 1))));
 * 
*

* {@link javax.cache.configuration.OptionalFeature}, though not specific to * cache configuration, allows application to determine the optional features * supported at runtime. * * @author Greg Luck * @since 1.0 */ package javax.cache.configuration; ================================================ FILE: src/main/java/javax/cache/event/CacheEntryCreatedListener.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; /** * Invoked after a cache entry is created, or if a batch call is made, after the * entries are created. *

* If an entry for the key existed prior to the operation it is not invoked, * instead {@link CacheEntryUpdatedListener} is invoked. * * @param the type of key * @param the type of value * @author Yannis Cosmadopoulos * @author Greg Luck * @see CacheEntryUpdatedListener * @since 1.0 */ public interface CacheEntryCreatedListener extends CacheEntryListener { /** * Called after one or more entries have been created. * * @param events The entries just created. * @throws CacheEntryListenerException if there is problem executing the listener */ void onCreated(Iterable> events) throws CacheEntryListenerException; } ================================================ FILE: src/main/java/javax/cache/event/CacheEntryEvent.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; import javax.cache.Cache; import javax.cache.configuration.CacheEntryListenerConfiguration; import java.util.EventObject; /** * A Cache entry event base class. * * @param the type of key * @param the type of value * @author Greg Luck * @since 1.0 */ public abstract class CacheEntryEvent extends EventObject implements Cache.Entry { private EventType eventType; /** * Constructs a cache entry event from a given cache as source * * @param source the cache that originated the event * @param eventType the event type for this event */ public CacheEntryEvent(Cache source, EventType eventType) { super(source); this.eventType = eventType; } /** * {@inheritDoc} */ @Override public final Cache getSource() { return (Cache) super.getSource(); } /** * Returns the value stored in the cache when this entry was created or updated. *

* The value will be available * for {@link CacheEntryCreatedListener} and {@link CacheEntryUpdatedListener}. * Returns the same value as {@link #getOldValue()} for * {@link CacheEntryExpiredListener} and {@link CacheEntryRemovedListener}. * Cache clients that need to maintain compatibility with JSR107 version 1.0 * cache implementations, need to use this method for retrieving the expired * or removed value. When using cache implementations compatible with JSR107 * version 1.1, clients should prefer the method {@link #getOldValue()}. * * @return the value corresponding to this entry * @see #getOldValue() */ @Override public abstract V getValue(); /** * Returns the previous value that existed for entry in the cache before * modification or removal. * * The old value will be available * for {@link CacheEntryUpdatedListener}, {@link CacheEntryExpiredListener} * and {@link CacheEntryRemovedListener} * if {@link CacheEntryListenerConfiguration#isOldValueRequired()} is true. * The old value may be available for {@link CacheEntryUpdatedListener}, * {@link CacheEntryExpiredListener} and {@link CacheEntryRemovedListener} * if {@link CacheEntryListenerConfiguration#isOldValueRequired()} is false. * * @return the previous value or null if there was no previous * value or the previous value is not available */ public abstract V getOldValue(); /** * Whether the old value is available. The old value will be available * for {@link CacheEntryUpdatedListener}, {@link CacheEntryExpiredListener} * and {@link CacheEntryRemovedListener} * if {@link CacheEntryListenerConfiguration#isOldValueRequired()} is true. * The old value may be available for {@link CacheEntryUpdatedListener}, * {@link CacheEntryExpiredListener} and {@link CacheEntryRemovedListener} * if {@link CacheEntryListenerConfiguration#isOldValueRequired()} is false. * * @return true if the old value is definitely available */ public abstract boolean isOldValueAvailable(); /** * Gets the event type of this event * * @return the event type. */ public final EventType getEventType() { return eventType; } } ================================================ FILE: src/main/java/javax/cache/event/CacheEntryEventFilter.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; /** * A function that may be used to check {@link CacheEntryEvent}s prior to being * dispatched to {@link CacheEntryListener}s. *

* A filter must not create side effects. * * @param the type of key * @param the type of value * @author Greg Luck * @author Brian Oliver * @since 1.0 */ public interface CacheEntryEventFilter { /** * Evaluates specified {@link CacheEntryEvent}. * * @param event the event that occurred * @return true if the evaluation passes, otherwise false. * The effect of returning true is that listener will be invoked * @throws CacheEntryListenerException if there is problem executing the listener */ boolean evaluate(CacheEntryEvent event) throws CacheEntryListenerException; } ================================================ FILE: src/main/java/javax/cache/event/CacheEntryExpiredListener.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; /** * Invoked if a cache entry or entries are evicted due to expiration. * * @param the type of key * @param the type of value * @author Greg Luck * @since 1.0 */ public interface CacheEntryExpiredListener extends CacheEntryListener { /** * Called after one or more entries have been expired by the cache. This is not * necessarily when an entry is expired, but when the cache detects the expiry. * * @param events The entries just removed. * @throws CacheEntryListenerException if there is problem executing the listener */ void onExpired(Iterable> events) throws CacheEntryListenerException; } ================================================ FILE: src/main/java/javax/cache/event/CacheEntryListener.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; import java.util.EventListener; /** * A tagging interface for cache entry listeners. *

* Sub-interfaces exist for the various cache events allowing a listener to be * created that implements only those listeners it is interested in. *

* Listeners should be implemented with care. In particular it is important to * consider their impact on performance and latency. *

* Listeners: *

    *
  • are fired after the entry is mutated in the cache
  • *
  • if synchronous are fired, for a given key, in the order that events * occur
  • *
  • block the calling thread until the listener returns, * where the listener was registered as synchronous
  • *
  • that are asynchronous iterate through multiple events with an undefined * ordering, except that events on the same key are in the order that the * events occur.
  • *
* Listeners follow the observer pattern. An exception thrown by a * listener does not cause the cache operation to fail. *

* Listeners can only throw {@link CacheEntryListenerException}. Caching * implementations must catch any other {@link Exception} from a listener, then * wrap and rethrow it as a {@link CacheEntryListenerException}. *

* A listener that mutates a cache on the CacheManager may cause a deadlock. * Detection and response to deadlocks is implementation specific. * * @param the type of key * @param the type of value * @author Yannis Cosmadopoulos * @author Greg Luck * @see CacheEntryCreatedListener * @see CacheEntryUpdatedListener * @see CacheEntryRemovedListener * @see CacheEntryExpiredListener * @see EventType * @since 1.0 */ public interface CacheEntryListener extends EventListener { } ================================================ FILE: src/main/java/javax/cache/event/CacheEntryListenerException.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; import javax.cache.CacheException; /** * An exception to indicate a problem has occurred with a listener. * As listeners are only called after the cache has been mutated, the mutation * to the cache is not affected. * * @author Greg Luck * @since 1.0 */ public class CacheEntryListenerException extends CacheException { private static final long serialVersionUID = 20130621110150L; /** * Constructs a new CacheEntryListenerException. */ public CacheEntryListenerException() { super(); } /** * Constructs a new CacheEntryListenerException with a message string. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public CacheEntryListenerException(String message) { super(message); } /** * Constructs a CacheEntryListenerException with a message string, and * a base exception * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheEntryListenerException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new CacheEntryListenerException with the specified cause and a * detail message of (cause==null ? null : cause.toString()) * (that typically contains the class and detail message of * cause). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheEntryListenerException(Throwable cause) { super(cause); } } ================================================ FILE: src/main/java/javax/cache/event/CacheEntryRemovedListener.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; /** * Invoked if a cache entry is removed, or if a batch call is made, after the * entries are removed. * * @param the type of key * @param the type of value * @author Yannis Cosmadopoulos * @author Greg Luck * @since 1.0 */ public interface CacheEntryRemovedListener extends CacheEntryListener { /** * Called after one or more entries have been removed. If no entry existed for * a key an event is not raised for it. * * @param events The entries just removed. * @throws CacheEntryListenerException if there is problem executing the listener */ void onRemoved(Iterable> events) throws CacheEntryListenerException; } ================================================ FILE: src/main/java/javax/cache/event/CacheEntryUpdatedListener.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; /** * Invoked if an existing cache entry is updated, or if a batch call is made, * after the entries are updated. * * @param the type of key * @param the type of value * @author Yannis Cosmadopoulos * @author Greg Luck * @see CacheEntryCreatedListener * @since 1.0 */ public interface CacheEntryUpdatedListener extends CacheEntryListener { /** * Called after one or more entries have been updated. * * @param events The entries just updated. * @throws CacheEntryListenerException if there is problem executing the listener */ void onUpdated(Iterable> events) throws CacheEntryListenerException; } ================================================ FILE: src/main/java/javax/cache/event/EventType.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.event; /** * The type of event received by the listener. * * @author Greg Luck * @since 1.0 */ public enum EventType { /** * An event type indicating that the cache entry was created. */ CREATED, /** * An event type indicating that the cache entry was updated. i.e. a previous * mapping existed */ UPDATED, /** * An event type indicating that the cache entry was removed. */ REMOVED, /** * An event type indicating that the cache entry has expired. */ EXPIRED } ================================================ FILE: src/main/java/javax/cache/event/package-info.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ /** * This package contains event listener interfaces. *

* These may be registered for callback notification of the cache events. * The specific interface should be implemented for each event type a callback * is desired on. *

* Event notifications occur synchronously in the line of execution of the calling thread. * The calling thread blocks until the listener has completed execution or thrown a {@link javax.cache.event.CacheEntryCreatedListener}. *

* Listeners are invoked after the cache is updated. If the listener throws * an {@link javax.cache.event.CacheEntryCreatedListener} this will propagate back to the caller but it does not affect the cache update * as it already completed before the listener was called. * * @author Greg Luck * @author Yannis Cosmadopoulos * @since 1.0 */ package javax.cache.event; ================================================ FILE: src/main/java/javax/cache/expiry/AccessedExpiryPolicy.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.expiry; import javax.cache.configuration.Factory; import javax.cache.configuration.FactoryBuilder; import java.io.Serializable; /** * An {@link ExpiryPolicy} that defines the expiry {@link Duration} * of a Cache Entry based on the last time it was accessed. Accessed * does not include a cache update. * * @author Greg Luck * @author Brian Oliver * @since 1.0 * @see ExpiryPolicy */ public final class AccessedExpiryPolicy implements ExpiryPolicy, Serializable { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201305101601L; /** * The {@link Duration} a Cache Entry should be available before it expires. */ private Duration expiryDuration; /** * Constructs an {@link AccessedExpiryPolicy} {@link ExpiryPolicy}. * * @param expiryDuration the {@link Duration} a Cache Entry should exist be * before it expires after being accessed */ public AccessedExpiryPolicy(Duration expiryDuration) { this.expiryDuration = expiryDuration; } /** * Obtains a {@link Factory} for an Accessed {@link ExpiryPolicy}. * @param duration The expiry duration * @return a {@link Factory} for an Accessed {@link ExpiryPolicy}. */ public static Factory factoryOf(Duration duration) { return new FactoryBuilder.SingletonFactory(new AccessedExpiryPolicy(duration)); } /** * {@inheritDoc} */ @Override public Duration getExpiryForCreation() { //the initial expiry duration is the same as if the entry was accessed return expiryDuration; } /** * {@inheritDoc} */ @Override public Duration getExpiryForAccess() { //when a cache entry is accessed, we return the specified expiry duration, //ignoring the current expiry duration return expiryDuration; } /** * {@inheritDoc} */ @Override public Duration getExpiryForUpdate() { //modifying a cache entry has no affect on the current expiry duration return null; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expiryDuration == null) ? 0 : expiryDuration.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!(object instanceof AccessedExpiryPolicy)) { return false; } AccessedExpiryPolicy other = (AccessedExpiryPolicy) object; if (expiryDuration == null) { if (other.expiryDuration != null) { return false; } } else if (!expiryDuration.equals(other.expiryDuration)) { return false; } return true; } } ================================================ FILE: src/main/java/javax/cache/expiry/CreatedExpiryPolicy.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.expiry; import javax.cache.configuration.Factory; import javax.cache.configuration.FactoryBuilder; import java.io.Serializable; /** * An {@link ExpiryPolicy} that defines the expiry {@link Duration} * of a Cache Entry based on when it was created. An update does not reset * the expiry time. * * @author Greg Luck * @author Brian Oliver * @since 1.0 * @see ExpiryPolicy */ public final class CreatedExpiryPolicy implements ExpiryPolicy, Serializable { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201305291023L; /** * The {@link Duration} a Cache Entry should be available before it expires. */ private Duration expiryDuration; /** * Constructs an {@link CreatedExpiryPolicy} {@link ExpiryPolicy}. * * @param expiryDuration the {@link Duration} a Cache Entry should exist be * before it expires after being modified */ public CreatedExpiryPolicy(Duration expiryDuration) { this.expiryDuration = expiryDuration; } /** * Obtains a {@link Factory} for a Created {@link ExpiryPolicy}. * @param duration The expiry duration * @return a {@link Factory} for a Created {@link ExpiryPolicy}. */ public static Factory factoryOf(Duration duration) { return new FactoryBuilder.SingletonFactory(new CreatedExpiryPolicy(duration)); } /** * {@inheritDoc} */ @Override public Duration getExpiryForCreation() { //for newly created entries we use the specified expiry duration return expiryDuration; } /** * {@inheritDoc} */ @Override public Duration getExpiryForAccess() { //accessing a cache entry has no affect on the current expiry duration return null; } /** * {@inheritDoc} */ @Override public Duration getExpiryForUpdate() { //updating a cache entry has no affect on the current expiry duration return null; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expiryDuration == null) ? 0 : expiryDuration.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!(object instanceof CreatedExpiryPolicy)) { return false; } CreatedExpiryPolicy other = (CreatedExpiryPolicy) object; if (expiryDuration == null) { if (other.expiryDuration != null) { return false; } } else if (!expiryDuration.equals(other.expiryDuration)) { return false; } return true; } } ================================================ FILE: src/main/java/javax/cache/expiry/Duration.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.expiry; import java.io.Serializable; import java.util.concurrent.TimeUnit; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.SECONDS; /** * A {@link java.io.Serializable} duration of time. * *

Although this class is not declared final, it is not intended for extension. The behavior * is undefined when subclasses are created and used. * * @author Yannis Cosmadopoulos * @author Greg Luck * @author Brian Oliver * @since 1.0 * @see ExpiryPolicy */ public class Duration implements Serializable { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201305101442L; /** * ETERNAL (forever). */ public static final Duration ETERNAL = new Duration(); /** * One day. */ public static final Duration ONE_DAY = new Duration(DAYS, 1); /** * One hour. */ public static final Duration ONE_HOUR = new Duration(HOURS, 1); /** * Thirty minutes. */ public static final Duration THIRTY_MINUTES = new Duration(MINUTES, 30); /** * Twenty minutes. */ public static final Duration TWENTY_MINUTES = new Duration(MINUTES, 20); /** * Ten minutes. */ public static final Duration TEN_MINUTES = new Duration(MINUTES, 10); /** * Five minutes. */ public static final Duration FIVE_MINUTES = new Duration(MINUTES, 5); /** * One minute. */ public static final Duration ONE_MINUTE = new Duration(MINUTES, 1); /** * Zero (no time). */ public static final Duration ZERO = new Duration(SECONDS, 0); /** * The unit of time to specify time in. The minimum time unit is milliseconds. */ private final TimeUnit timeUnit; /** * How long, in the specified units, the cache entries should live. * The lifetime is measured from the cache entry was last accessed or * mutated. */ private final long durationAmount; /** * Constructs an eternal duration ({@link #isEternal} is true). Since the duration is immutable * the constant {@link #ETERNAL} should be used alternatively. */ public Duration() { this.timeUnit = null; this.durationAmount = 0; } /** * Constructs a duration. The eternal duration ({@link #isEternal} is true) is represented by * specifying {@code null} for {@code timeUnit} and {@code 0} for {@code durationAmount}. * * @param timeUnit the unit of time to specify time in. The minimum time unit is milliseconds. * @param durationAmount how long, in the specified units, the cache entries should live. * @throws NullPointerException if timeUnit is null and the {@code durationAmount} is not 0 * @throws IllegalArgumentException if durationAmount is less than 0 or a TimeUnit less than milliseconds is specified */ public Duration(TimeUnit timeUnit, long durationAmount) { if (timeUnit == null) { if (durationAmount == 0) { //allow creation of an Eternal Duration this.timeUnit = null; this.durationAmount = 0; } else { throw new NullPointerException(); } } else { switch (timeUnit) { case NANOSECONDS: case MICROSECONDS: throw new IllegalArgumentException("Must specify a TimeUnit of milliseconds or higher."); default: this.timeUnit = timeUnit; break; } if (durationAmount < 0) { throw new IllegalArgumentException("Cannot specify a negative durationAmount."); } this.durationAmount = durationAmount; } } /** * Constructs a {@link Duration} based on the duration between two * specified points in time (since the Epoc), measured in milliseconds. * *

If either parameter is {@code Long.MAX_VALUE} an eternal duration ({@link #isEternal} * is true) will be constructed. * * @param startTime the start time (since the Epoc) * @param endTime the end time (since the Epoc) */ public Duration(long startTime, long endTime) { if (startTime == Long.MAX_VALUE || endTime == Long.MAX_VALUE) { //we're dealing with arithmetic involving an ETERNAL value //so the result must be ETERNAL timeUnit = null; durationAmount = 0; } else if (startTime < 0) { throw new IllegalArgumentException("Cannot specify a negative startTime."); } else if (endTime < 0) { throw new IllegalArgumentException("Cannot specify a negative endTime."); } else { timeUnit = TimeUnit.MILLISECONDS; durationAmount = Math.max(startTime, endTime) - Math.min(startTime, endTime); } } /** * Obtain the TimeUnit for the Duration * * @return the TimeUnit */ public TimeUnit getTimeUnit() { return timeUnit; } /** * Obtain the number of TimeUnits in the Duration * * @return the number of TimeUnits */ public long getDurationAmount() { return durationAmount; } /** * Determines if a {@link Duration} is eternal (forever). * * @return true if the {@link Duration} is eternal */ public boolean isEternal() { return timeUnit == null && durationAmount == 0; } /** * Determines if a {@link Duration} is zero. * * @return true if the {@link Duration} is zero */ public boolean isZero() { return timeUnit != null && durationAmount == 0; } /** * Calculates the adjusted time (represented in milliseconds from the Epoc) * given a specified time in milliseconds (to be adjusted) by the duration. * *

If this instance represents an eternal duration ({@link #isEternal} * is true), the value {@code Long.MAX_VALUE} is returned. * * @param time the time from which to adjust given the duration * @return the adjusted time */ public long getAdjustedTime(long time) { if (isEternal()) { return Long.MAX_VALUE; } else { return time + timeUnit.toMillis(durationAmount); } } /** * {@inheritDoc} */ @Override public boolean equals(Object other) { if (this == other) { return true; } else if (other == null || getClass() != other.getClass()) { return false; } else { Duration duration = (Duration) other; if (this.timeUnit == null && duration.timeUnit == null && this.durationAmount == duration.durationAmount) { return true; } else if (this.timeUnit != null && duration.timeUnit != null) { long time1 = timeUnit.toMillis(durationAmount); long time2 = duration.timeUnit.toMillis(duration.durationAmount); return time1 == time2; } else { return false; } } } /** * {@inheritDoc} */ @Override public int hashCode() { return timeUnit == null ? -1 : (int)timeUnit.toMillis(durationAmount); } } ================================================ FILE: src/main/java/javax/cache/expiry/EternalExpiryPolicy.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.expiry; import javax.cache.configuration.Factory; import javax.cache.configuration.FactoryBuilder; import java.io.Serializable; import static javax.cache.expiry.Duration.ETERNAL; /** * An eternal {@link ExpiryPolicy} specifies that Cache Entries * won't expire. This however doesn't mean they won't be evicted if an * underlying implementation needs to free-up resources where by it may * choose to evict entries that are not due to expire. * * @author Greg Luck * @author Brian Oliver * @since 1.0 * @see ExpiryPolicy */ public final class EternalExpiryPolicy implements ExpiryPolicy, Serializable { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201305101603L; /** * Obtains a {@link Factory} for an Eternal {@link ExpiryPolicy}. * @return a {@link Factory} for an Eternal {@link ExpiryPolicy}. */ public static Factory factoryOf() { return new FactoryBuilder.SingletonFactory( new EternalExpiryPolicy()); } /** * {@inheritDoc} */ @Override public Duration getExpiryForCreation() { return ETERNAL; } /** * {@inheritDoc} */ @Override public Duration getExpiryForAccess() { return null; } /** * {@inheritDoc} */ @Override public Duration getExpiryForUpdate() { return null; } /** * {@inheritDoc} */ @Override public int hashCode() { return EternalExpiryPolicy.class.hashCode(); } /** * {@inheritDoc} */ @Override public boolean equals(Object other) { return other instanceof EternalExpiryPolicy; } } ================================================ FILE: src/main/java/javax/cache/expiry/ExpiryPolicy.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.expiry; /** * Defines functions to determine when cache entries will expire based on * creation, access and modification operations. *

* Each of the functions return a new {@link Duration} that specifies the * amount of time that must pass before a cache entry is considered expired. * {@link Duration} has constants defined for useful durations. * * @author Brian Oliver * @author Greg Luck * @since 1.0 * @see Duration */ public interface ExpiryPolicy { /** * Gets the {@link Duration} before a newly created Cache.Entry is considered * expired. *

* This method is called by a caching implementation after a Cache.Entry is * created, but before a Cache.Entry is added to a cache, to determine the * {@link Duration} before an entry expires. If a {@link Duration#ZERO} * is returned the new Cache.Entry is considered to be already expired and * will not be added to the Cache. *

* Should an exception occur while determining the Duration, an implementation * specific default {@link Duration} will be used. * * @return the new {@link Duration} before a created entry expires */ Duration getExpiryForCreation(); /** * Gets the {@link Duration} before an accessed Cache.Entry is * considered expired. *

* This method is called by a caching implementation after a Cache.Entry is * accessed to determine the {@link Duration} before an entry expires. If a * {@link Duration#ZERO} is returned a Cache.Entry will be * considered immediately expired. Returning null will result * in no change to the previously understood expiry {@link Duration}. *

* Should an exception occur while determining the Duration, an implementation * specific default Duration will be used. * * @return the new {@link Duration} before an accessed entry expires */ Duration getExpiryForAccess(); /** * Gets the {@link Duration} before an updated Cache.Entry is considered * expired. *

* This method is called by the caching implementation after a Cache.Entry is * updated to determine the {@link Duration} before the updated entry expires. * If a {@link Duration#ZERO} is returned a Cache.Entry is considered * immediately expired. Returning null will result in no change * to the previously understood expiry {@link Duration}. *

* Should an exception occur while determining the Duration, an implementation * specific default Duration will be used. * * @return the new {@link Duration} before an updated entry expires */ Duration getExpiryForUpdate(); } ================================================ FILE: src/main/java/javax/cache/expiry/ModifiedExpiryPolicy.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.expiry; import javax.cache.configuration.Factory; import javax.cache.configuration.FactoryBuilder; import java.io.Serializable; /** * An {@link ExpiryPolicy} that defines the expiry {@link Duration} * of a Cache Entry based on the last time it was updated. Updating * includes created and changing (updating) an entry. * * @author Greg Luck * @author Brian Oliver * @since 1.0 * @see ExpiryPolicy */ public final class ModifiedExpiryPolicy implements ExpiryPolicy, Serializable { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201305101602L; /** * The {@link Duration} a Cache Entry should be available before it expires. */ private Duration expiryDuration; /** * Constructs an {@link ModifiedExpiryPolicy} {@link ExpiryPolicy}. * * @param expiryDuration the {@link Duration} a Cache Entry should exist be * before it expires after being modified */ public ModifiedExpiryPolicy(Duration expiryDuration) { this.expiryDuration = expiryDuration; } /** * Obtains a {@link Factory} for a Modified {@link ExpiryPolicy}. * * @param duration The expiry duration * @return a {@link Factory} for a Modified {@link ExpiryPolicy}. */ public static Factory factoryOf(Duration duration) { return new FactoryBuilder.SingletonFactory(new ModifiedExpiryPolicy(duration)); } /** * {@inheritDoc} */ @Override public Duration getExpiryForCreation() { //for newly created entries we use the specified expiry duration return expiryDuration; } /** * {@inheritDoc} */ @Override public Duration getExpiryForAccess() { //accessing a cache entry has no affect on the current expiry duration return null; } /** * {@inheritDoc} */ @Override public Duration getExpiryForUpdate() { //when a cache entry is modified, we return the specified expiry duration, //ignoring the current expiry duration return expiryDuration; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expiryDuration == null) ? 0 : expiryDuration.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!(object instanceof ModifiedExpiryPolicy)) { return false; } ModifiedExpiryPolicy other = (ModifiedExpiryPolicy) object; if (expiryDuration == null) { if (other.expiryDuration != null) { return false; } } else if (!expiryDuration.equals(other.expiryDuration)) { return false; } return true; } } ================================================ FILE: src/main/java/javax/cache/expiry/TouchedExpiryPolicy.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.expiry; import javax.cache.configuration.Factory; import javax.cache.configuration.FactoryBuilder; import java.io.Serializable; /** * An {@link ExpiryPolicy} that defines the expiry {@link Duration} * of a Cache Entry based on when it was last touched. A touch includes * creation, update or access. * * @author Greg Luck * @author Brian Oliver * @since 1.0 * @see ExpiryPolicy */ public final class TouchedExpiryPolicy implements ExpiryPolicy, Serializable { /** * The serialVersionUID required for {@link java.io.Serializable}. */ public static final long serialVersionUID = 201305291023L; /** * The {@link Duration} a Cache Entry should be available before it expires. */ private Duration expiryDuration; /** * Constructs an {@link TouchedExpiryPolicy} {@link ExpiryPolicy}. * * @param expiryDuration the {@link Duration} a Cache Entry should exist be * before it expires after being modified */ public TouchedExpiryPolicy(Duration expiryDuration) { this.expiryDuration = expiryDuration; } /** * Obtains a {@link Factory} for a Touched {@link ExpiryPolicy}. * @param duration The expiry duration * @return a {@link Factory} for a Touched {@link ExpiryPolicy}. */ public static Factory factoryOf(Duration duration) { return new FactoryBuilder.SingletonFactory(new TouchedExpiryPolicy(duration)); } /** * {@inheritDoc} */ @Override public Duration getExpiryForCreation() { //for newly created entries we use the specified expiry duration. return expiryDuration; } /** * {@inheritDoc} */ @Override public Duration getExpiryForAccess() { //accessing a cache entry resets the duration. return expiryDuration; } /** * {@inheritDoc} */ @Override public Duration getExpiryForUpdate() { //updating a cache entry resets the duration. return expiryDuration; } /** * {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((expiryDuration == null) ? 0 : expiryDuration.hashCode()); return result; } /** * {@inheritDoc} */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object == null) { return false; } if (!(object instanceof TouchedExpiryPolicy)) { return false; } TouchedExpiryPolicy other = (TouchedExpiryPolicy) object; if (expiryDuration == null) { if (other.expiryDuration != null) { return false; } } else if (!expiryDuration.equals(other.expiryDuration)) { return false; } return true; } } ================================================ FILE: src/main/java/javax/cache/expiry/package-info.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ /** This package contains expiry policies @author Greg Luck @since 1.0 */ package javax.cache.expiry; ================================================ FILE: src/main/java/javax/cache/integration/CacheLoader.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.integration; import javax.cache.configuration.CompleteConfiguration; import java.util.Map; /** * Used when a cache is read-through or when loading data into a cache via the * {@link javax.cache.Cache#loadAll(java.util.Set, boolean, * CompletionListener)} method. * * @param the type of keys handled by this loader * @param the type of values generated by this loader * @author Greg Luck * @author Yannis Cosmadopoulos * @see CompleteConfiguration#isReadThrough() * @see CacheWriter * @since 1.0 */ public interface CacheLoader { /** * Loads an object. Application developers should implement this * method to customize the loading of a value for a cache entry. This method * is called by a cache when a requested entry is not in the cache. If * the object can't be loaded null should be returned. * * @param key the key identifying the object being loaded * @return The value for the entry that is to be stored in the cache or * null if the object can't be loaded * @throws CacheLoaderException if there is problem executing the loader. */ V load(K key) throws CacheLoaderException; /** * Loads multiple objects. Application developers should implement this * method to customize the loading of cache entries. This method is called * when the requested object is not in the cache. If an object can't be loaded, * it is not returned in the resulting map. * * @param keys keys identifying the values to be loaded * @return A map of key, values to be stored in the cache. * @throws CacheLoaderException if there is problem executing the loader. */ Map loadAll(Iterable keys) throws CacheLoaderException; } ================================================ FILE: src/main/java/javax/cache/integration/CacheLoaderException.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.integration; import javax.cache.CacheException; /** * An exception to indicate a problem has occurred executing a {@link CacheLoader}. *

* A Caching Implementation must wrap any {@link Exception} thrown by a {@link * CacheLoader} in this exception. * * @author Greg Luck * @since 1.0 */ public class CacheLoaderException extends CacheException { private static final long serialVersionUID = 20130822163231L; /** * Constructs a new CacheLoaderException. */ public CacheLoaderException() { super(); } /** * Constructs a new CacheLoaderException with a message string. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public CacheLoaderException(String message) { super(message); } /** * Constructs a CacheLoaderException with a message string, and * a base exception * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheLoaderException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new CacheLoaderException with the specified cause and a * detail message of (cause==null ? null : cause.toString()) * (that typically contains the class and detail message of * cause). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheLoaderException(Throwable cause) { super(cause); } } ================================================ FILE: src/main/java/javax/cache/integration/CacheWriter.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.integration; import javax.cache.Cache; import java.util.Collection; /** * A CacheWriter is used for write-through to an external resource. *

* Under Default Consistency, the non-batch writer methods are atomic with respect * to the corresponding cache operation. *

* For batch methods under Default Consistency, the entire cache operation * is not required to be atomic in {@link Cache} and is therefore not required to * be atomic in the writer. As individual writer operations can fail, cache * operations are not required to occur until after the writer batch method has * returned or, in the case of partial success, thrown an exception. In the case * of partial success, the collection of entries return must only contain * those entries that failed. *

* The entry passed into {@link #write(Cache.Entry)} is independent * of the cache mapping for that key, meaning that if the value changes in the * cache or is removed it does not change the entry. * * @param the type of keys maintained by this map * @param the type of mapped values * @author Greg Luck * @author Brian Oliver * @see CacheLoader * @since 1.0 */ public interface CacheWriter { /** * Write the specified value under the specified key to the external resource. *

* This method is intended to support both key/value creation and value update * for a specific key. * * @param entry the entry to be written * @throws CacheWriterException if the write fails. If thrown the * cache mutation will not occur. */ void write(Cache.Entry entry) throws CacheWriterException; /** * Write the specified entries to the external resource. This method is intended * to support both insert and update. *

* The order that individual writes occur is undefined, as * {@link Cache#putAll(java.util.Map)} also has undefined ordering. *

* If this operation fails (by throwing an exception) after a partial success, * the writer must remove any successfully written entries from the entries * collection so that the caching implementation knows what succeeded and can * mutate the cache. * * @param entries a mutable collection to write. Upon invocation, it contains * the entries to write for write-through. Upon return the * collection must only contain entries that were not * successfully written. (see partial success above) * @throws CacheWriterException if one or more of the writes fail. If * thrown cache mutations will occur for * entries that succeeded. */ void writeAll(Collection> entries) throws CacheWriterException; /** * Delete the cache entry from the external resource. *

* Expiry of a cache entry is not a delete hence will not cause this method to * be invoked. *

* This method is invoked even if no mapping for the key exists. * * @param key the key that is used for the delete operation * @throws CacheWriterException if delete fails. If thrown the cache delete will * not occur. */ void delete(Object key) throws CacheWriterException; /** * Remove data and keys from the external resource for the given collection of * keys, if present. *

* The order that individual deletes occur is undefined, as * {@link Cache#removeAll(java.util.Set)} also has undefined ordering. *

* If this operation fails (by throwing an exception) after a partial success, * the writer must remove any successfully written entries from the entries * collection so that the caching implementation knows what succeeded and can * mutate the cache. *

* Expiry of a cache entry is not a delete hence will not cause this method to * be invoked. *

* This method may include keys even if there is no mapping for that key, * in which case the data represented by that key should be removed from the * underlying resource. * * @param keys a mutable collection of keys for entries to delete. Upon * invocation, it contains the keys to delete for write-through. * Upon return the collection must only contain the keys that were * not successfully deleted. (see partial success above) * @throws CacheWriterException if one or more deletes fail. If thrown * cache deletes will occur for entries that * succeeded. */ void deleteAll(Collection keys) throws CacheWriterException; } ================================================ FILE: src/main/java/javax/cache/integration/CacheWriterException.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.integration; import javax.cache.CacheException; /** * An exception to indicate a problem has occurred executing a {@link CacheWriter}. *

* A Caching Implementation must wrap any {@link Exception} thrown by a {@link * CacheWriter} in this exception. * * @author Greg Luck * @since 1.0 */ public class CacheWriterException extends CacheException { private static final long serialVersionUID = 20130822161612L; /** * Constructs a new CacheWriterException. */ public CacheWriterException() { super(); } /** * Constructs a new CacheWriterException with a message string. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public CacheWriterException(String message) { super(message); } /** * Constructs a CacheWriterException with a message string, and * a base exception * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheWriterException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new CacheWriterException with the specified cause and a * detail message of (cause==null ? null : cause.toString()) * (that typically contains the class and detail message of * cause). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public CacheWriterException(Throwable cause) { super(cause); } } ================================================ FILE: src/main/java/javax/cache/integration/CompletionListener.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.integration; /** * A CompletionListener is implemented by an application when it needs to be * notified of the completion of some Cache operation. *

* When the operation is complete, the Cache provider notifies the application * by calling the {@link #onCompletion()} method of the {@link * CompletionListener}. *

* If the operation fails for any reason, the Cache provider calls the * {@link #onException(Exception)} method of the {@link CompletionListener}. *

* To support a Java Future-based approach to synchronously wait for a Cache * operation to complete, use a {@link CompletionListenerFuture}. *

* A Cache provider will use an implementation specific thread to call methods * on this interface. * * @author Brian Oliver * @since 1.0 * @see CompletionListenerFuture */ public interface CompletionListener { /** * Notifies the application that the operation completed successfully. */ void onCompletion(); /** * Notifies the application that the operation failed. * * @param e the Exception that occurred */ void onException(Exception e); } ================================================ FILE: src/main/java/javax/cache/integration/CompletionListenerFuture.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.integration; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A CompletionListenerFuture is a CompletionListener implementation that * supports being used as a Future. *

* For example: *


 * //create a completion future to use to wait for loadAll
 * CompletionListenerFuture future = new CompletionListenerFuture();
 * 
 * //load the values for the set of keys, replacing those that may already exist
 * //in the cache
 * cache.loadAll(keys, true, future);
 * 
 * //wait for the cache to load the keys
 * future.get();
 * 
*

* A CompletionListenerFuture may only be used once. Attempts to use an instance * multiple times, as part of multiple asynchronous calls will result in an * {@link java.lang.IllegalStateException} being raised. * * @author Brian Oliver * @author Greg Luck * @author Jens Wilke * @since 1.0 */ public class CompletionListenerFuture implements CompletionListener, Future { private final Object lock = new Object(); private boolean isCompleted; private Exception exception; /** * Constructs a CompletionListenerFuture. */ public CompletionListenerFuture() { this.isCompleted = false; this.exception = null; } /** * Notifies the application that the operation completed successfully. * @throws IllegalStateException if the instance is used more than once */ @Override public void onCompletion() throws IllegalStateException { synchronized (lock) { if (isCompleted) { throw new IllegalStateException("Attempted to use a CompletionListenerFuture instance more than once"); } markAsCompleted(); } } /** * Notifies the application that the operation failed. * * @param e the Exception that occurred * @throws IllegalStateException if the instance is used more than once */ @Override public void onException(Exception e) throws IllegalStateException { synchronized (lock) { if (isCompleted) { throw new IllegalStateException("Attempted to use a CompletionListenerFuture instance more than once"); } exception = e; markAsCompleted(); } } /** * Mark operation as completed and wakeup all listeners, called under lock. */ private void markAsCompleted() { assert Thread.holdsLock(lock); isCompleted = true; lock.notifyAll(); } /** * Cancelling is not supported, always throws exception. * * @throws UnsupportedOperationException thrown always */ @Override public boolean cancel(boolean b) { throw new UnsupportedOperationException("CompletionListenerFutures can't be cancelled"); } /** * Cancelling is not supported, always returns false * * @return always false. */ @Override public boolean isCancelled() { return false; } @Override public boolean isDone() { synchronized (lock) { return isCompleted; } } /** * Waits if necessary for the operation to complete. Always returns {@code null}. * * @return always {@code null} * @throws ExecutionException if the computation threw an * exception. This wraps the exception received by {@link #onException * (Exception)} * @throws InterruptedException if the current thread was interrupted * while waiting */ @Override public Void get() throws InterruptedException, ExecutionException { synchronized (lock) { while (!isCompleted) { lock.wait(); } if (exception != null) { throw new ExecutionException(exception); } } return null; } /** * Waits if necessary for at most the given time for the operation * to complete. Always returns {@code null}. * * @param timeout the maximum time to wait * @param unit the time unit of the timeout argument * @return always {@code null} * @throws ExecutionException if the computation threw an * exception. This wraps the exception received by {@link #onException * (Exception)} * @throws InterruptedException if the current thread was interrupted * while waiting * @throws TimeoutException if the wait timed out */ @Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { long endTime = System.currentTimeMillis() + unit.toMillis(timeout); synchronized (lock) { while (!isCompleted) { long waitTime = endTime - System.currentTimeMillis(); if (waitTime <= 0) { throw new TimeoutException(); } lock.wait(waitTime); } if (exception != null) { throw new ExecutionException(exception); } } return null; } } ================================================ FILE: src/main/java/javax/cache/integration/package-info.java ================================================ /** * Copyright (c) 2011-2013 Terracotta, Inc. * Copyright (c) 2011-2013 Oracle and/or its affiliates. * * All rights reserved. Use is subject to license terms. */ /** * This package contains interfaces for integration. *

* It contains the {@link javax.cache.integration.CacheLoader} and * {@link javax.cache.integration.CacheWriter} interfaces that * allow loading from and writing to other systems respectively. *

* A cache with a registered loader can be configured as a read-through cache, so * that access will automatically load missing entries. And similarly a cache * with a registered writer can be configured * as a write-through cache, so that changes are written through to an underlying * system. *

* In addition a common idiom is to use a loader to initially * populate or refresh a cache. For that purpose there is the * {@link javax.cache.Cache#loadAll(java.util.Set, boolean, CompletionListener)} * method. * * @author Greg Luck * @since 1.0 */ package javax.cache.integration; ================================================ FILE: src/main/java/javax/cache/management/CacheMXBean.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.management; import javax.cache.Cache; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheWriter; import javax.management.MXBean; /** * A management bean for cache. It provides configuration information. It does not * allow mutation of configuration or mutation of the cache. *

* Each cache's management object must be registered with an ObjectName that is * unique and has the following type and attributes: *

* Type: * javax.cache:type=CacheConfiguration *

* Required Attributes: *

    *
  • CacheManager the URI of the CacheManager *
  • Cache the name of the Cache *
* * @author Greg Luck * @author Yannis Cosmadopoulos * @since 1.0 */ @MXBean public interface CacheMXBean { /** * Determines the required type of keys for this {@link Cache}, if any. * * @return the fully qualified class name of the key type, * or "java.lang.Object" if the type is undefined. */ String getKeyType(); /** * Determines the required type of values for this {@link Cache}, if any. * @return the fully qualified class name of the value type, * or "java.lang.Object" if the type is undefined. */ String getValueType(); /** * Determines if a {@link Cache} should operate in read-through mode. *

* When in read-through mode, cache misses that occur due to cache entries * not existing as a result of performing a "get" call via one of * {@link Cache#get}, * {@link Cache#getAll}, * {@link Cache#getAndRemove} and/or * {@link Cache#getAndReplace} will appropriately * cause the configured {@link CacheLoader} to be * invoked. *

* The default value is false. * * @return true when a {@link Cache} is in * "read-through" mode. * @see CacheLoader */ boolean isReadThrough(); /** * Determines if a {@link Cache} should operate in "write-through" * mode. *

* When in "write-through" mode, cache updates that occur as a result of * performing "put" operations called via one of * {@link Cache#put}, * {@link Cache#getAndRemove}, * {@link Cache#removeAll}, * {@link Cache#getAndPut} * {@link Cache#getAndRemove}, * {@link Cache#getAndReplace}, * {@link Cache#invoke} * {@link Cache#invokeAll} *

* will appropriately cause the configured {@link CacheWriter} to be invoked. *

* The default value is false. * * @return true when a {@link Cache} is in "write-through" mode. * @see CacheWriter */ boolean isWriteThrough(); /** * Whether storeByValue (true) or storeByReference (false). * When true, both keys and values are stored by value. *

* When false, both keys and values are stored by reference. * Caches stored by reference are capable of mutation by any threads holding * the reference. The effects are: *

    *
  • if the key is mutated, then the key may not be retrievable or * removable
  • *
  • if the value is mutated, then all threads in the JVM can potentially * observe those mutations, subject to the normal Java Memory Model rules.
  • *
* Storage by reference only applies to the local heap. If an entry is moved off * heap it will need to be transformed into a representation. Any mutations that * occur after transformation may not be reflected in the cache. *

* When a cache is storeByValue, any mutation to the key or value does not affect * the key of value stored in the cache. *

* The default value is true. * * @return true if the cache is store by value */ boolean isStoreByValue(); /** * Checks whether statistics collection is enabled in this cache. *

* The default value is false. * * @return true if statistics collection is enabled */ boolean isStatisticsEnabled(); /** * Checks whether management is enabled on this cache. *

* The default value is false. * * @return true if management is enabled */ boolean isManagementEnabled(); } ================================================ FILE: src/main/java/javax/cache/management/CacheStatisticsMXBean.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.management; import javax.management.MXBean; /** * Cache statistics. *

* Statistics are accumulated from the time a cache is created. They can be reset * to zero using {@link #clear}. *

* There are no defined consistency semantics for statistics. Refer to the * implementation for precise semantics. *

* Each cache's statistics object must be registered with an ObjectName that is * unique and has the following type and attributes: *

* Type: * javax.cache:type=CacheStatistics *

* Required Attributes: *

    *
  • CacheManager the URI of the CacheManager *
  • Cache the name of the Cache *
* * @author Greg Luck * @since 1.0 */ @MXBean public interface CacheStatisticsMXBean { /** * Clears the statistics counters to 0 for the associated Cache. */ void clear(); /** * The number of get requests that were satisfied by the cache. *

* {@link javax.cache.Cache#containsKey(Object)} is not a get request for * statistics purposes. *

* In a caches with multiple tiered storage, a hit may be implemented as a hit * to the cache or to the first tier. *

* For an {@link javax.cache.processor.EntryProcessor}, a hit occurs when the * key exists and an entry processor can be invoked against it, even if no * methods of {@link javax.cache.Cache.Entry} or * {@link javax.cache.processor.MutableEntry} are called. * * @return the number of hits */ long getCacheHits(); /** * This is a measure of cache efficiency. *

* It is calculated as: * {@link #getCacheHits} divided by {@link #getCacheGets ()} * 100. * * @return the percentage of successful hits, as a decimal e.g 75. */ float getCacheHitPercentage(); /** * A miss is a get request that is not satisfied. *

* In a simple cache a miss occurs when the cache does not satisfy the request. *

* {@link javax.cache.Cache#containsKey(Object)} is not a get request for * statistics purposes. *

* For an {@link javax.cache.processor.EntryProcessor}, a miss occurs when the * key does not exist and therefore an entry processor cannot be invoked * against it. *

* In a caches with multiple tiered storage, a miss may be implemented as a miss * to the cache or to the first tier. *

* In a read-through cache a miss is an absence of the key in the cache that * will trigger a call to a CacheLoader. So it is still a miss even though the * cache will load and return the value. *

* Refer to the implementation for precise semantics. * * @return the number of misses */ long getCacheMisses(); /** * Returns the percentage of cache accesses that did not find a requested entry * in the cache. *

* This is calculated as {@link #getCacheMisses()} divided by * {@link #getCacheGets()} * 100. * * @return the percentage of accesses that failed to find anything */ float getCacheMissPercentage(); /** * The total number of requests to the cache. This will be equal to the sum of * the hits and misses. *

* A "get" is an operation that returns the current or previous value. It does * not include checking for the existence of a key. *

* In a caches with multiple tiered storage, a gets may be implemented as a get * to the cache or to the first tier. * * @return the number of gets */ long getCacheGets(); /** * The total number of puts to the cache. *

* A put is counted even if it is immediately evicted. *

* Replaces, where a put occurs which overrides an existing mapping is counted * as a put. * * @return the number of puts */ long getCachePuts(); /** * The total number of removals from the cache. This does not include evictions, * where the cache itself initiates the removal to make space. * * @return the number of removals */ long getCacheRemovals(); /** * The total number of evictions from the cache. An eviction is a removal * initiated by the cache itself to free up space. An eviction is not treated as * a removal and does not appear in the removal counts. * * @return the number of evictions */ long getCacheEvictions(); /** * The mean time to execute gets. *

* In a read-through cache the time taken to load an entry on miss is not * included in get time. * * @return the time in µs */ float getAverageGetTime(); /** * The mean time to execute puts. * * @return the time in µs */ float getAveragePutTime(); /** * The mean time to execute removes. * * @return the time in µs */ float getAverageRemoveTime(); } ================================================ FILE: src/main/java/javax/cache/management/package-info.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ /** * This package contains management interfaces. * * @author Greg Luck * @since 1.0 */ package javax.cache.management; ================================================ FILE: src/main/java/javax/cache/package-info.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ /** * This package contains the API for JCache. JCache describes the technique * whereby Java developers use a {@link javax.cache.spi.CachingProvider} to * temporarily cache Java objects. It provides a common way for Java programs * to create, access, update and remove entries from caches. *

Core Concepts

* The Java Caching API defines five core interfaces: * {@link javax.cache.spi.CachingProvider}, {@link javax.cache.CacheManager}, * {@link javax.cache.Cache}, {@link javax.cache.Cache.Entry} and * {@link javax.cache.expiry.ExpiryPolicy}. *

* A {@link javax.cache.spi.CachingProvider} defines the mechanism to establish, * configure, acquire, manage and control zero or more * {@link javax.cache.CacheManager}s. An application may access and use zero * or more {@link javax.cache.spi.CachingProvider}s at runtime. *

* A {@link javax.cache.CacheManager} defines the mechanism to establish, * configure, acquire, manage and control zero or more uniquely named * {@link javax.cache.Cache}s all within the context of the * {@link javax.cache.CacheManager}. A {@link javax.cache.CacheManager} is * owned by a single {@link javax.cache.spi.CachingProvider}. *

* A {@link javax.cache.Cache} is a Map-like data-structure that permits * the temporary storage of Key-based Values, some what like * {@link java.util.Map} data-structure. A {@link javax.cache.Cache} is owned * by a single {@link javax.cache.CacheManager}. *

* An {@link javax.cache.Cache.Entry} is a single key-value pair stored by a * {@link javax.cache.Cache}. *

* Each entry stored by a {@link javax.cache.Cache} has a defined duration, called * the Expiry Duration, during which they may be accessed, updated and removed. * Once this duration has passed, the entry is said to be expired. Once expired, * entries are no longer available to be accessed, updated or removed, just as if * they never existed in a {@link javax.cache.Cache}. Expiry is set using an * {@link javax.cache.expiry.ExpiryPolicy}. *

Store-By-Value and Store-By-Reference

* Entries are stored by individual {@link javax.cache.Cache}s using one of two * mechanisms: * store-by-value and store-by-reference. *

Store-By-Value

* The default mechanism, called store-by-value, instructs an implementation to * make a copy of application provided keys and values prior to storing them in a * {@link javax.cache.Cache} and later to return a new copy of the entries when * accessed from a {@link javax.cache.Cache}. *

* The purpose of copying entries as they are stored in a {@link javax.cache.Cache} * and again when they are returned from a {@link javax.cache.Cache} is to allow * applications to continue mutating the state of the keys and values without causing * side-effects to entries held by a {@link javax.cache.Cache}. *

Store-By-Reference

* The alternative and optional mechanism, called store-by-reference, instructs a * {@link javax.cache.Cache} implementation to simply store and return references to * the application provided keys and values, instead of making a copies as required by * the store-by-value approach. Should an application later mutate the keys or values * provided to a {@link javax.cache.Cache} using store-by-reference semantics, the * side-effects of the mutations will be visible to those accessing the entries from * the {@link javax.cache.Cache}, without an application having to update the * {@link javax.cache.Cache}. *

{@link javax.cache.Cache}s and {@link java.util.Map}s

* While {@link javax.cache.Cache}s and {@link java.util.Map}s share somewhat similar * APIs, {@link javax.cache.Cache}s are not Maps and {@link java.util.Map}s are not * {@link javax.cache.Cache}s. * The following section outlines the main similarities and differences. *

* Like {@link java.util.Map}-based data-structures: *

    *
  • {@link javax.cache.Cache} values are stored and accessed through an associated * key.
  • *
  • Each key may only be associated with a single value in a * {@link javax.cache.Cache}.
  • Great care must be exercised if mutable objects are * used as keys. The behavior of a {@link javax.cache.Cache} is undefined if a key * is mutated in a manner that affects equals comparisons when a key is used with * a {@link javax.cache.Cache}.
  • {@link javax.cache.Cache}s depend on the * concept of equality to determine when keys and values are the same. Consequently * custom key and value classes should define a suitable implementation of the * {@link java.lang.Object#equals} method.
  • Custom key classes should * additionally provide a suitable implementation of the * {@link java.lang.Object#hashCode()} method. *

    * Although recommended, implementations are not required to call either the * Object.hashCode or Object.equals methods defined by custom key classes. * Implementations are free to use optimizations whereby the invocation of these * methods is avoided. *

    * As this specification does not define the concept of object equivalence it * should be noted applications that make use of custom key classes and rely on * implementation specific optimizations to determine equivalence may not be * portable.

  • *
* Unlike {@link java.util.Map}-based data-structures: *
    *
  • {@link javax.cache.Cache} keys and values must not be null.
  • *
  • Any attempt to use null for keys or values will result in a * {@link java.lang.NullPointerException} being thrown, regardless of the use.
  • *
  • Entries may expire.
  • *
  • Entries may be evicted.
  • *
  • To support the compare-and-swap (CAS) operations, those that atomically * compare and exchange values, custom value classes should provide a suitable * implementation of {@link java.lang.Object#equals}. *

    * Although recommended, implementations are not required to call the * {@link java.lang.Object#equals} method defined by custom value classes. * Implementations are free to implement optimizations whereby the invocation * of this method is avoided.

  • *
  • Implementations may require Keys and Values to be serializable in some * manner.
  • *
  • {@link javax.cache.Cache}s may be configured to control how entries are stored, * either using * store-by-value or optionally using store-by-reference semantics.
  • *
  • Implementations may optionally enforce security restrictions. In case of a * violation, a {@link java.lang.SecurityException} must be thrown.
  • *
*

Consistency

* Consistency refers to the behavior of caches and the guarantees that exist when * concurrent cache mutation occur together with the visibility of the mutations * when multiple threads are accessing a cache. *

* All implementations must support the Default Consistency model as outlined * below. *

Default Consistency

* When using the default consistency mode, most {@link javax.cache.Cache} operations * are performed as if a locking mechanism exists for each key in a * {@link javax.cache.Cache}. When a cache operation acquires an exclusive read and * write lock on a key all subsequent operations on that key will block until that * lock is released. The consequences are that operations performed by a thread * happen-before read or mutation operations performed by another thread, including * threads in different Java Virtual Machines. *

* For some {@link javax.cache.Cache} operations the value returned by a * {@link javax.cache.Cache} is considered the last value. The last value might be an * old value or a new value, especially in the case where an entry is concurrently being * updated. It is implementation dependent which is returned. *

* Other operations follow a different convention in that mutations may only occur * when the current state of an entry matches a desired state. In such operations * multiple threads are free to compete to apply these changes i.e. as if they * share a lock. *

* As these methods must interact with other {@link javax.cache.Cache} operations * acting as if they had an exclusive lock, the CAS methods cannot write new values * without acting as if they also had an exclusive lock. *

* See the JCache Specification for further details. *

Further Consistency Models

* An implementation may provide support for different consistency models in * addition to the required Default Consistency mode *

A Simple Example

*

This simple example creates a default {@link javax.cache.CacheManager}, * configures a {@link javax.cache.Cache} on it called “simpleCache” with a key type * of String and a value type of Integer and an expiry of one hour and then performs * a some cache operations. *

*

 * //resolve a cache manager
 * CachingProvider cachingProvider = Caching.getCachingProvider();
 * CacheManager cacheManager = cachingProvider.getCacheManager();
 *
 * //configure the cache
 * MutableConfiguration<String, Integer> config =
 *    new MutableConfiguration<>()
 *    .setTypes(String.class, Integer.class)
 *    .setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(ONE_HOUR))
 *    .setStatisticsEnabled(true);
 *
 * //create the cache
 * Cache<String, Integer> cache = cacheManager.createCache("simpleCache", config);
 *
 * //cache operations
 * String key = "key";
 * Integer value1 = 1;
 * cache.put("key", value1);
 * Integer value2 = cache.get(key);
 * cache.remove(key);
 * 
* * @author Greg Luck * @since 1.0 */ package javax.cache; ================================================ FILE: src/main/java/javax/cache/processor/EntryProcessor.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.processor; import javax.cache.Cache; import javax.cache.event.CacheEntryListener; import javax.cache.expiry.ExpiryPolicy; import javax.cache.integration.CacheWriter; /** * An invocable function that allows applications to perform compound operations * on a {@link javax.cache.Cache.Entry} atomically, according to the defined * consistency of a {@link Cache}. *

* Any {@link javax.cache.Cache.Entry} mutations will not take effect until after * the {@link EntryProcessor#process(MutableEntry, Object...)} method has completed * execution. *

* If an exception is thrown by an {@link EntryProcessor}, a Caching Implementation * must wrap any {@link Exception} thrown wrapped in an {@link * EntryProcessorException}. If this occurs no mutations will be made to the * {@link javax.cache.Cache.Entry}. *

* Implementations may execute {@link EntryProcessor}s in situ, thus avoiding * locking, round-trips and expensive network transfers. * *

Effect of {@link MutableEntry} operations

* {@link javax.cache.Cache.Entry} access, via a call to * {@link javax.cache.Cache.Entry#getValue()}, will behave as if * {@link Cache#get(Object)} was called for the key. This includes updating * necessary statistics, consulting the configured {@link ExpiryPolicy} and loading * from a configured {@link javax.cache.integration.CacheLoader}. *

* {@link javax.cache.Cache.Entry} mutation, via a call to * {@link MutableEntry#setValue(Object)}, will behave as if {@link * Cache#put(Object, Object)} was called for the key. This includes updating * necessary statistics, consulting the configured {@link * ExpiryPolicy}, notifying {@link CacheEntryListener}s and writing to a * configured {@link CacheWriter}. *

* {@link javax.cache.Cache.Entry} removal, via a call to * {@link MutableEntry#remove()}, will behave as if {@link Cache#remove(Object)} * was called for the key. This includes updating necessary statistics, notifying * {@link CacheEntryListener}s and causing a delete on a configured * {@link CacheWriter}. *

* As implementations may choose to execute {@link EntryProcessor}s remotely, * {@link EntryProcessor}s, together with specified parameters and return * values, may be required to implement {@link java.io.Serializable}. * *

Effect of multiple {@link MutableEntry} operations performed by one {@link * EntryProcessor}

* Only the net effect of multiple operations has visibility outside of the Entry * Processor. The entry is locked by the entry processor for the entire scope * of the entry processor, so intermediate effects are not visible. *

Example 1

* In this example, an {@link EntryProcessor} calls: *
    *
  1. {@link MutableEntry#getValue()}
  2. *
  3. {@link MutableEntry#setValue(Object)}
  4. *
  5. {@link MutableEntry#getValue()}
  6. *
  7. {@link MutableEntry#setValue(Object)}
  8. *
* This will have the following {@link Cache} effects: *
* Final value of the cache: last setValue
* Statistics: one get and one put as the second get and the first put are * internal to the EntryProcessor.
* Listeners: second put will cause either a put or an update depending on whether * there was an initial value for the entry.
* CacheLoader: Invoked by the first get only if the entry is not present, a * loader was registered and read through is enabled.
* CacheWriter: Invoked by the second put only as the first put was internal to * the Entry Processor.
* ExpiryPolicy: The first get and the second put only are visible to the * ExpiryPolicy.
* *

Example 2

* In this example, an {@link EntryProcessor} calls: *
    *
  1. {@link MutableEntry#getValue()}
  2. *
  3. {@link MutableEntry#remove()}}
  4. *
  5. {@link MutableEntry#getValue()}
  6. *
  7. {@link MutableEntry#setValue(Object)}
  8. *
* This will have the following {@link Cache} effects: *
* Final value of the cache: last setValue
* Statistics: one get and one put as the second get and the first put are * internal to the EntryProcessor.
* Listeners: second put will cause either a put or an update depending on whether * there was an initial value for the entry.
* CacheLoader: Invoked by the first get only if the entry is not present, a loader * was registered and read through is enabled.
* CacheWriter: Invoked by the second put only as the first put was internal to * the Entry Processor.
* ExpiryPolicy: The first get and the second put only are visible to the * ExpiryPolicy.
* *

Example 3

* In this example, an {@link EntryProcessor} calls: *
    *
  1. {@link MutableEntry#getValue()}
  2. *
  3. {@link MutableEntry#setValue(Object)}}
  4. *
  5. {@link MutableEntry#getValue()}
  6. *
  7. {@link MutableEntry#setValue(Object)}
  8. *
  9. {@link MutableEntry#remove()}
  10. *
* This will have the following {@link Cache} effects: *
* Final value of the cache: the entry is removed if it was present
* Statistics: one get and one remove as the second get and the two puts are * internal to the EntryProcessor.
* Listeners: remove if there was initial value in the cache, otherwise no * listener invoked. *
CacheLoader: Invoked by the first get only if the entry is not present, * a loader was registered and read through is enabled. *
CacheWriter: Invoked by the remove only as the two puts are internal to * the Entry Processor, provided that the first #getValue was non-null.
* ExpiryPolicy: The first get only is visible to the ExpiryPolicy. There is no * remove event in ExpiryPolicy. * * @param the type of keys maintained by this cache * @param the type of cached values * @param the type of the return value * @author Greg Luck * @since 1.0 */ public interface EntryProcessor { /** * Process an entry. * * @param entry the entry * @param arguments a number of arguments to the process. * @return the user-defined result of the processing, if any. * @throws EntryProcessorException if there is a failure in entry processing. */ T process(MutableEntry entry, Object... arguments) throws EntryProcessorException; } ================================================ FILE: src/main/java/javax/cache/processor/EntryProcessorException.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.processor; import javax.cache.CacheException; /** * An exception to indicate a problem occurred attempting to execute an * {@link EntryProcessor} against an entry. *

* An implementation must wrap any {@link Exception} thrown by an * {@link EntryProcessor} in this exception. * * @author Greg Luck * @since 1.0 */ public class EntryProcessorException extends CacheException { private static final long serialVersionUID = 20130822110920L; /** * Constructs a new CacheLoaderException. */ public EntryProcessorException() { super(); } /** * Constructs a new CacheLoaderException with a message string. * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. */ public EntryProcessorException(String message) { super(message); } /** * Constructs a CacheLoaderException with a message string, and * a base exception * * @param message the detail message. The detail message is saved for * later retrieval by the {@link #getMessage()} method. * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public EntryProcessorException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new CacheLoaderException with the specified cause and a * detail message of (cause==null ? null : cause.toString()) * (that typically contains the class and detail message of * cause). This constructor is useful for runtime exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (that is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.0 */ public EntryProcessorException(Throwable cause) { super(cause); } } ================================================ FILE: src/main/java/javax/cache/processor/EntryProcessorResult.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.processor; import javax.cache.CacheException; /** * A mechanism to represent and obtain the result of processing * a {@link javax.cache.Cache} entry using an {@link EntryProcessor}. * * @param the type of the return value * * @author Brian Oliver * @since 1.0 */ public interface EntryProcessorResult { /** * Obtain the result of processing an entry with an {@link EntryProcessor}. *

* If an exception was thrown during the processing of an entry, either by * the {@link EntryProcessor} itself or by the Caching implementation, * the exceptions will be wrapped and re-thrown as a * {@link EntryProcessorException} when calling this method. * * @return the result of processing * * @throws CacheException if the implementation failed to execute * the {@link EntryProcessor} * @throws EntryProcessorException if the {@link EntryProcessor} raised * an exception, this exception will be * used to wrap the causing exception */ T get() throws EntryProcessorException; } ================================================ FILE: src/main/java/javax/cache/processor/MutableEntry.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.processor; import javax.cache.Cache; import javax.cache.integration.CacheLoader; /** * A mutable representation of a {@link javax.cache.Cache.Entry}. *

* Mutable entries are used by {@link EntryProcessor}s to mutate * {@link Cache.Entry}s in place, atomically. * * @param the type of key * @param the type of value * * @author Greg Luck * @since 1.0 * @see EntryProcessor */ public interface MutableEntry extends Cache.Entry { /** * Checks for the existence of the entry in the cache * * @return true if the entry exists */ boolean exists(); /** * Removes the entry from the Cache. *

* This has the same semantics as calling {@link Cache#remove}. */ void remove(); /** * Returns the value stored in the cache. *

* If the cache is configured to use read-through, and this method * would return null because the entry is missing from the cache, * the Cache's {@link CacheLoader} is called in an attempt to load * the entry. * * @return the value corresponding to this entry */ V getValue(); /** * Sets or replaces the value associated with the key. *

* If {@link #exists} is false and setValue is called * then a mapping is added to the cache visible once the EntryProcessor * completes. Moreover a second invocation of {@link #exists()} * will return true. * * @param value the value to update the entry with * @throws ClassCastException if the implementation supports and is * configured to perform runtime-type-checking, * and value type is incompatible with that * which has been configured for the * {@link Cache} */ void setValue(V value); } ================================================ FILE: src/main/java/javax/cache/processor/package-info.java ================================================ /** * Copyright (c) 2011-2013 Terracotta, Inc. * Copyright (c) 2011-2013 Oracle and/or its affiliates. * * All rights reserved. Use is subject to license terms. */ /** * This package contains the API for Entry Processors. *

* Implementations may optionally enforce security restrictions. In case of a * violation, a {@link java.lang.SecurityException} must be thrown. * * @author Greg Luck * @since 1.0 */ package javax.cache.processor; ================================================ FILE: src/main/java/javax/cache/spi/CachingProvider.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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 javax.cache.spi; import javax.cache.CacheException; import javax.cache.CacheManager; import javax.cache.configuration.OptionalFeature; import java.io.Closeable; import java.net.URI; import java.util.Properties; /** * Provides mechanisms to create, request and later manage the life-cycle of * configured {@link CacheManager}s, identified by {@link URI}s and scoped by * {@link ClassLoader}s. *

* The meaning and semantics of the {@link URI} used to identify a * {@link CacheManager} is implementation dependent. For applications to remain * implementation independent, they should avoid attempting to create {@link URI}s * and instead use those returned by {@link #getDefaultURI()}. * * @author Brian Oliver * @author Greg Luck * @since 1.0 */ public interface CachingProvider extends Closeable { /** * Requests a {@link CacheManager} configured according to the implementation * specific {@link URI} be made available that uses the provided * {@link ClassLoader} for loading underlying classes. *

* Multiple calls to this method with the same {@link URI} and * {@link ClassLoader} must return the same {@link CacheManager} instance, * except if a previously returned {@link CacheManager} has been closed. *

* Properties are used in construction of a {@link CacheManager} and do not form * part of the identity of the CacheManager. i.e. if a second call is made to * with the same {@link URI} and {@link ClassLoader} but different properties, * the {@link CacheManager} created in the first call is returned. *

* Properties names follow the same scheme as package names. * The prefixes {@code java} and {@code javax} are reserved. * Properties are passed through and can be retrieved via * {@link CacheManager#getProperties()}. * Properties within the package scope of a caching implementation may be used for * additional configuration. * * @param uri an implementation specific URI for the * {@link CacheManager} (null means use * {@link #getDefaultURI()}) * @param classLoader the {@link ClassLoader} to use for the * {@link CacheManager} (null means use * {@link #getDefaultClassLoader()}) * @param properties the {@link Properties} for the {@link CachingProvider} * to create the {@link CacheManager} (null means no * implementation specific Properties are required) * @throws CacheException when a {@link CacheManager} for the * specified arguments could not be produced * @throws SecurityException when the operation could not be performed * due to the current security settings */ CacheManager getCacheManager(URI uri, ClassLoader classLoader, Properties properties); /** * Obtains the default {@link ClassLoader} that will be used by the * {@link CachingProvider}. * * @return the default {@link ClassLoader} used by the {@link CachingProvider} */ ClassLoader getDefaultClassLoader(); /** * Obtains the default {@link URI} for the {@link CachingProvider}. *

* Use this method to obtain a suitable {@link URI} for the * {@link CachingProvider}. * * @return the default {@link URI} for the {@link CachingProvider} */ URI getDefaultURI(); /** * Obtains the default {@link Properties} for the {@link CachingProvider}. *

* Use this method to obtain suitable {@link Properties} for the * {@link CachingProvider}. * * @return the default {@link Properties} for the {@link CachingProvider} */ Properties getDefaultProperties(); /** * Requests a {@link CacheManager} configured according to the implementation * specific {@link URI} that uses the provided {@link ClassLoader} for loading * underlying classes. *

* Multiple calls to this method with the same {@link URI} and * {@link ClassLoader} must return the same {@link CacheManager} instance, * except if a previously returned {@link CacheManager} has been closed. * * @param uri an implementation specific {@link URI} for the * {@link CacheManager} (null means * use {@link #getDefaultURI()}) * @param classLoader the {@link ClassLoader} to use for the * {@link CacheManager} (null means * use {@link #getDefaultClassLoader()}) * @throws CacheException when a {@link CacheManager} for the * specified arguments could not be produced * @throws SecurityException when the operation could not be performed * due to the current security settings */ CacheManager getCacheManager(URI uri, ClassLoader classLoader); /** * Requests a {@link CacheManager} configured according to the * {@link #getDefaultURI()} and {@link #getDefaultProperties()} be made * available that using the {@link #getDefaultClassLoader()} for loading * underlying classes. *

* Multiple calls to this method must return the same {@link CacheManager} * instance, except if a previously returned {@link CacheManager} has been * closed. * * @throws SecurityException when the operation could not be performed * due to the current security settings */ CacheManager getCacheManager(); /** * Closes all of the {@link CacheManager} instances and associated resources * created and maintained by the {@link CachingProvider} across all * {@link ClassLoader}s. *

* After closing the {@link CachingProvider} will still be operational. It * may still be used for acquiring {@link CacheManager} instances, though * those will now be new. * * @throws SecurityException when the operation could not be performed * due to the current security settings */ void close(); /** * Closes all {@link CacheManager} instances and associated resources created * by the {@link CachingProvider} using the specified {@link ClassLoader}. *

* After closing the {@link CachingProvider} will still be operational. It * may still be used for acquiring {@link CacheManager} instances, though * those will now be new for the specified {@link ClassLoader} . * * @param classLoader the {@link ClassLoader} to release * @throws SecurityException when the operation could not be performed * due to the current security settings */ void close(ClassLoader classLoader); /** * Closes all {@link CacheManager} instances and associated resources created * by the {@link CachingProvider} for the specified {@link URI} and * {@link ClassLoader}. * * @param uri the {@link URI} to release * @param classLoader the {@link ClassLoader} to release * @throws SecurityException when the operation could not be performed * due to the current security settings */ void close(URI uri, ClassLoader classLoader); /** * Determines whether an optional feature is supported by the * {@link CachingProvider}. * * @param optionalFeature the feature to check for * @return true if the feature is supported */ boolean isSupported(OptionalFeature optionalFeature); } ================================================ FILE: src/main/java/javax/cache/spi/package-info.java ================================================ /** * Copyright 2011-2016 Terracotta, Inc. * Copyright 2011-2016 Oracle America Incorporated * * 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. */ /** The javax.cache.spi package defines the classes and interfaces that are implemented by the caching provider for use by the {@link javax.cache.Caching} class @author Yannis Cosmadopoulos @since 1.0 */ package javax.cache.spi;