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 com.google.common.base.Preconditions;
11 import com.google.common.base.Verify;
12 import com.google.common.io.ByteStreams;
13 import java.io.DataInput;
14 import java.io.Externalizable;
15 import java.io.IOException;
16 import java.io.ObjectInput;
17 import java.io.ObjectOutput;
18 import java.io.Serializable;
19 import javax.annotation.Nonnull;
20 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
21 import org.opendaylight.yangtools.concepts.Identifiable;
22 import org.opendaylight.yangtools.concepts.Identifier;
25 * Abstract base class for {@link Payload}s which hold a single {@link Identifier}.
27 * @author Robert Varga
29 public abstract class AbstractIdentifiablePayload<T extends Identifier> extends Payload implements Identifiable<T>, Serializable {
30 protected abstract static class AbstractProxy<T extends Identifier> implements Externalizable {
31 private static final long serialVersionUID = 1L;
32 private byte[] serialized;
35 public AbstractProxy() {
39 protected AbstractProxy(final byte[] serialized) {
40 this.serialized = Preconditions.checkNotNull(serialized);
44 public final void writeExternal(final ObjectOutput out) throws IOException {
45 out.writeInt(serialized.length);
46 out.write(serialized);
50 public final void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
51 final int length = in.readInt();
52 serialized = new byte[length];
53 in.readFully(serialized);
54 identifier = Verify.verifyNotNull(readIdentifier(ByteStreams.newDataInput(serialized)));
57 protected final Object readResolve() {
58 return Verify.verifyNotNull(createObject(identifier, serialized));
61 protected abstract @Nonnull T readIdentifier(@Nonnull DataInput in) throws IOException;
62 protected abstract @Nonnull Identifiable<T> createObject(@Nonnull T identifier, @Nonnull byte[] serialized);
65 private static final long serialVersionUID = 1L;
66 private final byte[] serialized;
67 private final T identifier;
69 AbstractIdentifiablePayload(final @Nonnull T identifier, final @Nonnull byte[] serialized) {
70 this.identifier = Preconditions.checkNotNull(identifier);
71 this.serialized = Preconditions.checkNotNull(serialized);
75 public final T getIdentifier() {
80 public final int size() {
81 return serialized.length;
84 protected final Object writeReplace() {
85 return Verify.verifyNotNull(externalizableProxy(serialized));
88 protected abstract @Nonnull AbstractProxy<T> externalizableProxy(@Nonnull byte[] serialized);