6 Running the Coherence Examples

The Coherence distribution provides a collection of example code. The examples show how to use multiple Coherence features and are implemented the same across Java, C++, and .NET.

This chapter includes the following sections:

6.1 Overview of Coherence Examples

The Coherence examples are grouped into feature sets. Each feature set contains multiple examples that demonstrate key functionality.

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 Stream API. See Streams.

LambdaExample

Performs cache operations using lambda expressions. See Lambda.

MapDefaultMethodExample

Performs cache operations using overridden default methods from the Map API. See Map Default Method.

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.

6.2 Obtaining the Examples

The Coherence examples are included in 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.

6.3 How to Build the Examples

The Coherence examples’ source files must be built using the scripts in the examples directory. Scripts are provided for the Java, C++, and .NET (C#) programming languages.

Note:

You must build and run the Java example even for C++ and .NET. This is because the cache server runs in Java.

This section contains the following topics:

6.3.1 How to Build the Java Examples

This section contains the following topics:

6.3.1.1 Prerequisites for Java

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

$COHERENCE_HOME

Make sure that the COHERENCE_HOME environment variable points to the location of the Coherence installation directory.

$JAVA_HOME

Make sure that the JAVA_HOME environment variable points to the location of a 1.8 or greater JDK before building the example. A Java runtime 1.8 or greater is needed to run the example

6.3.1.2 Directory Structure for Java

The directory structure described below is relative to the examples directory.

Table 6-8 Directory Structure for Java

Directory Name Description

java/bin

Scripts for building and executing the example. There are two sets of scripts. Scripts with no file extension are bash scripts. Scripts with a .cmd file extension are Windows command scripts. The following description refers to the script names without specifying the file extension.

  • build—builds an example

java/src

All example source. The examples are in the com.tangosol.examples.<example name> package. The classes for objects stored in the cache are in the com.tangosol.examples.pof package.

java/classes

The class files output from a build. This directory will not exist until the build script is executed.

java/resource/config

The common Coherence configuration files required by the examples.

java/resource/<example name>

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 java/resource/security.

$COHERENCE_HOME/lib

Coherence libraries used for compiling and running the example.

6.3.1.3 Build Instructions for Java

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.

6.3.2 How to Build the .NET Examples

This section contains the following topics:

6.3.2.1 Prerequisites for .NET

To build the example, you must have Coherence for .NET and Visual Studio 2008 or later or Visual Studio 2008 Express or later. 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.

6.3.2.2 Directory Structure for .NET

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 Tangosol.Examples.<example name> namespace. The classes for objects stored in the cache are in the Tangosol.Examples.Pof namespace.

The examples are in the Visual Studio 2008 examples solution. Each example has its own Visual Studio 2008 project in the src directory. For example, src contains projects for the contacts and security examples.

The Coherence configuration files required by the example.

src\pof\config

The common Coherence configuration files required by the examples.

src\<example name>\config

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 security\config.

6.3.2.3 Build Instructions for .NET

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).

6.3.3 How to Build the C++ Examples

This section contains the following topics:

6.3.3.1 Prerequisites for C++

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

%COHERENCE_HOME%

Make sure that the COHERENCE_HOME environment variable points to the location of the unpacked Coherence directory.

%JAVA_HOME%

Make sure that the JAVA_HOME environment variable points to the location of a 1.8 or greater JDK before building the examples. A Java runtime 1.8 or greater is needed to run the examples.

%COHERENCE_CPP_HOME%

Make sure that the COHERENCE_CPP_HOME environment variable points to the location of the unpacked C++ development environment. Compiler environments supported.

6.3.3.2 Directory Structure for C++

The directory structure described below is relative to the examples directory.

Table 6-10 Directory Structure for C++

Directory Name Description

cpp\bin

Scripts for building and executing the examples. Scripts with no file extension are bash scripts. Scripts with a .cmd file extension are Windows command scripts. The following description refers to the script names without specifying any file extension.

