2 * Copyright (c) 2016 Cisco Systems, 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.datastore.persisted;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Verify;
14 import com.google.common.io.ByteStreams;
15 import java.io.DataInput;
16 import java.io.Externalizable;
17 import java.io.IOException;
18 import java.io.ObjectInput;
19 import java.io.ObjectOutput;
20 import java.io.Serializable;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
23 import org.opendaylight.yangtools.concepts.Identifiable;
24 import org.opendaylight.yangtools.concepts.Identifier;
27 * Abstract base class for {@link Payload}s which hold a single {@link Identifier}.
29 * @author Robert Varga
31 public abstract class AbstractIdentifiablePayload<T extends Identifier>
32 extends Payload implements Identifiable<T>, Serializable {
33 protected abstract static class AbstractProxy<T extends Identifier> implements Externalizable {
34 private static final long serialVersionUID = 1L;
35 private byte[] serialized;
38 public AbstractProxy() {
42 protected AbstractProxy(final byte[] serialized) {
43 this.serialized = Preconditions.checkNotNull(serialized);
47 public final void writeExternal(final ObjectOutput out) throws IOException {
48 out.writeInt(serialized.length);
49 out.write(serialized);
53 public final void readExternal(final ObjectInput in) throws IOException {
54 final int length = in.readInt();
55 serialized = new byte[length];
56 in.readFully(serialized);
57 identifier = Verify.verifyNotNull(readIdentifier(ByteStreams.newDataInput(serialized)));
60 protected final Object readResolve() {
61 return Verify.verifyNotNull(createObject(identifier, serialized));
64 protected abstract @NonNull T readIdentifier(@NonNull DataInput in) throws IOException;
66 @SuppressWarnings("checkstyle:hiddenField")
67 protected abstract @NonNull Identifiable<T> createObject(@NonNull T identifier, byte @NonNull[] serialized);
70 private static final long serialVersionUID = 1L;
71 private final byte[] serialized;
72 private final T identifier;
74 AbstractIdentifiablePayload(final @NonNull T identifier, final byte @NonNull[] serialized) {
75 this.identifier = requireNonNull(identifier);
76 this.serialized = requireNonNull(serialized);
80 public final T getIdentifier() {
85 public final int size() {
86 return serialized.length;
89 protected final Object writeReplace() {
90 return Verify.verifyNotNull(externalizableProxy(serialized));
93 @SuppressWarnings("checkstyle:hiddenField")
94 protected abstract @NonNull AbstractProxy<T> externalizableProxy(byte @NonNull[] serialized);