Update MRI projects for Aluminium
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / LibraryModulesSchemas.java
index a3e258248d8808ccb93dadaca3b309459eec5618..ae21d80753688ccc2d29d90b479f0ffcc7a0d422 100644 (file)
@@ -7,17 +7,16 @@
  */
 package org.opendaylight.netconf.sal.connect.netconf;
 
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
 import static javax.xml.bind.DatatypeConverter.printBase64Binary;
-import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
-import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_QNAME;
-import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
-import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_NODEID;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_NODEID;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_GET_PATH;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
 import com.google.gson.stream.JsonReader;
 import java.io.IOException;
 import java.io.InputStream;
@@ -25,27 +24,37 @@ import java.io.InputStreamReader;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
 import java.net.URI;
+import java.net.URISyntaxException;
 import java.net.URL;
 import java.net.URLConnection;
-import java.util.AbstractMap;
-import java.util.Collections;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.util.AbstractMap.SimpleImmutableEntry;
+import java.util.Collection;
+import java.util.HashMap;
 import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
 import java.util.regex.Pattern;
 import javax.xml.parsers.DocumentBuilder;
+import javax.xml.stream.XMLStreamException;
 import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
-import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext;
+import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.binding.runtime.spi.BindingRuntimeHelpers;
+import org.opendaylight.mdsal.dom.api.DOMRpcResult;
 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.ModulesState;
-import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.ModulesState;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160621.module.list.Module;
 import org.opendaylight.yangtools.util.xml.UntrustedXML;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
@@ -53,12 +62,14 @@ import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
+import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
 import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
 import org.slf4j.Logger;
@@ -66,54 +77,57 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
+import org.xml.sax.SAXException;
 
 /**
  * Holds URLs with YANG schema resources for all yang modules reported in
  * ietf-netconf-yang-library/modules-state/modules node.
  */
-public class LibraryModulesSchemas implements NetconfDeviceSchemas {
+public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
     private static final Logger LOG = LoggerFactory.getLogger(LibraryModulesSchemas.class);
     private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");
-    private static final SchemaContext LIBRARY_CONTEXT;
-
-    static {
-        final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
-        moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang
-                .library.rev160409.$YangModuleInfoImpl.getInstance());
-        LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
-    }
-
-    private final Map<QName, URL> availableModels;
+    private static final EffectiveModelContext LIBRARY_CONTEXT = BindingRuntimeHelpers.createEffectiveModel(
+        ModulesState.class);
+
+    private static final NodeIdentifier MODULES_STATE_NID = NodeIdentifier.create(ModulesState.QNAME);
+    private static final NodeIdentifier MODULE_NID = NodeIdentifier.create(Module.QNAME);
+    private static final NodeIdentifier NAME_NID = NodeIdentifier.create(QName.create(Module.QNAME, "name").intern());
+    private static final NodeIdentifier REVISION_NID = NodeIdentifier.create(
+        QName.create(Module.QNAME, "revision").intern());
+    private static final NodeIdentifier SCHEMA_NID = NodeIdentifier.create(
+        QName.create(Module.QNAME, "schema").intern());
+    private static final NodeIdentifier NAMESPACE_NID = NodeIdentifier.create(
+        QName.create(Module.QNAME, "namespace").intern());
+
+    private static final JSONCodecFactory JSON_CODECS = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
+            .getShared(LIBRARY_CONTEXT);
 
     private static final YangInstanceIdentifier MODULES_STATE_MODULE_LIST =
-            YangInstanceIdentifier.builder().node(ModulesState.QNAME).node(Module.QNAME).build();
+            YangInstanceIdentifier.create(MODULES_STATE_NID, MODULE_NID);
 
-    private static final ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC;
+    private static final ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC = Builders.containerBuilder()
+            .withNodeIdentifier(NETCONF_GET_NODEID)
+            .withChild(NetconfMessageTransformUtil.toFilterStructure(MODULES_STATE_MODULE_LIST, LIBRARY_CONTEXT))
+            .build();
 
-    static {
-        final DataContainerChild<?, ?> filter =
-                NetconfMessageTransformUtil.toFilterStructure(MODULES_STATE_MODULE_LIST, LIBRARY_CONTEXT);
-        GET_MODULES_STATE_MODULE_LIST_RPC =
-                Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_GET_QNAME)).withChild(filter).build();
-    }
+    private final ImmutableMap<QName, URL> availableModels;
 