cpp

All example source organized under the <example name> (such as contacts and security) and pof directories.

cpp\contacts

The contacts example source. The examples are in the coherence::examples namespace. The next level of the name after examples represents a related set of example classes. "Driver" in coherence::examples::LoaderExample is the Loader for the contacts example. In other words, the name of the example is the name after coherence::examples.

cpp\security

The security example source. The examples are in the coherence::examples namespace.

cpp\pof

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 Contact has a ContactSerializer class whose purpose is to register the model type with Coherence and serialization operations.

The generated output will be in the form of a dynamic library.

cpp\config

The common Coherence configuration files required by the examples.

cpp\config\<example name>

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 config/security.

cpp\<example name>\out

The object files output from a build. This directory will not exist until the build script is executed.

%COHERENCE_CPP_HOME%\include

Contains the Coherence header files.

%COHERENCE_CPP_HOME%\lib

Contains the Coherence library.

6.3.3.3 Build Instructions for C++

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.

6.4 How to Run the Examples

The Coherence examples are run using the scripts in the examples directory. Scripts are provided for the Java, C++, and .NET (C#) programming languages.

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 topics:

6.4.1 How to Run the Java Examples

This section contains the following topics:

6.4.1.1 Prerequisites for Java

To run the examples, you must have Coherence installed and use the currently supported JDK. See System Requirements.

Environment Variable Description

$COHERENCE_HOME

Make sure that the COHERENCE_HOME environment variable points to the location of the unpacked Coherence directory.

$JAVA_HOME

Make sure that the JAVA_HOME environment variable points to the location of a supported JDK before building the examples.

6.4.1.2 Directory Structure for Java

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

java/bin

Scripts for building and executing examples. There are two sets of scripts. Scripts with no file extension are bash scripts. Scripts with a .cmd file extension are Windows command scripts. The following description refers to the script names without specifying any file extension.

  • run—Runs an example collection

  • run-cache-server—Runs the cache server used for the examples. The command is also used to start a proxy service that is required for extend clients.

java/classes

The class files output from a build. This directory will not exist until the build script is executed.

java/resource/config

The common Coherence configuration files required by the examples.

java/resource/<example name>

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 java/resource/security.

$COHERENCE_HOME/lib

Coherence libraries used for compiling and running the examples.

resource

The data file used for the contacts LoaderExample: contacts.csv.

6.4.1.3 Instructions for Java

Execute the run script for each example.

contacts example

  1. 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.

  2. 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.

  1. 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.

  2. 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

  1. Start at least two 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.

  2. 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

  1. Start a cache server: bin/run-cache-server.

  2. 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

  1. Start a cache server: bin/run-cache-server.

  2. 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

  1. Start ClusterA using: bin/run-cache-server federation ClusterA.

  2. In a new command shell, start ClusterB using: bin/run-cache-server federation ClusterB.

  3. 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.

  4. 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.

  5. Add objects to a cluster and observe that the objects are being replicated to the other cluster.

  6. 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:

  1. 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
    
  2. 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
    
  3. 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.

  4. 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

  1. start one or more cache servers: bin/run-cache-server persistence

  2. 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).

  3. Start the notification listener: bin/run persistence notifications.

  4. Run the persistence example: bin/run persistence. Output is emitted that indicates that Persistence operations are being completed

  5. Use CTRL+C to interrupt the notifications listener.

  6. 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).

  7. Download the JSch library jsch-0.1.51.jar or later and extract the contents into the classes directory.

  8. Build the archiver example: bin/build archiver.

  9. 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.

  10. Run the archive example: bin/run archiver.

  11. Inspect the remote SFTP machine to see the archive directory.

6.4.2 How to Run the .NET Examples

This section contains the following topics:

6.4.2.1 Prerequisites for .NET

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.

6.4.2.2 Directory Structure for .NET

The directory structure described below is relative to the "examples" directory.

Table 6-12 Directory Structure for .NET

