Update MRI projects for Aluminium
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / LibraryModulesSchemas.java
index 8b06c5f89f12ca3ca347872e1058ecad78929b3a..ae21d80753688ccc2d29d90b479f0ffcc7a0d422 100644 (file)
@@ -7,13 +7,14 @@
  */
 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_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 static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toId;
 
-import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableMap;
 import com.google.gson.stream.JsonReader;
@@ -28,11 +29,11 @@ import java.net.URL;
 import java.net.URLConnection;
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
-import java.util.AbstractMap;
-import java.util.Collections;
+import java.util.AbstractMap.SimpleImmutableEntry;
+import java.util.Collection;
 import java.util.HashMap;
-import java.util.Locale;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
@@ -40,7 +41,8 @@ import java.util.regex.Pattern;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.transform.dom.DOMSource;
-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;
@@ -52,6 +54,7 @@ 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;
@@ -66,7 +69,7 @@ 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;
@@ -84,35 +87,39 @@ 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.rev160621.$YangModuleInfoImpl.getInstance());
-        LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
-    }
+    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 final Map<QName, URL> availableModels;
-
     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 = Builders.containerBuilder()
             .withNodeIdentifier(NETCONF_GET_NODEID)
             .withChild(NetconfMessageTransformUtil.toFilterStructure(MODULES_STATE_MODULE_LIST, LIBRARY_CONTEXT))
             .build();
 
-    private LibraryModulesSchemas(final Map<QName, URL> availableModels) {
-        this.availableModels = availableModels;
+    private final ImmutableMap<QName, URL> availableModels;
+
+    private LibraryModulesSchemas(final ImmutableMap<QName, URL> availableModels) {
+        this.availableModels = requireNonNull(availableModels);
     }
 
     public Map<SourceIdentifier, URL> getAvailableModels() {
         final Map<SourceIdentifier, URL> result = new HashMap<>();
-        for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
+        for (final Entry<QName, URL> entry : availableModels.entrySet()) {
             final SourceIdentifier sId = RevisionSourceIdentifier.create(entry.getKey().getLocalName(),
                 entry.getKey().getRevision());
             result.put(sId, entry.getValue());
@@ -128,9 +135,8 @@ public final 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) {
@@ -145,7 +151,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
         } catch (final IOException e) {
             LOG.warn("Unable to download yang library from {}", url, e);
-            return new LibraryModulesSchemas(Collections.emptyMap());
+            return new LibraryModulesSchemas(ImmutableMap.of());
         }
     }
 
@@ -162,44 +168,41 @@ public final 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.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.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());
+            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, toId(ModulesState.QNAME));
-        return new LibraryModulesSchemas(Collections.emptyMap());
+        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);
             }
         }
 
@@ -212,21 +215,18 @@ public final 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.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) {
@@ -239,7 +239,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
             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) {
@@ -251,56 +251,34 @@ public final 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.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.emptyMap());
         }
-    }
 
-    private static boolean guessJsonFromFileName(final String fileName) {
-        String extension = "";
-        final int i = fileName.lastIndexOf(46);
-        if (i != -1) {
-            extension = fileName.substring(i).toLowerCase(Locale.ROOT);
+        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) {
@@ -350,55 +328,44 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
         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 (!Revision.STRING_FORMAT_PATTERN.matcher(revision.get()).matches()) {
                 LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get());
-                return Optional.empty();
+                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), moduleName);
 
         try {
-            return Optional.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.empty();
+            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) {
+    private static Optional<String> getValueOfSimpleNode(final NormalizedNode<?, ?> node) {
         final String valueStr = node.getValue().toString();
         return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
     }