+

Search Tips   |   Advanced Search


Example: Java Serialization

In this example, the requests and responses carry HTTP Content-type headers equal to application/x-java-serialized-object and include serialized objects in binary format.

To decode and encode this type of requests and responses, it is necessary to write the Binder, Encoder, and Decoder.


JavaSerializationBinder

import static com.google.common.base.Predicates.instanceOf;
import static com.neotys.extensions.codec.predicates.MorePredicates.hasHTTPContentType;

import java.io.Serializable;
import com.neotys.extensions.codec.AbstractBinder;

public class JavaSerializationBinder extends AbstractBinder {

	private static final String CONTENT_TYPE = "application/x-java-serialized-object";

	@Override
	protected void configure() {
		whenEntity(hasHTTPContentType(CONTENT_TYPE)).decodeWith(JavaSerializationDecoder.class);
		whenObject(instanceOf(Serializable.class)).encodeWith(JavaSerializationEncoder.class);
	}
}

Any request or response whose Content-type is application/x-java-serialized-object will be decoded with JavaSerializationDecoder.

JavaSerializationDecoder returns java.io.Serializable instances.

Instances of java.io.Serializable are encoded using JavaSerializationEncoder.


JavaSerializationDecoder

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import com.neotys.extensions.codec.functions.Decoder;

public class JavaSerializationDecoder implements Decoder {
	@Override
	public Object apply(final byte[] input) {
		try (final ObjectInputStream objectIn = new ObjectInputStream(new ByteArrayInputStream(input))) {
			return objectIn.readObject();
		} catch (final IOException | ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}
}

JavaSerializationDecoder simply uses the Java Serialization mecanism to read an object from bytes. For more information, refer to the Java Object Serialization Specification page in the Oracle website.


JavaSerializationEncoder

public class JavaSerializationEncoder implements Encoder {
	@Override
	public byte[] apply(final Object input) {
		final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		try (final ObjectOutputStream objectOut = new ObjectOutputStream(byteOut)) {
			objectOut.writeObject(input);
		} catch (final IOException e) {
			e.printStackTrace();
		}
		return byteOut.toByteArray();
	}
}

JavaSerializationEncoder uses the Java Serialization mecanism to write an object from bytes. For more information, refer to the Java Object Serialization Specification page in the Oracle website.


META-INF/services/com.neotys.extensions.codec.AbstractBinder file

This file only contains the line:

com.neotys.sample.serialization.JavaSerializationBinder


Home