-    private LibraryModulesSchemas(final Map<QName, URL> availableModels) {
-        this.availableModels = availableModels;
+    private LibraryModulesSchemas(final ImmutableMap<QName, URL> availableModels) {
+        this.availableModels = requireNonNull(availableModels);
     }
 
     public Map<SourceIdentifier, URL> getAvailableModels() {
-        final Map<SourceIdentifier, URL> result = Maps.newHashMap();
-        for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
-            final SourceIdentifier sId = RevisionSourceIdentifier
-                .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
+        final Map<SourceIdentifier, URL> result = new HashMap<>();
+        for (final Entry<QName, URL> entry : availableModels.entrySet()) {
+            final SourceIdentifier sId = RevisionSourceIdentifier.create(entry.getKey().getLocalName(),
+                entry.getKey().getRevision());
             result.put(sId, entry.getValue());
         }
 
         return result;
     }
 
-
     /**
      * Resolves URLs with YANG schema resources from modules-state. Uses basic http authenticaiton
      *
@@ -121,15 +135,14 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
      */
     public static LibraryModulesSchemas create(final String url, final String username, final String password) {
-        Preconditions.checkNotNull(url);
         try {
-            final URL urlConnection = new URL(url);
+            final URL urlConnection = new URL(requireNonNull(url));
             final URLConnection connection = urlConnection.openConnection();
 
             if (connection instanceof HttpURLConnection) {
                 connection.setRequestProperty("Accept", "application/xml");
                 final String userpass = username + ":" + password;
-                final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
+                final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes(StandardCharsets.UTF_8));
 
                 connection.setRequestProperty("Authorization", basicAuth);
             }
@@ -138,7 +151,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
         } catch (final IOException e) {
             LOG.warn("Unable to download yang library from {}", url, e);
-            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(ImmutableMap.of());
         }
     }
 
@@ -147,7 +160,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
         final DOMRpcResult moduleListNodeResult;
         try {
             moduleListNodeResult =
-                    deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_MODULES_STATE_MODULE_LIST_RPC).get();
+                    deviceRpc.invokeRpc(NETCONF_GET_PATH, GET_MODULES_STATE_MODULE_LIST_RPC).get();
         } catch (final InterruptedException e) {
             Thread.currentThread().interrupt();
             throw new RuntimeException(deviceId + ": Interrupted while waiting for response to "
@@ -155,44 +168,41 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
         } catch (final ExecutionException e) {
             LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
                     MODULES_STATE_MODULE_LIST, e);
-            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(ImmutableMap.of());
         }
 
         if (moduleListNodeResult.getErrors().isEmpty() == false) {
             LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
                     deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors());
-            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(ImmutableMap.of());
         }
 
-
         final Optional<? extends NormalizedNode<?, ?>> modulesStateNode =
                 findModulesStateNode(moduleListNodeResult.getResult());
         if (modulesStateNode.isPresent()) {
-            Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode,
-                    "Expecting container containing schemas, but was %s", modulesStateNode.get());
-            return create(((ContainerNode) modulesStateNode.get()));
-        } else {
-            LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
-            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+            final NormalizedNode<?, ?> node = modulesStateNode.get();
+            checkState(node instanceof ContainerNode, "Expecting container containing schemas, but was %s", node);
+            return create((ContainerNode) node);
         }
+
+        LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, MODULES_STATE_NID);
+        return new LibraryModulesSchemas(ImmutableMap.of());
     }
 
     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
