Use Optional.isEmpty()
[netconf.git] / netconf / sal-netconf-connector / src / main / java / org / opendaylight / netconf / sal / connect / netconf / NetconfStateSchemas.java
index 5083b2edc04cf7d850cee6cffede1ddf8823b45b..496809cf68e3b6d22c782b122b2e063fe400a1ee 100644 (file)
@@ -5,31 +5,40 @@
  * 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.netconf.sal.connect.netconf;
 
-import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+import static com.google.common.base.Verify.verify;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DATA_NODEID;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_FILTER_NODEID;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_FILTER_QNAME;
+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_QNAME;
+import static org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_TYPE_QNAME;
 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.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Sets;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
 import java.net.URI;
-import java.util.Collections;
+import java.net.URISyntaxException;
+import java.util.HashSet;
 import java.util.Optional;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
-import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.transform.dom.DOMSource;
+import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.mdsal.dom.api.DOMRpcResult;
+import org.opendaylight.mdsal.dom.api.DOMRpcService;
+import org.opendaylight.netconf.api.xml.XmlUtil;
 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemas;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
-import org.opendaylight.netconf.sal.connect.netconf.schema.mapping.BaseSchema;
 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.util.NetconfUtil;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.Yang;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.netconf.state.Schemas;
@@ -37,6 +46,7 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.mon
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
@@ -45,28 +55,45 @@ 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.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
 
 /**
  * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
  */
 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
+    public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(ImmutableSet.of());
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemas.class);
-
-    public static final NetconfStateSchemas EMPTY = new NetconfStateSchemas(Collections.emptySet());
-
     private static final YangInstanceIdentifier STATE_SCHEMAS_IDENTIFIER =
             YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
-
-    private static final ContainerNode GET_SCHEMAS_RPC;
+    private static final @NonNull ContainerNode GET_SCHEMAS_RPC;
 
     static {
-        final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
-                BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
-        GET_SCHEMAS_RPC
-                = Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_GET_QNAME)).withChild(filter).build();
+        final Document document = XmlUtil.newDocument();
+
+        final Element filterElem = XmlUtil.createElement(document, NETCONF_FILTER_QNAME.getLocalName(),
+            Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
+        filterElem.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
+            "subtree");
+
+        final Element stateElem = XmlUtil.createElement(document, NetconfState.QNAME.getLocalName(),
+            Optional.of(NetconfState.QNAME.getNamespace().toString()));
+        stateElem.appendChild(XmlUtil.createElement(document, Schemas.QNAME.getLocalName(),
+            Optional.of(Schemas.QNAME.getNamespace().toString())));
+        filterElem.appendChild(stateElem);
+
+        GET_SCHEMAS_RPC = Builders.containerBuilder()
+                .withNodeIdentifier(NETCONF_GET_NODEID)
+                .withChild(Builders.anyXmlBuilder()
+                    .withNodeIdentifier(NETCONF_FILTER_NODEID)
+                    .withValue(new DOMSource(filterElem))
+                    .build())
+                .build();
     }
 
     private final Set<RemoteYangSchema> availableYangSchemas;
