This chapter includes the following sections:
The Coherence examples include:
Basic Features
The Coherence Basic Features Examples include the following:
Table 6-1 Coherence Basic Features Examples
| Example Name | Description |
|---|---|
|
Basic Data Access |
"Getting", "putting" and "removing" data from the Coherence Data Grid. See Basic Data Access Example. |
|
Data Loading |
Loading example data into the Coherence Data Grid. See Loader Example. |
|
Parallel Querying |
Querying the Coherence Data Grid including the use of indexes. See Query Example. |
|
Observable |
Listening for changes to data in the Coherence Data Grid. See Observer Example. |
|
Processing |
Co-locating data processing with the data itself in the Coherence Data Grid. See Processor Example. |
|
Query Language |
How to use the Coherence Query Language. See Query Example. |
Security Features
The Coherence Security Examples include the following:
Table 6-2 Coherence Security Examples
| Example Name | Description |
|---|---|
|
Password Example |
Requiring a password to access Coherence. See Password Example. |
|
Access Control Example |
Simplified role based access control. See Access Control Example. |
|
Password Identity Transformer |
Creates a custom security token that contains the required password and then adds a list of Principal names. See Password Identity Transformer. |
|
Password Identity Asserter |
Asserts that the security token contains the required password and then constructs a Subject based on a list of Principal names. See Password Identity Asserter. |
|
Entitled Cache Service |
Wraps a cache service for access control. See Entitled Cache Service. |
|
Entitled Invocation Service |
Wraps an invocation service for access control. See Entitled Invocation Service. |
|
Entitled Named Cache |
Wraps a named cache for access control. See Entitled Named Cache. |
Live Events
The Coherence Live Events Examples are available for the Java platform only. They include the following:
Table 6-3 Coherence Live Events Examples
| Example Name | Description |
|---|---|
|
EventsExamples |
Illustrates various features within Live Events, such as providing mean elapsed times split by event type, the different semantics in throwing exceptions in pre-events compared to post-events, and logging of partition movement when enabled. See EventsExamples. |
|
TimedTraceInterceptor |
Provides timings between pre- and post-commit events for different types of events. See TimedTraceInterceptor. |
|
CantankerousInterceptor |
Responds with runtime exceptions at either pre- or post-commit time, based on the type of key being inserted. See CantankerousInterceptor. |
|
RedistributionInterceptor |
Logs partition events when enabled. See RedistributionInterceptor. |
|
RedistributionInvocable |
Defines three actionable states that will be executed on various members of the cluster. The states are enable logging performed by the RedistributionInterceptor, disable logging, or terminate the JVM that the invocable (RedistributionInvocable) is executed on. See RedistributionInvocable. |
|
LazyProcessor |
Creates a superficial delay between the processing of events. See LazyProcessor. |
Java 8 Features
The Coherence Java 8 Examples demonstrate how to use Coherence with various features introduced in Java 8. The examples are available for the Java platform only. They include the following:
Table 6-4 Coherence Java 8 Examples
| Example Name | Description |
|---|---|
|
StreamsExample |
Queries a cache using the |
|
LambdaExample |
Performs cache operations using lambda expressions. See Lambda. |
|
MapDefaultMethodExample |
Performs cache operations using overridden default methods from the |
Asynchronous Features
The Coherence Asynchronous Examples demonstrate how to use asynchronous processing using the AsyncNamedCache interface. The examples are available for the Java platform only. They include the following:
Table 6-5 Coherence Asynchronous Examples
| Example Name | Description |
|---|---|
|
DataAccessExample |
Performs cache operations asynchronously. See Asynchronous Data Access. |
|
ProcessorExample |
Process cache entries asynchronously. See Asynchronous Entry Processor. |
|
AggregatorExample |
Aggregates cache entries asynchronously. See Asynchronous Aggregator. |
Federated Caching
The Coherence Federated Caching Examples demonstrates how to configure and use Federated Caching. Two clusters are started and are configured to use Active-Active replication, which means data can be replicated from either cluster to the other. Each cluster includes a GUI to insert data or clear the caches in either cluster. The Federated Caching Examples also includes steps to configure SSL between cluster participants. The examples are available for the Java platform only.
Persistence
The Coherence Persistence Examples demonstrate how to save and restore the contents of a cache to disk. The examples are available for the Java platform only. They include the following:
Table 6-6 Coherence Persistence Examples
| Example Name | Description |
|---|---|
|
Basic Snapshot Operations |
Persists the contacts cache to disk. Destroys the cache and then reloads the cache from disk. See Basic Snapshot Operations. |
|
Persistence Notifications |
Subscribes to persistence notifications to determine the duration of persistence operations. See Persistence Notifications. |
|
Persistence Operations in Parallel |
Runs persistence operations in parallel across multiple services. See Persistence Operations in Parallel. |
|
SFTP Archiver |
Creates a custom snapshot archiver which uses SFTP to store and retrieve snapshots. See Archiving Snapshots with a Custom Archiver. |
REST
The Coherence REST Examples demonstrates how applications can interact with a Coherence Cache over the HTTP protocol. The example is a single web-based application that exercise serval Coherence features. The examples are available for the Java platform only and the client-side application is written using JavaScript. They include the following:
Table 6-7 Coherence REST Examples
| Example Name | Description |
|---|---|
|
Products Example |
Insert, edit and remove entries from a cache and update entries using an entry processor. See Products Page. |
|
Department Example |
Insert, edit, and remove entries from a cache. See Departments Page. |
|
Contacts Example |
Insert, edit, and remove entries from a cache. Query entries in a cache. See Contacts Page. |
|
Server-Sent Events |
Add listeners and monitor events for the products, department, and contacts caches. See Server-Sent Events. |
You can obtain the examples by performing a full Coherence installation with the coherence_version.jar or wls_version.jar installer file. The Coherence examples appear as an installation option in the Oracle Universal Installer and are installed to COHERENCE_HOME/examples.
If you installed Coherence using coherence_quick_version.jar, you can obtain the examples by running the coherence_quick_supp_version.jar supplemental installer file. The supplemental installer contains only API documentation and examples. Note that the coherence_quick_version.jar quick installer file does not install the examples or API documentation.
Note:
You must build and run the Java example even for .NET and C++. This is because the cache server runs in Java.
This section contains the following information:
This section contains the following information:
To build the example, you must have Coherence and a Java Development Kit (JDK) 1.8 or later. Ensure that the following environment variables are set.
| Environment Variable | Description |
|---|---|
|
|
Make sure that the |
|
|
Make sure that the |
The directory structure described below is relative to the examples directory.
Table 6-8 Directory Structure for Java
| Directory Name | Description |
|---|---|
|
|
Scripts for building and executing the example. There are two sets of scripts. Scripts with no file extension are bash scripts. Scripts with a
|
|
|
All example source. The examples are in the |
|
|
The class files output from a build. This directory will not exist until the build script is executed. |
|
|
The common Coherence configuration files required by the examples. |
|
|
If an example has configuration that is required instead of the common configuration, it will have its own directory. The security example uses configuration files from |
|
|
Coherence libraries used for compiling and running the example. |
Execute the build script with the name of the example collection:
bin/build contacts
bin/build security
bin/build events
bin/build java8
bin/build async
bin/build federation
bin/build persistence
The script builds the POF package files and then the files for the particular example. The contacts example is required for the other examples and should always be built first.
On Windows, change directories to the /bin directory then run the scripts.
This section contains the following information:
To build the example, you must have Coherence for .NET and Visual Studio 2008 or later or Visual Studio 2008 Express or later. For more information on .NET requirements, see Prerequisites.
To run the example, you will need the Java version of Coherence and a Java Development Kit (JDK) 1.8 or greater. The Java version is required because the Coherence*Extend proxy and cache servers require Java. Also, the examples depend on Java example classes that must be built before running the proxy and cache server. See the Java example readme.txt file for instructions on how to build and run.
The directory structure described below is relative to the examples directory.
Table 6-9 Directory Structure for .NET
| Directory Name | Description |
|---|---|
|
dotnet\src |
All example source. The examples are in the The examples are in the Visual Studio 2008 examples solution. Each example has its own Visual Studio 2008 project in the The Coherence configuration files required by the example. |
|
|
The common Coherence configuration files required by the examples. |
|
|
If an example has configuration that is required instead of the common configuration, it will have its own directory. The security example uses configuration files from |
Open the examples project from the examples\dotnet\src\contacts.csproj directory with Visual Studio
When installing Coherence for the .NET Framework, the installer registers the coherence.dll library with the assembly registry. The included Visual Studio projects have a reference to coherence.dll in the default location. If another version of the library is desired, or it was not installed in the default location, the Coherence reference can be overridden when configuring the reference, be sure to set the local copy attribute to true. This setting will copy and register the correct coherence.dll in the bin\debug directory.
After Coherence for .NET is configured, in Visual Studio select Build then Build Solution from the menu, Build Solution (F6), etc., to build the solution.
The build for the contacts example will copy resource\contacts.csv to the build output directory (examples\dotnet\src\bin\Debug).
This section contains the following information:
To run the examples, you will need the Java version of Coherence and a Java Development Kit (JDK) 1.8 or greater. The Java version is required because the Coherence*Extend proxy and cache servers require Java. Also, the examples depend on Java example classes that must be built before running the proxy and cache server. See the Java examples readme.txt for instructions on how to build and run.
Ensure that the following environment variables are set:
| Environment Variable | Description |
|---|---|
|
|
Make sure that the |
|
|
Make sure that the |
|
|
Make sure that the |
The directory structure described below is relative to the examples directory.
Table 6-10 Directory Structure for C++
| Directory Name | Description |
|---|---|
|
|
Scripts for building and executing the examples. Scripts with no file extension are bash scripts. Scripts with a |
|
|
All example source organized under the |
|
|
The |
|
|
The |
|
|
The data model is represented in this directory plus any classes that are serialized. The rationale is to show how to utilize an already existing data model and expose it in Coherence. The model classes do not contain any Coherence-specific code to prove this point. However, there is a serializer that is associated with each model type. For example the The generated output will be in the form of a dynamic library. |
|
|
The common Coherence configuration files required by the examples. |
|
|
If an example has configuration that is required instead of the common configuration, it will have its own directory. The security example uses configuration files from |
|
|
The object files output from a build. This directory will not exist until the build script is executed. |
|
|
Contains the Coherence header files. |
|
|
Contains the Coherence library. |
This section contains the following information:
Build Instructions for C++ on Windows
Open a development environment command prompt. This should have been installed with Visual Studio or the platform SDK. Go to the C++ examples directory and type bin\build.cmd <example name>. This will build both the pof (model) and the example executable. For example, bin\build.cmd contacts or bin\build.cmd security
The model will put the pof.lib and pof.dll file under cpp\pof\out. These are needed for building and running the contacts and security examples.
The executable contacts.exe will be generated in cpp\contacts\out directory. The executable security.exe will be generated in cpp\security\out directory.
To run the contacts example, type bin\run.cmd contacts after starting a proxy server and cache servers: bin/run-cache-server. The cache server also runs a proxy service which allows connections from Coherence*Extend clients.
As an alternative, in any command window you can cd to the C++ bin directory and run vcvars32.bat before trying to build the examples. With a default install of Visual Studio, the bin directory is C:\Program Files\Mircorsoft Visual Studio 9.0\vc\bin. Follow the previous instructions for running the build script.
Build Instructions for C++ on Linux/Mac and Solaris
Open a command shell. Go to the C++ examples directory and type bin/build <example name>. This will build both the pof (model) and the contacts examples executable.
The model dynamic library and lib file will be put in cpp/pof/out. These are needed for building and running the contacts and security examples.
The executable contacts, will be generated in cpp/contacts/out or cpp/security/out.
Note:
The Coherence examples are distributed as source, so they must first be built. See How to Build the Examples.
This section contains the following information:
This section contains the following information:
To run the examples, you must have Coherence installed and use the currently supported JDK. For details on the supported JDK, see "System Requirements."
| Environment Variable | Description |
|---|---|
|
|
Make sure that the |
|
|
Make sure that the |
The directory structure described below is relative to the examples directory, the directory into which the examples were unzipped.
Table 6-11 Directory Structure for Java
| Directory Name | Description |
|---|---|
|
|
Scripts for building and executing examples. There are two sets of scripts. Scripts with no file extension are bash scripts. Scripts with a
|
|
|
The class files output from a build. This directory will not exist until the build script is executed. |
|
|
The common Coherence configuration files required by the examples. |
|
|
If an example has configuration that is required instead of the common configuration, it will have its own directory. The |
|
|
Coherence libraries used for compiling and running the examples. |
|
|
The data file used for the contacts |
Execute the run script for each example.
contacts example
Start one or more cache servers: bin/run-cache-server. Each execution starts a cache server cluster node. To add additional nodes, execute the command in a new command shell.
In a new command shell, run with the name of the example: bin/run contacts. The Driver.main method runs through the features of the example with output going to the command window (stdout).
Starting with Coherence 12.1.2, an example of the new Query Language feature was added. This example shows how to configure and use a simple helper class FilterFactory using the Coherence InvocationService.
security example
The security example requires Coherence*Extend, which uses a proxy.
Start one or more cache servers: bin/run-cache-server security. The cache server also runs a proxy service which allows connections from Coherence*Extend clients.
In a new command shell, run with the name of the example: bin/run security. The Driver.main method runs through the features of the example with output going to the command window (stdout).
live events example
Start one or more cache servers: bin/run-cache-server events. Each execution starts a cache server cluster node. To add additional nodes, execute the command in a new command shell.
In a new command shell, run with the name of the example: bin/run events. The Driver.main method runs through the features of the example with output going to the command window (stdout).
Java 8 features example
Start a cache server: bin/run-cache-server.
In a new command shell, run with the name of the example: bin/run java8. The Driver.main method runs through the features of the example with output going to the command window (stdout). Inspect the output and refer to the code at src/com/tangosol/examples/java8.
asynchronous features example
Start a cache server: bin/run-cache-server.
In a new command shell, run with the name of the example: bin/run async. The Driver.main method runs through the features of the example with output going to the command window (stdout). Inspect the output and refer to the code at src/com/tangosol/examples/async.
federated caching example
Start ClusterA using: bin/run-cache-server federation ClusterA.
In a new command shell, start ClusterB using: bin/run-cache-server federation ClusterB.
Run the following to start a GUI which connects to ClusterA: bin/run federation ClusterA. Use the cohql or console argument to use CohQL or the console instead of a GUI.
Run the following to start a GUI which connects to ClusterB: bin/run federation ClusterB. Use the cohql or console argument to use CohQL or the console instead of a GUI.
Add objects to a cluster and observe that the objects are being replicated to the other cluster.
Remove objects from a cluster and observe that the objects are being removed from the other cluster.
The example above uses standard TCP connections between clusters. The example can also be configured to use SSL. SSL allows connections between clusters to be encrypted and ensures only authorized clusters can exchange information by using two-way authentication.
Note:
The SSL configuration uses self signed certificates and obvious passwords. You should follow security best practices and refer to the Coherence security documentation to configure this for production environments.
SSL configuration requires:
Generating keystores for each of the clusters
Creating SSL certificates for each cluster
Importing the certificates into a trust store that ensure only authorized members can communicate.
Note:
For windows environments, make sure you use %JAVA_HOME%\bin\keytool.
To configure SSL for the federation examples:
Generate Keystores for ClusterA and ClusterB
cd $COHERENCE_HOME/examples/java/classes $JAVA_HOME/bin/keytool -genkeypair -dname "cn=ClusterA, ou=Coherence, o=Oracle, c=US" -alias ClusterA -keypass password -keystore ClusterA-keystore.jks -storepass password $JAVA_HOME/bin/keytool -genkeypair -dname "cn=ClusterB, ou=Coherence, o=Oracle, c=US" -alias ClusterB -keypass password -keystore ClusterB-keystore.jks -storepass password
Export certificates from each store:
$JAVA_HOME/bin/keytool -export -alias ClusterA -storepass password -file ClusterA.cer -keystore ClusterA-keystore.jks $JAVA_HOME/bin/keytool -export -alias ClusterB -storepass password -file ClusterB.cer -keystore ClusterB-keystore.jks
Import both certificates into the trust store that defines which clusters can connect.
$JAVA_HOME/bin/keytool -import -v -trustcacerts -alias ClusterA -file ClusterA.cer -keystore trust.jks -storepass password $JAVA_HOME/bin/keytool -import -v -trustcacerts -alias ClusterB -file ClusterB.cer -keystore trust.jks -storepass password
Enter 'yes' for both of the above to confirm importing the certificates.
Validate the entries in the trust store using:
$JAVA_HOME/bin/keytool -list -keystore trust.jks -storepass password
Once the above has been completed, the classes directory contains the following:
trust.jks – keystore containing the ClusterA and ClusterB certificates
ClusterA.jks – keystore containing the ClusterA private key
ClusterB.jks – keystore containing the ClusterB private key
Re-run the examples and set the SSL environment variable in each command prompt window.
SET SSL=true (Windows)
export SSL=true (Unix)
In the cache server log files, notice that the connection is now tmbs (TCP Message Bus over SSL):
Connecting to service FederatedPartitionedPofCache at participant ClusterB with address tmbs://127.0.0.1:56217.39550
Note:
Removing a certificate from the trust store disables communication to that member and simulates an unauthorized communication.
When you have completed running the Federation examples with SSL, make sure to unset the SSL environment variable if you are going to run other examples.
persistence example
start one or more cache servers: bin/run-cache-server persistence
In a new command shell, run the persistence example: bin/run persistence. The Driver.main method will run through the features of the example with output going to the command window (stdout).
Start the notification listener: bin/run persistence notifications.
Run the persistence example: bin/run persistence. Output is emitted that indicates that Persistence operations are being completed
Use CTRL+C to interrupt the notifications listener.
Run the persistence parallel example: bin/run persistence parallel. The Driver.main method will run through the features of the example with output going to the command window (stdout).
Download the JSch library jsch-0.1.51.jar or later and extract the contents into the classes directory.
Build the archiver example: bin/build archiver.
Update the resource/archiver/tangosol-coherence-override.xml file and modify the third parameter for the custom archiver and replace the username, password and path to the location of a machine running SSH. If you have ssh equivalence setup to your machine, you can omit the password. You may also consider using a system property to hide your password if one is required.
Run the archive example: bin/run archiver.
Inspect the remote SFTP machine to see the archive directory.
This section contains the following information:
To run the examples, you must have Coherence for .NET and Visual Studio 2008 or later. To run the examples, you will also need to build the Java examples. The Java version is required because the Coherence*Extend proxy and cache servers require Java.
Also, the examples depend on Java example classes that must be built before running the proxy and cache server.
The directory structure described below is relative to the "examples" directory.
Table 6-12 Directory Structure for .NET
| Directory Name | Description |
|---|---|
|
|
The data file used for the contacts |
The following sections contain instructions for running the contacts and security examples.
contacts
Start one or more cache servers: bin/run-cache-server. The cache server also runs a proxy service which allows connections from Coherence*Extend clients.
From Visual Studio, start the contacts project without debugging or execute the contacts.exe produced from the build in a command shell. The Driver.Main method will run through the features of the example with the output going to the command window (stdout).
Starting with Coherence 12.1.2, a new example of the new Query Language feature was integrated. This example shows how configure and use a simple helper class "FilterFactory" using the Coherence InvocationService.
security
Following the java readme.txt instructions, start one or more cache servers: bin/run-cache-server security. The cache server also runs a proxy service which allows connections from Coherence*Extend clients.
From Visual Studio, start the security project without debugging or execute the contacts.exe produced from the build in a command shell. The Driver.Main method will run through the features of the example with the output going to the command window (stdout).
This section contains the following information:
To build the examples, you must have the appropriate C++ library of Coherence. Also you must have a C++ development environment. To run the examples, you will also need to build the Java examples. The Java version is required because the Coherence*Extend proxy and cache servers require Java. Also, the examples depend on Java example classes that must be built before running the proxy and cache server.
| Environment Variable | Description |
|---|---|
|
|
Make sure that the |
The supported C++ compilers are:
Windows —Microsoft Visual C++ Express/Studio 2008 or later or the equivalent Platform SDK.
Linux—g++ 4.0
Mac—g++ 4.0
The directory structure described below is relative to the examples directory.
Table 6-13 Directory Structure for C++
| Directory Name | Description |
|---|---|
|
|
Scripts for building and executing the examples. Scripts with no file extension are bash scripts. Scripts with a
|
|
|
All example source organized under the |
|
|
The object files output from a build. This directory will not exist until the build script is executed. |
|
|
The data file used for the contacts LoaderExample: contacts.csv. |
|
|
Contains the |
|
|
Contains the |
|
|
Contains the |
|
|
Contains the Coherence header files. |
|
|
Contains the Coherence library. |
Execute the run scripts. There are two parts to running the example. From within new command shells:
contacts example
Start one or more cache servers: bin/run-cache-server. The cache server also runs a proxy service which allows connections from Coherence*Extend clients.
In a new command shell, execute run with the name of the example:
Running the contacts Example on Windows:
Type bin\run.cmd contacts
Running the contacts Example on Linux/Mac and Solaris:
Type bin/run contacts
The Driver.main method will run through the features of the example with output going to the command window (stdout).
Starting with Coherence 12.1.2, an example of the new Query Language feature was added. This example shows how to configure and use a simple helper class FilterFactory using the Coherence InvocationService.
security example
Start one or more cache servers: bin/run-cache-server security. The cache server also runs a proxy service which allows connections from Coherence*Extend clients.
In a new command shell, execute run with the name of the example:
Running the security Example on Windows:
Type bin\run.cmd security
Running the security Example on Linux/Mac and Solaris:
Type bin/run security
The Driver.main method will run through the features of the example with output going to the command window (stdout).
The Coherence basic features examples are a collection of examples that show how to use the basic features of Coherence using a simplified contact information tracker and includes:
Basic Data Access—"Getting", "putting" and "removing" data from the Coherence Data Grid. See Basic Data Access Example.
Data Loading—Loading example data into the Coherence Data Grid. See Loader Example.
Parallel Querying —Querying the Coherence Data Grid including the use of indexes. See Query Example.
Observable—Listening for changes to data in the Coherence Data Grid. See Observer Example.
Processing—Co-locating data processing with the data itself in the Coherence Data Grid. See Processor Example.
Query Language—How to use the new 3.6 Coherence Query Language. See Query Language.
This example set uses example data represented by these Data Model classes.
Table 6-14 Data Model Classes for the Features Examples
| Name | Description |
|---|---|
|
|
Address information |
|
|
Contact information (includes addresses and phone numbers) |
|
|
The key (contact name) to the contact information |
|
|
Phone number |
This example set also ships with a contacts.csv file which is a comma-delimited value file containing sample Contacts information.
Review the following information:
Review the information on the Driver implementation found in Understanding the Features Driver File.
The Driver file has a static main method that executes all the Contacts examples in the following order:
LoaderExample
QueryExample
QueryLanguageExample
ObserverExample
BasicExample
ProcessorExample
The Driver file is implemented in each of the three programming languages supported by Coherence.
| Language | Implementation Class |
|---|---|
|
Java |
|
|
.NET |
Driver in namespace |
|
C++ |
Driver in namespace |
This example shows the most basic data access features of Coherence including getting, putting and removing data.
Java
Implementation Class: com.tangosol.examples.contacts.BasicExample in java/src
Associate a ContactId with a Contact in the cache:
cache.put(contactId, contact);
Retrieve the Contact associated with a ContactId from the cache:
contact = (Contact) cache.get(contactId);
Remove mapping of ContactId to Contact from the cache:
cache.remove(contactId);
.NET
Implementation Class: BasicExample in namespace Tangosol.Examples.Contacts in dotnet/src/contacts
Associate a ContactId with a Contact in the cache:
cache.Add(contactId, contact);
Retrieve the Contact associated with a ContactId from the cache:
contact = (Contact)cache[contactId];
Remove mapping of ContactId to Contact from the cache:
cache.Remove(contactId);
C++
Implementation Class: BasicExample in namespace coherence::examples in cpp/contacts
Associate a ContactId with a Contact in the cache:
hCache->put(vContactId, vContact);
Retrieve the Contact associated with a ContactId from the cache:
vContact = cast<Managed<Contact>::View>(hCache->get(vContactId));
Remove mapping of ContactId to Contact from the cache:
hCache->remove(vContactId);
The example output (due to "Observer Example"):
Example 6-1 Example Output of the Basic Data Access Example
entry inserted: John Nocyefqgqo Addresses Home: 1500 Boylston St. null Obopnof, NM 88824 US Work: 8 Yawkey Way null Ssedhvmdeq, OR 84217 US Phone Numbers work: +11 0 707 3776578 Birth Date: 1971-12-31 entry deleted: John Nocyefqgqo Addresses Home: 1500 Boylston St. null Obopnof, NM 88824 US Work: 8 Yawkey Way null Ssedhvmdeq, OR 84217 US Phone Numbers work: +11 0 707 3776578 Birth Date: 1971-12-31
This example loads contacts into the cache from a file or stream.
It demonstrates the most effective way of inserting data into a cache using bulk inserts. This will allow for minimizing the number of network roundtrips between the application and the cache.
Java
Implementation Class: com.tangosol.examples.contacts.LoaderExample in java/src
cache.putAll(mapBatch);
.NET
Implementation Class: LoaderExample in namespace Tangosol.Examples.Contacts in dotnet/src/contacts
cache.InsertAll(dictBatch);
C++
Implementation Class: LoaderExample in namespace coherence::examples in cpp/contacts
hCache->putAll(hMapBatch);
QueryExample runs sample queries for contacts.
The purpose of this example is to show how to create Extractors on cache data and how to create a KeyExtractor for the cache keys. It also illustrates how to use the indexes to filter the dataset to efficiently create a matching set. Finally, the example demonstrates how to use some of the built-in cache aggregators to do simple computational tasks on the cache data. A subset of the code is shown below.
Java
Implementation Class: com.tangosol.examples.contacts.QueryExample in java/src
Add an index to make queries more efficient.
cache.addIndex(new ChainedExtractor("getHomeAddress.getState"), /*fOrdered*/ false, /*comparator*/ null);
Find all contacts who live in Massachusetts.
Set setResults = cache.entrySet(new EqualsFilter("getHomeAddress.getState", "MA"));
Count contacts who are older than nAge for the entire cache dataset.
System.out.println("count > " + nAge + ": " + cache.aggregate(new GreaterFilter("getAge", nAge), new Count()));
.NET
Implementation Class: QueryExample in namespace Tangosol.Examples.Contacts in dotnet/src/contacts
Add an index to make queries more efficient.
cache.AddIndex(new ChainedExtractor("getHomeAddress.getState"),/*fOrdered*/ false, /*comparator*/ null);
Find all contacts who live in Massachusetts.
ICacheEntry[] aCacheEntry = cache.GetEntries(new EqualsFilter("getHomeAddress.getState", "MA"));
Count contacts who are older than nAge for the entire cache dataset.
Console.WriteLine("count > " + nAge + ": "+ cache.Aggregate(new GreaterFilter("getAge", nAge), new
Count()));
C++
Implementation Class: QueryExample in namespace coherence::examples in cpp/contacts
Add an index to make queries more efficient.
ValueExtractor::View vHomeStateExtractor = ChainedExtractor::create(
ChainedExtractor::createExtractors("getHomeAddress.getState"));
Find all contacts who live in Massachusetts.
Object::View voStateName = String::create("MA");
Set::View setResults = hCache->entrySet(
EqualsFilter::create(vHomeStateExtractor, voStateName));
Count contacts who are older than nAge for the entire cache dataset.
Integer32::View nAge = Integer32::valueOf(58); Object::View vResult = hCache->aggregate( (Filter::View) GreaterFilter::create(vAgeExtractor, nAge), Count::create()); std::cout << "count > " << nAge->getValue() << ": " << vResult << std::endl;
The example output is large due to 10,000 contacts and several queries. A sample of the query for Massachusetts residents:
Example 6-3 Example Output of the Query Example
MA Residents
ConverterEntry{Key="John Scqngqda", Value="John Scqngqda
Addresses
Home: 265 Beacon St.
Oaskxm, MA 88259
US
Work: Yoyodyne Propulsion Systems
330 Lectroid Rd.
Grover's Mill, OK 95744
US
Phone Numbers
work: +11 88 903 8991283
home: +11 98 553 5878221
Birth Date: 1960-01-03"}
ObserverExample demonstrates how to use a MapListener to monitor cache events such as when cache data has been inserted, updated, and removed. A subset of the code is shown below.
Java
Implementation Class: com.tangosol.examples.contacts.ObserverExample in java/src
ContactChangeListener is a class that implements the MapListener interface.
cache.addMapListener(new ContactChangeListener());
.NET
Implementation Class: ObserverExample in namespace Tangosol.Examples.Contacts in dotnet/src/contacts
ContactChangeListener is a class that implements the ICacheListener interface.
cache.AddCacheListener(new ContactChangeListener());
C++
Implementation Class: ObserverExample in namespace coherence::examples in cpp/contacts
ContactChangeListener is a class that implements the MapListener interface using Coherence implements clause.
ContactChangeListener::Handle hListener = ContactChangeListener::create(); hCache->addFilterListener(hListener);
Definition of ContactChangeListener:
class ContactChangeListener
: public class_spec<ContactChangeListener,
extends<Object>, implements <MapListener> >
There is no immediate output when this example is run. The registered listener outputs the entry when it is inserted, updated, and deleted. For an update, it outputs both the old value and the new value. The changes to entries are caused by running the "Basic Data Access Example" and the "Processor Example", so the output happens when those examples are run.
ProcessorExample demonstrates how to use a processor to modify a set of data in the cache. In the code sample that follows, all Contacts who live in MA will have their work address updated.
Java
Implementation Class: com.tangosol.examples.contacts.ProcessorExample in java/src
Helper Class: com.tangosol.examples.contacts.OfficeUpdater in java/src
Apply the OfficeUpdater on all contacts who live in MA. The OfficeUpdater is a class that implements the InvocableMap.EntryProcessor interface by extending AbstractProcessor.
cache.invokeAll(new EqualsFilter("getHomeAddress.getState", "MA"), new OfficeUpdater(addrWork));
.NET
Implementation Class: ProcessorExample in namespace Tangosol.Examples.Contacts in dotnet/src/contacts
Helper Class: OfficeUpdater in namespace Tangosol.Examples.Contacts in dotnet/src/contacts
Apply the OfficeUpdater on all contacts who live in MA. The OfficeUpdater is a class that implements the IEntryProcessor interface by extending AbstractProcessor.
cache.InvokeAll(new EqualsFilter("getHomeAddress.getState", "MA"), new OfficeUpdater(addrWork));
C++
Implementation Class: ProcessorExample in namespace coherence::examples in cpp/contacts
Helper Class: OfficeUpdater in namespace coherence::examples in cpp/contacts
The OfficeUpdater is a class that extends the UpdaterProcessor type.
class OfficeUpdater : public class_spec<OfficeUpdater, extends<UpdaterProcessor>, implements<PortableObject> >
Apply the OfficeUpdater on all contacts who live in MA.
Filter::View vEqualsFilter = EqualsFilter::create(
ChainedExtractor::create(ChainedExtractor::createExtractors(
"getHomeAddress.getState")),
String::create("MA"));
InvocableMap::EntryProcessor::Handle hOffice = OfficeUpdater::create(addrWork);
Map::View vMap = hCache->invokeAll(vEqualsFilter, hOffice);
The example Output (due to "Observer Example") is large due to the number of contacts. A sample of output:
Example 6-4 Example Output of the Processor Example
entry updated old value: John Keau Addresses Home: 443 Beacon St. Ophvowvw, MA 06539 US Work: Yoyodyne Propulsion Systems 330 Lectroid Rd. Grover's Mill, FL 86812 US Phone Numbers work: +11 8 919 9456102 home: +11 25 759 588823 Birth Date: 1968-12-31 new value: John Keau Addresses Home: 443 Beacon St. Ophvowvw, MA 06539 US Work: 200 Newbury St. Yoyodyne, Ltd. Boston, MA 02116 US Phone Numbers work: +11 8 919 9456102 home: +11 25 759 588823 entry updated old value: John Lbggblkd Addresses Home: 929 Beacon St. Trwylbmf, MA 50358 US Work: Yoyodyne Propulsion Systems 330 Lectroid Rd. Grover's Mill, AZ 19164 US Phone Numbers work: +11 60 699 203810 home: +11 34 149 5018157 Birth Date: 1964-01-02 new value: John Lbggblkd Addresses Home: 929 Beacon St. Trwylbmf, MA 50358 US Work: 200 Newbury St. Yoyodyne, Ltd. Boston, MA 02116 US Phone Numbers work: +11 60 699 203810 home: +11 34 149 5018157 Birth Date: 1964-01-02 Birth Date: 1968-12-31
This example shows how to run sample queries for contacts.
Java
Implementation Class: com.tangosol.examples.query.QueryExample in java/src
Add indexes to make queries more efficient.
cache.addIndex(ff.createExtractor("age"), /*fOrdered*/ true, /*comparator*/ null);
cache.addIndex(ff.createExtractor("homeAddress.state"), /*fOrdered*/ false, /*comparator*/ null);
Find all contacts who live in Massachusetts.
Set setResults = cache.entrySet(ff.createFilter("homeAddress.state = 'MA'"));
Count contacts who are older than nAge for the entire cache dataset.
final int nAge = 58;
Object[] aEnv = new Object[] {new Integer(nAge)};
System.out.println("count > " + nAge + ": " + cache.aggregate(ff.createFilter("age > ?1", aEnv), new
Count()));
.NET
Implementation Class: SimpleQueryExample in namespace Tangosol.Examples.Query in dotnet/src/query
Add indexes to make queries more efficient.
cache.AddIndex(ff.CreateExtractor("age"), /*fOrdered*/ true, /*comparator*/ null);
cache.AddIndex(ff.CreateExtractor("homeAddress.state"), /*fOrdered*/ false, /*comparator*/ null);
Find all contacts who live in Massachusetts.
ICollection results = cache.GetEntries(ff.CreateFilter("homeAddress.state = 'MA'"));
Count contacts who are older than age for the entire cache dataset.
const int age = 58;
object[] env = new object[] { age };
results = cache.GetEntries(ff.CreateFilter("age > ?1", env));
C++
Implementation Class: SimpleQueryExample in namespace coherence::examples in cpp/query
Add indexes to make queries more efficient.
hCache->addIndex(hff->createExtractor("age"), /*fOrdered*/ true, /*vComparator*/ NULL);
hCache->addIndex(hff->createExtractor("homeAddress.state"), /*fOrdered*/ false, /*vComparator*/ NULL);
Find all contacts who live in Massachusetts.
Set::View setResults = hCache->entrySet(hff->createFilter("homeAddress.state is 'MA'"));
s
Count contacts who are older than nAge for the entire cache dataset.
Integer32::View nAge = Integer32::valueOf(58);
ObjectArray::Handle haEnv = ObjectArray::create(1);
haEnv[0] = nAge;
HashMap::Handle hbinds = HashMap::create();
hbinds->put(String::create("nAge"), nAge);
setResults = hCache->entrySet(hff->createFilter("age > ?1", haEnv));
The example output (due to "Query Example"):
Example 6-5 Example Output of the Query Language Example
MA Residents
ConverterCacheEntry{Key="John Wmbltik", Value="John Wmbltik
Addresses
Home: 785 Beacon St.
Vpmji, MA 34400
US
Work: 200 Newbury St.
Yoyodyne, Ltd.
Boston, MA 02116
US
Phone Numbers
work: +11 62 133 6144503
home: +11 17 238 6189757
Birth Date: 1/1/1968 12:00:00 AM"}
ConverterCacheEntry{Key="John Dtpx", Value="John Dtpx
Addresses
Home: 673 Beacon St.
Mvblms, MA 25889
US
Work: 200 Newbury St.
Yoyodyne, Ltd.
Boston, MA 02116
US
Phone Numbers
work: +11 89 900 8436918
home: +11 32 686 9582798
Birth Date: 1/3/1960 12:00:00 AM"}
.
.
.
count > 58 : 496
Implementation Class: com.tangosol.examples.contacts.DataGenerator in java/src
The DataGenerator has a static main method that generates random Contact information and stores the results in a comma separated value file. This class was used to generate the contacts.csv that is packaged with the contacts examples and is included in case more sample data is needed.
It is implemented only in Java.
The Coherence security examples are a collection of examples that show how to use the security features of Coherence in order to provide access control.
These examples are simplified to show only the security features of Coherence. They are not examples of security best practices:
"Password Example"—Shows how a Coherence Proxy can require a password to access a cache.
"Access Control Example"—Shows simplified role based access control.
"Password Identity Transformer"—Creates a custom security token that contains the required password and then adds a list of Principal names.
"Password Identity Asserter"—Asserts that the security token contains the required password and then constructs a Subject based on a list of Principal names.
"Entitled Cache Service"—Wraps a cache service for access control.
"Entitled Invocation Service"—Wraps an invocation service for access control.
"Entitled Named Cache"—Wraps a named cache for access control.
Gets a cache reference that requires a password.
Attempts cache and invocation service operations that require different roles.
Review the following information:
Review the information on the security Driver implementation found in the next section.
Has a static main method that executes all the security examples in the following order:
PasswordExample
AccessControlExample.accessCache()
AccessControlExample.accessInvocationService()
Is implemented in each of the three programming languages supported by Coherence:
| Language | Implementation Class |
|---|---|
|
Java |
|
|
.NET |
Driver in namespace |
|
C++ |
Driver in namespace |
Please refer to this example set's example.zip file for more details on each of the examples outlined below.
This example shows how a Coherence Proxy can require a password to get a reference to a cache.
Java
Implementation Class: com.tangosol.examples.security.PasswordExample in java/src
The code logs in to get a Subject, and then tries to get a cache reference running in the context of the Subject.
The Password Identity Transformer will generate a security token that contains the password. The Password Identity Asserter (running in the proxy) will validate the security token to enforce the password. The token generation and validation occurs automatically when a connection to the proxy is made.
.NET
Implementation Class: PasswordExample in namespace Tangosol.Example.Security in dotnet/src/security
The code logs in to get a Principal, and then tries to get a cache reference running in the context of the Principal by making the Principal the Thread's current principal.
The Password Identity Transformer will generate a security token that contains the password. ThePassword Identity Asserter (running in the proxy) will validate the security token to enforce the password. The token generation and validation occurs automatically when a connection to the proxy is made.
C++
Implementation Class: AccessExample in namespace coherence::examples in cpp/security
The code logs in to get a Subject, and then tries to get a cache reference running in the context of the Subject.
The Password Identity Transformer will generate a security token that contains the password. The Password Identity Asserter (running in the proxy) will validate the security token to enforce the password. The token generation and validation occurs automatically when a connection to the proxy is made.
The example Output:
Example 6-6 Example Output of the Password Example
------password example begins------ ------password example succeeded------ ------password example completed------
This example shows simplified role-based access control.
Java
Implementation Class: com.tangosol.examples.security.AccessControlExample in java/src
The code logs in to get a Subject with a user-id with a particular role, gets a cache reference running in the context of the Subject, and then tries cache operations. Depending on the role granted to the user, the cache operation is allowed or denied.
Someone with a writer role is allowed to put and get. Someone with a reader role can get but not put. Someone with a writer role cannot destroy a cache. Someone with an admin role can destroy a cache.
Then a user with a particular role tries to use the invocation service. A reader is not allowed to invoke, but a writer is allowed.
Note that once the cache or invocation service reference is created in the context of a Subject, that identity is permanently associated with that reference. Any use of that cache or service reference is on behalf of that identity.
The Password Identity Transformer will generate a security token that contains the password, the user-id, and the roles. The Password Identity Asserter (running in the proxy) will validate the security token to enforce the password, and construct a Subject with the proper user-id and roles.
The production and assertion of the security token happens automatically.
See the Entitled Cache Service, Entitled Invocation Service, and Entitled Named Cache code for the implementation of access control.
.NET
Implementation Class: AccessControlExample in namespace Tangosol.Example.Security in dotnet/src/security
The code logs in to get a Principal with a user-id with a particular role, gets a cache reference running in the context of the Principal, and then tries cache operations. Depending on the role granted to the user, the cache operation is allowed or denied.
Someone with a writer role is allowed to put and get. Someone with a reader role can get but not put. Someone with a writer role cannot destroy a cache. Someone with an admin role can destroy a cache.
Then a user with a particular role tries to use the invocation service. A reader is not allowed to invoke, but a writer is allowed.
Note that once the cache or invocation service reference is created in the context of a Principal, that identity is permanently associated with that reference. Any use of that cache or service reference is on behalf of that identity.
The Password Identity Transformer will generate a security token that contains the password, the user-id, and the roles. The Password Identity Asserter (running in the proxy) will validate the security token to enforce the password, and construct a Subject with the proper user-id and roles.
The production and assertion of the security token happens automatically.
See the Entitled Cache Service, Entitled Invocation Service, and Entitled Named Cache code for the implementation of access control.
C++
Implementation Class: AccessControlExample in namespace coherence::examples in cpp/security
The code logs in to get a Subject with a user-id with a particular role, gets a cache reference running in the context of the Subject, and then tries cache operations. Depending on the role granted to the user, the cache operation is allowed or denied.
Someone with a writer role is allowed to put and get. Someone with a reader role can get but not put. Someone with a writer role cannot destroy a cache. Someone with an admin role can destroy a cache.
Then a user with a particular role tries to use the invocation service. A reader is not allowed to invoke, but a writer is allowed.
Note that once the cache or invocation service reference is created in the context of a Subject, that identity is permanently associated with that reference. Any use of that cache or service reference is on behalf of that identity.
The Password Identity Transformer will generate a security token that contains the password, the user-id, and the roles. The Password Identity Asserter (running in the proxy) will validate the security token to enforce the password, and construct a Subject with the proper user-id and roles.
The production and assertion of the security token happens automatically.
See the Entitled Cache Service, Entitled Invocation Service, and Entitled Named Cache code for the implementation of access control.
The example output:
Example 6-7 Example Output of the Access Control Example
------cache access control example begins------ Success: read and write allowed Success: read allowed Success: Correctly cannot write Success: Correctly cannot destroy the cache Success: Correctly allowed to destroy the cache ------cache access control example completed------ ------InvocationService access control example begins------ Success: Correctly allowed to use the invocation service Success: Correctly unable to use the invocation service ------InvocationService access control example completed------
This example shows how an IdentityTransformer produces a security token from an identity.
Java
Implementation Class: com.tangosol.examples.security.PasswordIdentityTransformer in java/src
The code produces a security token that is an array of strings. The first string is the password. The second string is the user-id and subsequent strings are the user's roles. Arrays of strings will be serialized by Coherence*Extend without requiring a custom serializer.
This class will be invoked automatically when the Extend client connects to a proxy or a channel is opened in an existing connection.
.NET
Implementation Class: PasswordIdentityTransformer in namespace Tangosol.Example.Security in dotnet/src/security
The code produces a security token that is an array of strings. The first string is the password. The second string is the user-id and subsequent strings are the user's roles. Arrays of strings will be serialized by Coherence*Extend without requiring a custom serializer.
This class will be invoked automatically when the Extend client connects to a proxy or a channel is opened in an existing connection.
C++
Implementation Class: PasswordIdentityTranfromer in namespace coherence::examples in cpp/security
The code produces a security token that is an array of strings. The first string is the password. The second string is the user-id and subsequent strings are the user's roles. Arrays of strings will be serialized by Coherence*Extend without requiring a custom serializer.
This class will be invoked automatically when the Extend client connects to a proxy or a channel is opened in an existing connection.
This example shows how an IdentityAsserter validates a security token and produces a Subject from a list of principal names.
Java
Implementation Class: com.tangosol.examples.security.PasswordIdentityAsserter in java/src
The code processes a security token that should be an array of strings. The first string must be the password. Subsequent strings are principals. Any failure processing the token results in a SecurityException that will deny access to the proxy.
.NET
Implementation Class: none
The IdentityAsserter runs only on the proxy (in Java), so it does not run in the .NET client. Therefore, there is no PasswordIdentityAsserter for .NET.
C++
Implementation Class: none
The PasswordIdentityAsserter runs only on the proxy (in Java), so it does not run in the C++ client. Therefore there is no PasswordIdentityAsserter for C++.
This example shows how a remote cache service can be wrapped to provide access control.
Java
Implementation Class: com.tangosol.examples.security.EntitledCachService in java/src
The code instantiates an Entitled Named Cache that provides access control for cache operations. The code also provides access control for the cache service methods release and destroy. The access control check is delegated to the Security Example Helper.
This class will be instantiated automatically when the cache service is started on the proxy.
.NET
There is no .NET implementation. The class runs only on the proxy in Java.
C++
There is no C++ implementation. The class runs only on the proxy in Java.
This example shows how a remote invocation service can be wrapped to provide access control.
Java
Implementation Class: com.tangosol.examples.security.EntitledInvocationService in java/src
The code provides access control for the invocation service methods. The access control check is delegated to the Security Example Helper.
This class will be instantiated automatically when the invocation service is started on the proxy.
.NET
There is no .NET implementation. The class runs only on the proxy in Java.
C++
There is no C++ implementation. The class runs only on the proxy in Java.
This example shows how a remote named cache can be wrapped to provide access control.
Java
Implementation Class: com.tangosol.examples.security.EntitledNamedCache in java/src
The code provides access control for the NamedCache methods. The access control check is delegated to the Security Example Helper.
This class will be instantiated automatically when the cache service is started on the proxy.
.NET
There is no .NET implementation. The class runs only on the proxy in Java.
C++
There is no C++ implementation. The class runs only on the proxy in Java.
This example is a helper class for authentication and access control.
Java
Implementation Class: com.tangosol.examples.security.SecurityExampleHelper in java/src
The code simulates authentication. For the sake of simplicity, it creates a Subject. A real implementation would do platform- and company-specific authentication. The login also does simple mapping of user names to roles.
The checkAccess method checks that the operation is allowed by the user's role.
.NET
Implementation Class: SecurityExampleHelper in namespace Tangosol.Example.Security in dotnet/src/security
The code simulates authentication. For the sake of simplicity, it creates a Principal. A real implementation would do platform- and company-specific authentication. The login also does simple mapping of user names to roles.
C++
Implementation Class: SecurityExampleHelper in namespace coherence::examples in cpp/security
The code simulates authentication. For the sake of simplicity, it creates a Subject. A real implementation would do platform- and company-specific authentication. The login also does simple mapping of user names to roles.
These examples illustrate the various event types in Coherence Live Events and how they can be consumed, including EntryEvents, EntryProcessorEvents and TransferEvents.
The Live Events Examples are available only in the Java programming language, as they are executed on the storage-enabled members of the partitioned service.
"EventsExamples"—Illustrates various features within Live Events.
"TimedTraceInterceptor"—Provides timings between pre- and post-commit events for different types of events.
"CantankerousInterceptor"—Responds with runtime exceptions at either pre- or post-commit time, based on the type of key being inserted.
"RedistributionInterceptor"—Logs partition events when enabled.
"RedistributionInvocable"—Defines three actionable states that will be executed on various members of the cluster. The states are enable logging performed by the RedistributionInterceptor, disable logging, or terminate the JVM that the invocable (RedistributionInvocable) is executed on.
"LazyProcessor"—Creates a superficial delay between the processing of events.
Illustrates how to measure the elapsed time between pre- and post-events which are inserted into a results cache.
Illustrates the semantics of throwing exceptions in pre- and post-commit events.
Illustrates how partition redistribution events can be logged.
Review the following information:
Review the information on the Live Events Driver implementation found in the next section.
Has a static main method that executes all the Live Events examples in the following order:
Timed Events Example
Veto Events Example
Partition Transfer Events Example
Is implemented only in the Java programming language:
| Language | Implementation Class |
|---|---|
|
Java |
|
Implementation Class: com.tangosol.examples.events.EventsExamples in java/src
The EventsExamples class illustrates various features within Live Events. This includes:
Providing mean elapsed times split by event type.
Illustrating the different semantics in throwing exceptions in pre-events compared to post-events.
Illustrating logging of partition movement when enabled.
The EventsExamples class defines these inner classes:
The EventsTimingExample inner class is a catalyst for action to be performed by TimedTraceInterceptor. This illustrates how the elapsed time between pre- and post-events can be measured which are inserted into a results cache. The entries inserted into the results cache are displayed by using the stdout of the process executing this class.
The example output:
Example 6-8 Example Output of the EventsTimingExample
Received stats [memberId=2, eventType=INSERTED, sample=1] = EventStats[name = INSERTED, sampleMean = 0.294040ms, mean = 0.294040ms] Received stats [memberId=3, eventType=INSERTED, sample=1] = EventStats[name = INSERTED, sampleMean = 0.397855ms, mean = 0.397855ms] Received stats [memberId=1, eventType=INSERTED, sample=1] = EventStats[name = INSERTED, sampleMean = 0.373270ms, mean = 0.373270ms] Received stats [memberId=3, eventType=UPDATED, sample=1] = EventStats[name = UPDATED, sampleMean = 0.187132ms, mean = 0.187132ms] Received stats [memberId=2, eventType=UPDATED, sample=1] = EventStats[name = UPDATED, sampleMean = 0.234314ms, mean = 0.234314ms] Received stats [memberId=1, eventType=UPDATED, sample=1] = EventStats[name = UPDATED, sampleMean = 0.237622ms, mean = 0.237622ms]
The VetodEventsExample inner class is a catalyst for action to be performed by CantankerousInterceptor. This illustrates the semantics of throwing exceptions in pre- and post-events. The exceptions that are expected to only be logged are inserted into a results cache. The entries inserted into the results cache are displayed by using the stdout of the process executing this class.
The example output:
Example 6-9 Example Output of the VetodEventsExample
Received event [memberId=3, eventType=NON_VETO, count=1] = Objection falls on deaf ears! value = value: 11 Received event [memberId=3, eventType=NON_VETO, count=2] = Objection falls on deaf ears! value = value: 22 Received event [memberId=3, eventType=NON_VETO, count=3] = Objection falls on deaf ears! value = value: 33 Received event [memberId=3, eventType=NON_VETO, count=4] = Objection falls on deaf ears! value = value: 44
The RedistributionEventsExample inner class is a catalyst for action to be performed by the RedistributionInterceptor class. This illustrates how partition redistribution events can be logged, by enabling logging in the RedistributionInterceptor and killing a member thus inducing partition redistribution.
The example output:
Example 6-10 Output of the RedistributionEventsExample
Choosing to kill member Member(Id=3, Timestamp=2014-01-02 16:38:17.942, Address=10.159.154.103:8092, MachineId=47251, Location=site:,machine:TPFAEFFL-LAP,process:8168, Role=CoherenceServer)
Implementation Class: com.tangosol.examples.events.TimedTraceInterceptor in java/src
The TimedTraceInterceptor class provides timings between pre- and post-commit events for each type of event; that is, inserts, updates, removes, and entry processor execution. These timings are collected and averaged at a sample rate defined by parameter cSample. Additionally they are output to the log at the same time. This implementation does maintain a strong reference to the each binary key however this is removed upon receiving the post-commit event for the same key.
The interceptor implements the EventInterceptor interface. The @Interceptor annotation provides the unique name of the interceptor with the identifier attribute and the order in which it should be executed (Order.HIGH) with the order attribute.
The interceptor also contains a protected EventTimer inner-class. This class times the elapsed time for each event it is notified of. The interceptor tracks the time between a pre- and post-commit event for each entry and the respective event types (INSERT, UPDATE, REMOVE). The timings are sent to the Coherence log in batches displaying sample and cumulative statistics.
As the generic argument is com.tangosol.net.events.partition.cache.Event, you will only get events that are consumers of that event, that is, EntryEvent and EntryProcessorEvent, without specifying any filtering.
Implementation Class: com.tangosol.examples.events.CantankerousInterceptor in java/src
The CantankerousInterceptor class is an EventInterceptor implementation that is argumentative in nature, hence the event of inserting certain keys will result in runtime exceptions at either pre- or post-commit phases.
If the exception is thrown at pre-commit time, then a rollback occurs and the exception is propagated to the client. If the exception occurs at post-commit time, then a log event is recorded. The keys used for the exceptions are VETO and NON-VETO. INSERTING and UPDATING are events that can be vetoed, whereas INSERTED and UPDATED events cannot be vetoed.
Implementation Class: com.tangosol.examples.events.RedistributionInterceptor in java/src
The RedistributionInterceptor class is an EventInterceptor that logs partition activity when enabled. Logging can be enabled by using setting the RedistributionInvocable.ENABLED constant.
Implementation Class: com.tangosol.examples.pof.RedistributionInvocable in java/src
The RedistributionInvocable class defines three actionable states that will be executed on various members of the cluster. For this example, define the states as follows:
DISABLE: Disable the logging performed by the RedistributionInterceptor event interceptor.
ENABLE: Enable the logging performed by the RedistributionInterceptor event interceptor.
KILL: Terminate the JVM that this invocable (RedistributionInvocable) is executed on.
Implementation Class: com.tangosol.examples.pof.LazyProcessor in java/src
The LazyProcessor class creates a superficial delay between the processing of events. The class specifies the number of milliseconds this processor should sleep between processing events. This class will be used by the EventsTimingExample subclass in the EventsExamples class.
These examples illustrate how to use Coherence with features available in Java 8. The examples demonstrate using Streams, Lambda, and default methods that were introduced in the Map interface. The features are organized as three separate examples; however, these features often build on each other and are not mutually exclusive.
Illustrates how to use the Java streams when querying and processing cache entries.
Illustrates how Lambda features can be used to simplify common Coherence tasks.
Illustrates how to query and process cache entries using new default methods from the Map interface that have been overridden in the Coherence InvocableMap interface.
Review the following information:
Review the information on the Java 8 Driver implementation found in the next section.
Has a static main method that executes all the Java 8 examples in the following order:
Streams
Lambda
Map Default Method
Is implemented only in the Java programming language:
| Language | Implementation Class |
|---|---|
|
Java |
|
Implementation Class: com.tangosol.examples.java8.StreamsExample in java/src.
The StreamsExample class perform multiple queries of the Contact cache using the Stream API and also makes use of Lambda expressions. The results of the queries are printed to the console. The class also uses the Coherence RemoteCollector interface which extends the standard Java Collector interface and adds support for serialization in order to process stream elements that are distributed.
Implementation Class: com.tangosol.examples.java8.LambdaExample in java/src.
The LambdaExample class uses lambda expressions to add a listener for the Contact cache and update a contact using an entry processor. Lastly a lambda expression is used to query the Contact cache using the Coherence Filters API.
Implementation Class: com.tangosol.examples.java8.MapDefaultMethdodExample in java/src.
The MapDefaultMethodExample class performs multiple queries of the Contact cache and updates several cache entries using default methods that have been added to the Map interface. Note that Coherence overrides the default methods in the InvocableMap interface. Note also that the example uses lambda expressions when querying the cache.
These examples illustrate how to perform asynchronous data grid operations using the AsyncNamedCache API. The examples also uses the java.util.concurrent.CompletableFuture API, which is used to check if an operations is complete, to wait for its completion, and to retrieve the result of the operation.
Illustrates how to asynchronously get and put data in a cache.
Illustrates how to asynchronously process cache entries.
Illustrates how to asynchronously aggregate cache entries.
Review the following information:
Review the information on the asynchronous Driver implementation found in the next section.
Has a static main method that executes all the asynchronous examples in the following order:
Data Access Example
Processor Example
Aggregator Example
Is implemented only in the Java programming language:
| Language | Implementation Class |
|---|---|
|
Java |
|
Implementation Class: com.tangosol.examples.async.DataAccessExample in java/src.
The DataAccessExample class uses the AsyncNamedCache API to get an instance of the Contact cache. The class creates a new contact and uses the AsyncNamedCache instance to put the contact in the cache and then gets the contact from the cache. The contact is changed and then put back into the cache.
Implementation Class: com.tangosol.examples.async.ProcessorExample in java/src.
The ProcessorExample class uses the AsyncNamedCache API to get an instance of the Contact cache. The AsyncNamedCache instance is used to query the cache and execute an entry processor which changes the set of contact names to uppercase. The entry processors are then used to change the names back to lower case.
Implementation Class: com.tangosol.examples.async.AggregatorExample in java/src.
The AggregatorExample class uses the AsyncNamedCache API to get an instance of the Contact cache. The AsyncNamedCache instance is used to query the cache and execute an aggregation on a set of contacts based on age.
The federated caching example starts two clusters: ClusterA and ClusterB. The clusters are configured in a federation topology and cached data is actively synchronized between the two clusters.
Illustrates federation cluster participant configuration
Illustrates an active-active replication topology configuration
Illustrates a federated cache service configuration
Illustrates SSL configuration to secure communication between cluster participants
Review the following information:
Review the information on the federated caching Driver implementation found in the next section.
Has a static main method that:
Starts two clusters.
Starts either a GUI application, CohQL, or console for each cluster.
Is implemented only in the Java programming language:
| Language | Implementation Class |
|---|---|
|
Java |
|
The federation example demonstrates configuration. Inspect the resource/federation/examples-cache-configure.xml file for an example of federated cache configuration. Inspect the resource/federation/tangosol-coherence-override.xml file for details about how to configure federation participants and replication topologies.
The persistence example demonstrate saving and recovering cache data from disk. The examples exercise many different persistence operations programmatically. Persistence operations can also be performed using the PersistenceCoordinatorMBean MBean and using CohQL commands.
Illustrates how to save and recover a cache snapshot
Illustrates how to register for persistence notifications
Illustrates how to perform persistence operations in parallel
Illustrates how to create and use a custom archiver
Review the following information:
Review the information on the persistence Driver implementation found in the next section.
Has a static main method that executes the persistence examples depending on the arguments that are entered.
Basic Snapshot Example
Persistence Notifications Example
Persistence Operations in Parallel Example
Custom Archiver Example
Is implemented only in the Java programming language:
| Language | Implementation Class |
|---|---|
|
Java |
|
Implementation Class: com.tangosol.examples.persistence.BasicSnapshotOperations in java/src
The BasicSnapshotOperations class demonstrates how to use persistence snapshots to the save and recover the contents of a cache. It uses the contacts example to populate a cache and then programmatically performs persistence operations as follows:
A snapshot of the contacts cache is created. The location for persistence files is java/persistence-data.
A list of available snapshots is discovered.
The contacts cache is cleared of all data.
The cache contents are recovered from the snapshot.
The size of cache is reported.
The snapshot of the contacts cache is removed.
A list of available snapshots verifies that the snapshot has been removed
Implementation Class: com.tangosol.examples.persistence.NotificationWatcher in java/src
The NotificationWatcher class demonstrates how to monitor notifications from persistence operations. The basic snapshot operations example is run with each operation being monitored. The class creates and registers a persistence notification listener on the contacts cache service. The notifications are then used to monitor the amount of time it takes for persistence operations to be performed.
Implementation Class: com.tangosol.examples.persistence.ParallelSnapshotOperations in java/src
The ParallelSnapshotOperations class demonstrates how to call snapshot operations for multiple partitioned cache services in parallel. The basic snapshot operations example is run and two instance of the contact cache service are created. The persistence operations are then performed for each cache service.
Implementation Class: com.tangosol.examples.archiver.SFTPSnapshotArchiver in java/src
The SFTPSnapshotArchiver class is a custom implementation of a snapshot archiver that uses JSch library from JCraft (http://www.jcraft.com/jsch/) to create an archiver that archives snapshots to a remote server using secure FTP. The SFTPSnapshotArchiver class extends the AbstractSnapshotArchiver class. To run this example, the JSch library must be downloaded and the remote server must support SSH.
The example Driver file performs the same operations as the basic snapshot operations example, but also includes archive operations. The persistence operations are performed as follows:
A snapshot of the contacts cache is created. The location for persistence files is java/persistence-data.
A list of available snapshots is discovered.
The snapshot of the contacts cache is archived using SFTP.
The snapshot of the contacts cache is removed.
The contacts cache is cleared of all data.
The size of cache is reported.
The archived snapshot is retrieved using SFTP.
A list of available snapshots is discovered.
The cache contents are recovered from the snapshot.
The size of cache is reported.
The snapshot and the archived snapshot are both removed.
The Coherence REST examples shows how to create a basic web-based application that uses the Coherence REST API. The example uses the Grizzly HTTP server to receive client HTTP requests. The example client is built using several JavaScript libraries and also the Angular JS framework.
Unlike the other Coherence examples, the Coherence REST examples uses Apache Maven to build and run the examples. Maven is the preferred approach when using Coherence REST and facilitates managing all library dependencies. The REST examples are organized in a standard Maven directory structure in the COHERENCE_HOME/examples/rest/ directory.
/src/main/java – Directory for Java source files
/src/main/resources – Directory for Coherence configuration files.
/src/main/resources/web – Directory for static HTML pages.
For documentation about Coherence REST, see Developing Remote Clients for Oracle Coherence.
Illustrates how create configure and deploy Coherence REST using the Grizzly HTTP server.
Illustrates how to build a basic JavaScript client that use the Coherence REST APIs.
Illustrates how to query, create, update and remove cache entries using standard REST API's in Coherence.
Illustrates how to use a custom entry processors
Illustrates how to use composite keys and shows the use of a KeyConverter class.
Illustrates how use server-sent events to be notified of cache events.
The examples are built and run using Maven 3.2.5 or above and require a browser that supports AngularJS 1.4.1 or above. See also, "Prerequisites for Java."
To build and run the examples:
Include the coherence.jar and coherence-rest.jar libraries in the local Maven repository.
mvn install:install-file -Dfile=COHERENCE_HOME/lib/coherence.jar -DpomFile=COHERENCE_HOME/plugins/maven/com/oracle/coherence/coherence /12.2.1/coherence.12.2.1.pom mvn install:install-file -Dfile=COHERENCE_HOME/lib/coherence-rest.jar -DpomFile=COHERENCE_HOME/plugins/maven/com/oracle/coherence/coherence-rest /12.2.1/coherence-rest.12.2.1.pom
Note:
You may need to specify the path to your settings.xml file to download the required dependencies. For example:
mvn -s /path/to/settings.xml ...
If you do not have a settings file and you are using a proxy server for internet access, you can utilize the sample settings.xml provided in the base directory. You can modify the file to add your proxy server settings.
Issue the following to build the REST examples:
mvn clean compile
Start a cache server and HTTP proxy:
mvn exec:exec -DhttpProxy
The application starts and the home page automatically loads in the default browser. If the home page does not load in the default browser, then navigate to the following URL:
http://127.0.0.1:8080/application/index.html
Note:
the HTTP server listens on all IP Addresses but you can change the address and port that the application runs on by passing the following to the mvn exec:exec command:
mvn exec:exec -DhttpProxy -Dhttp.address=x.x.x.x -Dhttp.port=7777
Optionally, start additional cache servers (without an HTTP server):
mvn exec:exec -DcacheServer
Implementation: COHERENCE_HOME\examples\rest\src\main\resources\web\js\products.js
The Products page shows how to query, create, update, remove or populate default products using standard REST API's in Coherence. The page also makes use of custom entry processors to increase product prices and receive additional quantities of an item.
Implementation: COHERENCE_HOME\examples\rest\src\main\resources\web\js\departments.js
The Department page shows how to query, create, update, remove or populate default departments using standard REST API's in Coherence.
Implementation: COHERENCE_HOME\examples\rest\src\main\resources\web\js\contacts.js
The Contacts page shows how to query, create, update, remove or populate default contacts using standard REST API's in Coherence. The example has composite keys and shows the use of a KeyConverter class to work with these keys. Lastly, the example shows how to sort queries that are returned from REST calls.
Implementation: COHERENCE_HOME\examples\rest\src\main\resources\web\js\sse.js
The server-sent events page listens for events from the Coherence REST API's. Click Start Listening to register a listener for the respective cache. Start a new instance of the application and modify the respective caches. Switch back to the original instance of the application to view the updated statistics.
Note:
Internet Explorer does not support server-sent events.