-        final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
-                new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
-        final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> moduleListNode =
-                modulesStateNode.getChild(moduleListNodeId);
-        Preconditions.checkState(moduleListNode.isPresent(),
-                "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
-        Preconditions.checkState(moduleListNode.get() instanceof MapNode,
-                "Unexpected structure for container: %s in : %s. Expecting a list",
-                moduleListNodeId, modulesStateNode);
-
-        final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
-        for (final MapEntryNode moduleNode : ((MapNode) moduleListNode.get()).getValue()) {
-            final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
-            if (schemaMappingEntry.isPresent()) {
-                schemasMapping.put(createFromEntry(moduleNode).get());
+        final Optional<DataContainerChild<?, ?>> moduleListNode = modulesStateNode.getChild(MODULE_NID);
+        checkState(moduleListNode.isPresent(), "Unable to find list: %s in %s", MODULE_NID, modulesStateNode);
+        final DataContainerChild<?, ?> node = moduleListNode.get();
+        checkState(node instanceof MapNode, "Unexpected structure for container: %s in : %s. Expecting a list",
+            MODULE_NID, modulesStateNode);
+
+        final MapNode moduleList = (MapNode) node;
+        final Collection<MapEntryNode> modules = moduleList.getValue();
+        final ImmutableMap.Builder<QName, URL> schemasMapping = ImmutableMap.builderWithExpectedSize(modules.size());
+        for (final MapEntryNode moduleNode : modules) {
+            final Entry<QName, URL> entry = createFromEntry(moduleNode);
+            if (entry != null) {
+                schemasMapping.put(entry);
             }
         }
 
@@ -205,34 +215,31 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
      * @return Resolved URLs with YANG schema resources for all yang modules from yang library
      */
     public static LibraryModulesSchemas create(final String url) {
-        Preconditions.checkNotNull(url);
+        final URLConnection connection;
         try {
-            final URL urlConnection = new URL(url);
-            final URLConnection connection = urlConnection.openConnection();
-
-            if (connection instanceof HttpURLConnection) {
-                connection.setRequestProperty("Accept", "application/xml");
-            }
-
-            return createFromURLConnection(connection);
-
+            connection = new URL(requireNonNull(url)).openConnection();
         } catch (final IOException e) {
             LOG.warn("Unable to download yang library from {}", url, e);
-            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(ImmutableMap.of());
+        }
+
+        if (connection instanceof HttpURLConnection) {
+            connection.setRequestProperty("Accept", "application/xml");
         }
+        return createFromURLConnection(connection);
     }
 
     private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
         if (result == null) {
-            return Optional.absent();
+            return Optional.empty();
         }
         final Optional<DataContainerChild<?, ?>> dataNode =
-                ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
+                ((DataContainerNode<?>) result).getChild(NETCONF_DATA_NODEID);
         if (dataNode.isPresent() == false) {
-            return Optional.absent();
+            return Optional.empty();
         }
 
-        return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
+        return ((DataContainerNode<?>) dataNode.get()).getChild(MODULES_STATE_NID);
     }
 
     private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
@@ -244,72 +251,48 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
             contentType = "application/json";
         }
 
-        Preconditions.checkNotNull(contentType, "Content type unknown");
-        Preconditions.checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
+        requireNonNull(contentType, "Content type unknown");
+        checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
                 "Only XML and JSON types are supported.");
-        try (InputStream in = connection.getInputStream()) {
-            final Optional<NormalizedNode<?, ?>> optionalModulesStateNode =
-                    contentType.equals("application/json") ? readJson(in) : readXml(in);
-
-            if (!optionalModulesStateNode.isPresent()) {
-                return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
-            }
 
-            final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
-            Preconditions.checkState(modulesStateNode.getNodeType().equals(ModulesState.QNAME),
-                    "Wrong QName %s", modulesStateNode.getNodeType());
-            Preconditions.checkState(modulesStateNode instanceof ContainerNode,
-                    "Expecting container containing module list, but was %s", modulesStateNode);
-
-            final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
-                    new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
-            final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> moduleListNode =
-                    ((ContainerNode) modulesStateNode).getChild(moduleListNodeId);
-            Preconditions.checkState(moduleListNode.isPresent(),
-                    "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
-            Preconditions.checkState(moduleListNode.get() instanceof MapNode,
-                    "Unexpected structure for container: %s in : %s. Expecting a list",
-                    moduleListNodeId, modulesStateNode);
-
-            final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
-            for (final MapEntryNode moduleNode : ((MapNode) moduleListNode.get()).getValue()) {
-                final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
-                if (schemaMappingEntry.isPresent()) {
-                    schemasMapping.put(createFromEntry(moduleNode).get());
-                }
-            }
-
-            return new LibraryModulesSchemas(schemasMapping.build());
+        Optional<NormalizedNode<?, ?>> optionalModulesStateNode = Optional.empty();
+        try (InputStream in = connection.getInputStream()) {
+            optionalModulesStateNode = contentType.equals("application/json") ? readJson(in) : readXml(in);
         } catch (final IOException e) {
             LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
-            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
         }
-    }
 
-    private static boolean guessJsonFromFileName(final String fileName) {
-        String extension = "";
-        final int i = fileName.lastIndexOf(46);
-        if (i != -1) {
-            extension = fileName.substring(i).toLowerCase();
+        if (!optionalModulesStateNode.isPresent()) {
+            return new LibraryModulesSchemas(ImmutableMap.of());
         }
 
-        return extension.equals(".json");
+        final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
+        checkState(modulesStateNode instanceof ContainerNode, "Expecting container containing module list, but was %s",
+            modulesStateNode);
+        final ContainerNode modulesState = (ContainerNode) modulesStateNode;
+        final NodeIdentifier nodeName = modulesState.getIdentifier();
+        checkState(MODULES_STATE_NID.equals(nodeName), "Wrong container identifier %s", nodeName);
+
+        return create((ContainerNode) modulesStateNode);
+    }
+
+    private static boolean guessJsonFromFileName(final String fileName) {
+        final int i = fileName.lastIndexOf('.');
+        return i != 1 && ".json".equalsIgnoreCase(fileName.substring(i));
     }
 
     private static Optional<NormalizedNode<?, ?>> readJson(final InputStream in) {
         final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
 
-        final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
-        final JsonReader reader = new JsonReader(new InputStreamReader(in));
+        final JsonParserStream jsonParser = JsonParserStream.create(writer, JSON_CODECS);
+        final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset()));
 
         jsonParser.parse(reader);
 
-        return resultHolder.isFinished()
-                ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
+        return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty();
     }
 
