Coherence Complete Application Save Retrieve Data Cache

In this tutorial you will have to setup Oracle Coherence Complete Application where we will save and retrieve data from the cache.

Tools needed:

  • Eclipse any latest version
  • Coherence jar (Already included in pom we are using version 12.1.3.0.2)
  • Maven (It comes with Eclipse)
  • JDK 1.8

Maven project structure:

  • pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>com.wfs.otc.coherenceByteSerializer</groupId>
	<artifactId>CoherenceByteSerializer</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>CoherenceByteSerializer</name>

	<properties>

		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>

		<org.apache.log4j.version>2.1</org.apache.log4j.version>
		<clusterAPI.version>1.0</clusterAPI.version>
		<coherence.version>12.1.3.0.2</coherence.version>
		<coherence-incubator.version>11.3.0</coherence-incubator.version>
		<galaxy.version>v_10_0_20141003</galaxy.version>
		<xercesImpl.version>unknown</xercesImpl.version>
		<org.springframework.version>4.1.5.RELEASE</org.springframework.version>		

	</properties>

	<dependencies>
	
	    <dependency>
			<groupId>com.javahonk.clusterAPI</groupId>
			<artifactId>ClusterClient</artifactId>
			<version>${clusterAPI.version}</version>
		</dependency>

		<dependency>
			<groupId>com.javahonk.clusterAPI</groupId>
			<artifactId>ClusterInfoInvocation</artifactId>
			<version>${clusterAPI.version}</version>
		</dependency>

		<dependency>
			<groupId>com.oracle.coherence</groupId>
			<artifactId>coherence</artifactId>
			<version>${coherence.version}</version>
		</dependency>

		<dependency>
			<groupId>com.oracle.coherence.incubator</groupId>
			<artifactId>coherence-common</artifactId>
			<version>${coherence-incubator.version}</version>
		</dependency>

		<dependency>
			<groupId>com.oracle.coherence.incubator</groupId>
			<artifactId>coherence-commandpattern</artifactId>
			<version>${coherence-incubator.version}</version>
		</dependency>

		<dependency>
			<groupId>com.oracle.coherence.incubator</groupId>
			<artifactId>coherence-messagingpattern</artifactId>
			<version>${coherence-incubator.version}</version>
		</dependency>

		<dependency>
			<groupId>com.oracle.coherence.incubator</groupId>
			<artifactId>coherence-processingpattern</artifactId>
			<version>${coherence-incubator.version}</version>
		</dependency>

		<dependency>
			<groupId>com.javahonk.galaxy</groupId>
			<artifactId>eqdframework</artifactId>
			<version>${galaxy.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${org.apache.log4j.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${org.apache.log4j.version}</version>
		</dependency>

		<dependency>
			<groupId>xerces</groupId>
			<artifactId>xercesImpl</artifactId>
			<version>${xercesImpl.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>
		
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.12</version>
		</dependency>
		
	</dependencies>

	<build>

		<resources>
			<resource>
				<directory>src/main/config</directory>
				<excludes>
					<exclude>*.xml</exclude>
					<exclude>*.properties</exclude>
				</excludes>
			</resource>
			<resource>
				<directory>src/main/resources</directory>
				<excludes>
					<exclude>*.xml</exclude>
					<exclude>*.properties</exclude>
				</excludes>
			</resource>
		</resources>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-dependency-plugin</artifactId>
				<version>2.8</version>
				<executions>
					<execution>
						<id>copy-dependencies</id>
						<phase>package</phase>
						<goals>
							<goal>copy-dependencies</goal>
						</goals>
						<configuration>
							<outputDirectory>${project.build.directory}/lib</outputDirectory>
							<overWriteReleases>false</overWriteReleases>
							<overWriteSnapshots>false</overWriteSnapshots>
							<overWriteIfNewer>true</overWriteIfNewer>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>

	</build>

</project>
  • all-cache-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">
	
	<context:annotation-config />
	<context:component-scan base-package="com.javahonk.cache" />
	
	<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<list>
				<value>JavaHonk.properties</value>
			</list>
		</property>
		<property name="ignoreUnresolvablePlaceholders" value="true"/>
		<property name="ignoreResourceNotFound" value="true"/>
	</bean>
	
	<bean id="SaveRetrieveByteArrayFromCache" class="com.javahonk.cache.SaveRetrieveByteArrayFromCache" />
	
</beans>
  • custom-types-pof-config.xml:
<?xml version="1.0"?>

<!DOCTYPE pof-config SYSTEM "pof-config.dtd">

<pof-config>

  <user-type-list>
    <include>coherence-pof-config.xml</include>
    <user-type>
		<type-id>5000</type-id>
		<class-name>com.javahonk.cache.serializer.Employee</class-name>
		<serializer>
			<class-name>com.javahonk.cache.serializer.EmployeeSerializer</class-name>
		</serializer>
	</user-type>
	<user-type>
		<type-id>5001</type-id>
		<class-name>com.javahonk.cache.serializer.Person</class-name>
		<serializer>
			<class-name>com.javahonk.cache.serializer.PersonSerializer</class-name>
		</serializer>
	</user-type>
  </user-type-list>
  
</pof-config>

  • JavaHonk.properties: This file is empty but you can use it define your properties here:
  • log4j.properties:
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=ERROR, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
  • log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO" shutdownHook="disable">

	<Properties>
		<Property name="envrionment.target">DEV</Property>
	</Properties>

	<Properties>
		<Property name="logging.dir">./</Property>
	</Properties>

	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="%d{dd-MM-yyy HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</Console>

		<RollingFile name="RollingFile"
			fileName="rolling-file.log"	filePattern="${sys:logging.dir}/logs/rolling-file-%d{yyyy-MM-dd}-%i.log">
			<PatternLayout pattern="%d{dd-MM-yyy HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
			<Policies>
				<TimeBasedTriggeringPolicy interval="1"	modulate="true" />
				<SizeBasedTriggeringPolicy size="100 MB" />
			</Policies>
			<DefaultRolloverStrategy max="4" />
		</RollingFile>

	</Appenders>


	<Loggers>

		<Root level="info">
			<AppenderRef ref="Console" />
			<AppenderRef ref="RollingFile" />
		</Root>
	</Loggers>
</Configuration>
  • Employee.java:
package com.javahonk.cache.serializer;

import java.util.Arrays;

public class Employee {
	
	private byte person[];
	public Employee(byte[] person) {
		super();
		this.person = person;
	}
	public byte[] getPerson() {
		return person;
	}
	public void setPerson(byte[] person) {
		this.person = person;
	}
	@Override
	public String toString() {
		return "Employee [person=" + Arrays.toString(person) + "]";
	}
	
}
  • EmployeeSerializer.java:
package com.javahonk.cache.serializer;

import java.io.IOException;

import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofSerializer;
import com.tangosol.io.pof.PofWriter;

public class EmployeeSerializer implements PofSerializer {

	@Override
	public Object deserialize(PofReader pofReader) throws IOException {

		byte person[] = pofReader.readByteArray(1);
		
		pofReader.readRemainder();

		return new Employee(person);
	}

	@Override
	public void serialize(PofWriter pofWriter, Object o) throws IOException {

		Employee employee = (Employee) o;

		pofWriter.writeByteArray(1,employee.getPerson());
		
		pofWriter.writeRemainder(null);

	}
}
  • Person.java:
package com.javahonk.cache.serializer;

import java.util.Date;

public class Person {
	
	private String name;
	private Date dob;
	private Integer zip;
	public Person(String name, Date dob, Integer zip) {
		super();
		this.name = name;
		this.dob = dob;
		this.zip = zip;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getDob() {
		return dob;
	}
	public void setDob(Date dob) {
		this.dob = dob;
	}
	public Integer getZip() {
		return zip;
	}
	public void setZip(Integer zip) {
		this.zip = zip;
	}
	@Override
	public String toString() {
		return "Person [name=" + name + ", dob=" + dob + ", zip=" + zip + "]";
	}
	
}
  • PersonSerializer.java:
package com.javahonk.cache.serializer;

import java.io.IOException;
import java.util.Date;

import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofSerializer;
import com.tangosol.io.pof.PofWriter;

public class PersonSerializer implements PofSerializer {

	@Override
	public Object deserialize(PofReader pofReader) throws IOException {

		String name = pofReader.readString(1);
		Date dob = pofReader.readDate(2);
		Integer zip = pofReader.readInt(3);
		
		pofReader.readRemainder();

		return new Person(name, dob, zip);
	}

	@Override
	public void serialize(PofWriter pofWriter, Object o) throws IOException {

		Person person = (Person) o;

		pofWriter.writeString(1,person.getName());
		pofWriter.writeDateTime(2,person.getDob());
		pofWriter.writeInt(3,person.getZip());
		
		pofWriter.writeRemainder(null);

	}
}
  • SerializationHelper.java: Very important class which converts object to byte array:
package com.javahonk.cache;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.InputStream;

import com.tangosol.io.WrapperBufferInput;
import com.tangosol.io.WrapperBufferOutput;
import com.tangosol.io.pof.PofContext;

public class SerializationHelper {

	public static Object Deserialize(PofContext context, byte[] payload) throws Exception{
		
		InputStream in = new ByteArrayInputStream(payload);
		
		DataInput dataInput = new DataInputStream(in);
		
		WrapperBufferInput ip = new WrapperBufferInput(dataInput);
		
		return context.deserialize(ip);
	}
	
	public static byte[] Serialize(PofContext context, Object payload) throws Exception{
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		DataOutput dataOut = new DataOutputStream(out);
		
		WrapperBufferOutput op = new WrapperBufferOutput(dataOut);
		
		context.serialize(op, payload);
		
		return out.toByteArray(); 
	}
	
}
  • SaveRetrieveByteArrayFromCache.java: Main class which is saving and retrieving data from cache:
package com.javahonk.cache;

import java.util.Date;

import com.javahonk.cache.serializer.Employee;
import com.javahonk.cache.serializer.Person;
import com.tangosol.io.pof.ConfigurablePofContext;
import com.tangosol.net.NamedCache;
import com.wachovia.cib.spt.datautil.CacheRegistry;

public class SaveRetrieveByteArrayFromCache {

	public void saveRetrieveDate() {

		NamedCache cache = (NamedCache) CacheRegistry.getNamedCache("Products");
		
		try {
			
			Person person = new Person("Java Honk", new Date(), new Integer(882221));
			
			Employee employee = new Employee(SerializationHelper.Serialize(new ConfigurablePofContext(), person));
			cache.put("employee", employee);
			Employee employee2 =  (Employee) cache.get("employee");
			
			Person person2 = (Person) SerializationHelper.Deserialize(new ConfigurablePofContext(), employee2.getPerson());
			
			System.out.println("First Name: "+person2.getName());
			System.out.println("DOB: "+person2.getDob());
			System.out.println("Zip: "+person2.getZip());
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
  • CoherenceSerializerTest.java: Test class to start the application and test its functionality:
package com.javahonk.cache;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class CoherenceSerializerTest {

	public static void main(String[] args) throws BeansException, InterruptedException {
		
		//OTC QA Strategic SIT cache
		System.setProperty("wells.ccu.clientconfig", "extend-access.xml");
		System.setProperty("wells.ccu.url", "http://cacheurl.com/clusterclient/java/server/");	
		System.setProperty("wells.cluster.extend.access", "true");
		System.setProperty("wells.ccu.serializer.config", "http://cacheurl.com/clusterclient/java/");
		System.setProperty("tangosol.pof.enabled", "true");
		System.setProperty("tangosol.pof.config", "custom-types-pof-config.xml");
		System.setProperty("logging.dir", "./");
		
		ApplicationContext context = new ClassPathXmlApplicationContext("all-cache-context.xml");
		
		context.getBean(SaveRetrieveByteArrayFromCache.class).saveRetrieveDate();

		((AbstractApplicationContext) context).close();

	}

}
  • Reference:

Leave a Reply

Your email address will not be published. Required fields are marked *