@@ -81,14 +108,16 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
 
     @Override
     public Set<QName> getAvailableYangSchemasQNames() {
-        return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), RemoteYangSchema::getQName));
+        return getAvailableYangSchemas().stream().map(RemoteYangSchema::getQName)
+                .collect(ImmutableSet.toImmutableSet());
     }
 
     /**
      * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas.
      */
     static NetconfStateSchemas create(final DOMRpcService deviceRpc,
-                                  final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
+            final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
+            final EffectiveModelContext schemaContext) {
         if (!remoteSessionCapabilities.isMonitoringSupported()) {
             // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support
             // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported...
@@ -98,7 +127,7 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
 
         final DOMRpcResult schemasNodeResult;
         try {
-            schemasNodeResult = deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_SCHEMAS_RPC).get();
+            schemasNodeResult = deviceRpc.invokeRpc(NETCONF_GET_QNAME, GET_SCHEMAS_RPC).get();
         } catch (final InterruptedException e) {
             Thread.currentThread().interrupt();
             throw new RuntimeException(id
@@ -114,16 +143,17 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
             return EMPTY;
         }
 
-        final Optional<? extends NormalizedNode<?, ?>> schemasNode = findSchemasNode(schemasNodeResult.getResult());
-
-        if (schemasNode.isPresent()) {
-            Preconditions.checkState(schemasNode.get() instanceof ContainerNode,
-                    "Expecting container containing schemas, but was %s", schemasNode.get());
-            return create(id, (ContainerNode) schemasNode.get());
-        } else {
+        final Optional<? extends NormalizedNode<?, ?>> optSchemasNode = findSchemasNode(schemasNodeResult.getResult(),
+                schemaContext);
+        if (optSchemasNode.isEmpty()) {
             LOG.warn("{}: Unable to detect available schemas, get to {} was empty", id, STATE_SCHEMAS_IDENTIFIER);
             return EMPTY;
         }
+
+        final NormalizedNode<?, ?> schemasNode = optSchemasNode.get();
+        checkState(schemasNode instanceof ContainerNode, "Expecting container containing schemas, but was %s",
+            schemasNode);
+        return create(id, (ContainerNode) schemasNode);
     }
 
     /**
@@ -131,40 +161,50 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
      */
     @VisibleForTesting
     protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
-        final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
+        final Set<RemoteYangSchema> availableYangSchemas = new HashSet<>();
 
         final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
                 schemasNode.getChild(toId(Schema.QNAME));
-        Preconditions.checkState(child.isPresent(),
-                "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode);
-        Preconditions.checkState(child.get() instanceof MapNode,
+        checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(),
+            schemasNode);
+        checkState(child.get() instanceof MapNode,
                 "Unexpected structure for container: %s in response: %s. Expecting a list",
                 Schema.QNAME.withoutRevision(), schemasNode);
 
         for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) {
             final Optional<RemoteYangSchema> fromCompositeNode =
                     RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
-            if (fromCompositeNode.isPresent()) {
-                availableYangSchemas.add(fromCompositeNode.get());
-            }
+            fromCompositeNode.ifPresent(availableYangSchemas::add);
         }
 
         return new NetconfStateSchemas(availableYangSchemas);
     }
 
-    private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
+    private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result,
+            final EffectiveModelContext schemaContext) {
         if (result == null) {
             return Optional.empty();
         }
-        final Optional<DataContainerChild<?, ?>> dataNode =
-                ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
-        if (!dataNode.isPresent()) {
+        final Optional<DataContainerChild<?, ?>> rpcResultOpt = ((ContainerNode)result).getChild(NETCONF_DATA_NODEID);
+        if (rpcResultOpt.isEmpty()) {
             return Optional.empty();
         }
 
-        final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
-                ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
-        if (!nStateNode.isPresent()) {
+        final DataContainerChild<?, ?> rpcResult = rpcResultOpt.get();
+        verify(rpcResult instanceof DOMSourceAnyxmlNode, "Unexpected result %s", rpcResult);
+        final NormalizedNode<?, ?> dataNode;
+
+        try {
+            dataNode = NetconfUtil.transformDOMSourceToNormalizedNode(schemaContext,
+                    ((DOMSourceAnyxmlNode) rpcResult).getValue()).getResult();
+        } catch (XMLStreamException | URISyntaxException | IOException | SAXException e) {
+            LOG.warn("Failed to transform {}", rpcResult, e);
+            return Optional.empty();
+        }
+
+        final Optional<DataContainerChild<?, ?>> nStateNode = ((DataContainerNode<?>) dataNode).getChild(
+            toId(NetconfState.QNAME));
+        if (nStateNode.isEmpty()) {
             return Optional.empty();
         }
 
@@ -184,8 +224,7 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
 
         static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
                                                                    final MapEntryNode schemaNode) {
-            Preconditions.checkArgument(
-                    schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
+            checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
 
             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
 
@@ -205,7 +244,7 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
 
             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE;
             final Optional<String> namespaceValue = getSingleChildNodeValue(schemaNode, childNode);
-            if (!namespaceValue.isPresent()) {
+            if (namespaceValue.isEmpty()) {
                 LOG.warn("{}: Ignoring schema due to missing namespace", id);
                 return Optional.empty();
             }
@@ -230,12 +269,11 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
          */
         private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
                                                          final QName childNodeQName) {
-            final Set<String> extractedValues = Sets.newHashSet();
+            final Set<String> extractedValues = new HashSet<>();
             final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
                     schemaNode.getChild(toId(childNodeQName));
-            Preconditions.checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
-            Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>,
-                    "Child nodes %s not present", childNodeQName);
+            checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName);
+            checkArgument(child.get() instanceof LeafSetNode<?>, "Child nodes %s not present", childNodeQName);
             for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
                 extractedValues.add(getValueOfSimpleNode(childNode).get());
             }
@@ -248,10 +286,9 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
                     schemaNode.getChild(toId(childNode));
             if (node.isPresent()) {
                 return getValueOfSimpleNode(node.get());
-            } else {
-                LOG.debug("Child node {} not present", childNode);
-                return Optional.empty();
             }
+            LOG.debug("Child node {} not present", childNode);
+            return Optional.empty();
         }
 
         private static Optional<String> getValueOfSimpleNode(