Remove NormalizedNodeStreamReader
[controller.git] / opendaylight / md-sal / sal-clustering-commons / src / main / java / org / opendaylight / controller / cluster / datastore / node / utils / stream / NormalizedNodeInputStreamReader.java
index 9201a94de326111856ad7d4d5246264cb9edfe46..3f6cbb743bc26568583b248a7276b87a11b3efa3 100644 (file)
@@ -1,20 +1,31 @@
 /*
+ * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
  *
- *  Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- *  This program and the accompanying materials are made available under the
- *  terms of the Eclipse Public License v1.0 which accompanies this distribution,
- *  and is available at http://www.eclipse.org/legal/epl-v10.html
- *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
 
 package org.opendaylight.controller.cluster.datastore.node.utils.stream;
 
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
+import java.io.DataInput;
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import javax.xml.transform.dom.DOMSource;
 import org.opendaylight.controller.cluster.datastore.node.utils.QNameFactory;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
@@ -29,18 +40,6 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNo
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import java.io.DataInput;
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
 
 /**
  * NormalizedNodeInputStreamReader reads the byte stream and constructs the normalized node including its children nodes.
@@ -49,7 +48,7 @@ import java.util.Set;
  *
  */
 
-public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamReader {
+public class NormalizedNodeInputStreamReader implements NormalizedNodeDataInput {
 
     private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeInputStreamReader.class);
 
@@ -64,20 +63,57 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
     private NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier,
                                       Object, LeafNode<Object>> leafBuilder;
 
-    private NormalizedNodeAttrBuilder<NodeWithValue, Object,
-                                      LeafSetEntryNode<Object>> leafSetEntryBuilder;
+    private NormalizedNodeAttrBuilder<NodeWithValue, Object, LeafSetEntryNode<Object>> leafSetEntryBuilder;
+
+    private final StringBuilder reusableStringBuilder = new StringBuilder(50);
+
+    private boolean readSignatureMarker = true;
+
+    /**
+     * @deprecated Use {@link #NormalizedNodeInputStreamReader(DataInput)} instead.
+     */
+    @Deprecated
+    public NormalizedNodeInputStreamReader(final InputStream stream) throws IOException {
+        this((DataInput) new DataInputStream(Preconditions.checkNotNull(stream)));
+    }
 
-    public NormalizedNodeInputStreamReader(InputStream stream) throws IOException {
-        Preconditions.checkNotNull(stream);
-        input = new DataInputStream(stream);
+    /**
+     * @deprecated Use {@link NormalizedNodeInputOutput#newDataInput(DataInput)} instead.
+     */
+    @Deprecated
+    public NormalizedNodeInputStreamReader(final DataInput input) {
+        this(input, false);
     }
 
-    public NormalizedNodeInputStreamReader(DataInput input) throws IOException {
+    NormalizedNodeInputStreamReader(final DataInput input, final boolean versionChecked) {
         this.input = Preconditions.checkNotNull(input);
+        readSignatureMarker = !versionChecked;
     }
 
     @Override
     public NormalizedNode<?, ?> readNormalizedNode() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return readNormalizedNodeInternal();
+    }
+
+    private void readSignatureMarkerAndVersionIfNeeded() throws IOException {
+        if(readSignatureMarker) {
+            readSignatureMarker = false;
+
+            final byte marker = input.readByte();
+            if (marker != TokenTypes.SIGNATURE_MARKER) {
+                throw new InvalidNormalizedNodeStreamException(String.format(
+                        "Invalid signature marker: %d", marker));
+            }
+
+            final short version = input.readShort();
+            if (version != TokenTypes.LITHIUM_VERSION) {
+                throw new InvalidNormalizedNodeStreamException(String.format("Unhandled stream version %s", version));
+            }
+        }
+    }
+
+    private NormalizedNode<?, ?> readNormalizedNodeInternal() throws IOException {
         // each node should start with a byte
         byte nodeType = input.readByte();
 
@@ -97,8 +133,13 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
                         withNodeIdentifier(augIdentifier)).build();
 
             case NodeTypes.LEAF_SET_ENTRY_NODE :
+                QName name = lastLeafSetQName;
+                if(name == null) {
+                    name = readQName();
+                }
+
                 Object value = readObject();
-                NodeWithValue leafIdentifier = new NodeWithValue(lastLeafSetQName, value);
+                NodeWithValue<Object> leafIdentifier = new NodeWithValue<>(name, value);
 
                 LOG.debug("Reading leaf set entry node {}, value {}", leafIdentifier, value);
 
@@ -136,7 +177,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
         return leafSetEntryBuilder;
     }
 
-    private NormalizedNode<?, ?> readNodeIdentifierDependentNode(byte nodeType, NodeIdentifier identifier)
+    private NormalizedNode<?, ?> readNodeIdentifierDependentNode(final byte nodeType, final NodeIdentifier identifier)
         throws IOException {
 
         switch(nodeType) {
@@ -147,8 +188,7 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
 
             case NodeTypes.ANY_XML_NODE :
                 LOG.debug("Read xml node");
-                Node<?> value = (Node<?>) readObject();
-                return Builders.anyXmlBuilder().withValue((Node<?>) readObject()).build();
+                return Builders.anyXmlBuilder().withValue((DOMSource) readObject()).build();
 
             case NodeTypes.MAP_NODE :
                 LOG.debug("Read map node {}", identifier);
@@ -185,6 +225,13 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
                 return addLeafSetChildren(identifier.getNodeType(),
                         Builders.leafSetBuilder().withNodeIdentifier(identifier)).build();
 
+            case NodeTypes.ORDERED_LEAF_SET:
+                LOG.debug("Read ordered leaf set node {}", identifier);
+                ListNodeBuilder<Object, LeafSetEntryNode<Object>> orderedLeafSetBuilder =
+                        Builders.orderedLeafSetBuilder().withNodeIdentifier(identifier);
+                orderedLeafSetBuilder = addLeafSetChildren(identifier.getNodeType(), orderedLeafSetBuilder);
+                return orderedLeafSetBuilder.build();
+
             default :
                 return null;
         }
@@ -196,24 +243,26 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
         String namespace = readCodedString();
         String revision = readCodedString();
 
-        // Not using stringbuilder as compiler optimizes string concatenation of +
         String qName;
         if(!Strings.isNullOrEmpty(revision)) {
-            qName = "(" + namespace + REVISION_ARG + revision + ")" +localName;
+            qName = reusableStringBuilder.append('(').append(namespace).append(REVISION_ARG).
+                        append(revision).append(')').append(localName).toString();
         } else {
-            qName = "(" + namespace + ")" + localName;
+            qName = reusableStringBuilder.append('(').append(namespace).append(')').
+                        append(localName).toString();
         }
 
+        reusableStringBuilder.delete(0, reusableStringBuilder.length());
         return QNameFactory.create(qName);
     }
 
 
     private String readCodedString() throws IOException {
         byte valueType = input.readByte();
-        if(valueType == NormalizedNodeOutputStreamWriter.IS_CODE_VALUE) {
+        if(valueType == TokenTypes.IS_CODE_VALUE) {
             return codedStringMap.get(input.readInt());
-        } else if(valueType == NormalizedNodeOutputStreamWriter.IS_STRING_VALUE) {
-            String value = input.readUTF();
+        } else if(valueType == TokenTypes.IS_STRING_VALUE) {
+            String value = input.readUTF().intern();
             codedStringMap.put(Integer.valueOf(codedStringMap.size()), value);
             return value;
         }
@@ -249,41 +298,61 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
                 return readObjSet();
 
             case ValueTypes.BOOL_TYPE :
-                return input.readBoolean();
+                return Boolean.valueOf(input.readBoolean());
 
             case ValueTypes.BYTE_TYPE :
-                return input.readByte();
+                return Byte.valueOf(input.readByte());
 
             case ValueTypes.INT_TYPE :
-                return input.readInt();
+                return Integer.valueOf(input.readInt());
 
             case ValueTypes.LONG_TYPE :
-                return input.readLong();
+                return Long.valueOf(input.readLong());
 
             case ValueTypes.QNAME_TYPE :
                 return readQName();
 
             case ValueTypes.SHORT_TYPE :
-                return input.readShort();
+                return Short.valueOf(input.readShort());
 
             case ValueTypes.STRING_TYPE :
                 return input.readUTF();
 
+            case ValueTypes.STRING_BYTES_TYPE:
+                return readStringBytes();
+
             case ValueTypes.BIG_DECIMAL_TYPE :
                 return new BigDecimal(input.readUTF());
 
             case ValueTypes.BIG_INTEGER_TYPE :
                 return new BigInteger(input.readUTF());
 
+            case ValueTypes.BINARY_TYPE :
+                byte[] bytes = new byte[input.readInt()];
+                input.readFully(bytes);
+                return bytes;
+
             case ValueTypes.YANG_IDENTIFIER_TYPE :
-            return readYangInstanceIdentifier();
+                return readYangInstanceIdentifierInternal();
 
             default :
                 return null;
         }
     }
 
+    private String readStringBytes() throws IOException {
+        byte[] bytes = new byte[input.readInt()];
+        input.readFully(bytes);
+        return new String(bytes, StandardCharsets.UTF_8);
+    }
+
+    @Override
     public YangInstanceIdentifier readYangInstanceIdentifier() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return readYangInstanceIdentifierInternal();
+    }
+
+    private YangInstanceIdentifier readYangInstanceIdentifierInternal() throws IOException {
         int size = input.readInt();
 
         List<PathArgument> pathArguments = new ArrayList<>(size);
@@ -303,7 +372,8 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
         return children;
     }
 
