BUG-5280: introduce Request/Response and related concepts
[controller.git] / opendaylight / md-sal / cds-access-api / src / main / java / org / opendaylight / controller / cluster / access / concepts / AbstractMessageProxy.java
1 /*
2  * Copyright (c) 2016 Cisco 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.access.concepts;
9
10 import com.google.common.base.Verify;
11 import java.io.DataInput;
12 import java.io.Externalizable;
13 import java.io.IOException;
14 import java.io.ObjectInput;
15 import java.io.ObjectOutput;
16 import javax.annotation.Nonnull;
17 import org.opendaylight.yangtools.concepts.WritableIdentifier;
18 import org.opendaylight.yangtools.concepts.WritableObjects;
19
20 /**
21  * Abstract Externalizable proxy for use with {@link Message} subclasses.
22  *
23  * @author Robert Varga
24  *
25  * @param <T> Target identifier type
26  * @param <C> Message class
27  */
28 abstract class AbstractMessageProxy<T extends WritableIdentifier, C extends Message<T, C>> implements Externalizable {
29     private static final long serialVersionUID = 1L;
30     private T target;
31     private long sequence;
32     private long retry;
33
34     protected AbstractMessageProxy() {
35         // For Externalizable
36     }
37
38     AbstractMessageProxy(final @Nonnull C message) {
39         this.target = message.getTarget();
40         this.sequence = message.getSequence();
41         this.retry = message.getRetry();
42     }
43
44     @Override
45     public void writeExternal(final ObjectOutput out) throws IOException {
46         target.writeTo(out);
47         WritableObjects.writeLongs(out, sequence, retry);
48     }
49
50     @Override
51     public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
52         target = Verify.verifyNotNull(readTarget(in));
53
54         final byte header = WritableObjects.readLongHeader(in);
55         sequence = WritableObjects.readFirstLong(in, header);
56         retry = WritableObjects.readSecondLong(in, header);
57     }
58
59     protected final Object readResolve() {
60         return Verify.verifyNotNull(createMessage(target, sequence, retry));
61     }
62
63     protected abstract @Nonnull T readTarget(@Nonnull DataInput in) throws IOException;
64     abstract @Nonnull C createMessage(@Nonnull T target, long sequence, long retry);
65 }