Remove support for inputs older than Magnesium
[yangtools.git] / codec / yang-data-codec-binfmt / src / main / java / org / opendaylight / yangtools / yang / data / codec / binfmt / 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.yangtools.yang.data.codec.binfmt;
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 = switch (version) {
36             case TokenTypes.MAGNESIUM_VERSION -> new MagnesiumDataInput(input);
37             case TokenTypes.POTASSIUM_VERSION -> new PotassiumDataInput(input);
38             default -> throw defunct("Unhandled stream version %s", version);
39         };
40
41         setDelegate(ret);
42         return ret;
43     }
44
45     private InvalidNormalizedNodeStreamException defunct(final String format, final Object... args) {
46         final InvalidNormalizedNodeStreamException ret = new InvalidNormalizedNodeStreamException(
47             String.format(format, args));
48         // Make sure the stream is not touched
49         setDelegate(new ForwardingNormalizedNodeDataInput() {
50             @Override
51             NormalizedNodeDataInput delegate() throws IOException {
52                 throw new InvalidNormalizedNodeStreamException("Stream is not usable", ret);
53             }
54         });
55         return ret;
56     }
57
58     private void setDelegate(final NormalizedNodeDataInput delegate) {
59         this.delegate = requireNonNull(delegate);
60         input = null;
61     }
62 }