Directory Name Description

resource

The data file used for the contacts LoaderExample: contacts.csv.

6.4.2.3 Instructions for .NET

The following sections contain instructions for running the contacts and security examples.

contacts

  1. 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.

  2. 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

  1. 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.

  2. 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).

6.4.3 How to Run the C++ Examples

This section contains the following topics:

6.4.3.1 Prerequisites for C++

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

$COHERENCE_CPP_HOME

Make sure that the COHERENCE_CPP_HOME environment variable points to the location of the unpacked Coherence C++ installation directory.

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

6.4.3.2 Directory Structure for C++

The directory structure described below is relative to the examples directory.

Table 6-13 Directory Structure for C++

Directory Name Description

cpp/bin

Scripts for building and executing the examples. Scripts with no file extension are bash scripts. Scripts with a .cmd file extension are Windows command scripts. The following description refers to the script names without specifying any file extension.

  • run—Runs an example, requires that java/bin/run-cache-server be run to start a proxy service.

cpp

All example source organized under the contacts and model directories.

contact/out

The object files output from a build. This directory will not exist until the build script is executed.

resource

The data file used for the contacts LoaderExample: contacts.csv.

cpp/contacts

Contains the contacts example sources.

cpp/security

Contains the security example sources.

cpp/pof

Contains the datamodel sources and any classes that require serialization.

$COHERENCE_CPP_HOME/include

Contains the Coherence header files.

$COHERENCE_CPP_HOME/lib

Contains the Coherence library.

6.4.3.3 Instructions for C++

Execute the run scripts. There are two parts to running the example. From within new command shells:

contacts example

  1. 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.

  2. 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

  1. 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.

  2. 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).

6.5 Coherence Basic Features Example

The Coherence Basic Features Examples are a collection of examples that demonstrate basic functionality using a simplified contact information tracker application:

This section includes the following topics:

6.5.1 Overview of the Basic Features Examples

The Coherence Basic Features examples include:

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

Address information

Contact

Contact information (includes addresses and phone numbers)

ContactId

The key (contact name) to the contact information

PhoneNumber

Phone number

This example set also ships with a contacts.csv file which is a comma-delimited value file containing sample Contacts information.

6.5.2 Running the Example Set

  1. Review the following information:

  2. Review the information on the Driver implementation found in Understanding the Features Driver File.

6.5.3 Understanding the Features Driver File

The Driver file has a static main method that executes all the Contacts examples in the following order:

  1. LoaderExample

  2. QueryExample

  3. QueryLanguageExample

  4. ObserverExample

  5. BasicExample

  6. ProcessorExample

The Driver file is implemented in each of the three programming languages supported by Coherence.

Language Implementation Class

Java

com.tangosol.examples.contacts.Driver in java/src

.NET

Driver in namespace Tangosol.Examples.Contacts in dotnet/src/contacts

C++

Driver in namespace coherence::examples in cpp/contacts

6.5.4 Basic Data Access Example

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);
    

Example Output

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

6.5.5 Loader Example

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);

Example Output

Example 6-2 Example Output

.........Added 10000 entries to cache

6.5.6 Query Example

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;
    

Example Output

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"}

6.5.7 Observer Example

ObserverExample demonstrates how to use a MapListener to monitor cache events such as when cache data has been inserted, updated, and removed. 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.

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> >
    

6.5.8 Processor Example

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);
    

Example Output

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

6.5.9 Query Language

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));
    

Example Output

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

6.5.10 Data Generator

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. The class is implemented only in Java.

6.6 Coherence Security Examples

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. The examples are simplified to show only the security features of Coherence. They are not examples of security best practices.

This section contains the following topics:

6.6.1 Overview of the Coherence Security Examples

The security examples include:

6.6.2 This Example Set

The Coherence security example set gets a cache reference that requires a password an attempts cache and invocation service operations that require different roles.

This section includes the following topics:

