Reduce the use of AttrBuilders
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / LibraryModulesSchemas.java
index 68fb36018b7e26cd2a8da7921b0c536b0323efe5..9b0b0f268c739aa4b8741017605937b13233c869 100644 (file)
@@ -8,15 +8,14 @@
 package org.opendaylight.netconf.sal.connect.netconf;
 
 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.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 static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.toPath;
 
 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;
@@ -24,25 +23,32 @@ 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.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
 import java.util.AbstractMap;
 import java.util.Collections;
+import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 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.parsers.ParserConfigurationException;
+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.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;
@@ -67,6 +73,7 @@ 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
@@ -81,7 +88,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
     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.rev160621.$YangModuleInfoImpl.getInstance());
         LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
     }
 
@@ -90,31 +97,26 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
     private static final YangInstanceIdentifier MODULES_STATE_MODULE_LIST =
             YangInstanceIdentifier.builder().node(ModulesState.QNAME).node(Module.QNAME).build();
 
-    private static final ContainerNode GET_MODULES_STATE_MODULE_LIST_RPC;
-
-    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 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;
     }
 
     public Map<SourceIdentifier, URL> getAvailableModels() {
-        final Map<SourceIdentifier, URL> result = Maps.newHashMap();
+        final Map<SourceIdentifier, URL> result = new HashMap<>();
         for (final Map.Entry<QName, URL> entry : availableModels.entrySet()) {
-            final SourceIdentifier sId = RevisionSourceIdentifier
-                .create(entry.getKey().getLocalName(), entry.getKey().getRevision());
+            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
      *
@@ -130,7 +132,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
             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);
             }
@@ -139,7 +141,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.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(Collections.emptyMap());
         }
     }
 
@@ -148,7 +150,7 @@ public final 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 "
@@ -156,13 +158,13 @@ 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.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(Collections.emptyMap());
         }
 
         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(Collections.emptyMap());
         }
 
 
@@ -175,7 +177,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
         }
 
         LOG.warn("{}: Unable to detect available schemas, get to {} was empty", deviceId, toId(ModulesState.QNAME));
-        return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+        return new LibraryModulesSchemas(Collections.emptyMap());
     }
 
     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
@@ -219,7 +221,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.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(Collections.emptyMap());
         }
     }
 
@@ -228,7 +230,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
             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.empty();
         }
@@ -253,7 +255,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
                     contentType.equals("application/json") ? readJson(in) : readXml(in);
 
             if (!optionalModulesStateNode.isPresent()) {
-                return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+                return new LibraryModulesSchemas(Collections.emptyMap());
             }
 
             final NormalizedNode<?, ?> modulesStateNode = optionalModulesStateNode.get();
@@ -283,7 +285,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
             return new LibraryModulesSchemas(schemasMapping.build());
         } catch (final IOException e) {
             LOG.warn("Unable to download yang library from {}", connection.getURL(), e);
-            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+            return new LibraryModulesSchemas(Collections.emptyMap());
         }
     }
 
@@ -291,7 +293,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
         String extension = "";
         final int i = fileName.lastIndexOf(46);
         if (i != -1) {
-            extension = fileName.substring(i).toLowerCase();
+            extension = fileName.substring(i).toLowerCase(Locale.ROOT);
         }
 
         return extension.equals(".json");
@@ -302,14 +304,13 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
         final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
 
         final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT);
-        final JsonReader reader = new JsonReader(new InputStreamReader(in));
+        final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset()));
 
         jsonParser.parse(reader);
 
         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,7 +339,8 @@ public final 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 | ParserConfigurationException
+                | SAXException e) {
             LOG.warn("Unable to parse yang library xml content", e);
         }
 
@@ -375,7 +377,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
                 : QName.create(URI.create(moduleNameSpace), moduleName);
 
         try {
-            return Optional.<Map.Entry<QName, URL>>of(new AbstractMap.SimpleImmutableEntry<>(
+            return Optional.of(new AbstractMap.SimpleImmutableEntry<>(
                     moduleQName, new URL(schemaUriAsString.get())));
         } catch (final MalformedURLException e) {
             LOG.warn("Skipping library schema for {}. URL {} representing yang schema resource is not valid",
@@ -394,9 +396,8 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
     private static Optional<String> getValueOfSimpleNode(
             final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
-        final Object value = node.getValue();
-        return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.empty()
-                : Optional.of(value.toString().trim());
+        final String valueStr = node.getValue().toString();
+        return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim());
     }
 
     @Override