860fe398748080ed42b8aee80411b03cd6977924
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / VersionedNormalizedNodeDataInput.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, s.r.o. 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.node.utils.stream;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.io.DataInput;
13 import java.io.IOException;
14
15 final class VersionedNormalizedNodeDataInput extends ForwardingNormalizedNodeDataInput {
16     private DataInput input;
17     private NormalizedNodeDataInput delegate;
18
19     VersionedNormalizedNodeDataInput(final DataInput input) {
20         this.input = requireNonNull(input);
21     }
22
23     @Override
24     NormalizedNodeDataInput delegate() throws IOException {
25         if (delegate != null) {
26             return delegate;
27         }
28
29         final byte marker = input.readByte();
30         if (marker != TokenTypes.SIGNATURE_MARKER) {
31             throw defunct("Invalid signature marker: %d", marker);
32         }
33
34         final short version = input.readShort();
35         final NormalizedNodeDataInput ret;
36         switch (version) {
37             case TokenTypes.LITHIUM_VERSION:
38                 ret = new NormalizedNodeInputStreamReader(input);
39                 break;
40             default:
41                 throw defunct("Unhandled stream version %s", version);
42         }
43
44         setDelegate(ret);
45         return ret;
46     }
47
48     private InvalidNormalizedNodeStreamException defunct(final String format, final Object... args) {
49         final InvalidNormalizedNodeStreamException ret = new InvalidNormalizedNodeStreamException(
50             String.format(format, args));
51         // Make sure the stream is not touched
52         setDelegate(new ForwardingNormalizedNodeDataInput() {
53             @Override
54             NormalizedNodeDataInput delegate() throws IOException {
55                 throw new InvalidNormalizedNodeStreamException("Stream is not usable", ret);
56             }
57         });
58         return ret;
59     }
60
61     private void setDelegate(final NormalizedNodeDataInput delegate) {
62         this.delegate = requireNonNull(delegate);
63         input = null;
64     }
65 }