Bug 4969: NPE in JSONCodecFactory by attempt to find codec for a leafref
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / codec / xml / XmlStreamUtils.java
index aa72a64645d76bec2707d4bdef0b1f1ef32c4e86..eeda8954c79231371567d674eda12e8b3fc6b482 100644 (file)
@@ -1,15 +1,25 @@
+/*
+ * Copyright (c) 2015 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
+ */
+
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
 import com.google.common.annotations.Beta;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+import com.google.common.base.Verify;
 import java.net.URI;
 import java.util.Map.Entry;
 import javax.annotation.Nonnull;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
@@ -34,6 +44,11 @@ public class XmlStreamUtils {
     private final XmlCodecProvider codecProvider;
     private final Optional<SchemaContext> schemaContext;
 
+    /**
+     * @deprecated Use {@link #create(XmlCodecProvider)} instead. This method will be hidden and the class
+     *             made final in a future release.
+     */
+    @Deprecated
     protected XmlStreamUtils(final XmlCodecProvider codecProvider) {
         this(codecProvider, null);
     }
@@ -50,28 +65,11 @@ public class XmlStreamUtils {
      * @return A new instance
      */
     public static XmlStreamUtils create(final XmlCodecProvider codecProvider) {
-        return new XmlStreamUtils(codecProvider);
+        return new XmlStreamUtils(codecProvider, null);
     }
 
-    /**
-     * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
-     * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
-     *
-     * @param writer XML Stream writer
-     * @param id InstanceIdentifier
-     * @throws XMLStreamException
-     *
-     * @deprecated Use {@link #writeInstanceIdentifier(XMLStreamWriter, YangInstanceIdentifier)} instead.
-     */
-    @Deprecated
-    public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
-        Preconditions.checkNotNull(writer, "Writer may not be null");
-        Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
-
-        final RandomPrefix prefixes = new RandomPrefix();
-        final String str = XmlUtils.encodeIdentifier(prefixes, id);
-        writeNamespaceDeclarations(writer,prefixes.getPrefixes());
-        writer.writeCharacters(str);
+    public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
+        return new XmlStreamUtils(codecProvider, schemaContext);
     }
 
     @VisibleForTesting
@@ -90,9 +88,10 @@ public class XmlStreamUtils {
      * @param writer XML Stream writer
      * @param schemaNode Schema node that describes the value
      * @param value data value
+     * @param parent optional parameter of a module QName owning the leaf definition
      * @throws XMLStreamException if an encoding problem occurs
      */
-    public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull SchemaNode schemaNode, final Object value) throws XMLStreamException {
+    public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
         if (value == null) {
             LOG.debug("Value of {}:{} is null, not encoding it", schemaNode.getQName().getNamespace(), schemaNode.getQName().getLocalName());
             return;
@@ -110,9 +109,18 @@ public class XmlStreamUtils {
         if (schemaContext.isPresent() && baseType instanceof LeafrefTypeDefinition) {
             LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
             baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaContext.get(), schemaNode);
+            Verify.verifyNotNull(baseType, "Unable to find base type for leafref node '%s'.", schemaNode.getPath());
         }
 
-        writeValue(writer, baseType, value);
+        writeValue(writer, baseType, value, parent);
+    }
+
+    public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value) throws XMLStreamException {
+        writeValue(writer, schemaNode, value, Optional.<QNameModule>absent());
+    }
+
+    public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final SchemaNode schemaNode, final Object value, final QNameModule parent) throws XMLStreamException {
+        writeValue(writer, schemaNode, value, Optional.of(parent));
     }
 
     /**
@@ -122,9 +130,10 @@ public class XmlStreamUtils {
      * @param writer XML Stream writer
      * @param type data type. In case of leaf ref this should be the type of leaf being referenced
      * @param value data value
+     * @param parent optional parameter of a module QName owning the leaf definition
      * @throws XMLStreamException if an encoding problem occurs
      */
