pekko/docs/src/test/java/jdocs/serialization/SerializationDocTest.java

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

204 lines
6.3 KiB
Java
Raw Normal View History

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, derived from Akka.
*/
/*
2022-02-04 12:36:44 +01:00
* Copyright (C) 2009-2022 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.serialization;
import org.apache.pekko.actor.typed.javadsl.Behaviors;
import org.apache.pekko.cluster.Cluster;
import org.apache.pekko.testkit.javadsl.TestKit;
import org.junit.Test;
2011-12-30 22:13:25 +01:00
import static org.junit.Assert.*;
// #imports
import org.apache.pekko.actor.*;
import org.apache.pekko.serialization.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
// #imports
public class SerializationDocTest {
public
// #my-own-serializer
static class MyOwnSerializer extends JSerializer {
// If you need logging here, introduce a constructor that takes an ExtendedActorSystem.
// public MyOwnSerializer(ExtendedActorSystem actorSystem)
// Get a logger using:
// private final LoggingAdapter logger = Logging.getLogger(actorSystem, this);
// This is whether "fromBinary" requires a "clazz" or not
@Override
public boolean includeManifest() {
return false;
}
// Pick a unique identifier for your Serializer,
// you've got a couple of billions to choose from,
// 0 - 40 is reserved by Pekko itself
@Override
public int identifier() {
return 1234567;
}
// "toBinary" serializes the given object to an Array of Bytes
@Override
public byte[] toBinary(Object obj) {
// Put the code that serializes the object here
// #...
return new byte[0];
// #...
}
// "fromBinary" deserializes the given array,
// using the type hint (if any, see "includeManifest" above)
@Override
public Object fromBinaryJava(byte[] bytes, Class<?> clazz) {
// Put your code that deserializes here
// #...
return null;
// #...
}
}
// #my-own-serializer
static class Customer {
public final String name;
Customer(String name) {
this.name = name;
}
}
static class User {
public final String name;
User(String name) {
this.name = name;
}
}
public
// #my-own-serializer2
static class MyOwnSerializer2 extends SerializerWithStringManifest {
private static final String CUSTOMER_MANIFEST = "customer";
private static final String USER_MANIFEST = "user";
private static final Charset UTF_8 = StandardCharsets.UTF_8;
// Pick a unique identifier for your Serializer,
// you've got a couple of billions to choose from,
// 0 - 40 is reserved by Pekko itself
@Override
public int identifier() {
return 1234567;
}
@Override
public String manifest(Object obj) {
if (obj instanceof Customer) return CUSTOMER_MANIFEST;
else if (obj instanceof User) return USER_MANIFEST;
else throw new IllegalArgumentException("Unknown type: " + obj);
}
// "toBinary" serializes the given object to an Array of Bytes
@Override
public byte[] toBinary(Object obj) {
// Put the real code that serializes the object here
if (obj instanceof Customer) return ((Customer) obj).name.getBytes(UTF_8);
else if (obj instanceof User) return ((User) obj).name.getBytes(UTF_8);
else throw new IllegalArgumentException("Unknown type: " + obj);
}
// "fromBinary" deserializes the given array,
// using the type hint
@Override
public Object fromBinary(byte[] bytes, String manifest) {
// Put the real code that deserializes here
if (manifest.equals(CUSTOMER_MANIFEST)) return new Customer(new String(bytes, UTF_8));
else if (manifest.equals(USER_MANIFEST)) return new User(new String(bytes, UTF_8));
else throw new IllegalArgumentException("Unknown manifest: " + manifest);
}
}
// #my-own-serializer2
@Test
public void serializeActorRefs() {
final ExtendedActorSystem extendedSystem = (ExtendedActorSystem) ActorSystem.create("whatever");
final ActorRef theActorRef = extendedSystem.deadLetters(); // Of course this should be you
// #actorref-serializer
// Serialize
// (beneath toBinary)
Disable Java serialization by default, #22333 (#27285) * akka.actor.allow-java-serialization = off * Moved primitive (Long, Int, String, ByteString) serializers from akka-remote to akka-actor since they had no dependency and are useful also in local systems, e.g. persistence. * e.g. needed for persistence-tck * less allow-java-serialization=on in tests * CborSerializable in Jackson/test module for ease of use * JavaSerializable for Java serialization in tests, already in akka-testkit, but misconfigured * Made tests pass * allow-java-serialization=on in akka-persistence * allow-java-serialization=on in classic remoting tests * JavaSerializable and CborSerializable in other remoting tests * Added serialization for * Boolean * java.util.concurrent.TimeoutException, AskTimeoutException * support for testing serialization with the inmem journal * utility to verifySerialization, in SerializationTestKit * remove AccountExampleWithCommandHandlersInState becuase not possible to serialize State when it's not static * Effect() is factory in EventSourcedBehavior class * test the account examples * SharedLeveldbJournal.configToEnableJavaSerializationForTest * support for exceptions from remote deployed child actors * fallback to akka.remote.serialization.ThrowableNotSerializableException if exception is not serializable when wrapped in system messages from remote deployed child actors and Status.Failure messages * it's implemented in `WrappedPayloadSupport.payloadBuilder` * update reference documentation * serialize-messages=off in most places, separate ticket for improving or removing that feature * migration guide, including description of rolling update * fix 2.13 compiler error * minor review feedback
2019-07-11 14:04:24 +02:00
String serializedRef = Serialization.serializedActorPath(theActorRef);
// Then just serialize the identifier however you like
// Deserialize
// (beneath fromBinary)
Disable Java serialization by default, #22333 (#27285) * akka.actor.allow-java-serialization = off * Moved primitive (Long, Int, String, ByteString) serializers from akka-remote to akka-actor since they had no dependency and are useful also in local systems, e.g. persistence. * e.g. needed for persistence-tck * less allow-java-serialization=on in tests * CborSerializable in Jackson/test module for ease of use * JavaSerializable for Java serialization in tests, already in akka-testkit, but misconfigured * Made tests pass * allow-java-serialization=on in akka-persistence * allow-java-serialization=on in classic remoting tests * JavaSerializable and CborSerializable in other remoting tests * Added serialization for * Boolean * java.util.concurrent.TimeoutException, AskTimeoutException * support for testing serialization with the inmem journal * utility to verifySerialization, in SerializationTestKit * remove AccountExampleWithCommandHandlersInState becuase not possible to serialize State when it's not static * Effect() is factory in EventSourcedBehavior class * test the account examples * SharedLeveldbJournal.configToEnableJavaSerializationForTest * support for exceptions from remote deployed child actors * fallback to akka.remote.serialization.ThrowableNotSerializableException if exception is not serializable when wrapped in system messages from remote deployed child actors and Status.Failure messages * it's implemented in `WrappedPayloadSupport.payloadBuilder` * update reference documentation * serialize-messages=off in most places, separate ticket for improving or removing that feature * migration guide, including description of rolling update * fix 2.13 compiler error * minor review feedback
2019-07-11 14:04:24 +02:00
final ActorRef deserializedRef = extendedSystem.provider().resolveActorRef(serializedRef);
// Then just use the ActorRef
// #actorref-serializer
TestKit.shutdownActorSystem(extendedSystem);
}
public void demonstrateDefaultAddress() {
// this is not meant to be run, only to be compiled
final ActorSystem system = ActorSystem.create();
Disable Java serialization by default, #22333 (#27285) * akka.actor.allow-java-serialization = off * Moved primitive (Long, Int, String, ByteString) serializers from akka-remote to akka-actor since they had no dependency and are useful also in local systems, e.g. persistence. * e.g. needed for persistence-tck * less allow-java-serialization=on in tests * CborSerializable in Jackson/test module for ease of use * JavaSerializable for Java serialization in tests, already in akka-testkit, but misconfigured * Made tests pass * allow-java-serialization=on in akka-persistence * allow-java-serialization=on in classic remoting tests * JavaSerializable and CborSerializable in other remoting tests * Added serialization for * Boolean * java.util.concurrent.TimeoutException, AskTimeoutException * support for testing serialization with the inmem journal * utility to verifySerialization, in SerializationTestKit * remove AccountExampleWithCommandHandlersInState becuase not possible to serialize State when it's not static * Effect() is factory in EventSourcedBehavior class * test the account examples * SharedLeveldbJournal.configToEnableJavaSerializationForTest * support for exceptions from remote deployed child actors * fallback to akka.remote.serialization.ThrowableNotSerializableException if exception is not serializable when wrapped in system messages from remote deployed child actors and Status.Failure messages * it's implemented in `WrappedPayloadSupport.payloadBuilder` * update reference documentation * serialize-messages=off in most places, separate ticket for improving or removing that feature * migration guide, including description of rolling update * fix 2.13 compiler error * minor review feedback
2019-07-11 14:04:24 +02:00
final ActorRef theActorRef = system.deadLetters();
// #external-address-default
Disable Java serialization by default, #22333 (#27285) * akka.actor.allow-java-serialization = off * Moved primitive (Long, Int, String, ByteString) serializers from akka-remote to akka-actor since they had no dependency and are useful also in local systems, e.g. persistence. * e.g. needed for persistence-tck * less allow-java-serialization=on in tests * CborSerializable in Jackson/test module for ease of use * JavaSerializable for Java serialization in tests, already in akka-testkit, but misconfigured * Made tests pass * allow-java-serialization=on in akka-persistence * allow-java-serialization=on in classic remoting tests * JavaSerializable and CborSerializable in other remoting tests * Added serialization for * Boolean * java.util.concurrent.TimeoutException, AskTimeoutException * support for testing serialization with the inmem journal * utility to verifySerialization, in SerializationTestKit * remove AccountExampleWithCommandHandlersInState becuase not possible to serialize State when it's not static * Effect() is factory in EventSourcedBehavior class * test the account examples * SharedLeveldbJournal.configToEnableJavaSerializationForTest * support for exceptions from remote deployed child actors * fallback to akka.remote.serialization.ThrowableNotSerializableException if exception is not serializable when wrapped in system messages from remote deployed child actors and Status.Failure messages * it's implemented in `WrappedPayloadSupport.payloadBuilder` * update reference documentation * serialize-messages=off in most places, separate ticket for improving or removing that feature * migration guide, including description of rolling update * fix 2.13 compiler error * minor review feedback
2019-07-11 14:04:24 +02:00
Address selfAddress = Cluster.get(system).selfAddress();
String serializedRef = theActorRef.path().toSerializationFormatWithAddress(selfAddress);
// #external-address-default
}
@Test
public void demonstrateTheProgrammaticAPI() {
// #programmatic
ActorSystem system = ActorSystem.create("example");
// Get the Serialization Extension
Serialization serialization = SerializationExtension.get(system);
// Have something to serialize
String original = "woohoo";
Disable Java serialization by default, #22333 (#27285) * akka.actor.allow-java-serialization = off * Moved primitive (Long, Int, String, ByteString) serializers from akka-remote to akka-actor since they had no dependency and are useful also in local systems, e.g. persistence. * e.g. needed for persistence-tck * less allow-java-serialization=on in tests * CborSerializable in Jackson/test module for ease of use * JavaSerializable for Java serialization in tests, already in akka-testkit, but misconfigured * Made tests pass * allow-java-serialization=on in akka-persistence * allow-java-serialization=on in classic remoting tests * JavaSerializable and CborSerializable in other remoting tests * Added serialization for * Boolean * java.util.concurrent.TimeoutException, AskTimeoutException * support for testing serialization with the inmem journal * utility to verifySerialization, in SerializationTestKit * remove AccountExampleWithCommandHandlersInState becuase not possible to serialize State when it's not static * Effect() is factory in EventSourcedBehavior class * test the account examples * SharedLeveldbJournal.configToEnableJavaSerializationForTest * support for exceptions from remote deployed child actors * fallback to akka.remote.serialization.ThrowableNotSerializableException if exception is not serializable when wrapped in system messages from remote deployed child actors and Status.Failure messages * it's implemented in `WrappedPayloadSupport.payloadBuilder` * update reference documentation * serialize-messages=off in most places, separate ticket for improving or removing that feature * migration guide, including description of rolling update * fix 2.13 compiler error * minor review feedback
2019-07-11 14:04:24 +02:00
// Turn it into bytes, and retrieve the serializerId and manifest, which are needed for
// deserialization
byte[] bytes = serialization.serialize(original).get();
int serializerId = serialization.findSerializerFor(original).identifier();
String manifest = Serializers.manifestFor(serialization.findSerializerFor(original), original);
Disable Java serialization by default, #22333 (#27285) * akka.actor.allow-java-serialization = off * Moved primitive (Long, Int, String, ByteString) serializers from akka-remote to akka-actor since they had no dependency and are useful also in local systems, e.g. persistence. * e.g. needed for persistence-tck * less allow-java-serialization=on in tests * CborSerializable in Jackson/test module for ease of use * JavaSerializable for Java serialization in tests, already in akka-testkit, but misconfigured * Made tests pass * allow-java-serialization=on in akka-persistence * allow-java-serialization=on in classic remoting tests * JavaSerializable and CborSerializable in other remoting tests * Added serialization for * Boolean * java.util.concurrent.TimeoutException, AskTimeoutException * support for testing serialization with the inmem journal * utility to verifySerialization, in SerializationTestKit * remove AccountExampleWithCommandHandlersInState becuase not possible to serialize State when it's not static * Effect() is factory in EventSourcedBehavior class * test the account examples * SharedLeveldbJournal.configToEnableJavaSerializationForTest * support for exceptions from remote deployed child actors * fallback to akka.remote.serialization.ThrowableNotSerializableException if exception is not serializable when wrapped in system messages from remote deployed child actors and Status.Failure messages * it's implemented in `WrappedPayloadSupport.payloadBuilder` * update reference documentation * serialize-messages=off in most places, separate ticket for improving or removing that feature * migration guide, including description of rolling update * fix 2.13 compiler error * minor review feedback
2019-07-11 14:04:24 +02:00
// Turn it back into an object
String back = (String) serialization.deserialize(bytes, serializerId, manifest).get();
// #programmatic
// Voilá!
assertEquals(original, back);
TestKit.shutdownActorSystem(system);
}
2019-09-19 17:53:02 +02:00
public void demonstrateTheProgrammaticAPITyped() {
// #programmatic-typed
org.apache.pekko.actor.typed.ActorSystem<Void> system =
org.apache.pekko.actor.typed.ActorSystem.create(Behaviors.empty(), "example");
2019-09-19 17:53:02 +02:00
// Get the Serialization Extension
Serialization serialization = SerializationExtension.get(system);
2019-09-19 17:53:02 +02:00
// #programmatic-typed
}
}