Adding serialization example
diff --git a/serialization/.classpath b/serialization/.classpath
new file mode 100644
index 0000000..364af6a
--- /dev/null
+++ b/serialization/.classpath
@@ -0,0 +1,11 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/javax.xml.bind"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/javax.persistence 2.1.0"/>
+ <classpathentry kind="lib" path="eclipselink.jar"/>
+ <classpathentry kind="lib" path="kryo-all.jar"/>
+ <classpathentry kind="lib" path="persistence.jar"/>
+ <classpathentry kind="output" path="classes"/>
+</classpath>
diff --git a/serialization/.project b/serialization/.project
new file mode 100644
index 0000000..9fe00b1
--- /dev/null
+++ b/serialization/.project
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>org.eclipse.persistence.example.serialization</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.wst.common.project.facet.core.builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.wst.validation.validationbuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
+ <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
+ </natures>
+</projectDescription>
diff --git a/serialization/build.xml b/serialization/build.xml
new file mode 100644
index 0000000..47149dd
--- /dev/null
+++ b/serialization/build.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project basedir="." default="build" name="org.eclipse.persistence.example.serialization">
+ <property environment="env"/>
+ <property name="JDBC_LIB" value="./h2.jar"/>
+ <property name="JPA_LIB" value="./persistence.jar"/>
+ <property name="KRYO_LIB" value="./kryo-all.jar"/>
+ <property name="COHERENCE_LIB" value="./coherence.jar"/>
+ <property name="ECLIPSELINK_LIB" value="./eclipselink.jar"/>
+ <property name="AGENT" value="-javaagent:${ECLIPSELINK_LIB}"/>
+ <property name="debuglevel" value="source,lines,vars"/>
+ <path id="example.classpath">
+ <pathelement location="classes"/>
+ <pathelement location="${JDBC_LIB}"/>
+ <pathelement location="${JPA_LIB}"/>
+ <pathelement location="${KRYO_LIB}"/>
+ <pathelement location="${COHERENCE_LIB}"/>
+ <pathelement location="${ECLIPSELINK_LIB}"/>
+ </path>
+ <target name="init" depends="clean">
+ <mkdir dir="classes"/>
+ </target>
+ <target name="clean">
+ <delete dir="classes"/>
+ </target>
+
+ <target depends="init" name="build">
+ <echo message="${ant.project.name}: ${ant.file}"/>
+ <javac debug="true" debuglevel="${debuglevel}" destdir="classes">
+ <src path="src"/>
+ <exclude name="**/.svn/**"/>
+ <exclude name="**/POFSerializer.java"/>
+ <classpath refid="example.classpath"/>
+ </javac>
+ <copy file="src/META-INF/persistence.xml" todir="classes/META-INF"/>
+ <copy file="src/META-INF/order-orm.xml" todir="classes/META-INF"/>
+ <copy file="src/model/jaxb.properties" todir="classes/model/"/>
+ </target>
+
+ <target name="test">
+ <java classname="example.Test"
+ maxmemory="512m"
+ fork="true">
+ <!--jvmarg value="${AGENT}"/-->
+ <classpath refid="example.classpath"/>
+ </java>
+ </target>
+</project>
diff --git a/serialization/serialization.zip b/serialization/serialization.zip
new file mode 100644
index 0000000..1617ede
--- /dev/null
+++ b/serialization/serialization.zip
Binary files differ
diff --git a/serialization/src/META-INF/order-orm.xml b/serialization/src/META-INF/order-orm.xml
new file mode 100644
index 0000000..53a3650
--- /dev/null
+++ b/serialization/src/META-INF/order-orm.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<entity-mappings version="2.1"
+ xmlns="http://www.eclipse.org/eclipselink/xsds/persistence/orm"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+
+ <named-query name="findCustomByName">
+ <query>Select c from Customer c where c.name = :name</query>
+ <hint name="eclipselink.query-results-cache" value="true"/>
+ </named-query>
+ <entity class="model.Order">
+ <table-generator name="ORD_SEQ" allocation-size="500"/>
+ </entity>
+ <entity class="model.Customer">
+ <table-generator name="CUST_SEQ" allocation-size="500"/>
+ </entity>
+
+</entity-mappings>
\ No newline at end of file
diff --git a/serialization/src/META-INF/persistence.xml b/serialization/src/META-INF/persistence.xml
new file mode 100644
index 0000000..d0132b6
--- /dev/null
+++ b/serialization/src/META-INF/persistence.xml
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
+ version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
+ <persistence-unit name="order" transaction-type="RESOURCE_LOCAL">
+ <class>model.Order</class>
+ <class>model.OrderLine</class>
+ <class>model.Customer</class>
+ <shared-cache-mode>NONE</shared-cache-mode>
+ <properties>
+ <!-- Change this to access your own database. -->
+ <!--property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver" />
+ <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:mem:test" />
+ <property name="javax.persistence.jdbc.user" value="sa" />
+ <property name="javax.persistence.jdbc.password" value="" /-->
+ <property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
+ <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test" />
+ <property name="javax.persistence.jdbc.user" value="sa" />
+ <property name="javax.persistence.jdbc.password" value="" />
+ <!-- property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
+ <property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@ottvm073:1521:orcl" />
+ <property name="javax.persistence.jdbc.user" value="jsutherl" />
+ <property name="javax.persistence.jdbc.password" value="password" /-->
+ <property name="eclipselink.jdbc.cache-statements" value="true" />
+ <property name="eclipselink.jdbc.batch-writing" value="jdbc" />
+ <property name="eclipselink.ddl-generation" value="create-tables" />
+ <property name="eclipselink.logging.level" value="off" />
+ </properties>
+ </persistence-unit>
+</persistence>
diff --git a/serialization/src/example/DatabaseSerializer.java b/serialization/src/example/DatabaseSerializer.java
new file mode 100644
index 0000000..af9684b
--- /dev/null
+++ b/serialization/src/example/DatabaseSerializer.java
@@ -0,0 +1,51 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.Persistence;
+
+/**
+ * Uses EclipseLink JPA to read/write an object to a database.
+ * @author James Sutherland
+ */
+public class DatabaseSerializer implements Serializer {
+ EntityManagerFactory factory;
+ Class lastClass;
+ Object lastId;
+
+ public DatabaseSerializer() {
+ this.factory = Persistence.createEntityManagerFactory("order");
+ }
+
+ public byte[] serialize(Object object) {
+ EntityManager em = this.factory.createEntityManager();
+ em.getTransaction().begin();
+ em.persist(object);
+ this.lastClass = object.getClass();
+ this.lastId = this.factory.getPersistenceUnitUtil().getIdentifier(object);
+ em.getTransaction().commit();
+ return new byte[]{};
+ }
+
+ public Object deserialize(byte[] bytes) {
+ EntityManager em = this.factory.createEntityManager();
+ return em.find(this.lastClass, this.lastId);
+ }
+
+ public String toString() {
+ return getClass().getSimpleName();
+ }
+}
diff --git a/serialization/src/example/JSONSerializer.java b/serialization/src/example/JSONSerializer.java
new file mode 100644
index 0000000..b48f667
--- /dev/null
+++ b/serialization/src/example/JSONSerializer.java
@@ -0,0 +1,73 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.Reader;
+import java.io.StringReader;
+import java.io.StringWriter;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import model.Order;
+
+/**
+ * Uses EclipseLink Moxy to convert an object to JSON.
+ * @author James Sutherland
+ */
+public class JSONSerializer implements Serializer {
+ JAXBContext context;
+ Marshaller marshaller;
+ Unmarshaller unmarshaller;
+
+ public JSONSerializer() {
+ try {
+ this.context = JAXBContext.newInstance(Order.class);
+ marshaller = this.context.createMarshaller();
+ marshaller.setProperty("eclipselink.media-type", "application/json");
+ unmarshaller = this.context.createUnmarshaller();
+ unmarshaller.setProperty("eclipselink.media-type", "application/json");
+ } catch (JAXBException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public byte[] serialize(Object object) {
+ try {
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ //StringWriter writer = new StringWriter();
+ marshaller.marshal(object, stream);
+ return stream.toByteArray();
+ } catch (JAXBException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public Object deserialize(byte[] bytes) {
+ try {
+ ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
+ //StringReader reader = new StringReader(new String(bytes));
+ return unmarshaller.unmarshal(stream);
+ } catch (JAXBException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public String toString() {
+ return getClass().getSimpleName();
+ }
+}
diff --git a/serialization/src/example/JavaSerializer.java b/serialization/src/example/JavaSerializer.java
new file mode 100644
index 0000000..20abef7
--- /dev/null
+++ b/serialization/src/example/JavaSerializer.java
@@ -0,0 +1,51 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+/**
+ * Plain old Java serialization.
+ * @author James Sutherland
+ */
+public class JavaSerializer implements Serializer {
+ public byte[] serialize(Object object) {
+ ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
+ try {
+ ObjectOutputStream objectOut = new ObjectOutputStream(byteOut);
+ objectOut.writeObject(object);
+ objectOut.flush();
+ } catch (IOException exception) {
+ throw new RuntimeException(exception);
+ }
+ return byteOut.toByteArray();
+ }
+
+ public Object deserialize(byte[] bytes) {
+ ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
+ try {
+ ObjectInputStream objectIn = new ObjectInputStream(byteIn);
+ return objectIn.readObject();
+ } catch (Exception exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public String toString() {
+ return getClass().getSimpleName();
+ }
+}
diff --git a/serialization/src/example/KryoSerializer.java b/serialization/src/example/KryoSerializer.java
new file mode 100644
index 0000000..57a4554
--- /dev/null
+++ b/serialization/src/example/KryoSerializer.java
@@ -0,0 +1,76 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import model.Order;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.io.Input;
+import com.esotericsoftware.kryo.io.Output;
+
+/**
+ * Uses Kyro to serialize the object.
+ * @author James Sutherland
+ */
+public class KryoSerializer implements Serializer {
+ Kryo kryo;
+
+ public KryoSerializer() {
+ this.kryo = new Kryo();
+ }
+
+ public Kryo getKryo() {
+ return kryo;
+ }
+
+ public void setKryo(Kryo kryo) {
+ this.kryo = kryo;
+ }
+
+ public byte[] serialize(Object object) {
+ try {
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ //FileOutputStream stream = new FileOutputStream("test");
+ Output output = new Output(stream);
+ this.kryo.writeObject(output, object);
+ //stream.flush();
+ output.close();
+ return stream.toByteArray();
+ } catch (Exception exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public Object deserialize(byte[] bytes) {
+ try {
+ ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
+ //FileInputStream stream = new FileInputStream("test");
+ Input input = new Input(stream);
+ Object result = this.kryo.readObject(input, Order.class);
+ input.close();
+ return result;
+ } catch (Exception exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public String toString() {
+ return getClass().getSimpleName();
+ }
+}
diff --git a/serialization/src/example/POFSerializer.java b/serialization/src/example/POFSerializer.java
new file mode 100644
index 0000000..7bd8509
--- /dev/null
+++ b/serialization/src/example/POFSerializer.java
@@ -0,0 +1,70 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import model.Order;
+import model.OrderLine;
+
+import com.tangosol.io.ByteArrayReadBuffer;
+import com.tangosol.io.ByteArrayWriteBuffer;
+import com.tangosol.io.ReadBuffer.BufferInput;
+import com.tangosol.io.WriteBuffer.BufferOutput;
+import com.tangosol.io.pof.PofContext;
+import com.tangosol.io.pof.PortableObjectSerializer;
+import com.tangosol.io.pof.SimplePofContext;
+
+/**
+ * Uses Coherence POF to serialize the object.
+ * @author James Sutherland
+ */
+public class POFSerializer implements Serializer {
+ PofContext context;
+
+ public POFSerializer() {
+ SimplePofContext simpleContext = new SimplePofContext();
+ simpleContext.registerUserType(1, Order.class, new PortableObjectSerializer(1));
+ simpleContext.registerUserType(2, OrderLine.class, new PortableObjectSerializer(2));
+ simpleContext.setReferenceEnabled(true);
+ this.context = simpleContext;
+ }
+
+ public POFSerializer(PofContext context) {
+ this.context = context;
+ }
+
+ public byte[] serialize(Object object) {
+ try {
+ BufferOutput output = new ByteArrayWriteBuffer(1000).getBufferOutput();
+ this.context.serialize(output, object);
+ output.close();
+ return output.getBuffer().toByteArray();
+ } catch (Exception exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public Object deserialize(byte[] bytes) {
+ try {
+ BufferInput input = new ByteArrayReadBuffer(bytes).getBufferInput();
+ Object result = this.context.deserialize(input);
+ input.close();
+ return result;
+ } catch (Exception exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public String toString() {
+ return getClass().getSimpleName();
+ }
+}
diff --git a/serialization/src/example/PerformanceResult.java b/serialization/src/example/PerformanceResult.java
new file mode 100644
index 0000000..f3a717e
--- /dev/null
+++ b/serialization/src/example/PerformanceResult.java
@@ -0,0 +1,40 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.io.StringWriter;
+
+/**
+ * Generic performance result.
+ */
+public class PerformanceResult {
+ String testName;
+ int runRepeats;
+ int runTime;
+ double average;
+ long min;
+ long max;
+ double standardDeviation;
+
+ public String toString() {
+ StringWriter writer = new StringWriter();
+ writer.write(this.testName + " Results");
+ writer.write("\nRun repeats:" + this.runRepeats);
+ writer.write("\nRun time:" + this.runTime + "ms");
+ writer.write("\nAverage result:" + this.average);
+ writer.write("\nMax result:" + this.max);
+ writer.write("\nMin result:" + this.min);
+ writer.write("\n% standard deviation:" + this.standardDeviation);
+ return writer.toString();
+ }
+}
diff --git a/serialization/src/example/PerformanceTest.java b/serialization/src/example/PerformanceTest.java
new file mode 100644
index 0000000..2e08c44
--- /dev/null
+++ b/serialization/src/example/PerformanceTest.java
@@ -0,0 +1,152 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Generic performance test.
+ * This allows executing a timed run and measures and logs the performance.
+ * Logs the executions per run (minute), logs average and % stdev.
+ */
+public class PerformanceTest {
+
+ public static int REPEATS = 5;
+ public static int RUN_TIME = 1000; //10 seconds.
+
+ /**
+ * Measure the performance of the run.
+ * Repeat the run REPEATS (5) times,
+ * and measure the number of execution in RUN_TIME (60s).
+ */
+ public static PerformanceResult executeRun(String name, Runnable runnable) {
+ System.out.println("Starting run: " + name);
+
+ List<Integer> results = new ArrayList<Integer>();
+ // Repeat the test and baseline for the number of repeats.
+ for (int index = 0; index < REPEATS; index++) {
+ long startTime, endTime;
+ int executions = 0;
+ System.gc();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ignore) {}
+ startTime = System.currentTimeMillis();
+ endTime = startTime;
+ // Count how many times the test can be invoked in the run time.
+ // This allows for the test run time to be easily changed.
+ while ((startTime + RUN_TIME) >= endTime) {
+ runnable.run();
+ executions++;
+ endTime = System.currentTimeMillis();
+ }
+ results.add(executions);
+ System.out.println("Done run: " + index + " for: " + name);
+ }
+
+ System.out.println("Completed run: " + name);
+
+ PerformanceResult result = new PerformanceResult();
+ result.testName = name;
+ result.runRepeats = REPEATS;
+ result.runTime = RUN_TIME;
+ result.average = averageResults(results);
+ result.max = maxResults(results);
+ result.min = minResults(results);
+ result.standardDeviation = standardDeviationResults(results);
+
+ System.out.println("");
+ System.out.println(result);
+ System.out.println("");
+ System.out.println("");
+
+ return result;
+ }
+
+ /**
+ * Compute the max of the results.
+ */
+ public static int maxResults(List<Integer> times) {
+ int testMax = 0;
+ for (int index = 0; index < times.size(); index++) {
+ int time = (int)times.get(index);
+ if (time > testMax) {
+ testMax = time;
+ }
+ }
+ return testMax;
+ }
+
+ /**
+ * Compute the min of the results.
+ */
+ public static int minResults(List<Integer> times) {
+ int testMin = 0;
+ for (int index = 0; index < times.size(); index++) {
+ int time = (int)times.get(index);
+ if ((testMin == 0) || (time < testMin)) {
+ testMin = time;
+ }
+ }
+ return testMin;
+ }
+
+ /**
+ * Filter max and min from results.
+ */
+ public static List<Integer> filterMaxMinResults(List<Integer> times) {
+ List filteredTimes = new ArrayList(times);
+ if (filteredTimes.size() > 3) {
+ filteredTimes.remove((Integer)maxResults(times));
+ filteredTimes.remove((Integer)minResults(times));
+ }
+ return filteredTimes;
+ }
+
+ /**
+ * Compute the average of the results rejecting the min and max.
+ */
+ public static double averageResults(List<Integer> allTimes) {
+ // Compute the average reject the min and max to improve consistency.
+ List<Integer> times = filterMaxMinResults(allTimes);
+ double testAverage = 0;
+ for (int index = 0; index < times.size(); index++) {
+ int time = (int)times.get(index);
+ testAverage = testAverage + time;
+ }
+ testAverage = testAverage / times.size();
+ return testAverage;
+ }
+
+ /**
+ * Compute the standard deviation of the results rejecting the min and max.
+ */
+ public static double standardDeviationResults(List<Integer> allTimes) {
+ // Compute the average reject the min and max to improve consistency.
+ double testAverage = averageResults(allTimes);
+
+ // Compute the standard deviation reject the min and max to improve consistency.
+ List<Integer> times = filterMaxMinResults(allTimes);
+ double testStandardDeviation = 0;
+ for (int index = 0; index < times.size(); index++) {
+ int time = (int)times.get(index);
+ testStandardDeviation = testStandardDeviation + Math.pow(time - testAverage, 2);
+ }
+ testStandardDeviation = testStandardDeviation / times.size();
+ testStandardDeviation = Math.sqrt(testStandardDeviation);
+ // As percent of average
+ testStandardDeviation = (testStandardDeviation / testAverage) * 100;
+ return testStandardDeviation;
+ }
+}
diff --git a/serialization/src/example/Serializer.java b/serialization/src/example/Serializer.java
new file mode 100644
index 0000000..0acd185
--- /dev/null
+++ b/serialization/src/example/Serializer.java
@@ -0,0 +1,22 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+/**
+ * Generic serializer interface.
+ * @author James Sutherland
+ */
+public interface Serializer {
+ byte[] serialize(Object object);
+ Object deserialize(byte[] bytes);
+}
diff --git a/serialization/src/example/Test.java b/serialization/src/example/Test.java
new file mode 100644
index 0000000..d762711
--- /dev/null
+++ b/serialization/src/example/Test.java
@@ -0,0 +1,152 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.swing.JOptionPane;
+
+//import oracle.toplink.exalogic.serializers.POFReflectionSerializer;
+
+//import org.eclipse.persistence.expressions.ExpressionBuilder;
+//import org.eclipse.persistence.queries.ReadAllQuery;
+
+//import com.tangosol.io.pof.PortableObjectSerializer;
+//import com.tangosol.io.pof.SimplePofContext;
+
+import model.Order;
+import model.OrderLine;
+
+/**
+ * Test the performance of various different serialization formats and objects.
+ * @author James Sutherland
+ */
+public class Test extends PerformanceTest {
+ public static interface Factory {
+ Object create();
+ }
+
+ public static void main(String[] args) throws Exception {
+ try {
+ Test test = new Test();
+ test.test();
+ } catch (Exception error) {
+ error.printStackTrace();
+ }
+ }
+
+ public void test() {
+ Factory factory = new Factory() {
+ public Object create() {
+ Order order = new Order();
+ //for (int index = 0; index < 100; index++) {
+ order.addOrderLine(new OrderLine());
+ //order.getOrderLines().add(new OrderLine());
+ //}
+ return order;
+ //ReadAllQuery query = new ReadAllQuery(Order.class);
+ //query.setSelectionCriteria(new ExpressionBuilder().get("id").equal(100));
+ //return query;
+ }
+ };
+
+ //SimplePofContext simpleContext = new SimplePofContext();
+ //simpleContext.registerUserType(1, Order.class, new POFReflectionSerializer(Order.class));
+ //simpleContext.registerUserType(2, OrderLine.class, new POFReflectionSerializer(OrderLine.class));
+ //simpleContext.setReferenceEnabled(true);
+ //POFSerializer pofReflect = new POFSerializer(simpleContext);
+
+ byte[] bytes = null;
+ Object object = null;
+ //POFSerializer pof = new POFSerializer();
+ //bytes = pof.serialize(factory.create());
+ //object = pof.deserialize(bytes);
+ KryoSerializer kyro = new KryoSerializer();
+ bytes = kyro.serialize(factory.create());
+ object = kyro.deserialize(bytes);
+ JSONSerializer json = new JSONSerializer();
+ bytes = json.serialize(factory.create());
+ object = json.deserialize(bytes);
+ XMLSerializer xml = new XMLSerializer();
+ bytes = xml.serialize(factory.create());
+ object = xml.deserialize(bytes);
+ JavaSerializer java = new JavaSerializer();
+ bytes = java.serialize(factory.create());
+ object = java.deserialize(bytes);
+ //DatabaseSerializer db = new DatabaseSerializer();
+ //bytes = db.serialize(factory.create());
+ //object = db.deserialize(bytes);
+
+ //JOptionPane.showMessageDialog(null, "Start");
+
+ List<List> results = new ArrayList<List>();
+ //results.add(testSerialization("order-POF-reflect", factory, pofReflect));
+ //results.add(testSerialization("order-POF", factory, pof));
+ results.add(testSerialization("order-JSON", factory, json));
+ results.add(testSerialization("order-XML", factory, xml));
+ //results.add(testSerialization("order-Database", factory, db));
+ results.add(testSerialization("order-Kryo", factory, kyro));
+ results.add(testSerialization("order-Java", factory, java));
+ //testSerialization("empty-HashMap", new HashMap(), new JavaSerializer());
+ //testSerialization("empty-ArrayList", new ArrayList(), new JavaSerializer());
+ //testSerialization("Class", JFormattedTextField.class, new JavaSerializer());
+
+ //JOptionPane.showMessageDialog(null, "Finish");
+
+ for (List result : results) {
+ for (int index = 0; index < result.size(); index = index + 3) {
+ System.out.println("");
+ System.out.println(((PerformanceResult)result.get(index)).testName + " : " + ((PerformanceResult)result.get(index)).average);
+ System.out.println(((PerformanceResult)result.get(index+ 1)).testName + " : " + ((PerformanceResult)result.get(index + 1)).average);
+ System.out.println("Size: " + result.get(index + 2));
+ }
+ }
+ }
+
+ public List testSerialization(String testName, final Factory factory, final Serializer serializer) {
+ List result = new ArrayList();
+ System.out.println("\n\nbegin test " + testName);
+ result.add(this.executeRun(testName + "-serialize", new Runnable() {
+ public void run() {
+ serializer.serialize(factory.create());
+ }
+ }));
+ final byte[] bytes = serializer.serialize(factory.create());
+ result.add(this.executeRun(testName + "-deserialize", new Runnable() {
+ public void run() {
+ serializer.deserialize(bytes);
+ }
+ }));
+ result.add(bytes.length);
+ System.out.println("serialization size: " + bytes.length + " bytes");
+ StringWriter writer = new StringWriter();
+ for (int index = 0; index < bytes.length; index++) {
+ char c = (char)bytes[index];
+ if (c == '<') {
+ writer.write("<");
+ } else if (c == '>') {
+ writer.write(">");
+ } else if (c < 32 || c > 126) {
+ writer.write('-');
+ } else {
+ writer.write(c);
+ }
+ }
+ System.out.println("\nserialization bytes:\n" + writer.toString());
+ System.out.println("\nfinish test " + testName);
+ return result;
+ }
+
+}
diff --git a/serialization/src/example/XMLSerializer.java b/serialization/src/example/XMLSerializer.java
new file mode 100644
index 0000000..f382f5f
--- /dev/null
+++ b/serialization/src/example/XMLSerializer.java
@@ -0,0 +1,71 @@
+/*******************************************************************************
+ * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package example;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.StringReader;
+import java.io.StringWriter;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.JAXBException;
+import javax.xml.bind.Marshaller;
+import javax.xml.bind.Unmarshaller;
+
+import model.Order;
+
+/**
+ * Uses JAXB to convert an object to XML.
+ * @author James Sutherland
+ */
+public class XMLSerializer implements Serializer {
+ JAXBContext context;
+ Marshaller marshaller;
+ Unmarshaller unmarshaller;
+
+ public XMLSerializer() {
+ try {
+ this.context = JAXBContext.newInstance(Order.class);
+ this.marshaller = context.createMarshaller();
+ this.marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
+ this.unmarshaller = context.createUnmarshaller();
+ } catch (JAXBException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public byte[] serialize(Object object) {
+ try {
+ ByteArrayOutputStream stream = new ByteArrayOutputStream();
+ //StringWriter writer = new StringWriter();
+ marshaller.marshal(object, stream);
+ return stream.toByteArray();
+ } catch (JAXBException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public Object deserialize(byte[] bytes) {
+ try {
+ ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
+ //StringReader reader = new StringReader(new String(bytes));
+ return unmarshaller.unmarshal(stream);
+ } catch (JAXBException exception) {
+ throw new RuntimeException(exception);
+ }
+ }
+
+ public String toString() {
+ return getClass().getSimpleName();
+ }
+}
diff --git a/serialization/src/model/Customer.java b/serialization/src/model/Customer.java
new file mode 100644
index 0000000..1f7ecb5
--- /dev/null
+++ b/serialization/src/model/Customer.java
@@ -0,0 +1,52 @@
+/*******************************************************************************
+ * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package model;
+
+import java.io.Serializable;
+
+import javax.persistence.*;
+
+/**
+ * Customer
+ * @author James Sutherland
+ */
+@Entity
+@Table(name="PERF_CUSTOMER")
+public class Customer implements Serializable {
+ @Id
+ @GeneratedValue(generator="CUST_SEQ")
+ @TableGenerator(name="CUST_SEQ")
+ private long id;
+ @Basic
+ private String name;
+
+ public Customer() {
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+}
diff --git a/serialization/src/model/Order.java b/serialization/src/model/Order.java
new file mode 100644
index 0000000..0981866
--- /dev/null
+++ b/serialization/src/model/Order.java
@@ -0,0 +1,144 @@
+/*******************************************************************************
+ * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package model;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlID;
+import javax.xml.bind.annotation.XmlRootElement;
+
+//import com.tangosol.io.pof.PofReader;
+//import com.tangosol.io.pof.PofWriter;
+//import com.tangosol.io.pof.PortableObject;
+
+/**
+ * Order
+ * @author James Sutherland
+ */
+@Entity
+@Table(name="PERF_ORDER")
+@XmlRootElement
+public class Order implements Serializable { //Externalizable {//, PortableObject {
+ @Id
+ @GeneratedValue(generator="ORD_SEQ")
+ @TableGenerator(name="ORD_SEQ")
+ @Column(name="ORDER_ID")
+ @XmlID
+ @XmlAttribute
+ private long id;
+ @Basic
+ @XmlAttribute
+ private String description;
+ @Basic
+ @XmlAttribute
+ private BigDecimal totalCost = BigDecimal.valueOf(0);
+ @OneToMany(mappedBy="order", fetch=FetchType.EAGER, cascade=CascadeType.ALL, orphanRemoval=true)
+ @OrderBy("lineNumber")
+ private List<OrderLine> orderLines = new ArrayList<OrderLine>();
+ @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
+ private Customer customer;
+
+ public Order() {
+ }
+
+ /*public void readExternal(PofReader in) throws IOException {
+ this.id = in.readLong(0);
+ this.description = in.readString(1);
+ this.totalCost = in.readBigDecimal(2);
+ this.customer = (Customer)in.readObject(3);
+ this.orderLines = (List)in.readCollection(4, new ArrayList());
+ }
+
+ public void writeExternal(PofWriter out) throws IOException {
+ out.writeLong(0, this.id);
+ out.writeString(1, this.description);
+ out.writeBigDecimal(2, this.totalCost);
+ out.writeObject(3, this.customer);
+ out.writeCollection(4, this.orderLines);
+ }*/
+
+ public void readExternal(ObjectInput stream) throws IOException, ClassNotFoundException {
+ this.id = stream.readLong();
+ this.description = (String)stream.readObject();
+ this.totalCost = (BigDecimal)stream.readObject();
+ this.customer = (Customer)stream.readObject();
+ this.orderLines = (List)stream.readObject();
+ }
+
+ public void writeExternal(ObjectOutput stream) throws IOException {
+ stream.writeLong(this.id);
+ stream.writeObject(this.description);
+ stream.writeObject(this.totalCost);
+ stream.writeObject(this.customer);
+ stream.writeObject(this.orderLines);
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public BigDecimal getTotalCost() {
+ return totalCost;
+ }
+
+ public void setTotalCost(BigDecimal totalCost) {
+ this.totalCost = totalCost;
+ }
+
+ public List<OrderLine> getOrderLines() {
+ return orderLines;
+ }
+
+ public void setOrderLines(List<OrderLine> orderLines) {
+ this.orderLines = orderLines;
+ }
+
+ public Customer getCustomer() {
+ return customer;
+ }
+
+ public void setCustomer(Customer customer) {
+ this.customer = customer;
+ }
+
+ /**
+ * Add the order line to the order, and set the back reference and update the order cost.
+ */
+ public void addOrderLine(OrderLine orderLine) {
+ orderLine.setOrder(this);
+ getOrderLines().add(orderLine);
+ orderLine.setLineNumber(getOrderLines().size());
+ setTotalCost(getTotalCost().add(orderLine.getCost()));
+ }
+}
diff --git a/serialization/src/model/OrderLine.java b/serialization/src/model/OrderLine.java
new file mode 100644
index 0000000..26d80f8
--- /dev/null
+++ b/serialization/src/model/OrderLine.java
@@ -0,0 +1,120 @@
+/*******************************************************************************
+ * Copyright (c) 2011, 2012 Oracle and/or its affiliates. All rights reserved.
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
+ * which accompanies this distribution.
+ * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
+ * and the Eclipse Distribution License is available at
+ * http://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * Contributors:
+ * Oracle - initial impl
+ ******************************************************************************/
+package model;
+
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.io.Serializable;
+import java.math.BigDecimal;
+
+import javax.persistence.*;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlIDREF;
+
+//import com.tangosol.io.pof.PofReader;
+//import com.tangosol.io.pof.PofWriter;
+//import com.tangosol.io.pof.PortableObject;
+
+/**
+ * OrderLine, held by Order.
+ * @author James Sutherland
+ */
+@Entity
+@Table(name="PERF_ORDERLINE")
+public class OrderLine implements Serializable { //Externalizable {//, PortableObject {
+ @Id
+ @ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
+ @JoinColumn(name="ORDER_ID")
+ @XmlIDREF
+ private Order order;
+ @Id
+ @XmlAttribute
+ private int lineNumber;
+ @Basic
+ @XmlAttribute
+ private String description;
+ @Basic
+ @XmlAttribute
+ private BigDecimal cost = BigDecimal.valueOf(0);
+
+ public OrderLine() {
+ }
+
+ /*public void readExternal(PofReader in) throws IOException {
+ this.lineNumber = in.readInt(0);
+ this.description = in.readString(1);
+ this.cost = in.readBigDecimal(2);
+ this.order = (Order)in.readObject(3);
+ }
+
+ public void writeExternal(PofWriter out) throws IOException {
+ out.writeInt(0, this.lineNumber);
+ out.writeString(1, this.description);
+ out.writeBigDecimal(2, this.cost);
+ out.writeObject(3, this.order);
+ }*/
+
+ public void readExternal(ObjectInput stream) throws IOException, ClassNotFoundException {
+ this.lineNumber = stream.readInt();
+ this.description = (String)stream.readObject();
+ this.cost = (BigDecimal)stream.readObject();
+ this.order = (Order)stream.readObject();
+ }
+
+ public void writeExternal(ObjectOutput stream) throws IOException {
+ stream.writeInt(this.lineNumber);
+ stream.writeObject(this.description);
+ stream.writeObject(this.cost);
+ stream.writeObject(this.order);
+ }
+
+ public OrderLine(String description, BigDecimal cost) {
+ this.description = description;
+ this.cost = cost;
+ }
+
+ public Order getOrder() {
+ return order;
+ }
+
+ public void setOrder(Order order) {
+ this.order = order;
+ }
+
+ public int getLineNumber() {
+ return lineNumber;
+ }
+
+ public void setLineNumber(int lineNumber) {
+ this.lineNumber = lineNumber;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public void setDescription(String description) {
+ this.description = description;
+ }
+
+ public BigDecimal getCost() {
+ return cost;
+ }
+
+ public void setCost(BigDecimal cost) {
+ this.cost = cost;
+ }
+
+}
diff --git a/serialization/src/model/jaxb.properties b/serialization/src/model/jaxb.properties
new file mode 100644
index 0000000..b2979f9
--- /dev/null
+++ b/serialization/src/model/jaxb.properties
@@ -0,0 +1 @@
+javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory