2 * Copyright (c) 2018 Red Hat, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.cluster.raft.persisted;
10 import static java.util.Objects.requireNonNull;
12 import akka.actor.ExtendedActorSystem;
13 import akka.serialization.JSerializer;
14 import akka.util.ClassLoaderObjectInputStream;
15 import java.io.ByteArrayInputStream;
16 import java.io.ByteArrayOutputStream;
17 import java.io.IOException;
18 import org.apache.commons.lang3.SerializationUtils;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
23 * Specialized serializer for {@link SimpleReplicatedLogEntry} that optimizes serialization.
25 * @author Thomas Pantelis
27 public class SimpleReplicatedLogEntrySerializer extends JSerializer {
28 private static final Logger LOG = LoggerFactory.getLogger(SimpleReplicatedLogEntrySerializer.class);
30 private final ExtendedActorSystem system;
32 public SimpleReplicatedLogEntrySerializer(final ExtendedActorSystem system) {
33 this.system = requireNonNull(system);
37 public int identifier() {
42 public boolean includeManifest() {
47 public byte[] toBinary(final Object obj) {
48 if (!(obj instanceof SimpleReplicatedLogEntry replicatedLogEntry)) {
49 throw new IllegalArgumentException("Unsupported object type " + obj.getClass());
52 final int estimatedSerializedSize = replicatedLogEntry.serializedSize();
54 final ByteArrayOutputStream bos = new ByteArrayOutputStream(estimatedSerializedSize);
55 SerializationUtils.serialize(replicatedLogEntry, bos);
56 final byte[] bytes = bos.toByteArray();
58 LOG.debug("Estimated serialized size {}, data size {} for payload: {}. Actual serialized size: {}",
59 estimatedSerializedSize, replicatedLogEntry.getData().size(), replicatedLogEntry.getData(), bytes.length);
65 public Object fromBinaryJava(final byte[] bytes, final Class<?> manifest) {
66 try (ClassLoaderObjectInputStream is = new ClassLoaderObjectInputStream(system.dynamicAccess().classLoader(),
67 new ByteArrayInputStream(bytes))) {
68 return is.readObject();
69 } catch (IOException | ClassNotFoundException e) {
70 throw new IllegalStateException("Failed to deserialize object", e);