-    private PathArgument readPathArgument() throws IOException {
+    @Override
+    public PathArgument readPathArgument() throws IOException {
         // read Type
         int type = input.readByte();
 
@@ -313,13 +383,13 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
                 return new YangInstanceIdentifier.AugmentationIdentifier(readQNameSet());
 
             case PathArgumentTypes.NODE_IDENTIFIER :
-            return new NodeIdentifier(readQName());
+                return new NodeIdentifier(readQName());
 
             case PathArgumentTypes.NODE_IDENTIFIER_WITH_PREDICATES :
-            return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
+                return new NodeIdentifierWithPredicates(readQName(), readKeyValueMap());
 
             case PathArgumentTypes.NODE_IDENTIFIER_WITH_VALUE :
-            return new NodeWithValue(readQName(), readObject());
+                return new NodeWithValue<>(readQName(), readObject());
 
             default :
                 return null;
@@ -327,33 +397,123 @@ public class NormalizedNodeInputStreamReader implements NormalizedNodeStreamRead
     }
 
     @SuppressWarnings("unchecked")
-    private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(QName nodeType,
-            ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
+    private ListNodeBuilder<Object, LeafSetEntryNode<Object>> addLeafSetChildren(final QName nodeType,
+            final ListNodeBuilder<Object, LeafSetEntryNode<Object>> builder) throws IOException {
 
         LOG.debug("Reading children of leaf set");
 
         lastLeafSetQName = nodeType;
 
-        LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNode();
+        LeafSetEntryNode<Object> child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
 
         while(child != null) {
             builder.withChild(child);
-            child = (LeafSetEntryNode<Object>)readNormalizedNode();
+            child = (LeafSetEntryNode<Object>)readNormalizedNodeInternal();
         }
         return builder;
     }
 
     @SuppressWarnings({ "unchecked", "rawtypes" })
     private NormalizedNodeContainerBuilder addDataContainerChildren(
-            NormalizedNodeContainerBuilder builder) throws IOException {
+            final NormalizedNodeContainerBuilder builder) throws IOException {
         LOG.debug("Reading data container (leaf nodes) nodes");
 
-        NormalizedNode<?, ?> child = readNormalizedNode();
+        NormalizedNode<?, ?> child = readNormalizedNodeInternal();
 
         while(child != null) {
             builder.addChild(child);
-            child = readNormalizedNode();
+            child = readNormalizedNodeInternal();
         }
         return builder;
     }
+
+    @Override
+    public void readFully(final byte[] b) throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        input.readFully(b);
+    }
+
+    @Override
+    public void readFully(final byte[] b, final int off, final int len) throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        input.readFully(b, off, len);
+    }
+
+    @Override
+    public int skipBytes(final int n) throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.skipBytes(n);
+    }
+
+    @Override
+    public boolean readBoolean() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readBoolean();
+    }
+
+    @Override
+    public byte readByte() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readByte();
+    }
+
+    @Override
+    public int readUnsignedByte() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readUnsignedByte();
+    }
+
+    @Override
+    public short readShort() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readShort();
+    }
+
+    @Override
+    public int readUnsignedShort() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readUnsignedShort();
+    }
+
+    @Override
+    public char readChar() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readChar();
+    }
+
+    @Override
+    public int readInt() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readInt();
+    }
+
+    @Override
+    public long readLong() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readLong();
+    }
+
+    @Override
+    public float readFloat() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readFloat();
+    }
+
+    @Override
+    public double readDouble() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readDouble();
+    }
+
+    @Override
+    public String readLine() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readLine();
+    }
+
+    @Override
+    public String readUTF() throws IOException {
+        readSignatureMarkerAndVersionIfNeeded();
+        return input.readUTF();
+    }
 }