6.6.2.1 Running the Security Example Set

  1. Review the following information:

  2. Review the information on the security Driver implementation found in the next section.

6.6.2.2 Understanding the Security Driver File

Has a static main method that executes all the security examples in the following order:

  1. PasswordExample

  2. AccessControlExample.accessCache()

  3. AccessControlExample.accessInvocationService()

Is implemented in each of the three programming languages supported by Coherence:

Language Implementation Class

Java

com.tangosol.examples.security.Driver in java/src

.NET

Driver in namespace Tangosol.Examples.Security in dotnet/src/security

C++

Driver in namespace coherence::examples in cpp/security

Please refer to this example set's example.zip file for more details on each of the examples outlined below.

6.6.3 Password Example

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. 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.

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.

Example Output

Example 6-6 Example Output of the Password Example

------password example begins------
------password example succeeded------
------password example completed------

6.6.4 Access Control Example

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.

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------

6.6.5 Password Identity Transformer

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.

6.6.6 Password Identity Asserter

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++.

6.6.7 Entitled Cache Service

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.

6.6.8 Entitled Invocation Service

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.

6.6.9 Entitled Named Cache

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.

6.6.10 Security Example Helper

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.

6.7 Coherence Live Events Example

The Coherence Live Events examples illustrate the various event types 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.

This section includes the following topics:

6.7.1 Overview of the Coherence Live Events Example

The Coherence Live Events examples include:

  • 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.

6.7.2 This Example Set

The live events example set illustrates: how to measure the elapsed time between pre- and post-events which are inserted into a results cache; the semantics of throwing exceptions in pre- and post-commit events, and how partition redistribution events can be logged.

This section includes the following topics:

6.7.2.1 Running the Live Events Example Set

  1. Review the following information:

  2. Review the information on the Live Events Driver implementation found in the next section.

6.7.2.2 Understanding the Live Events Driver File

Has a static main method that executes all the Live Events examples in the following order:

  1. Timed Events Example

  2. Veto Events Example

  3. Partition Transfer Events Example

Is implemented only in the Java programming language:

Language Implementation Class

Java

com.tangosol.examples.events.Driver in java/src

6.7.3 EventsExamples

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:

6.7.3.1 EventsTimingExample

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]

6.7.3.2 VetodEventsExample

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

6.7.3.3 RedistributionEventsExample

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)

6.7.4 TimedTraceInterceptor

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.

6.7.5 CantankerousInterceptor

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.

6.7.6 RedistributionInterceptor

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 setting the RedistributionInvocable.ENABLED constant. See RedistributionInvocable.

6.7.7 RedistributionInvocable

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.

6.7.8 LazyProcessor

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.

6.8 Coherence Java 8 Features Example

The Coherence Java 8 Features examples illustrate how to use Coherence with features that are 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.

This section includes the following topics:

6.8.1 This Example Set

The Coherence Java 8 features example illustrates: how to use the Java streams when querying and processing cache entries; how Lambda features can be used to simplify common Coherence tasks and how to query and process cache entries using new default methods from the Map interface that have been overridden in the Coherence InvocableMap interface.

This section includes the following topics:

6.8.1.1 Running the Java 8 Features Example Set

  1. Review the following information:

  2. Review the information on the Java 8 Driver implementation found in the next section.

6.8.1.2 Understanding the Java 8 Driver File

Has a static main method that executes all the Java 8 examples in the following order:

  1. Streams

  2. Lambda

  3. Map Default Method

Is implemented only in the Java programming language:

Language Implementation Class

Java

com.tangosol.examples.java8.Driver in java/src

6.8.2 Streams

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.

6.8.3 Lambda

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.

6.8.4 Map Default Method

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.

6.9 Coherence Asynchronous Features Example

These Asynchronous 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.

This section includes the following topics:

6.9.1 This Example Set

The Coherence asynchronous features example illustrates: how to asynchronously get and put data in a cache; how to asynchronously process cache entries; how to asynchronously aggregate cache entries.

