9eff5afebed28178bdb1c8fbb46b5ffced1ac101
[controller.git] / opendaylight / md-sal / sal-distributed-datastore / src / main / java / org / opendaylight / controller / cluster / datastore / messages / VersionedExternalizableMessage.java
1 /*
2  * Copyright (c) 2015 Brocade Communications Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.cluster.datastore.messages;
9
10 import java.io.Externalizable;
11 import java.io.IOException;
12 import java.io.ObjectInput;
13 import java.io.ObjectOutput;
14 import org.eclipse.jdt.annotation.NonNull;
15 import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
16 import org.opendaylight.controller.cluster.datastore.node.utils.stream.NormalizedNodeStreamVersion;
17
18 /**
19  * Abstract base class for a versioned Externalizable message.
20  *
21  * @author Thomas Pantelis
22  */
23 public abstract class VersionedExternalizableMessage implements Externalizable, SerializableMessage {
24     private static final long serialVersionUID = 1L;
25
26     private short version = DataStoreVersions.CURRENT_VERSION;
27
28     public VersionedExternalizableMessage() {
29     }
30
31     public VersionedExternalizableMessage(final short version) {
32         this.version = version <= DataStoreVersions.CURRENT_VERSION ? version : DataStoreVersions.CURRENT_VERSION;
33     }
34
35     public short getVersion() {
36         return version;
37     }
38
39     protected final @NonNull NormalizedNodeStreamVersion getStreamVersion() {
40         return version < DataStoreVersions.SODIUM_VERSION
41                 ? NormalizedNodeStreamVersion.LITHIUM : NormalizedNodeStreamVersion.SODIUM;
42     }
43
44     @Override
45     public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
46         version = in.readShort();
47     }
48
49     @Override
50     public void writeExternal(final ObjectOutput out) throws IOException {
51         out.writeShort(version);
52     }
53
54     @Override
55     public final Object toSerializable() {
56         if (getVersion() < DataStoreVersions.BORON_VERSION) {
57             throw new UnsupportedOperationException("Versions prior to " + DataStoreVersions.BORON_VERSION
58                     + " are not supported");
59         }
60
61         return this;
62     }
63
64     @Override
65     public String toString() {
66         return getClass().getSimpleName() + " [version=" + getVersion() + "]";
67     }
68 }