-    @SuppressWarnings("checkstyle:IllegalCatch")
     private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
         try {
             final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder();
@@ -338,65 +321,53 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
             xmlParser.traverse(new DOMSource(doc.getDocumentElement()));
             final NormalizedNode<?, ?> parsed = resultHolder.getResult();
             return Optional.of(parsed);
-        } catch (final Exception e) {
+        } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
             LOG.warn("Unable to parse yang library xml content", e);
         }
 
-        return Optional.<NormalizedNode<?, ?>>absent();
+        return Optional.empty();
     }
 
-    private static Optional<Map.Entry<QName, URL>> createFromEntry(final MapEntryNode moduleNode) {
-        Preconditions.checkArgument(
-                moduleNode.getNodeType().equals(Module.QNAME), "Wrong QName %s", moduleNode.getNodeType());
+    private static @Nullable Entry<QName, URL> createFromEntry(final MapEntryNode moduleNode) {
+        checkArgument(moduleNode.getNodeType().equals(Module.QNAME), "Wrong QName %s", moduleNode.getNodeType());
 
-        YangInstanceIdentifier.NodeIdentifier childNodeId =
-                new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "name"));
-        final String moduleName = getSingleChildNodeValue(moduleNode, childNodeId).get();
-
-        childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision"));
-        final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
+        final String moduleName = getSingleChildNodeValue(moduleNode, NAME_NID).get();
+        final Optional<String> revision = getSingleChildNodeValue(moduleNode, REVISION_NID);
         if (revision.isPresent()) {
-            if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
+            if (!Revision.STRING_FORMAT_PATTERN.matcher(revision.get()).matches()) {
                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
-                return Optional.<Map.Entry<QName, URL>>absent();
+                return null;
             }
         }
 
         // FIXME leaf schema with url that represents the yang schema resource for this module is not mandatory
         // don't fail if schema node is not present, just skip the entry or add some default URL
-        childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "schema"));
-        final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, childNodeId);
-
-        childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "namespace"));
-        final String moduleNameSpace = getSingleChildNodeValue(moduleNode, childNodeId).get();
+        final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, SCHEMA_NID);
+        final String moduleNameSpace = getSingleChildNodeValue(moduleNode, NAMESPACE_NID).get();
 
         final QName moduleQName = revision.isPresent()
                 ? QName.create(moduleNameSpace, revision.get(), moduleName)
-                : QName.create(URI.create(moduleNameSpace), null, moduleName);
+                : QName.create(URI.create(moduleNameSpace), moduleName);
 
         try {
-            return Optional.<Map.Entry<QName, URL>>of(new AbstractMap.SimpleImmutableEntry<>(
-                    moduleQName, new URL(schemaUriAsString.get())));
+            return new SimpleImmutableEntry<>(moduleQName, new URL(schemaUriAsString.get()));
         } catch (final MalformedURLException e) {
             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
                     moduleNode, schemaUriAsString.get());
-            return Optional.<Map.Entry<QName, URL>>absent();
+            return null;
         }
     }
 
     private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
-                                                            final YangInstanceIdentifier.NodeIdentifier childNodeId) {
-        final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
-                schemaNode.getChild(childNodeId);
-        Preconditions.checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
+                                                            final NodeIdentifier childNodeId) {
+        final Optional<DataContainerChild<?, ?>> node = schemaNode.getChild(childNodeId);
+        checkArgument(node.isPresent(), "Child node %s not present", childNodeId.getNodeType());
         return getValueOfSimpleNode(node.get());
     }
 
-    private static Optional<String> getValueOfSimpleNode(
-            final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
-        final Object value = node.getValue();
-        return value == null || Strings.isNullOrEmpty(value.toString())
-                ? Optional.<String>absent() : Optional.of(value.toString().trim());
+    private static Optional<String> getValueOfSimpleNode(final NormalizedNode<?, ?> node) {
+        final String valueStr = node.getValue().toString();
+        return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
     }
 
     @Override