This section includes the following topics:

6.9.1.1 Running the Asynchronous Features Example Set

  1. Review the following information:

  2. Review the information on the asynchronous Driver implementation found in the next section.

6.9.1.2 Understanding the Asynchronous Driver File

Has a static main method that executes all the asynchronous examples in the following order:

  1. Data Access Example

  2. Processor Example

  3. Aggregator Example

Is implemented only in the Java programming language:

Language Implementation Class

Java

com.tangosol.examples.async.Driver in java/src

6.9.2 Asynchronous Data Access

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.

6.9.3 Asynchronous Entry Processor

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.

6.9.4 Asynchronous Aggregator

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.

6.10 Coherence Federated Caching Example

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.

This section includes the following topics:

6.10.1 This Example Set

The Coherence federated caching example set illustrates: federation cluster participant configuration; an active-active replication topology configuration; a federated cache service configuration; SSL configuration to secure communication between cluster participants.

This section includes the following topics:

6.10.1.1 Running the Federated Caching Example Set

  1. Review the following information:

  2. Review the information on the federated caching Driver implementation found in the next section.

6.10.1.2 Understanding the Federated Caching Driver File

Has a static main method that:

  1. Starts two clusters.

  2. Starts either a GUI application, CohQL, or console for each cluster.

Is implemented only in the Java programming language:

Language Implementation Class

Java

com.tangosol.examples.federation.Driver in java/src

6.10.2 Federation Configuration

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.

6.11 Coherence Persistence Example

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.

This section includes the following topics:

6.11.1 This Example Set

The Coherence persistence example set illustrates: how to save and recover a cache snapshot; how to register for persistence notifications how to perform persistence operations in parallel; how to create and use a custom archiver.

This section includes the following topics:

6.11.1.1 Running the Persistence Example Set

  1. Review the following information:

  2. Review the information on the persistence Driver implementation found in the next section.

6.11.1.2 Understanding the Persistence Driver File

Has a static main method that executes the persistence examples depending on the arguments that are entered.

  1. Basic Snapshot Example

  2. Persistence Notifications Example

  3. Persistence Operations in Parallel Example

  4. Custom Archiver Example

Is implemented only in the Java programming language:

Language Implementation Class

Java

com.tangosol.examples.async.Driver in java/src

6.11.2 Basic Snapshot Operations

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

6.11.3 Persistence Notifications

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.

6.11.4 Persistence Operations in Parallel

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.

6.11.5 Archiving Snapshots with a Custom Archiver

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.

6.12 Coherence REST Examples

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. For complete documentation about Coherence REST, see Using Coherence REST in Developing Remote Clients for Oracle Coherence.

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 and JavaScript files.

This section includes the following topics:

6.12.1 This Example Set

  • 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.

  • Illustrates how to use pass-through for native JSON objects and static binary objects.

6.12.2 Building and Running the Example

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.

To build and run the examples:

  1. 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.

  2. Issue the following to build the REST examples:

    mvn clean compile
    
  3. 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
    
  4. Optionally, start additional cache servers (without an HTTP server):

    mvn exec:exec -DcacheServer
    

6.12.3 Products Page

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.

6.12.4 Departments Page

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.

6.12.5 Contacts Page

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.

6.12.6 Server-Sent Events

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.

6.12.7 JSON Pass-Through Page

Implementation: COHERENCE_HOME\examples\rest\src\main\resources\web\js\json.js

The JSON Pass-through page shows how a cache can store and retrieve native JSON objects. The objects are serialized in the cache using POF and JSON attribute ordering is preserved. The page also shows how native JSON objects in a cache can be processed and aggregated like any other value object.

6.12.8 Binary Pass-Through Page

Implementation: COHERENCE_HOME\examples\rest\src\main\resources\web\js\static.js

The Binary Pass-through page shows how a cache can store and delete static binary content (such as a graphic). The example makes use of the PassThroughResourceConfig resource, which supports pass-through access to caches.