-    public void writeValue(final @Nonnull XMLStreamWriter writer, final @Nonnull TypeDefinition<?> type, final Object value) throws XMLStreamException {
+    public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final Optional<QNameModule> parent) throws XMLStreamException {
         if (value == null) {
             LOG.debug("Value of {}:{} is null, not encoding it", type.getQName().getNamespace(), type.getQName().getLocalName());
             return;
@@ -132,42 +141,61 @@ public class XmlStreamUtils {
         TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
 
         if (baseType instanceof IdentityrefTypeDefinition) {
-            write(writer, (IdentityrefTypeDefinition) baseType, value);
+            if (parent.isPresent()) {
+                write(writer, (IdentityrefTypeDefinition) baseType, value, parent);
+            } else {
+                write(writer, (IdentityrefTypeDefinition) baseType, value, Optional.<QNameModule>absent());
+            }
         } else if (baseType instanceof InstanceIdentifierTypeDefinition) {
             write(writer, (InstanceIdentifierTypeDefinition) baseType, value);
         } else {
-            final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(baseType);
+            final TypeDefinitionAwareCodec<Object, ?> codec = codecProvider.codecFor(type);
             String text;
             if (codec != null) {
                 try {
                     text = codec.serialize(value);
                 } catch (ClassCastException e) {
-                    LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, baseType, e);
+                    LOG.error("Provided node value {} did not have type {} required by mapping. Using stream instead.", value, type, e);
                     text = String.valueOf(value);
                 }
             } else {
-                LOG.error("Failed to find codec for {}, falling back to using stream", baseType);
+                LOG.error("Failed to find codec for {}, falling back to using stream", type);
                 text = String.valueOf(value);
             }
             writer.writeCharacters(text);
         }
     }
 
-    private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull IdentityrefTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+    public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value, final QNameModule parent) throws XMLStreamException {
+        writeValue(writer, type, value, Optional.of(parent));
+    }
+
+    public void writeValue(@Nonnull final XMLStreamWriter writer, @Nonnull final TypeDefinition<?> type, final Object value) throws XMLStreamException {
+        writeValue(writer, type, value, Optional.<QNameModule>absent());
+    }
+
+    @VisibleForTesting
+    static void write(@Nonnull final XMLStreamWriter writer, @Nonnull final IdentityrefTypeDefinition type, @Nonnull final Object value, final Optional<QNameModule>  parent) throws XMLStreamException {
         if (value instanceof QName) {
             final QName qname = (QName) value;
             final String prefix = "x";
 
-            final String ns = qname.getNamespace().toString();
-            writer.writeNamespace(prefix, ns);
-            writer.writeCharacters(prefix + ':' + qname.getLocalName());
+            //in case parent is present and same as element namespace write value without namespace
+            if (parent.isPresent() && qname.getNamespace().equals(parent.get().getNamespace())){
+                writer.writeCharacters(qname.getLocalName());
+            } else {
+                final String ns = qname.getNamespace().toString();
+                writer.writeNamespace(prefix, ns);
+                writer.writeCharacters(prefix + ':' + qname.getLocalName());
+            }
+
         } else {
             LOG.debug("Value of {}:{} is not a QName but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
             writer.writeCharacters(String.valueOf(value));
         }
     }
 
-    private void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+    private void write(@Nonnull final XMLStreamWriter writer, @Nonnull final InstanceIdentifierTypeDefinition type, @Nonnull final Object value) throws XMLStreamException {
         if (value instanceof YangInstanceIdentifier) {
             writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
         } else {
@@ -176,7 +204,7 @@ public class XmlStreamUtils {
         }
     }
 
-    public void writeInstanceIdentifier(XMLStreamWriter writer, YangInstanceIdentifier value) throws XMLStreamException {
+    public void writeInstanceIdentifier(final XMLStreamWriter writer, final YangInstanceIdentifier value) throws XMLStreamException {
         if(schemaContext.isPresent()) {
             RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(schemaContext.get());
             String serializedValue = iiCodec.serialize(value);
@@ -184,19 +212,15 @@ public class XmlStreamUtils {
             writer.writeCharacters(serializedValue);
         } else {
             LOG.warn("Schema context not present in {}, serializing {} without schema.",this,value);
-            write(writer,value);
+            writeInstanceIdentifier(writer, value);
         }
     }
 
-    private static void writeNamespaceDeclarations(XMLStreamWriter writer, Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
+    private static void writeNamespaceDeclarations(final XMLStreamWriter writer, final Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
         for (Entry<URI, String> e: prefixes) {
             final String ns = e.getKey().toString();
             final String p = e.getValue();
             writer.writeNamespace(p, ns);
         }
     }
-
-    public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
-        return new XmlStreamUtils(codecProvider, schemaContext);
-    }
 }