Maui
Maui

Reputation: 59

Java object serialization in camel 3.x?

In camel 2.x there was marshal().serialization(). It’s no longer there in camel 3.x. Is Java object serialization possible in camel 3?

Upvotes: 1

Views: 893

Answers (1)

Gerry Mantha
Gerry Mantha

Reputation: 1098

You can write your own Processor, Bean, DataFormat, or TypeConverter to do so. Here is a way to do this using a bean that you can then reuse anywhere in your Camel routes:

@Component
public class Serializer {
    @Handler
    public String serializeToBase64String(@Body Serializable inputObject) {
        Assert.notNull(inputObject, "Object in Exchange Body must implement Serializable!");

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        try (ObjectOutputStream oos = new ObjectOutputStream(baos)) {
            oos.writeObject(inputObject);
        } catch (IOException e) {
            // ...
        }

        return Base64.getEncoder().encodeToString(baos.toByteArray());
    }
}

Then to use in your Camel route, just use:

.bean("serializer") 

Instead of:

.marshal().serialization()

That being said if you can help it, avoid serializing any Java object for long term storage or for communication between applications. The serialized class may have had changed after being stored and no longer work. If used for communication it adds an unacceptable amount of coupling between applications. Not only are we forcing the applications to be implemented using the same language (Java) but even the same version of classes intended to be serialized/deserialized, forcing both to share a domain-specific model library.

Instead if you are able to, preferably use JSON, XML, or some other form of language/class-agnostic communication to reduce coupling.

Upvotes: 1

Related Questions