Update MRI projects for Aluminium
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / LibraryModulesSchemas.java
index 500d53c0575bf3cbe525fb8ac2dce3eb5c972bcc..ae21d80753688ccc2d29d90b479f0ffcc7a0d422 100644 (file)
@@ -14,7 +14,6 @@ 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.Strings;
 import com.google.common.collect.ImmutableMap;
@@ -31,6 +30,7 @@ import java.net.URLConnection;
 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;
@@ -41,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;
@@ -68,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;
@@ -86,20 +87,24 @@ 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 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)
@@ -114,7 +119,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
     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());
@@ -180,23 +185,24 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
             return create((ContainerNode) node);
         }
 
-        LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
+        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 NodeIdentifier moduleListNodeId = new NodeIdentifier(Module.QNAME);
-        final Optional<DataContainerChild<?, ?>> moduleListNode = modulesStateNode.getChild(moduleListNodeId);
-        checkState(moduleListNode.isPresent(), "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
+        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",
-                moduleListNodeId, modulesStateNode);
-
-        final ImmutableMap.Builder<QName, URL> schemasMapping = new ImmutableMap.Builder<>();
-        for (final MapEntryNode moduleNode : ((MapNode) node).getValue()) {
-            final Optional<Map.Entry<QName, URL>> schemaMappingEntry = createFromEntry(moduleNode);
-            if (schemaMappingEntry.isPresent()) {
-                schemasMapping.put(createFromEntry(moduleNode).get());
+            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);
             }
         }
 
@@ -209,20 +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) {
+        final URLConnection connection;
         try {
-            final URL urlConnection = new URL(requireNonNull(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(ImmutableMap.of());
         }
+
+        if (connection instanceof HttpURLConnection) {
+            connection.setRequestProperty("Accept", "application/xml");
+        }
+        return createFromURLConnection(connection);
     }
 
     private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
@@ -235,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) {
@@ -250,41 +254,26 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
         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(ImmutableMap.of());
-            }
 
-            final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
-            final QName nodeType = modulesStateNode.getNodeType();
-            checkState(nodeType.equals(ModulesState.QNAME), "Wrong QName %s", nodeType);
-            checkState(modulesStateNode instanceof ContainerNode,
-                "Expecting container containing module list, but was %s", modulesStateNode);
-
-            final NodeIdentifier moduleListNodeId = new NodeIdentifier(Module.QNAME);
-            final Optional<DataContainerChild<?, ?>> moduleListNode =
-                    ((ContainerNode) modulesStateNode).getChild(moduleListNodeId);
-            checkState(moduleListNode.isPresent(), "Unable to find list: %s in %s", moduleListNodeId, modulesStateNode);
-            final DataContainerChild<?, ?> node = moduleListNode.get();
-            checkState(node 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) node).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);
+        }
+
+        if (!optionalModulesStateNode.isPresent()) {
             return new LibraryModulesSchemas(ImmutableMap.of());
         }
+
+        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) {
@@ -339,39 +328,33 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
         return Optional.empty();
     }
 
-    private static Optional<Entry<QName, URL>> createFromEntry(final MapEntryNode moduleNode) {
+    private static @Nullable Entry<QName, URL> createFromEntry(final MapEntryNode moduleNode) {
         checkArgument(moduleNode.getNodeType().equals(Module.QNAME), "Wrong QName %s", moduleNode.getNodeType());
 
-        NodeIdentifier childNodeId = new NodeIdentifier(QName.create(Module.QNAME, "name"));
-        final String moduleName = getSingleChildNodeValue(moduleNode, childNodeId).get();
-
-        childNodeId = new 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 NodeIdentifier(QName.create(Module.QNAME, "schema"));
-        final Optional<String> schemaUriAsString = getSingleChildNodeValue(moduleNode, childNodeId);
-
-        childNodeId = new 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 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;
         }
     }