The Coherence distribution provides a collection of example code in the examples.zip
file. These examples demonstrate how to use basic Coherence functionality, security, and events features in all supported languages (Java, .NET, and C++). The examples are organized as collections of code that show how to use one or more features. They also provide a single common way (per language) to build and run all examples.
This appendix has the following sections:
There are a number of differences between the examples in the examples.zip
file described in this appendix and the examples that are presented in the main body of the tutorial:
The examples in the examples.zip
must be built and run from the command line. The tutorial uses an IDE to compile and run the code.
The examples in the examples.zip
file demonstrate how to use basic Coherence functionality and security features in all supported languages (Java, .NET, and C++). The tutorial covers only Java implementations.
The Java examples in the examples.zip
file are only a subset of the Java examples presented in the tutorial.
The Java code files in the examples.zip
file are similar, but not identical to, the files used in the tutorial. In many instances, the code in the tutorial has been simplified for demonstration purposes.
The Coherence Basic Features Examples include the following:
Table A-1 Coherence Basic Features Examples
Example Name | Description |
---|---|
Basic Data Access |
"Getting", "putting" and "removing" data from the Coherence Data Grid. See Section A.5.3, "Basic Data Access Example." |
Data Loading |
Loading example data into the Coherence Data Grid. See Section A.5.4, "Loader Example." |
Parallel Querying |
Querying the Coherence Data Grid including the use of indexes. See Section A.5.5, "Query Example." |
Observable |
Listening for changes to data in the Coherence Data Grid. See Section A.5.6, "Observer Example." |
Processing |
Co-locating data processing with the data itself in the Coherence Data Grid. See Section A.5.7, "Processor Example." |
Query Language |
How to use the Coherence Query Language. See Section A.5.5, "Query Example." |
The Coherence Security Examples include the following:
Table A-2 Coherence Security Examples
Example Name | Description |
---|---|
Password Example |
Requiring a password to access Coherence. See Section A.6.2, "Password Example." |
Access Control Example |
Simplified role based access control. See Section A.6.3, "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 Section A.6.4, "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 Section A.6.5, "Password Identity Asserter." |
Entitled Cache Service |
Wraps a cache service for access control. See Section A.6.6, "Entitled Cache Service." |
Entitled Invocation Service |
Wraps an invocation service for access control. See Section A.6.7, "Entitled Invocation Service." |
Entitled Named Cache |
Wraps a named cache for access control. See Section A.6.8, "Entitled Named Cache." |
The Coherence Live Events Examples are available for the Java platform only. They include the following:
Table A-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 Section A.7.2, "EventsExamples." |
TimedTraceInterceptor |
Provides timings between pre- and post-commit events for different types of events. See Section A.7.3, "TimedTraceInterceptor." |
CantankerousInterceptor |
Responds with runtime exceptions at either pre- or post-commit time, based on the type of key being inserted. See Section A.7.4, "CantankerousInterceptor." |
RedistributionInterceptor |
Logs partition events when enabled. See Section A.7.5, "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 Section A.7.6, "RedistributionInvocable." |
LazyProcessor |
Creates a superficial delay between the processing of events. See Section A.7.7, "LazyProcessor." |
You can obtain the examples.zip
file 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.
If you have already installed Coherence but without the examples, you can obtain the examples.zip
file 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.
Unzip the contents of the examples.zip
file into an examples
directory.
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 version 3.7 or later and a Java development kit (JDK) 1.6 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 A-4 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, for example: bin/build
contacts
, bin/build
security
, or bin/build
events
.
The script will build the POF package files and then the files for the particular example. 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 version 3.7 or later for .NET and Visual Studio 2008 or later or Visual Studio 2008 Express or later.
To run the example, you will need the Java version of Coherence 3.7 or later and a Java development kit (JDK) 1.6 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. Note that the Java run-proxy
script must be executed; the Java run-cache-server
is optional because the proxy is storage enabled.
The directory structure described below is relative to the examples
directory.
Table A-5 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 3.7 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 the desired Coherence 3.7 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 3.7 or later and a Java development kit (JDK) 1.6 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. Note that the Java run-proxy
script must be executed; the Java run-cache-server
is optional because the proxy is storage enabled.
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 A-6 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, java\bin\run-proxy
, and an additional cache server java\bin\run-cache-server
.
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 Section A.3, "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 version 3.7 and a Java development kit (JDK) 1.6 or greater.
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 A-7 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. There are two parts to running the example.
Start one or more cache servers: bin/run-cache-server
. Each execution will start 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 will run through the features of the example with output going to the command window (stdout
).
Starting with Coherence 3.7, 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
.
The security
example requires Coherence*Extend, which uses a proxy.
Start a proxy: bin/run-proxy security
.
Optionally, start one or more cache servers as described in the contacts
example. The proxy is storage-enabled, so it will act as both a proxy and a cache server node.
In a new command shell, run with the name of the example: bin/run security
. The Driver.main
method will run through the features of the example with output going to the command window (stdout
).
Start one or more cache servers: bin/run-cache-server
. Each execution will start 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 will run through the features of the example with output going to the command window (stdout
).
This section contains the following information:
To run the examples, you must have Coherence version 3.7 or later 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.
The following sections contain instructions for running the contacts
and security
examples.
Following the Java instructions, start a proxy server (run-proxy
) and zero or more cache servers (run-cache-server
).
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 3.7, 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
.
Following the java readme.txt instructions, start a proxy server (java/bin/run-proxy security
) and zero or more cache servers.
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 version 3.7. 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 A-9 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:
Start one proxy server: java/bin/run-proxy contacts
.
Optionally, start one or more cache servers: bin/run-cache-server
. Each execution will start a cache server cluster node. To add additional nodes, execute the command in a new command shell.
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 3.7, 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
.
Start one proxy server: java/bin/run-proxy security
.
Optionally, start one or more cache servers: bin/run-cache-server
. Each execution will start a cache server cluster node. To add additional nodes, execute the command in a new command shell.
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 Section A.5.3, "Basic Data Access Example."
Data Loading—Loading example data into the Coherence Data Grid. See Section A.5.4, "Loader Example."
Parallel Querying —Querying the Coherence Data Grid including the use of indexes. See Section A.5.5, "Query Example."
Observable—Listening for changes to data in the Coherence Data Grid. See Section A.5.6, "Observer Example."
Processing—Co-locating data processing with the data itself in the Coherence Data Grid. See Section A.5.7, "Processor Example."
Query Language—How to use the new 3.6 Coherence Query Language. See Section A.5.8, "Query Language."
This example set uses example data represented by these Data Model classes.
Table A-10 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 Section A.5.2, "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 |
Please refer to this example set's examples.zip
file for more details on each of the examples outlined below.
This example shows the most basic data access features of Coherence including getting, putting and removing data.
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);
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);
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 A-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.
Implementation Class: com.tangosol.examples.contacts.LoaderExample
in java/src
cache.putAll(mapBatch);
Implementation Class: LoaderExample
in namespace Tangosol.Examples.Contacts
in dotnet/src/contacts
cache.InsertAll(dictBatch);
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.
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()));
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()));
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 A-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.
Implementation Class: com.tangosol.examples.contacts.ObserverExample
in java/src
ContactChangeListener
is a class that implements the MapListener
interface.
cache.addMapListener(new ContactChangeListener());
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());
Implementation Class: ObserverExample
in namespace coherence::examples
in cpp/contacts
ContactChangeListener
is a class that extends the MapListener
type using Coherence extend
macro.
ContactChangeListener::Handle hListener = ContactChangeListener::create(); hCache->addFilterListener(hListener);
Definition of ContactChangeListener
:
class ContactChangeListener : public class_spec<ContactChangeListener, extends <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.
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));
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));
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 A-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.
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()));
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));
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 A-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.
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.
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.
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:
This example shows simplified role-based access control.
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.
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.
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 A-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.
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.
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.
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.
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.
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.
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.
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.
There is no .NET implementation. The class runs only on the proxy in Java.
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.
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.
There is no .NET implementation. The class runs only on the proxy in Java.
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.
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.
There is no .NET implementation. The class runs only on the proxy in Java.
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.
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.
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.
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 A-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 A-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:
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.