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 java.io.ByteArrayInputStream;
13 import java.io.ByteArrayOutputStream;
14 import java.io.IOException;
15 import org.apache.commons.lang3.SerializationUtils;
16 import org.apache.pekko.actor.ExtendedActorSystem;
17 import org.apache.pekko.serialization.JSerializer;
18 import org.apache.pekko.util.ClassLoaderObjectInputStream;
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 var baos = new ByteArrayOutputStream(estimatedSerializedSize);
55 SerializationUtils.serialize(replicatedLogEntry, baos);
56 final byte[] bytes = baos.toByteArray();
58 if (LOG.isDebugEnabled()) {
59 final var data = replicatedLogEntry.getData();
60 LOG.debug("Estimated serialized size {}, data size {} for payload: {}. Actual serialized size: {}",
61 estimatedSerializedSize, data.size(), data, bytes.length);
68 public Object fromBinaryJava(final byte[] bytes, final Class<?> manifest) {
69 try (ClassLoaderObjectInputStream is = new ClassLoaderObjectInputStream(system.dynamicAccess().classLoader(),
70 new ByteArrayInputStream(bytes))) {
71 return is.readObject();
72 } catch (IOException | ClassNotFoundException e) {
73 throw new IllegalStateException("Failed to deserialize object", e);