Bug 8153: Enforce check-style rules for netconf - sal-netconf-connector 60/56160/3
authormatus.kubica <matus.kubica@pantheon.tech>
Thu, 27 Apr 2017 13:06:53 +0000 (15:06 +0200)
committermatus.kubica <matus.kubica@pantheon.tech>
Tue, 2 May 2017 07:36:37 +0000 (09:36 +0200)
    Organize Imports for Checkstyle compliance.
    Checkstyle compliance: line length.
    Checkstyle compliance: various types of small changes.
    Checkstyle compliant Exception handling.
    Checkstyle final clean up & enforcement.
    Add the fail on violation flag into the pom.xml .

Change-Id: I741ea586178981d6c66533259619c27c24bbd744
Signed-off-by: matus.kubica <matus.kubica@pantheon.tech>
69 files changed:
netconf/sal-netconf-connector/pom.xml
netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModuleFactory.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/NetconfDeviceSchemasResolver.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/RemoteDevice.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasResolverImpl.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UserPreferences.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceDataBroker.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationService.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacade.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadOnlyTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadWriteTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChain.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/BaseRpcSchemalessTransformer.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/BaseSchema.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/SchemalessMessageTransformer.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOps.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfMessageTransformUtil.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfRpcFutureCallback.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfRpcStructureTransformer.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NodeContainerProxy.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/RpcStructureTransformer.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/util/MessageCounter.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/util/RemoteDeviceId.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDeviceTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToNotificationTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/NetconfToRpcRequestTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/SchemalessNetconfDeviceTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicatorTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferencesTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacadeTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/MountInstanceTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceDataBrokerTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpcTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacadeTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapterTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpcTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/NetconfDeviceWriteOnlyTxTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadOnlyTxTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChainTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTxTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTxTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteRunningTxTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProviderTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/BaseRpcSchemalessTransformerTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformerTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/SchemalessMessageTransformerTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformerTest.java

index 8106409eeee4cbd2424c91f21dc5bcc676726191..bccd4a782f04752f7bc1e457ac23a61520b4515e 100644 (file)
     <tag>HEAD</tag>
     <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
   </scm>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
 </project>
index 755959b64f0320e5532db2e1afd3be21f31e7a2c..34f2cbed1ff6304710b904f447a809044d911523 100644 (file)
@@ -44,14 +44,20 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Instead of using loopback (controller-config mount point) to create your netconf-connector, you should use the network-topology capability.
+ * Instead of using loopback (controller-config mount point) to create your netconf-connector,
+ * you should use the network-topology capability.
+ *
  * <p>
- * Follow instructions provided in this <a href="https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf#Spawning_netconf_connectors_via_topology_configuration">wiki</a>.
+ * Follow instructions provided in this
+ * <a href="https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf#Spawning_netconf_connectors_via_topology_configuration">wiki</a>.
+ *
  * <p>
  * Deprecation notice in Carbon, removal planned for Nitrogen.
  */
 @Deprecated
-public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule implements BindingAwareConsumer {
+public final class NetconfConnectorModule
+        extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule
+        implements BindingAwareConsumer {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class);
 
     private static final InstanceIdentifier<Topology> TOPOLOGY_PATH = InstanceIdentifier.create(NetworkTopology.class)
@@ -60,12 +66,15 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
     private InstanceIdentifier<Node> nodePath;
     private DataBroker dataBroker;
 
-    public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+    public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+                                  final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
         instanceName = identifier.getInstanceName();
     }
 
-    public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
+    public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+                                  final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+                                  final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) {
         super(identifier, dependencyResolver, oldModule, oldInstance);
         instanceName = identifier.getInstanceName();
     }
@@ -73,7 +82,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
     @Override
     protected void customValidation() {
         checkNotNull(getAddress(), addressJmxAttribute);
-        checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
+        checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(),
+                addressJmxAttribute);
         checkNotNull(getPort(), portJmxAttribute);
 
         checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute);
@@ -93,8 +103,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
     }
 
     private static boolean isHostAddressPresent(final Host address) {
-        return address.getDomainName() != null ||
-                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
+        return address.getDomainName() != null || address.getIpAddress() != null
+                && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
     }
 
     @Override
@@ -120,8 +130,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.error("Node {} creation failed: {}", instanceName, t);
+            public void onFailure(final Throwable throwable) {
+                LOG.error("Node {} creation failed: {}", instanceName, throwable);
             }
         });
     }
@@ -138,8 +148,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
                 }
 
                 @Override
-                public void onFailure(final Throwable t) {
-                    LOG.error("Node {} deletion failed: {}", instanceName, t);
+                public void onFailure(final Throwable throwable) {
+                    LOG.error("Node {} deletion failed: {}", instanceName, throwable);
                 }
             });
 
@@ -161,7 +171,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         }
 
         NonModuleCapabilities nonModuleCapabilities = null;
-        if(getNonModuleCapabilities() != null) {
+        if (getNonModuleCapabilities() != null) {
             nonModuleCapabilities = new NonModuleCapabilitiesBuilder()
                     .setOverride(getNonModuleCapabilities().getOverride())
                     .setCapability(getNonModuleCapabilities().getCapability())
index 3e5fe6b247e7c21896bd863efd9bb11e3fe6d370..0e5bb46b6b76987e0eea2d0d041325290ad0c246 100644 (file)
@@ -19,15 +19,16 @@ public class NetconfConnectorModuleFactory extends
     @Override
     public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
             final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
-        final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
-                old, bundleContext);
+        final NetconfConnectorModule module =
+                (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, old, bundleContext);
         return module;
     }
 
     @Override
-    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver,
-                bundleContext);
+    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
+                               final BundleContext bundleContext) {
+        final NetconfConnectorModule module =
+                (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, bundleContext);
         return module;
     }
 }
index c1a465ef6e6cab6c8c78bddf1415a08d168a51ac..8031c15554facdb0cb378016c59e26b33153079b 100644 (file)
@@ -13,8 +13,9 @@ import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 
 /**
- * Factory for netconf device schemas
+ * Factory for netconf device schemas.
  */
 public interface NetconfDeviceSchemasResolver {
-    NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id);
+    NetconfDeviceSchemas resolve(
+            NetconfDeviceRpc deviceRpc, NetconfSessionPreferences remoteSessionCapabilities, RemoteDeviceId id);
 }
index dac321c749fde435e5b9ec56527810880f681079..e4f45f64bc587d7e45833ce493eff5c7a3a66deb 100644 (file)
@@ -8,7 +8,7 @@
 package org.opendaylight.netconf.sal.connect.api;
 
 /**
- *
+ * Remote device.
  */
 public interface RemoteDevice<PREF, M, LISTENER extends RemoteDeviceCommunicator<M>> {
 
index 9924d6fc75f2743928d8e468f242b7e50ec36418..9f59dba6957fd06c609249b9be94cf1c5b30efb6 100644 (file)
@@ -66,7 +66,7 @@ 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
+ * ietf-netconf-yang-library/modules-state/modules node.
  */
 public class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
@@ -76,9 +76,8 @@ public 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());
+        moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang
+                .library.rev160409.$YangModuleInfoImpl.getInstance());
         LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
     }
 
@@ -104,7 +103,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
         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()));
+                .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision()));
             result.put(sId, entry.getValue());
         }
 
@@ -123,7 +122,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
             final URL urlConnection = new URL(url);
             final URLConnection connection = urlConnection.openConnection();
 
-            if(connection instanceof HttpURLConnection) {
+            if (connection instanceof HttpURLConnection) {
                 connection.setRequestProperty("Accept", "application/xml");
                 final String userpass = username + ":" + password;
                 final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes());
@@ -150,11 +149,12 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
             throw new RuntimeException(deviceId + ": Interrupted while waiting for response to "
                     + MODULES_STATE_MODULE_LIST, e);
         } catch (final ExecutionException e) {
-            LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId, MODULES_STATE_MODULE_LIST, e);
+            LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId,
+                    MODULES_STATE_MODULE_LIST, e);
             return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
         }
 
-        if(moduleListNodeResult.getErrors().isEmpty() == false) {
+        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());
@@ -163,7 +163,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
         final Optional<? extends NormalizedNode<?, ?>> modulesStateNode =
                 findModulesStateNode(moduleListNodeResult.getResult());
-        if(modulesStateNode.isPresent()) {
+        if (modulesStateNode.isPresent()) {
             Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode,
                     "Expecting container containing schemas, but was %s", modulesStateNode.get());
             return create(((ContainerNode) modulesStateNode.get()));
@@ -173,18 +173,6 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
         }
     }
 
-    private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
-        if(result == null) {
-            return Optional.absent();
-        }
-        final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
-        if(dataNode.isPresent() == false) {
-            return Optional.absent();
-        }
-
-       return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
-    }
-
     private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) {
         final YangInstanceIdentifier.NodeIdentifier moduleListNodeId =
                 new YangInstanceIdentifier.NodeIdentifier(Module.QNAME);
@@ -207,6 +195,42 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
         return new LibraryModulesSchemas(schemasMapping.build());
     }
 
+    /**
+     * Resolves URLs with YANG schema resources from modules-state.
+     * @param url URL pointing to yang library
+     * @return Resolved URLs with YANG schema resources for all yang modules from yang library
+     */
+    public static LibraryModulesSchemas create(final String url) {
+        Preconditions.checkNotNull(url);
+        try {
+            final URL urlConnection = new URL(url);
+            final URLConnection connection = urlConnection.openConnection();
+
+            if (connection instanceof HttpURLConnection) {
+                connection.setRequestProperty("Accept", "application/xml");
+            }
+
+            return createFromURLConnection(connection);
+
+        } catch (final IOException e) {
+            LOG.warn("Unable to download yang library from {}", url, e);
+            return new LibraryModulesSchemas(Collections.<QName, URL>emptyMap());
+        }
+    }
+
+    private static Optional<? extends NormalizedNode<?, ?>> findModulesStateNode(final NormalizedNode<?, ?> result) {
+        if (result == null) {
+            return Optional.absent();
+        }
+        final Optional<DataContainerChild<?, ?>> dataNode =
+                ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
+        if (dataNode.isPresent() == false) {
+            return Optional.absent();
+        }
+
+        return ((DataContainerNode<?>) dataNode.get()).getChild(toId(ModulesState.QNAME));
+    }
+
     private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) {
 
         String contentType = connection.getContentType();
@@ -219,7 +243,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
         Preconditions.checkNotNull(contentType, "Content type unknown");
         Preconditions.checkState(contentType.equals("application/json") || contentType.equals("application/xml"),
                 "Only XML and JSON types are supported.");
-        try (final InputStream in = connection.getInputStream()) {
+        try (InputStream in = connection.getInputStream()) {
             final Optional<NormalizedNode<?, ?>> optionalModulesStateNode =
                     contentType.equals("application/json") ? readJson(in) : readXml(in);
 
@@ -258,33 +282,10 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
         }
     }
 
-    /**
-     * Resolves URLs with YANG schema resources from modules-state
-     * @param url URL pointing to yang library
-     * @return Resolved URLs with YANG schema resources for all yang modules from yang library
-     */
-    public static LibraryModulesSchemas create(final String url) {
-        Preconditions.checkNotNull(url);
-        try {
-            final URL urlConnection = new URL(url);
-            final URLConnection connection = urlConnection.openConnection();
-
-            if(connection instanceof HttpURLConnection) {
-                connection.setRequestProperty("Accept", "application/xml");
-            }
-
-            return createFromURLConnection(connection);
-
-        } catch (final IOException e) {
-            LOG.warn("Unable to download yang library from {}", url, 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) {
+        if (i != -1) {
             extension = fileName.substring(i).toLowerCase();
         }
 
@@ -300,9 +301,8 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
         jsonParser.parse(reader);
 
-        return resultHolder.isFinished() ?
-                Optional.of(resultHolder.getResult()) :
-                Optional.<NormalizedNode<?, ?>>absent();
+        return resultHolder.isFinished()
+                ? Optional.of(resultHolder.getResult()) : Optional.<NormalizedNode<?, ?>>absent();
     }
 
     private static Optional<NormalizedNode<?, ?>> readXml(final InputStream in) {
@@ -317,7 +317,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
                     parserFactory.getContainerNodeParser().parse(Collections.singleton(XmlUtil.readXmlToElement(in)),
                             (ContainerSchemaNode) LIBRARY_CONTEXT.getDataChildByName(ModulesState.QNAME));
             return Optional.of(parsed);
-        } catch (IOException|SAXException e) {
+        } catch (IOException | SAXException e) {
             LOG.warn("Unable to parse yang library xml content", e);
         }
 
@@ -334,8 +334,8 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas {
 
         childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision"));
         final Optional<String> revision = getSingleChildNodeValue(moduleNode, childNodeId);
-        if(revision.isPresent()) {
-            if(!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) {
+        if (revision.isPresent()) {
+            if (!SourceIdentifier.REVISION_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();
             }
index 86ef2abc7f770db998bbc18997cfde26215799e1..45e67e363140a6778bf789e754397e232f961a24 100644 (file)
@@ -72,14 +72,15 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
+ *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade.
  */
-public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
+public class NetconfDevice
+        implements RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class);
 
     public static final Function<QName, SourceIdentifier> QNAME_TO_SOURCE_ID_FUNCTION =
-            input -> RevisionSourceIdentifier.create(input.getLocalName(),
+        input -> RevisionSourceIdentifier.create(input.getLocalName(),
                 Optional.fromNullable(input.getFormattedRevision()));
 
     protected final RemoteDeviceId id;
@@ -92,23 +93,28 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
     protected final SchemaRepository schemaRepository;
     private final NetconfDeviceSchemasResolver stateSchemasResolver;
     private final NotificationHandler notificationHandler;
-    protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations = Lists.newArrayList();
+    protected final List<SchemaSourceRegistration<? extends SchemaSourceRepresentation>> sourceRegistrations =
+            Lists.newArrayList();
 
     // Message transformer is constructed once the schemas are available
     private MessageTransformer<NetconfMessage> messageTransformer;
 
     /**
-     * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded
+     * Create rpc implementation capable of handling RPC for monitoring and notifications
+     * even before the schemas of remote device are downloaded.
      */
-    static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) {
-        final BaseSchema baseSchema = notificationSupport ?
-                BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
-                BaseSchema.BASE_NETCONF_CTX;
-
-        return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
+    static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener,
+                                                    final boolean notificationSupport) {
+        final BaseSchema baseSchema = notificationSupport
+                ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS
+                : BaseSchema.BASE_NETCONF_CTX;
+
+        return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener,
+                new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema));
     }
 
-    public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
+    public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id,
+                         final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
                          final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) {
         this.id = id;
         this.reconnectOnSchemasChange = reconnectOnSchemasChange;
@@ -131,8 +137,10 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         // http://netty.io/wiki/thread-model.html
         LOG.debug("{}: Session to remote device established with {}", id, remoteSessionCapabilities);
 
-        final NetconfDeviceRpc initRpc = getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
-        final DeviceSourcesResolver task = new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
+        final NetconfDeviceRpc initRpc =
+                getRpcForInitialization(listener, remoteSessionCapabilities.isNotificationsSupported());
+        final DeviceSourcesResolver task =
+                new DeviceSourcesResolver(remoteSessionCapabilities, id, stateSchemasResolver, initRpc);
         final ListenableFuture<DeviceSources> sourceResolverFuture = processingExecutor.submit(task);
 
         if (shouldListenOnSchemaChange(remoteSessionCapabilities)) {
@@ -151,18 +159,20 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.warn("{}: Unexpected error resolving device sources: {}", id, t);
-                handleSalInitializationFailure(t, listener);
+            public void onFailure(final Throwable throwable) {
+                LOG.warn("{}: Unexpected error resolving device sources: {}", id, throwable);
+                handleSalInitializationFailure(throwable, listener);
             }
         };
 
         Futures.addCallback(sourceResolverFuture, resolvedSourceCallback);
     }
 
-    private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc, final NetconfDeviceCommunicator listener) {
+    private void registerToBaseNetconfStream(final NetconfDeviceRpc deviceRpc,
+                                             final NetconfDeviceCommunicator listener) {
        // TODO check whether the model describing create subscription is present in schema
-        // Perhaps add a default schema context to support create-subscription if the model was not provided (same as what we do for base netconf operations in transformer)
+        // Perhaps add a default schema context to support create-subscription if the model was not provided
+        // (same as what we do for base netconf operations in transformer)
         final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultListenableFuture = deviceRpc.invokeRpc(
             NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME),
             NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT);
@@ -172,7 +182,8 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
             public Optional<DOMNotification> filterNotification(final DOMNotification notification) {
                 if (isCapabilityChanged(notification)) {
                     LOG.info("{}: Schemas change detected, reconnecting", id);
-                    // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting
+                    // Only disconnect is enough,
+                    // the reconnecting nature of the connector will take care of reconnecting
                     listener.disconnect();
                     return Optional.absent();
                 }
@@ -191,8 +202,9 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly", t);
+            public void onFailure(final Throwable throwable) {
+                LOG.warn("Unable to subscribe to base notification stream. Schemas will not be reloaded on the fly",
+                        throwable);
             }
         });
     }
@@ -205,9 +217,8 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
                                         final NetconfSessionPreferences remoteSessionCapabilities,
                                         final DOMRpcService deviceRpc) {
         final BaseSchema baseSchema =
-                remoteSessionCapabilities.isNotificationsSupported() ?
-                BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
-                BaseSchema.BASE_NETCONF_CTX;
+                remoteSessionCapabilities.isNotificationsSupported()
+                        ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : BaseSchema.BASE_NETCONF_CTX;
         messageTransformer = new NetconfMessageTransformer(result, true, baseSchema);
 
         updateTransformer(messageTransformer);
@@ -218,15 +229,16 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         LOG.info("{}: Netconf connector initialized successfully", id);
     }
 
-    void handleSalInitializationFailure(final Throwable t, final RemoteDeviceCommunicator<NetconfMessage> listener) {
-        LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t);
+    void handleSalInitializationFailure(final Throwable throwable,
+                                        final RemoteDeviceCommunicator<NetconfMessage> listener) {
+        LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable);
         listener.close();
         onRemoteSessionDown();
         resetMessageTransformer();
     }
 
     /**
-     * Set the transformer to null as is in initial state
+     * Set the transformer to null as is in initial state.
      */
     private void resetMessageTransformer() {
         updateTransformer(null);
@@ -240,7 +252,8 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         final SchemaSourceProvider<YangTextSchemaSource> yangProvider = deviceSources.getSourceProvider();
         for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) {
             sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider,
-                    PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
+                    PotentialSchemaSource.create(
+                            sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
         }
     }
 
@@ -249,7 +262,8 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         notificationHandler.onRemoteSchemaDown();
 
         salFacade.onDeviceDisconnected();
-        for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration : sourceRegistrations) {
+        for (final SchemaSourceRegistration<? extends SchemaSourceRepresentation> sourceRegistration
+                : sourceRegistrations) {
             sourceRegistration.close();
         }
         resetMessageTransformer();
@@ -311,48 +325,54 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         private final RemoteDeviceId id;
         private final NetconfDeviceSchemasResolver stateSchemasResolver;
 
-        DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities,
-                                     final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
+        DeviceSourcesResolver(final NetconfDeviceRpc deviceRpc,
+                              final NetconfSessionPreferences remoteSessionCapabilities,
+                              final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver) {
             this.deviceRpc = deviceRpc;
             this.remoteSessionCapabilities = remoteSessionCapabilities;
             this.id = id;
             this.stateSchemasResolver = stateSchemasResolver;
         }
 
-        public DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id, final NetconfDeviceSchemasResolver stateSchemasResolver, final NetconfDeviceRpc rpcForMonitoring) {
+        DeviceSourcesResolver(final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id,
+                                     final NetconfDeviceSchemasResolver stateSchemasResolver,
+                                     final NetconfDeviceRpc rpcForMonitoring) {
             this(rpcForMonitoring, remoteSessionCapabilities, id, stateSchemasResolver);
         }
 
         @Override
         public DeviceSources call() throws Exception {
-            final NetconfDeviceSchemas availableSchemas = stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
-            LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id, availableSchemas.getAvailableYangSchemasQNames());
+            final NetconfDeviceSchemas availableSchemas =
+                    stateSchemasResolver.resolve(deviceRpc, remoteSessionCapabilities, id);
+            LOG.debug("{}: Schemas exposed by ietf-netconf-monitoring: {}", id,
+                    availableSchemas.getAvailableYangSchemasQNames());
 
             final Set<QName> requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps());
             final Set<QName> providedSources = availableSchemas.getAvailableYangSchemasQNames();
 
             final Set<QName> requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources);
             if (!requiredSourcesNotProvided.isEmpty()) {
-                LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}",
-                        id, requiredSourcesNotProvided);
+                LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities,"
+                        + " required but not provided: {}", id, requiredSourcesNotProvided);
                 LOG.warn("{}: Attempting to build schema context from required sources", id);
             }
 
             // Here all the sources reported in netconf monitoring are merged with those reported in hello.
             // It is necessary to perform this since submodules are not mentioned in hello but still required.
-            // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector
-            // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models.
+            // This clashes with the option of a user to specify supported yang models manually in configuration
+            // for netconf-connector and as a result one is not able to fully override yang models of a device.
+            // It is only possible to add additional models.
             final Set<QName> providedSourcesNotRequired = Sets.difference(providedSources, requiredSources);
             if (!providedSourcesNotRequired.isEmpty()) {
-                LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}",
-                        id, providedSourcesNotRequired);
+                LOG.warn("{}: Netconf device provides additional yang models not reported in "
+                        + "hello message capabilities: {}", id, providedSourcesNotRequired);
                 LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id);
                 LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources);
                 requiredSources.addAll(providedSourcesNotRequired);
             }
 
             final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
-            if(availableSchemas instanceof LibraryModulesSchemas) {
+            if (availableSchemas instanceof LibraryModulesSchemas) {
                 sourceProvider = new YangLibrarySchemaYangSourceProvider(id,
                         ((LibraryModulesSchemas) availableSchemas).getAvailableModels());
             } else {
@@ -371,7 +391,7 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         private final Set<QName> providedSources;
         private final SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
 
-        public DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
+        DeviceSources(final Set<QName> requiredSources, final Set<QName> providedSources,
                              final SchemaSourceProvider<YangTextSchemaSource> sourceProvider) {
             this.requiredSources = requiredSources;
             this.providedSources = providedSources;
@@ -408,7 +428,8 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         private final RemoteDeviceCommunicator<NetconfMessage> listener;
         private final NetconfDeviceCapabilities capabilities;
 
-        public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator<NetconfMessage> listener) {
+        SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities,
+                           final RemoteDeviceCommunicator<NetconfMessage> listener) {
             this.deviceSources = deviceSources;
             this.remoteSessionCapabilities = remoteSessionCapabilities;
             this.listener = listener;
@@ -431,49 +452,58 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         private Collection<SourceIdentifier> filterMissingSources(final Collection<SourceIdentifier> requiredSources) {
 
             return requiredSources.parallelStream().filter(sourceIdentifier -> {
-                    boolean remove = false;
-                    try {
-                        schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
-                    } catch (SchemaSourceException e) {
-                        remove = true;
-                    }
-                    return remove;
-                }).collect(Collectors.toList());
+                boolean remove = false;
+                try {
+                    schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet();
+                } catch (SchemaSourceException e) {
+                    remove = true;
+                }
+                return remove;
+            }).collect(Collectors.toList());
         }
 
         /**
-         * Build schema context, in case of success or final failure notify device
+         * Build schema context, in case of success or final failure notify device.
          */
+        @SuppressWarnings("checkstyle:IllegalCatch")
         private void setUpSchema(Collection<SourceIdentifier> requiredSources) {
             while (!requiredSources.isEmpty()) {
                 LOG.trace("{}: Trying to build schema context from {}", id, requiredSources);
                 try {
-                    final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources);
+                    final CheckedFuture<SchemaContext, SchemaResolutionException> schemaBuilderFuture =
+                            schemaContextFactory.createSchemaContext(requiredSources);
                     final SchemaContext result = schemaBuilderFuture.checkedGet();
                     LOG.debug("{}: Schema context built successfully from {}", id, requiredSources);
-                    final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet());
+                    final Collection<QName> filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(),
+                            capabilities.getUnresolvedCapabilites().keySet());
                     capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder()
-                            .setCapability(entry.toString()).setCapabilityOrigin(remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
+                            .setCapability(entry.toString()).setCapabilityOrigin(
+                                    remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build())
                             .collect(Collectors.toList()));
 
-                    capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
-                            .setCapability(entry).setCapabilityOrigin(remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
+                    capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities
+                            .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder()
+                            .setCapability(entry).setCapabilityOrigin(
+                                            remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build())
                             .collect(Collectors.toList()));
 
                     handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result));
                     return;
                 } catch (final Throwable t) {
-                    if (t instanceof MissingSchemaSourceException){
-                        requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
+                    if (t instanceof MissingSchemaSourceException) {
+                        requiredSources =
+                                handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t);
                     } else if (t instanceof SchemaResolutionException) {
                         // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException
                         // that might be wrapping a MissingSchemaSourceException so we need to look
                         // at the cause of the exception to make sure we don't misinterpret it.
                         if (t.getCause() instanceof MissingSchemaSourceException) {
-                            requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause());
+                            requiredSources = handleMissingSchemaSourceException(
+                                    requiredSources, (MissingSchemaSourceException) t.getCause());
                             continue;
                         }
-                        requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
+                        requiredSources =
+                                handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t);
                     } else {
                         // unknown error, fail
                         handleSalInitializationFailure(t, listener);
@@ -487,36 +517,47 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
             salFacade.onDeviceFailed(cause);
         }
 
-        private Collection<SourceIdentifier> handleMissingSchemaSourceException(final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException t) {
+        private Collection<SourceIdentifier> handleMissingSchemaSourceException(
+                final Collection<SourceIdentifier> requiredSources, final MissingSchemaSourceException exception) {
             // In case source missing, try without it
-            final SourceIdentifier missingSource = t.getSourceId();
-            LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource);
-            LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t);
-            final Collection<QName> qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
+            final SourceIdentifier missingSource = exception.getSourceId();
+            LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id,
+                    missingSource);
+            LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it",
+                    exception);
+            final Collection<QName> qNameOfMissingSource =
+                    getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource));
             if (!qNameOfMissingSource.isEmpty()) {
-                capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
+                capabilities.addUnresolvedCapabilities(
+                        qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource);
             }
             return stripUnavailableSource(requiredSources, missingSource);
         }
 
-        private Collection<SourceIdentifier> handleSchemaResolutionException(final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
+        private Collection<SourceIdentifier> handleSchemaResolutionException(
+            final Collection<SourceIdentifier> requiredSources, final SchemaResolutionException resolutionException) {
             // In case resolution error, try only with resolved sources
             // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model
             // FIXME Do we really have assurance that these two cases cannot happen at once?
             if (resolutionException.getFailedSource() != null) {
                 // flawed model - exclude it
                 final SourceIdentifier failedSourceId = resolutionException.getFailedSource();
-                LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, failedSourceId);
-                LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, resolutionException);
-                capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)),
-                        UnavailableCapability.FailureReason.UnableToResolve);
+                LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
+                        id, failedSourceId);
+                LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it",
+                        id, resolutionException);
+                capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(
+                        Collections.singleton(failedSourceId)), UnavailableCapability.FailureReason.UnableToResolve);
                 return stripUnavailableSource(requiredSources, resolutionException.getFailedSource());
             }
             // unsatisfied imports
             final Set<SourceIdentifier> unresolvedSources = resolutionException.getUnsatisfiedImports().keySet();
-            capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
-            LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports());
-            LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException);
+            capabilities.addUnresolvedCapabilities(
+                getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve);
+            LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
+                    id, resolutionException.getUnsatisfiedImports());
+            LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only",
+                    resolutionException);
             return resolutionException.getResolvedSources();
         }
 
@@ -524,10 +565,12 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
             return new NetconfDeviceRpc(result, listener, new NetconfMessageTransformer(result, true));
         }
 
-        private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources, final SourceIdentifier sIdToRemove) {
+        private Collection<SourceIdentifier> stripUnavailableSource(final Collection<SourceIdentifier> requiredSources,
+                                                                    final SourceIdentifier sourceIdToRemove) {
             final LinkedList<SourceIdentifier> sourceIdentifiers = Lists.newLinkedList(requiredSources);
-            final boolean removed = sourceIdentifiers.remove(sIdToRemove);
-            Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources);
+            final boolean removed = sourceIdentifiers.remove(sourceIdToRemove);
+            Preconditions.checkState(
+                    removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources);
             return sourceIdentifiers;
         }
 
@@ -535,7 +578,8 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
             final Collection<QName> qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier);
 
             if (qNames.isEmpty()) {
-                LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers);
+                LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id,
+                        identifiers);
             }
             return Collections2.filter(qNames, Predicates.notNull());
         }
@@ -556,8 +600,10 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
                     return qname;
                 }
             }
-            LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier, deviceSources.getRequiredSourcesQName());
-            // return null since we cannot find the QName, this capability will be removed from required sources and not reported as unresolved-capability
+            LOG.warn("Unable to map identifier to a devices reported capability: {} Available: {}",identifier,
+                    deviceSources.getRequiredSourcesQName());
+            // return null since we cannot find the QName,
+            // this capability will be removed from required sources and not reported as unresolved-capability
             return null;
         }
 
index 3986c8f371bceab36e5f93786bafa40a891e201d..de51f47165502323e109b8c939cbe9f9a5d29024 100644 (file)
@@ -50,7 +50,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas
+ * Holds QNames for all yang modules reported by ietf-netconf-monitoring/state/schemas.
  */
 public final class NetconfStateSchemas implements NetconfDeviceSchemas {
 
@@ -62,6 +62,7 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
             YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).build();
 
     private static final ContainerNode GET_SCHEMAS_RPC;
+
     static {
         final DataContainerChild<?, ?> filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER,
                 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext());
@@ -81,19 +82,21 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
 
     @Override
     public Set<QName> getAvailableYangSchemasQNames() {
-        return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), new Function<RemoteYangSchema, QName>() {
-            @Override
-            public QName apply(final RemoteYangSchema input) {
-                return input.getQName();
-            }
-        }));
+        return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(),
+                new Function<RemoteYangSchema, QName>() {
+                    @Override
+                    public QName apply(final RemoteYangSchema input) {
+                        return input.getQName();
+                    }
+                }));
     }
 
     /**
-     * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas
+     * 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) {
-        if(remoteSessionCapabilities.isMonitoringSupported() == false) {
+    static NetconfStateSchemas create(final DOMRpcService deviceRpc,
+                                  final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
+        if (remoteSessionCapabilities.isMonitoringSupported() == false) {
             // 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...
             LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id);
@@ -105,20 +108,22 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
             schemasNodeResult = deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_SCHEMAS_RPC).get();
         } catch (final InterruptedException e) {
             Thread.currentThread().interrupt();
-            throw new RuntimeException(id + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
+            throw new RuntimeException(id
+                    + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e);
         } catch (final ExecutionException e) {
             LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e);
             return EMPTY;
         }
 
-        if(schemasNodeResult.getErrors().isEmpty() == false) {
-            LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}", id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
+        if (schemasNodeResult.getErrors().isEmpty() == false) {
+            LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}",
+                    id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors());
             return EMPTY;
         }
 
         final Optional<? extends NormalizedNode<?, ?>> schemasNode = findSchemasNode(schemasNodeResult.getResult());
 
-        if(schemasNode.isPresent()) {
+        if (schemasNode.isPresent()) {
             Preconditions.checkState(schemasNode.get() instanceof ContainerNode,
                     "Expecting container containing schemas, but was %s", schemasNode.get());
             return create(id, (ContainerNode) schemasNode.get());
@@ -128,38 +133,25 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
         }
     }
 
-    private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
-        if(result == null) {
-            return Optional.absent();
-        }
-        final Optional<DataContainerChild<?, ?>> dataNode = ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
-        if(dataNode.isPresent() == false) {
-            return Optional.absent();
-        }
-
-        final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
-                ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
-        if(nStateNode.isPresent() == false) {
-            return Optional.absent();
-        }
-
-        return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
-    }
-
     /**
-     * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas
+     * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas.
      */
     @VisibleForTesting
     protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) {
         final Set<RemoteYangSchema> availableYangSchemas = Sets.newHashSet();
 
-        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, "Unexpected structure for container: %s in response: %s. Expecting a list", Schema.QNAME.withoutRevision(), schemasNode);
+        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,
+                "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()) {
+            final Optional<RemoteYangSchema> fromCompositeNode =
+                    RemoteYangSchema.createFromNormalizedNode(id, schemaNode);
+            if (fromCompositeNode.isPresent()) {
                 availableYangSchemas.add(fromCompositeNode.get());
             }
         }
@@ -167,7 +159,26 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
         return new NetconfStateSchemas(availableYangSchemas);
     }
 
-    public final static class RemoteYangSchema {
+    private static Optional<? extends NormalizedNode<?, ?>> findSchemasNode(final NormalizedNode<?, ?> result) {
+        if (result == null) {
+            return Optional.absent();
+        }
+        final Optional<DataContainerChild<?, ?>> dataNode =
+                ((DataContainerNode<?>) result).getChild(toId(NETCONF_DATA_QNAME));
+        if (dataNode.isPresent() == false) {
+            return Optional.absent();
+        }
+
+        final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> nStateNode =
+                ((DataContainerNode<?>) dataNode.get()).getChild(toId(NetconfState.QNAME));
+        if (nStateNode.isPresent() == false) {
+            return Optional.absent();
+        }
+
+        return ((DataContainerNode<?>) nStateNode.get()).getChild(toId(Schemas.QNAME));
+    }
+
+    public static final class RemoteYangSchema {
         private final QName qname;
 
         RemoteYangSchema(final QName qname) {
@@ -178,21 +189,23 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
             return qname;
         }
 
-        static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id, final MapEntryNode schemaNode) {
-            Preconditions.checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
+        static Optional<RemoteYangSchema> createFromNormalizedNode(final RemoteDeviceId id,
+                                                                   final MapEntryNode schemaNode) {
+            Preconditions.checkArgument(
+                    schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType());
 
             QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT;
 
             final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get();
 
-            if(formatAsString.equals(Yang.QNAME.toString()) == false) {
+            if (formatAsString.equals(Yang.QNAME.toString()) == false) {
                 LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString);
                 return Optional.absent();
             }
 
             childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION;
             final Set<String> locationsAsString = getAllChildNodeValues(schemaNode, childNode);
-            if(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
+            if (locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) {
                 LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString);
                 return Optional.absent();
             }
@@ -220,21 +233,26 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
         }
 
         /**
-         * Extracts all values of a leaf-list node as a set of strings
+         * Extracts all values of a leaf-list node as a set of strings.
          */
-        private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode, final QName childNodeQName) {
+        private static Set<String> getAllChildNodeValues(final DataContainerNode<?> schemaNode,
+                                                         final QName childNodeQName) {
             final Set<String> extractedValues = Sets.newHashSet();
-            final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = schemaNode.getChild(toId(childNodeQName));
+            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);
+            Preconditions.checkArgument(child.get() instanceof LeafSetNode<?>,
+                    "Child nodes %s not present", childNodeQName);
             for (final LeafSetEntryNode<?> childNode : ((LeafSetNode<?>) child.get()).getValue()) {
                 extractedValues.add(getValueOfSimpleNode(childNode).get());
             }
             return extractedValues;
         }
 
-        private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode, final QName childNode) {
-            final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node = schemaNode.getChild(toId(childNode));
+        private static Optional<String> getSingleChildNodeValue(final DataContainerNode<?> schemaNode,
+                                                                final QName childNode) {
+            final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> node =
+                    schemaNode.getChild(toId(childNode));
             if (node.isPresent()) {
                 return getValueOfSimpleNode(node.get());
             } else {
@@ -243,21 +261,23 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
             }
         }
 
-        private static Optional<String> getValueOfSimpleNode(final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> node) {
+        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());
+            return value == null || Strings.isNullOrEmpty(value.toString())
+                    ? Optional.<String>absent() : Optional.of(value.toString().trim());
         }
 
         @Override
-        public boolean equals(final Object o) {
-            if (this == o) {
+        public boolean equals(final Object obj) {
+            if (this == obj) {
                 return true;
             }
-            if (o == null || getClass() != o.getClass()) {
+            if (obj == null || getClass() != obj.getClass()) {
                 return false;
             }
 
-            final RemoteYangSchema that = (RemoteYangSchema) o;
+            final RemoteYangSchema that = (RemoteYangSchema) obj;
 
             if (!qname.equals(that.qname)) {
                 return false;
index 6931cf8733d5bd625af96a1fc56aa01b2f57e13b..c2947d9860a8a50b981e4787e5479da283155411 100644 (file)
@@ -17,15 +17,18 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.librar
 import org.opendaylight.yangtools.yang.common.QName;
 
 /**
- * Default implementation resolving schemas QNames from netconf-state or from modules-state
+ * Default implementation resolving schemas QNames from netconf-state or from modules-state.
  */
 public final class NetconfStateSchemasResolverImpl implements NetconfDeviceSchemasResolver {
 
     @Override
-    public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
+    public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc,
+                                        final NetconfSessionPreferences remoteSessionCapabilities,
+                                        final RemoteDeviceId id) {
         if (remoteSessionCapabilities.isMonitoringSupported()) {
             return NetconfStateSchemas.create(deviceRpc, remoteSessionCapabilities, id);
-        } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME, "ietf-yang-library"))) {
+        } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME,
+                "ietf-yang-library"))) {
             return LibraryModulesSchemas.create(deviceRpc, id);
         }
         return NetconfStateSchemas.EMPTY;
index 232c7c7569730965fe24debe23aa548d9bd5bac9..5b28366c07703d2b5337866f355438b5691bd4f2 100644 (file)
@@ -41,7 +41,7 @@ final class NotificationHandler {
     }
 
     synchronized void handleNotification(final NetconfMessage notification) {
-        if(passNotifications) {
+        if (passNotifications) {
             passNotification(transformNotification(notification));
         } else {
             queueNotification(notification);
@@ -50,7 +50,7 @@ final class NotificationHandler {
 
     /**
      * Forward all cached notifications and pass all notifications from this point directly to sal facade.
-     * @param messageTransformer
+     * @param messageTransformer Message transformer
      */
     synchronized void onRemoteSchemaUp(final MessageTransformer<NetconfMessage> messageTransformer) {
         this.messageTransformer = Preconditions.checkNotNull(messageTransformer);
@@ -66,7 +66,8 @@ final class NotificationHandler {
 
     private DOMNotification transformNotification(final NetconfMessage cachedNotification) {
         final DOMNotification parsedNotification = messageTransformer.toNotification(cachedNotification);
-        Preconditions.checkNotNull(parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification);
+        Preconditions.checkNotNull(
+                parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification);
         return parsedNotification;
     }
 
@@ -74,7 +75,7 @@ final class NotificationHandler {
         Preconditions.checkState(passNotifications == false);
 
         LOG.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification);
-        if(LOG.isTraceEnabled()) {
+        if (LOG.isTraceEnabled()) {
             LOG.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument()));
         }
 
@@ -84,7 +85,7 @@ final class NotificationHandler {
     private synchronized void passNotification(final DOMNotification parsedNotification) {
         LOG.debug("{}: Forwarding notification {}", id, parsedNotification);
 
-        if(filter == null || filter.filterNotification(parsedNotification).isPresent()) {
+        if (filter == null || filter.filterNotification(parsedNotification).isPresent()) {
             salFacade.onNotification(parsedNotification);
         }
     }
@@ -99,7 +100,7 @@ final class NotificationHandler {
         messageTransformer = null;
     }
 
-    static interface NotificationFilter {
+    interface NotificationFilter {
 
         Optional<DOMNotification> filterNotification(DOMNotification notification);
     }
index 00dd66f260f8e3e75b4316b68129f2ce56028bf1..83ee068eb65e77c9e76ba6f434946e89408823d5 100644 (file)
@@ -44,7 +44,8 @@ import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
+public class NetconfDeviceCommunicator
+        implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
 
@@ -73,19 +74,24 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
         return isSessionClosing.get();
     }
 
-    public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
-            final UserPreferences NetconfSessionPreferences, final int rpcMessageLimit) {
-        this(id, remoteDevice, Optional.of(NetconfSessionPreferences), rpcMessageLimit);
+    public NetconfDeviceCommunicator(
+            final RemoteDeviceId id,
+            final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+            final UserPreferences netconfSessionPreferences, final int rpcMessageLimit) {
+        this(id, remoteDevice, Optional.of(netconfSessionPreferences), rpcMessageLimit);
     }
 
-    public NetconfDeviceCommunicator(final RemoteDeviceId id,
-                                     final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
-                                     final int rpcMessageLimit) {
+    public NetconfDeviceCommunicator(
+            final RemoteDeviceId id,
+            final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+            final int rpcMessageLimit) {
         this(id, remoteDevice, Optional.<UserPreferences>absent(), rpcMessageLimit);
     }
 
-    private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
-                                      final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
+    private NetconfDeviceCommunicator(
+            final RemoteDeviceId id,
+            final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> remoteDevice,
+            final Optional<UserPreferences> overrideNetconfCapabilities, final int rpcMessageLimit) {
         this.concurentRpcMsgs = rpcMessageLimit;
         this.id = id;
         this.remoteDevice = remoteDevice;
@@ -124,21 +130,22 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
             if (!firstConnectionFuture.isDone()) {
                 firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities());
             }
-        }
-        finally {
+        } finally {
             sessionLock.unlock();
         }
     }
 
     /**
+     * Initialize remote connection.
      *
-     * @param dispatcher
-     * @param config
+     * @param dispatcher {@code NetconfCLientDispatcher}
+     * @param config     {@code NetconfClientConfiguration}
      * @return future that returns succes on first succesfull connection and failure when the underlying
-     * reconnecting strategy runs out of reconnection attempts
+     *     reconnecting strategy runs out of reconnection attempts
      */
-    public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
-        if(config instanceof NetconfReconnectingClientConfiguration) {
+    public ListenableFuture<NetconfDeviceCapabilities> initializeRemoteConnection(
+            final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) {
+        if (config instanceof NetconfReconnectingClientConfiguration) {
             initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
         } else {
             initFuture = dispatcher.createClient(config);
@@ -159,7 +166,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
 
     public void disconnect() {
         // If session is already in closing, no need to close it again
-        if(session != null && isSessionClosing.compareAndSet(false, true)) {
+        if (session != null && isSessionClosing.compareAndSet(false, true)) {
             session.close();
         }
     }
@@ -172,9 +179,8 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
         final List<UncancellableFuture<RpcResult<NetconfMessage>>> futuresToCancel = Lists.newArrayList();
         sessionLock.lock();
         try {
-            if( session != null ) {
+            if (session != null) {
                 session = null;
-
                 /*
                  * Walk all requests, check if they have been executing
                  * or cancelled and remove them from the queue.
@@ -183,7 +189,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                 while (it.hasNext()) {
                     final Request r = it.next();
                     if (r.future.isUncancellable()) {
-                        futuresToCancel.add( r.future );
+                        futuresToCancel.add(r.future);
                         it.remove();
                     } else if (r.future.isCancelled()) {
                         // This just does some house-cleaning
@@ -193,18 +199,17 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
 
                 remoteDevice.onRemoteSessionDown();
             }
-        }
-        finally {
+        } finally {
             sessionLock.unlock();
         }
 
         // Notify pending request futures outside of the sessionLock to avoid unnecessarily
         // blocking the caller.
         for (final UncancellableFuture<RpcResult<NetconfMessage>> future : futuresToCancel) {
-            if( Strings.isNullOrEmpty( reason ) ) {
-                future.set( createSessionDownRpcResult() );
+            if (Strings.isNullOrEmpty(reason)) {
+                future.set(createSessionDownRpcResult());
             } else {
-                future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) );
+                future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT, reason));
             }
         }
 
@@ -212,22 +217,22 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
     }
 
     private RpcResult<NetconfMessage> createSessionDownRpcResult() {
-        return createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
-                             String.format( "The netconf session to %1$s is disconnected", id.getName() ) );
+        return createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
+                String.format("The netconf session to %1$s is disconnected", id.getName()));
     }
 
     private static RpcResult<NetconfMessage> createErrorRpcResult(final RpcError.ErrorType errorType,
             final String message) {
         return RpcResultBuilder.<NetconfMessage>failed()
-                .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build();
+            .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build();
     }
 
     @Override
-    public void onSessionDown(final NetconfClientSession session, final Exception e) {
+    public void onSessionDown(final NetconfClientSession session, final Exception exception) {
         // If session is already in closing, no need to call tearDown again.
         if (isSessionClosing.compareAndSet(false, true)) {
-            LOG.warn("{}: Session went down", id, e);
-            tearDown( null );
+            LOG.warn("{}: Session went down", id, exception);
+            tearDown(null);
         }
     }
 
@@ -235,13 +240,13 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
     public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) {
         // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing.
         LOG.warn("{}: Session terminated {}", id, reason);
-        tearDown( reason.getErrorMessage() );
+        tearDown(reason.getErrorMessage());
     }
 
     @Override
     public void close() {
         // Cancel reconnect if in progress
-        if(initFuture != null) {
+        if (initFuture != null) {
             initFuture.cancel(false);
         }
         // Disconnect from device
@@ -272,7 +277,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                 requests.poll();
                 // we have just removed one request from the queue
                 // we can also release one permit
-                if(semaphore != null) {
+                if (semaphore != null) {
                     semaphore.release();
                 }
             } else {
@@ -280,28 +285,28 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                 LOG.warn("{}: Ignoring unsolicited message {}", id,
                         msgToS(message));
             }
-        }
-        finally {
+        } finally {
             sessionLock.unlock();
         }
 
-        if( request != null ) {
+        if (request != null) {
 
             LOG.debug("{}: Message received {}", id, message);
 
-            if(LOG.isTraceEnabled()) {
-                LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) );
+            if (LOG.isTraceEnabled()) {
+                LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message));
             }
 
             try {
-                NetconfMessageTransformUtil.checkValidReply( request.request, message );
+                NetconfMessageTransformUtil.checkValidReply(request.request, message);
             } catch (final NetconfDocumentedException e) {
                 LOG.warn(
-                        "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
+                        "{}: Invalid request-reply match,"
+                                + "reply message contains different message-id, request: {}, response: {}",
                         id, msgToS(request.request), msgToS(message), e);
 
-                request.future.set( RpcResultBuilder.<NetconfMessage>failed()
-                        .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
+                request.future.set(RpcResultBuilder.<NetconfMessage>failed()
+                        .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
 
                 //recursively processing message to eventually find matching request
                 processMessage(message);
@@ -311,17 +316,17 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
 
             try {
                 NetconfMessageTransformUtil.checkSuccessReply(message);
-            } catch(final NetconfDocumentedException e) {
+            } catch (final NetconfDocumentedException e) {
                 LOG.warn(
                         "{}: Error reply from remote device, request: {}, response: {}",
                         id, msgToS(request.request), msgToS(message), e);
 
-                request.future.set( RpcResultBuilder.<NetconfMessage>failed()
-                        .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
+                request.future.set(RpcResultBuilder.<NetconfMessage>failed()
+                        .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build());
                 return;
             }
 
-            request.future.set( RpcResultBuilder.success( message ).build() );
+            request.future.set(RpcResultBuilder.success(message).build());
         }
     }
 
@@ -334,11 +339,13 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
         sessionLock.lock();
 
         if (semaphore != null && !semaphore.tryAcquire()) {
-            LOG.warn("Limit of concurrent rpc messages was reached (limit :" +
-                    concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName());
+            LOG.warn("Limit of concurrent rpc messages was reached (limit :"
+                    + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id"
+                    + id.getName());
             sessionLock.unlock();
-            return Futures.immediateFailedFuture(new NetconfDocumentedException("Limit of rpc messages was reached (Limit :" +
-                    concurentRpcMsgs + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
+            return Futures.immediateFailedFuture(new NetconfDocumentedException(
+                    "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs
+                            + ") waiting for emptying the queue of Netconf device with id" + id.getName()));
         }
 
         try {
@@ -348,37 +355,36 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
         }
     }
 
-    private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(
-                                               final NetconfMessage message, final QName rpc) {
-        if(LOG.isTraceEnabled()) {
+    private ListenableFuture<RpcResult<NetconfMessage>> sendRequestWithLock(final NetconfMessage message,
+                                                                            final QName rpc) {
+        if (LOG.isTraceEnabled()) {
             LOG.trace("{}: Sending message {}", id, msgToS(message));
         }
 
         if (session == null) {
             LOG.warn("{}: Session is disconnected, failing RPC request {}",
                     id, message);
-            return Futures.immediateFuture( createSessionDownRpcResult() );
+            return Futures.immediateFuture(createSessionDownRpcResult());
         }
 
         final Request req = new Request(new UncancellableFuture<>(true), message);
         requests.add(req);
 
         session.sendMessage(req.request).addListener(future -> {
-            if( !future.isSuccess() ) {
+            if (!future.isSuccess()) {
                 // We expect that a session down will occur at this point
                 LOG.debug("{}: Failed to send request {}", id,
                         XmlUtil.toString(req.request.getDocument()),
                         future.cause());
 
-                if( future.cause() != null ) {
-                    req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT,
-                                                          future.cause().getLocalizedMessage() ) );
+                if (future.cause() != null) {
+                    req.future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT,
+                            future.cause().getLocalizedMessage()));
                 } else {
-                    req.future.set( createSessionDownRpcResult() ); // assume session is down
+                    req.future.set(createSessionDownRpcResult()); // assume session is down
                 }
-                req.future.setException( future.cause() );
-            }
-            else {
+                req.future.setException(future.cause());
+            } else {
                 LOG.trace("Finished sending request {}", req.request);
             }
         });
@@ -387,7 +393,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
     }
 
     private void processNotification(final NetconfMessage notification) {
-        if(LOG.isTraceEnabled()) {
+        if (LOG.isTraceEnabled()) {
             LOG.trace("{}: Notification received: {}", id, notification);
         }
 
index 6525f019d767d233470381e0d7ec48268a6cef78..a08996da909d9db63b76bf0c6e2a3e74ed5a6375 100644 (file)
@@ -72,7 +72,8 @@ public final class NetconfSessionPreferences {
     private final Map<QName, CapabilityOrigin> moduleBasedCaps;
     private final Map<String, CapabilityOrigin> nonModuleCaps;
 
-    NetconfSessionPreferences(final Map<String, CapabilityOrigin> nonModuleCaps, final Map<QName, CapabilityOrigin> moduleBasedCaps) {
+    NetconfSessionPreferences(final Map<String, CapabilityOrigin> nonModuleCaps,
+                              final Map<QName, CapabilityOrigin> moduleBasedCaps) {
         this.nonModuleCaps = Preconditions.checkNotNull(nonModuleCaps);
         this.moduleBasedCaps = Preconditions.checkNotNull(moduleBasedCaps);
     }
@@ -96,7 +97,7 @@ public final class NetconfSessionPreferences {
     // allows partial matches - assuming parameters are in the same order
     public boolean containsPartialNonModuleCapability(final String capability) {
         final Iterator<String> iterator = getNonModuleCaps().iterator();
-        while(iterator.hasNext()) {
+        while (iterator.hasNext()) {
             if (iterator.next().startsWith(capability)) {
                 LOG.trace("capability {} partially matches {}", capability, nonModuleCaps);
                 return true;
@@ -144,32 +145,35 @@ public final class NetconfSessionPreferences {
 
     public boolean isMonitoringSupported() {
         return containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)
-                || containsPartialNonModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
+                || containsPartialNonModuleCapability(
+                        NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
     }
 
     /**
-     * Merge module-based list of capabilities with current list of module-based capabilities
+     * Merge module-based list of capabilities with current list of module-based capabilities.
      *
      * @param netconfSessionModuleCapabilities capabilities to merge into this
      *
      * @return new instance of preferences with merged module-based capabilities
      */
     public NetconfSessionPreferences addModuleCaps(final NetconfSessionPreferences netconfSessionModuleCapabilities) {
-        final Map<QName, CapabilityOrigin> mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size() + netconfSessionModuleCapabilities.getModuleBasedCaps().size());
+        final Map<QName, CapabilityOrigin> mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size()
+                + netconfSessionModuleCapabilities.getModuleBasedCaps().size());
         mergedCaps.putAll(moduleBasedCaps);
         mergedCaps.putAll(netconfSessionModuleCapabilities.getModuleBasedCapsOrigin());
         return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), mergedCaps);
     }
 
     /**
-     * Override current list of module-based capabilities
+     * Override current list of module-based capabilities.
      *
      * @param netconfSessionPreferences capabilities to override in this
      *
      * @return new instance of preferences with replaced module-based capabilities
      */
     public NetconfSessionPreferences replaceModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) {
-        return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin());
+        return new NetconfSessionPreferences(
+                getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin());
     }
 
     public NetconfSessionPreferences replaceModuleCaps(final Map<QName, CapabilityOrigin> newModuleBasedCaps) {
@@ -178,7 +182,7 @@ public final class NetconfSessionPreferences {
 
 
     /**
-     * Merge list of non-module based capabilities with current list of non-module based capabilities
+     * Merge list of non-module based capabilities with current list of non-module based capabilities.
      *
      * @param netconfSessionNonModuleCapabilities capabilities to merge into this
      *
@@ -194,14 +198,15 @@ public final class NetconfSessionPreferences {
     }
 
     /**
-     * Override current list of non-module based capabilities
+     * Override current list of non-module based capabilities.
      *
      * @param netconfSessionPreferences capabilities to override in this
      *
      * @return new instance of preferences with replaced non-module based capabilities
      */
     public NetconfSessionPreferences replaceNonModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) {
-        return new NetconfSessionPreferences(netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin());
+        return new NetconfSessionPreferences(
+                netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin());
     }
 
     public static NetconfSessionPreferences fromNetconfSession(final NetconfClientSession session) {
@@ -221,7 +226,8 @@ public final class NetconfSessionPreferences {
         return fromStrings(capabilities, CapabilityOrigin.DeviceAdvertised);
     }
 
-    public static NetconfSessionPreferences fromStrings(final Collection<String> capabilities, final CapabilityOrigin capabilityOrigin) {
+    public static NetconfSessionPreferences fromStrings(final Collection<String> capabilities,
+                                                        final CapabilityOrigin capabilityOrigin) {
         final Map<QName, CapabilityOrigin> moduleBasedCaps = new HashMap<>();
         final Map<String, CapabilityOrigin> nonModuleCaps = new HashMap<>();
 
@@ -241,7 +247,8 @@ public final class NetconfSessionPreferences {
 
             String revision = REVISION_PARAM.from(queryParams);
             if (!Strings.isNullOrEmpty(revision)) {
-                addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin);
+                addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName),
+                        capabilityOrigin);
                 continue;
             }
 
@@ -255,22 +262,27 @@ public final class NetconfSessionPreferences {
                 revision = BROKEN_REVISON_PARAM.from(queryParams);
                 if (Strings.isNullOrEmpty(revision)) {
                     LOG.warn("Netconf device returned revision incorrectly escaped for {}, ignoring it", capability);
-                    addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin);
+                    addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+                            cachedQName(namespace, moduleName), capabilityOrigin);
                 } else {
-                    addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin);
+                    addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+                            cachedQName(namespace, revision, moduleName), capabilityOrigin);
                 }
                 continue;
             }
 
             // Fallback, no revision provided for module
-            addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin);
+            addModuleQName(moduleBasedCaps, nonModuleCaps, capability,
+                    cachedQName(namespace, moduleName), capabilityOrigin);
         }
 
         return new NetconfSessionPreferences(ImmutableMap.copyOf(nonModuleCaps), ImmutableMap.copyOf(moduleBasedCaps));
     }
 
-    private static void addModuleQName(final Map<QName, CapabilityOrigin> moduleBasedCaps, final Map<String, CapabilityOrigin> nonModuleCaps, final String capability, final QName qName, final CapabilityOrigin capabilityOrigin) {
-        moduleBasedCaps.put(qName, capabilityOrigin);
+    private static void addModuleQName(final Map<QName, CapabilityOrigin> moduleBasedCaps,
+                                       final Map<String, CapabilityOrigin> nonModuleCaps, final String capability,
+                                       final QName qualifiedName, final CapabilityOrigin capabilityOrigin) {
+        moduleBasedCaps.put(qualifiedName, capabilityOrigin);
         nonModuleCaps.remove(capability);
     }
 
index d4973e6aa77edbf1e50a5cada8cfc4115ad5a8fc..85b45e9f945bee13556afb1a3e38a999d6ad25b0 100644 (file)
@@ -16,7 +16,7 @@ final class UncancellableFuture<V> extends AbstractFuture<V> {
     @GuardedBy("this")
     private boolean uncancellable = false;
 
-    public UncancellableFuture(final boolean uncancellable) {
+    UncancellableFuture(final boolean uncancellable) {
         this.uncancellable = uncancellable;
     }
 
index 10742e0b5c4d4047c6c1150738b9335c58d70f86..627bf226fd30449b6fe504f4205ba21b39fc1a97 100644 (file)
@@ -10,7 +10,7 @@ package org.opendaylight.netconf.sal.connect.netconf.listener;
 import javax.annotation.Nonnull;
 
 /**
- * DTO with user capabilities to override or merge with device specific capabilities
+ * DTO with user capabilities to override or merge with device specific capabilities.
  */
 public class UserPreferences {
 
index c450ac68fecd83c40d8eff6c306e30d02e6b35c1..2e33b57beb86f484d147b43d3982c74a7d397cd4 100644 (file)
@@ -66,7 +66,8 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
     private volatile DOMRpcService currentDeviceRpc;
 
     public KeepaliveSalFacade(final RemoteDeviceId id, final RemoteDeviceHandler<NetconfSessionPreferences> salFacade,
-                              final ScheduledExecutorService executor, final long keepaliveDelaySeconds, final long defaultRequestTimeoutMillis) {
+                              final ScheduledExecutorService executor, final long keepaliveDelaySeconds,
+                              final long defaultRequestTimeoutMillis) {
         this.id = id;
         this.salFacade = salFacade;
         this.executor = executor;
@@ -81,7 +82,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
     }
 
     /**
-     * Set the netconf session listener whenever ready
+     * Set the netconf session listener whenever ready.
      *
      * @param listener netconf session listener
      */
@@ -93,21 +94,22 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
      * Just cancel current keepalive task.
      * If its already started, let it finish ... not such a big deal.
      *
+     * <p>
      * Then schedule next keepalive.
      */
     private void resetKeepalive() {
         LOG.trace("{}: Resetting netconf keepalive timer", id);
-        if(currentKeepalive != null) {
+        if (currentKeepalive != null) {
             currentKeepalive.cancel(false);
         }
         scheduleKeepalive();
     }
 
     /**
-     * Cancel current keepalive and also reset current deviceRpc
+     * Cancel current keepalive and also reset current deviceRpc.
      */
     private void stopKeepalives() {
-        if(currentKeepalive != null) {
+        if (currentKeepalive != null) {
             currentKeepalive.cancel(false);
         }
         currentDeviceRpc = null;
@@ -121,9 +123,11 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
     }
 
     @Override
-    public void onDeviceConnected(final SchemaContext remoteSchemaContext, final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
+    public void onDeviceConnected(final SchemaContext remoteSchemaContext,
+                          final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
         this.currentDeviceRpc = deviceRpc;
-        final DOMRpcService deviceRpc1 = new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
+        final DOMRpcService deviceRpc1 =
+                new KeepaliveDOMRpcService(deviceRpc, resetKeepaliveTask, defaultRequestTimeoutMillis, executor);
         salFacade.onDeviceConnected(remoteSchemaContext, netconfSessionPreferences, deviceRpc1);
 
         LOG.debug("{}: Netconf session initiated, starting keepalives", id);
@@ -162,8 +166,8 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
 
     // Keepalive RPC static resources
     private static final SchemaPath PATH = toPath(NETCONF_GET_CONFIG_QNAME);
-    private static final ContainerNode KEEPALIVE_PAYLOAD =
-            NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
+    private static final ContainerNode KEEPALIVE_PAYLOAD = NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME,
+            getSourceNode(NETCONF_RUNNING_QNAME), NetconfMessageTransformUtil.EMPTY_FILTER);
 
     /**
      * Invoke keepalive RPC and check the response. In case of any received response the keepalive
@@ -175,7 +179,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
 
         private final ScheduledFuture<?> previousKeepalive;
 
-        public Keepalive(final ScheduledFuture<?> previousKeepalive) {
+        Keepalive(final ScheduledFuture<?> previousKeepalive) {
             this.previousKeepalive = previousKeepalive;
         }
 
@@ -184,7 +188,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
             LOG.trace("{}: Invoking keepalive RPC", id);
 
             try {
-                if(previousKeepalive != null && !previousKeepalive.isDone()) {
+                if (previousKeepalive != null && !previousKeepalive.isDone()) {
                     onFailure(new IllegalStateException("Previous keepalive timed out"));
                 } else {
                     Futures.addCallback(currentDeviceRpc.invokeRpc(PATH, KEEPALIVE_PAYLOAD), this);
@@ -210,27 +214,29 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
         }
 
         @Override
-        public void onFailure(@Nonnull final Throwable t) {
-            LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, t);
+        public void onFailure(@Nonnull final Throwable throwable) {
+            LOG.warn("{}: Keepalive RPC failed. Reconnecting netconf session.", id, throwable);
             reconnect();
         }
     }
 
     /**
-     * Reset keepalive after each RPC response received
+     * Reset keepalive after each RPC response received.
      */
     private class ResetKeepalive implements FutureCallback<DOMRpcResult> {
         @Override
         public void onSuccess(@Nullable final DOMRpcResult result) {
-            // No matter what response we got, rpc-reply or rpc-error, we got it from device so the netconf session is OK
+            // No matter what response we got,
+            // rpc-reply or rpc-error, we got it from device so the netconf session is OK.
             resetKeepalive();
         }
 
         @Override
-        public void onFailure(@Nonnull final Throwable t) {
-            // User/Application RPC failed (The RPC did not reach the remote device or .. TODO what other reasons could cause this ?)
+        public void onFailure(@Nonnull final Throwable throwable) {
+            // User/Application RPC failed (The RPC did not reach the remote device or ..
+            // TODO what other reasons could cause this ?)
             // There is no point in keeping this session. Reconnect.
-            LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, t);
+            LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable);
             reconnect();
         }
     }
@@ -244,7 +250,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
 
         private final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture;
 
-        public RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
+        RequestTimeoutTask(final CheckedFuture<DOMRpcResult, DOMRpcException> rpcResultFuture) {
             this.rpcResultFuture = rpcResultFuture;
         }
 
@@ -267,7 +273,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
         private final long defaultRequestTimeoutMillis;
         private final ScheduledExecutorService executor;
 
-        public KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
+        KeepaliveDOMRpcService(final DOMRpcService deviceRpc, final ResetKeepalive resetKeepaliveTask,
                 final long defaultRequestTimeoutMillis, final ScheduledExecutorService executor) {
             this.deviceRpc = deviceRpc;
             this.resetKeepaliveTask = resetKeepaliveTask;
@@ -277,8 +283,10 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
 
         @Nonnull
         @Override
-        public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, final NormalizedNode<?, ?> input) {
-            final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture = deviceRpc.invokeRpc(type, input);
+        public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
+                                                                      final NormalizedNode<?, ?> input) {
+            final CheckedFuture<DOMRpcResult, DOMRpcException> domRpcResultDOMRpcExceptionCheckedFuture =
+                    deviceRpc.invokeRpc(type, input);
             Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask);
 
             final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture);
@@ -288,7 +296,8 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
         }
 
         @Override
-        public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+        public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+                @Nonnull final T listener) {
             // There is no real communication with the device (yet), no reset here
             return deviceRpc.registerRpcListener(listener);
         }
index 2a56d01b1a4f4702ba4d95b7560dfb76d92c948f..803b8ca524722019415ef5bb4d1f33c0d3b8cea6 100644 (file)
@@ -42,7 +42,8 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker {
     private final boolean candidateSupported;
     private final boolean runningWritable;
 
-    public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext, final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) {
+    public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext,
+                                   final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) {
         this.id = id;
         this.netconfOps = new NetconfBaseOps(rpc, schemaContext);
         // get specific attributes from netconf preferences and get rid of it
@@ -51,7 +52,8 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker {
         runningWritable = netconfSessionPreferences.isRunningWritable();
         rollbackSupport = netconfSessionPreferences.isRollbackSupported();
         Preconditions.checkArgument(candidateSupported || runningWritable,
-            "Device %s has advertised neither :writable-running nor :candidate capability. At least one of these should be advertised. Failed to establish a session.", id.getName());
+            "Device %s has advertised neither :writable-running nor :candidate capability."
+                    + "At least one of these should be advertised. Failed to establish a session.", id.getName());
     }
 
     @Override
@@ -66,8 +68,8 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker {
 
     @Override
     public DOMDataWriteTransaction newWriteOnlyTransaction() {
-        if(candidateSupported) {
-            if(runningWritable) {
+        if (candidateSupported) {
+            if (runningWritable) {
                 return new WriteCandidateRunningTx(id, netconfOps, rollbackSupport);
             } else {
                 return new WriteCandidateTx(id, netconfOps, rollbackSupport);
@@ -78,7 +80,9 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker {
     }
 
     @Override
-    public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener, final DataChangeScope triggeringScope) {
+    public ListenerRegistration<DOMDataChangeListener> registerDataChangeListener(
+            final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener,
+            final DataChangeScope triggeringScope) {
         throw new UnsupportedOperationException(id + ": Data change listeners not supported for netconf mount point");
     }
 
index 8838ef15ee01268704c192ba33bf17ff756f6910..e27a7b2ec241c25952fbbd2ecffa2aaad6bb15f8 100644 (file)
@@ -29,6 +29,7 @@ public class NetconfDeviceNotificationService implements DOMNotificationService
 
     // Notification publish is very simple and hijacks the thread of the caller
     // TODO shouldnt we reuse the implementation for notification router from sal-broker-impl ?
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public synchronized void publishNotification(final DOMNotification notification) {
         for (final DOMNotificationListener domNotificationListener : listeners.get(notification.getType())) {
             try {
@@ -41,7 +42,8 @@ public class NetconfDeviceNotificationService implements DOMNotificationService
     }
 
     @Override
-    public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(@Nonnull final T listener, @Nonnull final Collection<SchemaPath> types) {
+    public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(
+            @Nonnull final T listener, @Nonnull final Collection<SchemaPath> types) {
         for (final SchemaPath type : types) {
             listeners.put(type, listener);
         }
@@ -62,7 +64,8 @@ public class NetconfDeviceNotificationService implements DOMNotificationService
     }
 
     @Override
-    public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(@Nonnull final T listener, final SchemaPath... types) {
+    public synchronized <T extends DOMNotificationListener> ListenerRegistration<T> registerNotificationListener(
+            @Nonnull final T listener, final SchemaPath... types) {
         return registerNotificationListener(listener, Lists.newArrayList(types));
     }
 }
index ff27e3c9129404d36f9329bf7afd975ebe388e99..cd9311b9c32ada42988e6d96d63530beefdabf5b 100644 (file)
@@ -37,18 +37,20 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath;
  */
 public final class NetconfDeviceRpc implements DOMRpcService {
 
-    private static final Function<RpcDefinition, DOMRpcIdentifier> RPC_TO_RPC_IDENTIFIER = new Function<RpcDefinition, DOMRpcIdentifier>() {
-        @Override
-        public DOMRpcIdentifier apply(final RpcDefinition input) {
-            return DOMRpcIdentifier.create(input.getPath());
-        }
-    };
+    private static final Function<RpcDefinition, DOMRpcIdentifier> RPC_TO_RPC_IDENTIFIER =
+        new Function<RpcDefinition, DOMRpcIdentifier>() {
+            @Override
+            public DOMRpcIdentifier apply(final RpcDefinition input) {
+                return DOMRpcIdentifier.create(input.getPath());
+            }
+        };
 
     private final RemoteDeviceCommunicator<NetconfMessage> listener;
     private final MessageTransformer<NetconfMessage> transformer;
     private final Collection<DOMRpcIdentifier> availableRpcs;
 
-    public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator<NetconfMessage> listener, final MessageTransformer<NetconfMessage> transformer) {
+    public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator<NetconfMessage> listener,
+                            final MessageTransformer<NetconfMessage> transformer) {
         this.listener = listener;
         this.transformer = transformer;
 
@@ -57,33 +59,37 @@ public final class NetconfDeviceRpc implements DOMRpcService {
 
     @Nonnull
     @Override
-    public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
+    public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type,
+                                                                  @Nullable final NormalizedNode<?, ?> input) {
         final NetconfMessage message = transformer.toRpcRequest(type, input);
-        final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult = listener.sendRequest(message, type.getLastComponent());
+        final ListenableFuture<RpcResult<NetconfMessage>> delegateFutureWithPureResult =
+                listener.sendRequest(message, type.getLastComponent());
 
-        final ListenableFuture<DOMRpcResult> transformed = Futures.transform(delegateFutureWithPureResult, new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
-            @Override
-            public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
-                if (input.isSuccessful()) {
-                    return transformer.toRpcResult(input.getResult(), type);
-                } else {
-                    return new DefaultDOMRpcResult(input.getErrors());
+        final ListenableFuture<DOMRpcResult> transformed =
+            Futures.transform(delegateFutureWithPureResult, new Function<RpcResult<NetconfMessage>, DOMRpcResult>() {
+                @Override
+                public DOMRpcResult apply(final RpcResult<NetconfMessage> input) {
+                    if (input.isSuccessful()) {
+                        return transformer.toRpcResult(input.getResult(), type);
+                    } else {
+                        return new DefaultDOMRpcResult(input.getErrors());
+                    }
                 }
-            }
-        });
+            });
 
         return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
             @Nullable
             @Override
-            public DOMRpcException apply(@Nullable final Exception e) {
-                return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s", type);
+            public DOMRpcException apply(@Nullable final Exception exception) {
+                return new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type);
             }
         });
     }
 
     @Nonnull
     @Override
-    public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+    public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+            @Nonnull final T listener) {
 
         listener.onRpcAvailable(availableRpcs);
 
index a6ffe7aeb18823c68f64db619a5ac33bd427f828..5d42d3de4df17b8830ea89820285312720a72147 100644 (file)
@@ -50,14 +50,18 @@ public final class NetconfDeviceSalFacade implements AutoCloseable, RemoteDevice
 
     @Override
     public synchronized void onDeviceConnected(final SchemaContext schemaContext,
-                                               final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) {
+                                               final NetconfSessionPreferences netconfSessionPreferences,
+                                               final DOMRpcService deviceRpc) {
 
-        final DOMDataBroker domBroker = new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences);
+        final DOMDataBroker domBroker =
+                new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences);
 
         final NetconfDeviceNotificationService notificationService = new NetconfDeviceNotificationService();
 
-        salProvider.getMountInstance().onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService);
-        salProvider.getTopologyDatastoreAdapter().updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
+        salProvider.getMountInstance()
+                .onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService);
+        salProvider.getTopologyDatastoreAdapter()
+                .updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
     }
 
     @Override
@@ -80,6 +84,7 @@ public final class NetconfDeviceSalFacade implements AutoCloseable, RemoteDevice
         closeGracefully(salProvider);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     private void closeGracefully(final AutoCloseable resource) {
         if (resource != null) {
             try {
index e9d74c0637beb8b1bd9ff0eb2bfd19770a60253b..4ad1dde5fefac226d5ee04bb4853ec132edf51c5 100644 (file)
@@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory;
 
 public class NetconfDeviceSalProvider implements AutoCloseable {
 
-    private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
+    private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
 
     private final RemoteDeviceId id;
     private final MountInstance mountInstance;
@@ -39,8 +39,9 @@ public class NetconfDeviceSalProvider implements AutoCloseable {
 
     private final TransactionChainListener transactionChainListener =  new TransactionChainListener() {
         @Override
-        public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
-            logger.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
+        public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
+                                             final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+            LOG.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
             chain.close();
             resetTransactionChainForAdapaters();
             throw new IllegalStateException(id + "  TransactionChain(" + chain + ") not committed correctly", cause);
@@ -48,7 +49,7 @@ public class NetconfDeviceSalProvider implements AutoCloseable {
 
         @Override
         public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
-            logger.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
+            LOG.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
         }
     };
 
@@ -85,7 +86,7 @@ public class NetconfDeviceSalProvider implements AutoCloseable {
 
         topologyDatastoreAdapter.setTxChain(txChain);
 
-        logger.trace("{}: Resetting TransactionChain {}", id, txChain);
+        LOG.trace("{}: Resetting TransactionChain {}", id, txChain);
 
     }
 
@@ -119,7 +120,8 @@ public class NetconfDeviceSalProvider implements AutoCloseable {
             Preconditions.checkNotNull(mountService, "Closed");
             Preconditions.checkState(topologyRegistration == null, "Already initialized");
 
-            final DOMMountPointService.DOMMountPointBuilder mountBuilder = mountService.createMountPoint(id.getTopologyPath());
+            final DOMMountPointService.DOMMountPointBuilder mountBuilder =
+                    mountService.createMountPoint(id.getTopologyPath());
             mountBuilder.addInitialSchemaContext(initialCtx);
 
             mountBuilder.addService(DOMDataBroker.class, broker);
@@ -128,13 +130,14 @@ public class NetconfDeviceSalProvider implements AutoCloseable {
             this.notificationService = notificationService;
 
             topologyRegistration = mountBuilder.register();
-            logger.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration);
+            LOG.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration);
 
         }
 
+        @SuppressWarnings("checkstyle:IllegalCatch")
         public synchronized void onTopologyDeviceDisconnected() {
-            if(topologyRegistration == null) {
-                logger.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id);
+            if (topologyRegistration == null) {
+                LOG.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id);
                 return;
             }
 
@@ -142,9 +145,9 @@ public class NetconfDeviceSalProvider implements AutoCloseable {
                 topologyRegistration.close();
             } catch (final Exception e) {
                 // Only log and ignore
-                logger.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e);
+                LOG.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e);
             } finally {
-                logger.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration);
+                LOG.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration);
                 topologyRegistration = null;
             }
         }
@@ -155,7 +158,8 @@ public class NetconfDeviceSalProvider implements AutoCloseable {
         }
 
         public synchronized void publish(final DOMNotification domNotification) {
-            Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}", domNotification);
+            Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}",
+                    domNotification);
             notificationService.publishNotification(domNotification);
         }
     }
index 4d67bdd662d569729f3f57a586ffe031efaf4754..8d068bb5487a40ac5994406ec218c5b273c44179 100644 (file)
@@ -57,9 +57,10 @@ import org.slf4j.LoggerFactory;
 public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class);
-    public static final Function<Entry<QName, FailureReason>, UnavailableCapability> UNAVAILABLE_CAPABILITY_TRANSFORMER = input -> new UnavailableCapabilityBuilder()
-            .setCapability(input.getKey().toString())
-            .setFailureReason(input.getValue()).build();
+    public static final Function<Entry<QName, FailureReason>, UnavailableCapability>
+            UNAVAILABLE_CAPABILITY_TRANSFORMER =
+                input -> new UnavailableCapabilityBuilder()
+                        .setCapability(input.getKey().toString()).setFailureReason(input.getValue()).build();
 
     private final RemoteDeviceId id;
     private BindingTransactionChain txChain;
@@ -73,7 +74,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
         this.txChain = Preconditions.checkNotNull(txChain);
 
         this.networkTopologyPath = InstanceIdentifier.builder(NetworkTopology.class).build();
-        this.topologyListPath = networkTopologyPath.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
+        this.topologyListPath = networkTopologyPath
+                .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
 
         initDeviceData();
     }
@@ -84,7 +86,7 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
         createNetworkTopologyIfNotPresent(writeTx);
 
         final InstanceIdentifier<Node> path = id.getTopologyBindingPath();
-        NodeBuilder nodeBuilder = getNodeIdBuilder(id);
+        final NodeBuilder nodeBuilder = getNodeIdBuilder(id);
         NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder();
         netconfNodeBuilder.setConnectionStatus(ConnectionStatus.Connecting);
         netconfNodeBuilder.setHost(id.getHost());
@@ -117,7 +119,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
         LOG.trace(
                 "{}: Update device state transaction {} merging operational data started.",
                 id, writeTx.getIdentifier());
-        writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+        writeTx.put(LogicalDatastoreType.OPERATIONAL,
+                id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
         LOG.trace(
                 "{}: Update device state transaction {} merging operational data ended.",
                 id, writeTx.getIdentifier());
@@ -125,14 +128,16 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
         commitTransaction(writeTx, "update");
     }
 
-    public void updateClusteredDeviceData(final boolean up, final String masterAddress, final NetconfDeviceCapabilities capabilities) {
+    public void updateClusteredDeviceData(final boolean up, final String masterAddress,
+                                          final NetconfDeviceCapabilities capabilities) {
         final NetconfNode data = buildDataForNetconfClusteredNode(up, masterAddress, capabilities);
 
         final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
         LOG.trace(
                 "{}: Update device state transaction {} merging operational data started.",
                 id, writeTx.getIdentifier());
-        writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+        writeTx.put(LogicalDatastoreType.OPERATIONAL,
+                id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
         LOG.trace(
                 "{}: Update device state transaction {} merging operational data ended.",
                 id, writeTx.getIdentifier());
@@ -143,13 +148,15 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
     public void setDeviceAsFailed(final Throwable throwable) {
         String reason = (throwable != null && throwable.getMessage() != null) ? throwable.getMessage() : UNKNOWN_REASON;
 
-        final NetconfNode data = new NetconfNodeBuilder().setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build();
+        final NetconfNode data = new NetconfNodeBuilder()
+                .setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build();
 
         final WriteTransaction writeTx = txChain.newWriteOnlyTransaction();
         LOG.trace(
                 "{}: Setting device state as failed {} putting operational data started.",
                 id, writeTx.getIdentifier());
-        writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
+        writeTx.put(LogicalDatastoreType.OPERATIONAL,
+                id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true);
         LOG.trace(
                 "{}: Setting device state as failed {} putting operational data ended.",
                 id, writeTx.getIdentifier());
@@ -165,8 +172,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
         final AvailableCapabilitiesBuilder avCapabalitiesBuilder = new AvailableCapabilitiesBuilder();
         avCapabalitiesBuilder.setAvailableCapability(capabilityList);
 
-        final UnavailableCapabilities unavailableCapabilities =
-                new UnavailableCapabilitiesBuilder().setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet())
+        final UnavailableCapabilities unavailableCapabilities = new UnavailableCapabilitiesBuilder()
+                .setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet())
                         .transform(UNAVAILABLE_CAPABILITY_TRANSFORMER).toList()).build();
 
         final NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder()
@@ -179,7 +186,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
         return netconfNodeBuilder.build();
     }
 
-    private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress, final NetconfDeviceCapabilities capabilities) {
+    private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress,
+                                                         final NetconfDeviceCapabilities capabilities) {
         List<AvailableCapability> capabilityList = new ArrayList<>();
         capabilityList.addAll(capabilities.getNonModuleBasedCapabilities());
         capabilityList.addAll(capabilities.getResolvedCapabilities());
@@ -229,7 +237,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
                 NetworkTopology.QNAME, writeTx.getIdentifier());
         writeTx.merge(LogicalDatastoreType.OPERATIONAL, networkTopologyPath, networkTopology);
 
-        final Topology topology = new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
+        final Topology topology =
+                new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build();
         LOG.trace("{}: Merging {} container to ensure its presence", id,
                 Topology.QNAME, writeTx.getIdentifier());
         writeTx.merge(LogicalDatastoreType.OPERATIONAL, topologyListPath, topology);
@@ -248,10 +257,11 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
+            public void onFailure(final Throwable throwable) {
                 LOG.error("{}: Transaction({}) {} FAILED!", id, txType,
-                        transaction.getIdentifier(), t);
-                throw new IllegalStateException(id + "  Transaction(" + txType + ") not committed correctly", t);
+                        transaction.getIdentifier(), throwable);
+                throw new IllegalStateException(
+                        id + "  Transaction(" + txType + ") not committed correctly", throwable);
             }
         });
 
index 7448367e0ce969a9e832653fb0b13a64e52bd587..4856e1178df76f2231f8a923c00ced57f68dfd28 100644 (file)
@@ -42,7 +42,8 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService {
     private final SchemalessMessageTransformer schemalessTransformer;
     private final RemoteDeviceId deviceId;
 
-    public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId, final RemoteDeviceCommunicator<NetconfMessage> listener,
+    public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId,
+                                      final RemoteDeviceCommunicator<NetconfMessage> listener,
                                       final BaseRpcSchemalessTransformer baseRpcTransformer,
                                       final SchemalessMessageTransformer messageTransformer) {
         this.deviceId = deviceId;
@@ -61,30 +62,34 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService {
         } else if (isBaseRpc(type)) {
             transformer = baseRpcTransformer;
         } else {
-            return Futures.immediateFailedCheckedFuture(new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type));
+            return Futures.immediateFailedCheckedFuture(
+                    new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type));
         }
         return handleRpc(type, input, transformer);
     }
 
-    private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(@Nonnull final SchemaPath type,
-                                                                   @Nullable final NormalizedNode<?, ?> input,
-                                                                   final MessageTransformer<NetconfMessage> transformer) {
+    private CheckedFuture<DOMRpcResult, DOMRpcException> handleRpc(
+            @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input,
+            final MessageTransformer<NetconfMessage> transformer) {
         final NetconfMessage netconfMessage = transformer.toRpcRequest(type, input);
-        final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture = listener.sendRequest(netconfMessage, type.getLastComponent());
+        final ListenableFuture<RpcResult<NetconfMessage>> rpcResultListenableFuture =
+                listener.sendRequest(netconfMessage, type.getLastComponent());
 
-        final ListenableFuture<DOMRpcResult> transformed = Futures.transform(rpcResultListenableFuture, (Function<RpcResult<NetconfMessage>, DOMRpcResult>) input1 -> {
-            if (input1.isSuccessful()) {
-                return transformer.toRpcResult(input1.getResult(), type);
-            } else {
-                return new DefaultDOMRpcResult(input1.getErrors());
-            }
-        });
+        final ListenableFuture<DOMRpcResult> transformed =
+            Futures.transform(rpcResultListenableFuture, (Function<RpcResult<NetconfMessage>, DOMRpcResult>) input1 -> {
+                if (input1.isSuccessful()) {
+                    return transformer.toRpcResult(input1.getResult(), type);
+                } else {
+                    return new DefaultDOMRpcResult(input1.getErrors());
+                }
+            });
 
         return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
             @Nullable
             @Override
-            public DOMRpcException apply(@Nullable final Exception e) {
-                return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s on device %s", type, deviceId);
+            public DOMRpcException apply(@Nullable final Exception exception) {
+                return new DOMRpcImplementationNotAvailableException(
+                        exception, "Unable to invoke rpc %s on device %s", type, deviceId);
             }
         });
     }
@@ -96,7 +101,8 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService {
 
     @Nonnull
     @Override
-    public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
+    public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
+            @Nonnull final T listener) {
         throw new UnsupportedOperationException("Not available for netconf 1.0");
     }
 
index d0f89bc9b4910520baf01725160fe1965f3b13ec..14926d99f20d0e45b494c572970ecd04ab924b13 100644 (file)
@@ -72,7 +72,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
 
     @Override
     public synchronized boolean cancel() {
-        if(isFinished()) {
+        if (isFinished()) {
             return false;
         }
         listeners.forEach(listener -> listener.onTransactionCancelled(this));
@@ -91,37 +91,46 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
     }
 
     @Override
-    public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+    public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                                 final NormalizedNode<?, ?> data) {
         checkEditable(store);
 
-        // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
-        if(containsOnlyNonVisibleData(path, data)) {
+        // Trying to write only mixin nodes (not visible when serialized).
+        // Ignoring. Some devices cannot handle empty edit-config rpc
+        if (containsOnlyNonVisibleData(path, data)) {
             LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
             return;
         }
 
-        final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.of(ModifyAction.REPLACE), path);
+        final DataContainerChild<?, ?> editStructure =
+                netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
+                        Optional.of(ModifyAction.REPLACE), path);
         editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put");
     }
 
     @Override
-    public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+    public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                                   final NormalizedNode<?, ?> data) {
         checkEditable(store);
 
-        // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
+        // Trying to write only mixin nodes (not visible when serialized).
+        // Ignoring. Some devices cannot handle empty edit-config rpc
         if (containsOnlyNonVisibleData(path, data)) {
             LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
             return;
         }
 
-        final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.<ModifyAction>absent(), path);
+        final DataContainerChild<?, ?> editStructure =
+                netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data),
+                        Optional.<ModifyAction>absent(), path);
         editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
     }
 
     /**
-     * Check whether the data to be written consists only from mixins
+     * Check whether the data to be written consists only from mixins.
      */
-    private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+    private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path,
+                                                      final NormalizedNode<?, ?> data) {
         // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
         // any other mixin nodes are contained by a "regular" node thus visible when serialized
         return path.getPathArguments().size() == 1 && data instanceof MixinNode;
@@ -130,8 +139,11 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
     @Override
     public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
         checkEditable(store);
-        final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(), Optional.of(ModifyAction.DELETE), path);
-        editConfig(path, Optional.<NormalizedNode<?, ?>>absent(), editStructure, Optional.of(ModifyAction.NONE), "delete");
+        final DataContainerChild<?, ?> editStructure =
+                netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(),
+                        Optional.of(ModifyAction.DELETE), path);
+        editConfig(path, Optional.<NormalizedNode<?, ?>>absent(),
+                editStructure, Optional.of(ModifyAction.NONE), "delete");
     }
 
     @Override
@@ -146,14 +158,16 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
                 if (result != null && result.isSuccessful()) {
                     listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this));
                 } else {
-                    final TransactionCommitFailedException cause = new TransactionCommitFailedException("Transaction failed", result.getErrors().toArray(new RpcError[result.getErrors().size()]));
+                    final TransactionCommitFailedException cause =
+                            new TransactionCommitFailedException("Transaction failed",
+                                    result.getErrors().toArray(new RpcError[result.getErrors().size()]));
                     listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause));
                 }
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, t));
+            public void onFailure(final Throwable throwable) {
+                listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable));
             }
         });
         return result;
@@ -163,10 +177,13 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
 
     private void checkEditable(final LogicalDatastoreType store) {
         checkNotFinished();
-        Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can edit only configuration data, not %s", store);
+        Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION,
+                "Can edit only configuration data, not %s", store);
     }
 
-    protected abstract void editConfig(final YangInstanceIdentifier path, final Optional<NormalizedNode<?, ?>> data, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final String operation);
+    protected abstract void editConfig(YangInstanceIdentifier path, Optional<NormalizedNode<?, ?>> data,
+                                       DataContainerChild<?, ?> editStructure,
+                                       Optional<ModifyAction> defaultOperation, String operation);
 
     protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
         final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
@@ -175,7 +192,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
             @Override
             public void onSuccess(final List<DOMRpcResult> domRpcResults) {
                 domRpcResults.forEach(domRpcResult -> {
-                    if(!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
+                    if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
                         final NetconfDocumentedException exception =
                                 new NetconfDocumentedException(id + ":RPC during tx failed",
                                         DocumentedException.ErrorType.APPLICATION,
@@ -185,7 +202,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
                     }
                 });
 
-                if(!transformed.isDone()) {
+                if (!transformed.isDone()) {
                     transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
                 }
             }
index a420c3cdffce48f885db3d1c5b65a771b6538839..b974d9fc9ae6f6a8a56d798ee61441093f30ef3c 100644 (file)
@@ -62,22 +62,28 @@ public final class ReadOnlyTx implements DOMDataReadOnlyTransaction {
     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(
             final LogicalDatastoreType store, final YangInstanceIdentifier path) {
         switch (store) {
-        case CONFIGURATION: {
-            return readConfigurationData(path);
-        }
-        case OPERATIONAL: {
-            return readOperationalData(path);
-        }
+            case CONFIGURATION: {
+                return readConfigurationData(path);
+            }
+            case OPERATIONAL: {
+                return readOperationalData(path);
+            }
+            default: {
+                LOG.info("Unknown datastore type: {}.", store);
+            }
         }
 
-        throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
+        throw new IllegalArgumentException(String.format(
+                "%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
     }
 
     @Override
-    public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+    public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+                                                              final YangInstanceIdentifier path) {
         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> data = read(store, path);
         final ListenableFuture<Boolean> result =
-                Futures.transform(data, (Optional<NormalizedNode<?, ?>> a) -> a != null && a.isPresent());
+                Futures.transform(data, (Optional<NormalizedNode<?, ?>> optionalNode) ->
+                        optionalNode != null && optionalNode.isPresent());
         return MappingCheckedFuture.create(result, ReadFailedException.MAPPER);
     }
 
index b063cba63ac8603861b9a387ff79dd5a42b43bf6..c6012bbf2183a5c71e82df7e36bb7eeb66248a28 100644 (file)
@@ -38,12 +38,14 @@ public class ReadWriteTx implements DOMDataReadWriteTransaction {
     }
 
     @Override
-    public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+    public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                    final NormalizedNode<?, ?> data) {
         delegateWriteTx.put(store, path, data);
     }
 
     @Override
-    public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+    public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                      final NormalizedNode<?, ?> data) {
         delegateWriteTx.merge(store, path, data);
     }
 
index 7dbc835a3f9720c5d191dcf3932f4c08d04f318d..2547d7013c0554a273d57518527e615fa1f57210 100644 (file)
@@ -104,6 +104,7 @@ public class TxChain implements DOMTransactionChain, TxListener {
         currentTransaction = null;
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     private void removePendingTx(final AbstractWriteTx transaction) {
         try {
             pendingTransactions.remove(transaction).close();
index 2729444311417022e777eacb78fe639d046b2b5f..b5198ec836a2aa7b21c26ddd8ecd9731452a0dae 100644 (file)
@@ -15,7 +15,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Tx implementation for netconf devices that support only candidate datastore and writable running
+ * Tx implementation for netconf devices that support only candidate datastore and writable running.
  * The sequence goes exactly as with only candidate supported, with one addition:
  * <ul>
  *     <li>Running datastore is locked as the first thing and this lock has to succeed</li>
@@ -25,7 +25,8 @@ public class WriteCandidateRunningTx extends WriteCandidateTx {
 
     private static final Logger LOG  = LoggerFactory.getLogger(WriteCandidateRunningTx.class);
 
-    public WriteCandidateRunningTx(final RemoteDeviceId id, final NetconfBaseOps netOps, final boolean rollbackSupport) {
+    public WriteCandidateRunningTx(final RemoteDeviceId id, final NetconfBaseOps netOps,
+                                   final boolean rollbackSupport) {
         super(id, netOps, rollbackSupport);
     }
 
@@ -46,7 +47,8 @@ public class WriteCandidateRunningTx extends WriteCandidateTx {
     }
 
     /**
-     * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+     * This has to be non blocking since it is called from a callback on commit
+     * and its netty threadpool that is really sensitive to blocking calls.
      */
     private void unlockRunning() {
         netOps.unlockRunning(new NetconfRpcFutureCallback("Unlock running", id));
index e2cedbc2a47f3737c86f3e1c3188e592bd2e8678..2038d10ee4484ed283af39c1515af6018f100879 100644 (file)
@@ -31,7 +31,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Tx implementation for netconf devices that support only candidate datastore and no writable running
+ * Tx implementation for netconf devices that support only candidate datastore and no writable running.
  * The sequence goes as:
  * <ol>
  *   <li>Lock candidate datastore on tx construction
@@ -44,7 +44,8 @@ import org.slf4j.LoggerFactory;
  *   </li>
  *   <li>Edit-config in candidate N times
  *     <ul>
- *       <li>If any issue occurs during edit, datastore is discarded using discard-changes rpc, unlocked and an exception is thrown async</li>
+ *       <li>If any issue occurs during edit,
+ *       datastore is discarded using discard-changes rpc, unlocked and an exception is thrown async</li>
  *     </ul>
  *   </li>
  *   <li>Commit and Unlock candidate datastore async</li>
@@ -78,8 +79,8 @@ public class WriteCandidateTx extends AbstractWriteTx {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.warn("Lock candidate operation failed. {}", t);
+            public void onFailure(final Throwable throwable) {
+                LOG.warn("Lock candidate operation failed. {}", throwable);
                 discardChanges();
             }
         };
@@ -94,24 +95,28 @@ public class WriteCandidateTx extends AbstractWriteTx {
 
     @Override
     public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
-        final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
-            @Override
-            public Void apply(final RpcResult<TransactionStatus> input) {
-                Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(), "Submit failed with errors: %s", input.getErrors());
-                return null;
-            }
-        });
+        final ListenableFuture<Void> commitFutureAsVoid = Futures.transform(commit(),
+                new Function<RpcResult<TransactionStatus>, Void>() {
+                    @Override
+                    public Void apply(final RpcResult<TransactionStatus> input) {
+                        Preconditions.checkArgument(input.isSuccessful() && input.getErrors().isEmpty(),
+                                "Submit failed with errors: %s", input.getErrors());
+                        return null;
+                    }
+                });
 
         return Futures.makeChecked(commitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
             @Override
             public TransactionCommitFailedException apply(final Exception input) {
-                return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
+                return new TransactionCommitFailedException(
+                        "Submit of transaction " + getIdentifier() + " failed", input);
             }
         });
     }
 
     /**
-     * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+     * This has to be non blocking since it is called from a callback on commit
+     * and its netty threadpool that is really sensitive to blocking calls.
      */
     private void discardChanges() {
         netOps.discardChanges(new NetconfRpcFutureCallback("Discarding candidate", id));
@@ -129,7 +134,7 @@ public class WriteCandidateTx extends AbstractWriteTx {
             }
 
             @Override
-            public void onFailure(final Throwable t) {
+            public void onFailure(final Throwable throwable) {
                 // TODO If lock is cause of this failure cleanup will issue warning log
                 // cleanup is trying to do unlock, but this will fail
                 cleanup();
@@ -161,7 +166,8 @@ public class WriteCandidateTx extends AbstractWriteTx {
     }
 
     /**
-     * This has to be non blocking since it is called from a callback on commit and its netty threadpool that is really sensitive to blocking calls
+     * This has to be non blocking since it is called from a callback on commit
+     * and its netty threadpool that is really sensitive to blocking calls.
      */
     private void unlock() {
         netOps.unlockCandidate(new NetconfRpcFutureCallback("Unlock candidate", id));
index 63cbd5c7775f1fab635bfd482d940edc9ddd0f96..01b82c9e8b7e77376cf59b391975b81651407751 100644 (file)
@@ -30,7 +30,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Tx implementation for netconf devices that support only writable-running with no candidate
+ * Tx implementation for netconf devices that support only writable-running with no candidate.
  * The sequence goes as:
  * <ol>
  *   <li>Lock running datastore on tx construction
@@ -72,17 +72,19 @@ public class WriteRunningTx extends AbstractWriteTx {
 
     @Override
     public synchronized CheckedFuture<Void, TransactionCommitFailedException> submit() {
-        final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
-            @Override
-            public Void apply(final RpcResult<TransactionStatus> input) {
-                return null;
-            }
-        });
+        final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(),
+                new Function<RpcResult<TransactionStatus>, Void>() {
+                    @Override
+                    public Void apply(final RpcResult<TransactionStatus> input) {
+                        return null;
+                    }
+                });
 
         return Futures.makeChecked(commmitFutureAsVoid, new Function<Exception, TransactionCommitFailedException>() {
             @Override
             public TransactionCommitFailedException apply(final Exception input) {
-                return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed", input);
+                return new TransactionCommitFailedException("Submit of transaction " + getIdentifier() + " failed",
+                        input);
             }
         });
     }
@@ -123,7 +125,8 @@ public class WriteRunningTx extends AbstractWriteTx {
                                                        final boolean rollbackSupport) {
             final NetconfRpcFutureCallback editConfigCallback = new NetconfRpcFutureCallback("Edit running", id);
             if (defaultOperation.isPresent()) {
-                return netOps.editConfigRunning(editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport);
+                return netOps.editConfigRunning(
+                        editConfigCallback, editStructure, defaultOperation.get(), rollbackSupport);
             } else {
                 return netOps.editConfigRunning(editConfigCallback, editStructure, rollbackSupport);
             }
index 9146ff76af8cba2001fdd5873d80647719d32ce4..6bb12e7e4b19e083bf6aa6c0748f7c36375650c2 100644 (file)
@@ -55,8 +55,8 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
     private static final ExceptionMapper<SchemaSourceException> MAPPER = new ExceptionMapper<SchemaSourceException>(
             "schemaDownload", SchemaSourceException.class) {
         @Override
-        protected SchemaSourceException newWithCause(final String s, final Throwable throwable) {
-            return new SchemaSourceException(s, throwable);
+        protected SchemaSourceException newWithCause(final String message, final Throwable throwable) {
+            return new SchemaSourceException(message, throwable);
         }
     };
 
@@ -68,23 +68,31 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
         this.rpc = Preconditions.checkNotNull(rpc);
     }
 
-    private static final NodeIdentifier FORMAT_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "format").intern());
-    private static final NodeIdentifier GET_SCHEMA_PATHARG = new NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME);
-    private static final NodeIdentifier IDENTIFIER_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "identifier").intern());
-    private static final NodeIdentifier VERSION_PATHARG = new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version").intern());
+    private static final NodeIdentifier FORMAT_PATHARG =
+            new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "format").intern());
+    private static final NodeIdentifier GET_SCHEMA_PATHARG =
+            new NodeIdentifier(NetconfMessageTransformUtil.GET_SCHEMA_QNAME);
+    private static final NodeIdentifier IDENTIFIER_PATHARG =
+            new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "identifier").intern());
+    private static final NodeIdentifier VERSION_PATHARG =
+            new NodeIdentifier(QName.create(NetconfMessageTransformUtil.GET_SCHEMA_QNAME, "version").intern());
 
-    private static final LeafNode<?> FORMAT_LEAF = Builders.leafBuilder().withNodeIdentifier(FORMAT_PATHARG).withValue(Yang.QNAME).build();
+    private static final LeafNode<?> FORMAT_LEAF =
+            Builders.leafBuilder().withNodeIdentifier(FORMAT_PATHARG).withValue(Yang.QNAME).build();
 
-    private static final QName NETCONF_DATA = QName.create(GET_SCHEMA_QNAME, NETCONF_DATA_QNAME.getLocalName()).intern();
+    private static final QName NETCONF_DATA =
+            QName.create(GET_SCHEMA_QNAME, NETCONF_DATA_QNAME.getLocalName()).intern();
     private static final NodeIdentifier NETCONF_DATA_PATHARG = toId(NETCONF_DATA);
 
     public static ContainerNode createGetSchemaRequest(final String moduleName, final Optional<String> revision) {
-        final LeafNode<?> identifier = Builders.leafBuilder().withNodeIdentifier(IDENTIFIER_PATHARG).withValue(moduleName).build();
+        final LeafNode<?> identifier =
+                Builders.leafBuilder().withNodeIdentifier(IDENTIFIER_PATHARG).withValue(moduleName).build();
         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> builder = Builders.containerBuilder()
                 .withNodeIdentifier(GET_SCHEMA_PATHARG).withChild(identifier).withChild(FORMAT_LEAF);
 
         if (revision.isPresent()) {
-            builder.withChild(Builders.leafBuilder().withNodeIdentifier(VERSION_PATHARG).withValue(revision.get()).build());
+            builder.withChild(Builders.leafBuilder()
+                    .withNodeIdentifier(VERSION_PATHARG).withValue(revision.get()).build());
         }
 
         return builder.build();
@@ -95,7 +103,8 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
             return Optional.absent();
         }
 
-        final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child = ((ContainerNode) result).getChild(NETCONF_DATA_PATHARG);
+        final Optional<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> child =
+                ((ContainerNode) result).getChild(NETCONF_DATA_PATHARG);
 
         Preconditions.checkState(child.isPresent() && child.get() instanceof AnyXmlNode,
                 "%s Unexpected response to get-schema, expected response with one child %s, but was %s", id,
@@ -109,7 +118,8 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
     }
 
     @Override
-    public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(final SourceIdentifier sourceIdentifier) {
+    public CheckedFuture<YangTextSchemaSource, SchemaSourceException> getSource(
+            final SourceIdentifier sourceIdentifier) {
         final String moduleName = sourceIdentifier.getName();
 
         // If formatted revision is SourceIdentifier.NOT_PRESENT_FORMATTED_REVISION, we have to omit it from request
@@ -125,13 +135,14 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
                 rpc.invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME), getSchemaRequest),
                 new ResultToYangSourceTransformer(id, sourceIdentifier, moduleName, revision));
 
-        final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked = Futures.makeChecked(transformed, MAPPER);
+        final CheckedFuture<YangTextSchemaSource, SchemaSourceException> checked =
+                Futures.makeChecked(transformed, MAPPER);
 
         return checked;
     }
 
     /**
-     * Transform composite node to string schema representation and then to ASTSchemaSource
+     * Transform composite node to string schema representation and then to ASTSchemaSource.
      */
     private static final class ResultToYangSourceTransformer implements
             Function<DOMRpcResult, YangTextSchemaSource> {
@@ -141,7 +152,7 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
         private final String moduleName;
         private final Optional<String> revision;
 
-        public ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
+        ResultToYangSourceTransformer(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
                 final String moduleName, final Optional<String> revision) {
             this.id = id;
             this.sourceIdentifier = sourceIdentifier;
@@ -157,7 +168,8 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
                 final Optional<String> schemaString = getSchemaFromRpc(id, input.getResult());
 
                 Preconditions.checkState(schemaString.isPresent(),
-                        "%s: Unexpected response to get-schema, schema not present in message for: %s", id, sourceIdentifier);
+                        "%s: Unexpected response to get-schema, schema not present in message for: %s",
+                        id, sourceIdentifier);
 
                 LOG.debug("{}: YANG Schema successfully retrieved for {}:{}",
                         id, moduleName, revision);
@@ -179,8 +191,9 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource
         private final RemoteDeviceId id;
         private final Optional<String> schemaString;
 
-        public NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sId, final Optional<String> schemaString) {
-            super(sId);
+        NetconfYangTextSchemaSource(final RemoteDeviceId id, final SourceIdentifier sourceIdentifier,
+                                           final Optional<String> schemaString) {
+            super(sourceIdentifier);
             this.id = id;
             this.schemaString = schemaString;
         }
index 0f271261a9d2f0c4b960a7a903f567b4809d547d..33af8ec298be82279c80e9d13b3170eb0a16eaf1 100644 (file)
@@ -25,7 +25,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Provides YANG schema sources from yang library
+ * Provides YANG schema sources from yang library.
  */
 public final class YangLibrarySchemaYangSourceProvider implements SchemaSourceProvider<YangTextSchemaSource> {
 
@@ -48,19 +48,21 @@ public final class YangLibrarySchemaYangSourceProvider implements SchemaSourcePr
         return download(sourceIdentifier);
     }
 
-    private CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> download(final SourceIdentifier sId) {
-        final URL url = availableSources.get(sId);
-        try(final InputStream in = url.openStream()) {
+    private CheckedFuture<? extends YangTextSchemaSource, SchemaSourceException> download(
+            final SourceIdentifier sourceIdentifier) {
+        final URL url = availableSources.get(sourceIdentifier);
+        try (InputStream in = url.openStream()) {
             final String schemaContent = new String(ByteStreams.toByteArray(in));
             final NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource yangSource =
-                    new NetconfRemoteSchemaYangSourceProvider.
-                            NetconfYangTextSchemaSource(id, sId, Optional.of(schemaContent));
-            LOG.debug("Source {} downloaded from a yang library's url {}", sId, url);
+                    new NetconfRemoteSchemaYangSourceProvider
+                            .NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent));
+            LOG.debug("Source {} downloaded from a yang library's url {}", sourceIdentifier, url);
             return Futures.immediateCheckedFuture(yangSource);
         } catch (IOException e) {
-            LOG.warn("Unable to download source {} from a yang library's url {}", sId, url, e);
+            LOG.warn("Unable to download source {} from a yang library's url {}", sourceIdentifier, url, e);
             return Futures.immediateFailedCheckedFuture(
-                    new SchemaSourceException("Unable to download remote schema for " + sId + " from " + url, e));
+                    new SchemaSourceException(
+                            "Unable to download remote schema for " + sourceIdentifier + " from " + url, e));
         }
     }
 }
index 9c97d7ab4d65a27c00a865784b46737972c73488..cbf1f03a25abae4bcd0928287620b9d200cf869f 100644 (file)
@@ -35,12 +35,12 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 /**
- * Transforms base netconf rpcs
+ * Transforms base netconf RPCs.
  */
 public class BaseRpcSchemalessTransformer implements MessageTransformer<NetconfMessage> {
 
-    private static final Map<QName, RpcDefinition> mappedRpcs = BaseSchema.BASE_NETCONF_CTX.getMappedRpcs();
-    private static final SchemaContext schemaContext = BaseSchema.BASE_NETCONF_CTX.getSchemaContext();
+    private static final Map<QName, RpcDefinition> MAPPED_RPCS = BaseSchema.BASE_NETCONF_CTX.getMappedRpcs();
+    private static final SchemaContext SCHEMA_CONTEXT = BaseSchema.BASE_NETCONF_CTX.getSchemaContext();
 
     private final MessageCounter counter;
 
@@ -58,9 +58,10 @@ public class BaseRpcSchemalessTransformer implements MessageTransformer<NetconfM
         // In case no input for rpc is defined, we can simply construct the payload here
         final QName rpcQName = rpc.getLastComponent();
 
-        Preconditions.checkNotNull(mappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, mappedRpcs.keySet());
+        Preconditions.checkNotNull(MAPPED_RPCS.get(rpcQName), "Unknown rpc %s, available rpcs: %s",
+                rpcQName, MAPPED_RPCS.keySet());
         final DOMResult domResult = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
-        if (mappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
+        if (MAPPED_RPCS.get(rpcQName).getInput().getChildNodes().isEmpty()) {
             return new NetconfMessage(domResult.getNode().getOwnerDocument());
         }
 
@@ -73,7 +74,8 @@ public class BaseRpcSchemalessTransformer implements MessageTransformer<NetconfM
         final DOMResult result = domResult;
 
         try {
-            NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, inputPath, schemaContext);
+            NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result,
+                    inputPath, SCHEMA_CONTEXT);
         } catch (final XMLStreamException | IOException | IllegalStateException e) {
             throw new IllegalStateException("Unable to serialize " + inputPath, e);
         }
@@ -92,12 +94,14 @@ public class BaseRpcSchemalessTransformer implements MessageTransformer<NetconfM
             final Document data = XmlUtil.newDocument();
             data.appendChild(data.importNode(xmlData, true));
             AnyXmlNode xmlDataNode = Builders.anyXmlBuilder()
-                    .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
+                    .withNodeIdentifier(new YangInstanceIdentifier
+                            .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
                     .withValue(new DOMSource(data))
                     .build();
 
             normalizedNode = Builders.containerBuilder()
-                    .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+                    .withNodeIdentifier(new YangInstanceIdentifier
+                            .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
                     .withChild(xmlDataNode).build();
         } else {
             //other base rpcs don't have any output, we can simply construct the payload here
index 038c40461cbc39d6c3cef2f39ee224320cddc7b2..13331fbcadeff4ff3305f70cdc94957f570a8ede 100644 (file)
@@ -17,20 +17,27 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
+@SuppressWarnings("checkstyle:IllegalCatch")
 public enum BaseSchema {
 
     BASE_NETCONF_CTX(
             Lists.newArrayList(
-                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
-                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
+                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+                            .base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
+                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+                            .monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance()
             )
     ),
     BASE_NETCONF_CTX_WITH_NOTIFICATIONS(
             Lists.newArrayList(
-                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
-                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
-                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
-                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()
+                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+                            .monitoring.extension.rev131210.$YangModuleInfoImpl.getInstance(),
+                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+                            .notification._1._0.rev080714.$YangModuleInfoImpl.getInstance(),
+                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf
+                            .base._1._0.rev110601.$YangModuleInfoImpl.getInstance(),
+                    org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf
+                            .notifications.rev120206.$YangModuleInfoImpl.getInstance()
             )
     );
 
index 52f707645377842f04d618be4082567c890bb7ee..4367d8cf0ab097d09298af911f190104f0d6d303 100644 (file)
@@ -59,7 +59,8 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
 
     private static final Function<SchemaNode, QName> QNAME_FUNCTION = rpcDefinition -> rpcDefinition.getQName();
 
-    private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION = notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
+    private static final Function<SchemaNode, QName> QNAME_NOREV_FUNCTION =
+        notification -> QNAME_FUNCTION.apply(notification).withoutRevision();
 
     private final SchemaContext schemaContext;
     private final BaseSchema baseSchema;
@@ -72,10 +73,12 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
         this(schemaContext, strictParsing, BaseSchema.BASE_NETCONF_CTX);
     }
 
-    public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing, final BaseSchema baseSchema) {
+    public NetconfMessageTransformer(final SchemaContext schemaContext, final boolean strictParsing,
+                                     final BaseSchema baseSchema) {
         this.counter = new MessageCounter();
         this.schemaContext = schemaContext;
-        parserFactory = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
+        parserFactory = DomToNormalizedNodeParserFactory
+                .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, strictParsing);
         mappedRpcs = Maps.uniqueIndex(schemaContext.getOperations(), QNAME_FUNCTION);
         mappedNotifications = Multimaps.index(schemaContext.getNotifications(), QNAME_NOREV_FUNCTION);
         this.baseSchema = baseSchema;
@@ -86,17 +89,21 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
         final QName notificationNoRev;
         try {
-            notificationNoRev = QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
+            notificationNoRev = QName.create(
+                    stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
         } catch (final MissingNameSpaceException e) {
-            throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
+            throw new IllegalArgumentException(
+                    "Unable to parse notification " + message + ", cannot find namespace", e);
         }
         final Collection<NotificationDefinition> notificationDefinitions = mappedNotifications.get(notificationNoRev);
         Preconditions.checkArgument(notificationDefinitions.size() > 0,
-                "Unable to parse notification %s, unknown notification. Available notifications: %s", notificationDefinitions, mappedNotifications.keySet());
+                "Unable to parse notification %s, unknown notification. Available notifications: %s",
+                notificationDefinitions, mappedNotifications.keySet());
 
         final NotificationDefinition mostRecentNotification = getMostRecentNotification(notificationDefinitions);
 
-        final ContainerSchemaNode notificationAsContainerSchemaNode = NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
+        final ContainerSchemaNode notificationAsContainerSchemaNode =
+                NetconfMessageTransformUtil.createSchemaForNotification(mostRecentNotification);
 
         final Element element = stripped.getValue().getDomElement();
         final ContainerNode content;
@@ -109,8 +116,10 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
         return new NetconfDeviceNotification(content, stripped.getKey());
     }
 
-    private static NotificationDefinition getMostRecentNotification(final Collection<NotificationDefinition> notificationDefinitions) {
-        Comparator<NotificationDefinition> cmp = (o1, o2) -> o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
+    private static NotificationDefinition getMostRecentNotification(
+            final Collection<NotificationDefinition> notificationDefinitions) {
+        Comparator<NotificationDefinition> cmp = (o1, o2) ->
+                o1.getQName().getRevision().compareTo(o2.getQName().getRevision());
 
         return Collections.max(notificationDefinitions, cmp);
     }
@@ -121,16 +130,19 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
         final QName rpcQName = rpc.getLastComponent();
         Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
 
-        // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
+        // Determine whether a base netconf operation is being invoked
+        // and also check if the device exposed model for base netconf.
         // If no, use pre built base netconf operations model
         final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
-        if(needToUseBaseCtx) {
+        if (needToUseBaseCtx) {
             currentMappedRpcs = baseSchema.getMappedRpcs();
         }
 
-        Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName), "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
-        if(currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
-            return new NetconfMessage(NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
+        Preconditions.checkNotNull(currentMappedRpcs.get(rpcQName),
+                "Unknown rpc %s, available rpcs: %s", rpcQName, currentMappedRpcs.keySet());
+        if (currentMappedRpcs.get(rpcQName).getInput().getChildNodes().isEmpty()) {
+            return new NetconfMessage(NetconfMessageTransformUtil
+                    .prepareDomResultForRpcRequest(rpcQName, counter).getNode().getOwnerDocument());
         }
 
         Preconditions.checkNotNull(payload, "Transforming an rpc with input: %s, payload cannot be null", rpcQName);
@@ -142,7 +154,8 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
         final DOMResult result = NetconfMessageTransformUtil.prepareDomResultForRpcRequest(rpcQName, counter);
 
         try {
-            // If the schema context for netconf device does not contain model for base netconf operations, use default pre build context with just the base model
+            // If the schema context for netconf device does not contain model for base netconf operations,
+            // use default pre build context with just the base model
             // This way operations like lock/unlock are supported even if the source for base model was not provided
             SchemaContext ctx = needToUseBaseCtx ? baseSchema.getSchemaContext() : schemaContext;
             NetconfMessageTransformUtil.writeNormalizedRpc(((ContainerNode) payload), result, rpc, ctx);
@@ -156,9 +169,9 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
     }
 
     private static boolean isBaseOrNotificationRpc(final QName rpc) {
-        return rpc.getNamespace().equals(NETCONF_URI) ||
-                rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace()) ||
-                rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
+        return rpc.getNamespace().equals(NETCONF_URI)
+                || rpc.getNamespace().equals(IETF_NETCONF_NOTIFICATIONS.getNamespace())
+                || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
     }
 
 
@@ -168,30 +181,36 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
         final QName rpcQName = rpc.getLastComponent();
         if (NetconfMessageTransformUtil.isDataRetrievalOperation(rpcQName)) {
             final Element xmlData = NetconfMessageTransformUtil.getDataSubtree(message.getDocument());
-            final ContainerSchemaNode schemaForDataRead = NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
+            final ContainerSchemaNode schemaForDataRead =
+                    NetconfMessageTransformUtil.createSchemaForDataRead(schemaContext);
             final ContainerNode dataNode;
 
             try {
-                dataNode = parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
+                dataNode =
+                        parserFactory.getContainerNodeParser().parse(Collections.singleton(xmlData), schemaForDataRead);
             } catch (IllegalArgumentException e) {
                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
             }
 
-            normalizedNode = Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+            normalizedNode = Builders.containerBuilder()
+                    .withNodeIdentifier(new YangInstanceIdentifier
+                            .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
                     .withChild(dataNode).build();
         } else {
 
             Map<QName, RpcDefinition> currentMappedRpcs = mappedRpcs;
 
-            // Determine whether a base netconf operation is being invoked and also check if the device exposed model for base netconf
+            // Determine whether a base netconf operation is being invoked
+            // and also check if the device exposed model for base netconf.
             // If no, use pre built base netconf operations model
             final boolean needToUseBaseCtx = mappedRpcs.get(rpcQName) == null && isBaseOrNotificationRpc(rpcQName);
-            if(needToUseBaseCtx) {
+            if (needToUseBaseCtx) {
                 currentMappedRpcs = baseSchema.getMappedRpcs();
             }
 
             final RpcDefinition rpcDefinition = currentMappedRpcs.get(rpcQName);
-            Preconditions.checkArgument(rpcDefinition != null, "Unable to parse response of %s, the rpc is unknown", rpcQName);
+            Preconditions.checkArgument(rpcDefinition != null,
+                    "Unable to parse response of %s, the rpc is unknown", rpcQName);
 
             // In case no input for rpc is defined, we can simply construct the payload here
             if (rpcDefinition.getOutput().getChildNodes().isEmpty()) {
index 00fb9b4645d55a37b2e82132e2ae6b732a048d7f..d2cb8d52267daaa3dd419890bf6ad41156c20c81 100644 (file)
@@ -55,7 +55,8 @@ public class SchemalessMessageTransformer implements MessageTransformer<NetconfM
             notificationNoRev =
                     QName.create(stripped.getValue().getNamespace(), stripped.getValue().getName()).withoutRevision();
         } catch (final MissingNameSpaceException e) {
-            throw new IllegalArgumentException("Unable to parse notification " + message + ", cannot find namespace", e);
+            throw new IllegalArgumentException("Unable to parse notification "
+                    + message + ", cannot find namespace", e);
         }
 
         final AnyXmlNode notificationPayload = Builders.anyXmlBuilder()
@@ -79,8 +80,8 @@ public class SchemalessMessageTransformer implements MessageTransformer<NetconfM
     }
 
     /**
-     * Transforms reply message to anyXml node. In case, that rpc-reply doesn't contain data and contains only &lt;ok/&gt;
-     * element, returns null.
+     * Transforms reply message to anyXml node.
+     * In case, that rpc-reply doesn't contain data and contains only &lt;ok/&gt; element, returns null.
      * @param rpcReply reply message
      * @return anyxml
      */
@@ -88,7 +89,7 @@ public class SchemalessMessageTransformer implements MessageTransformer<NetconfM
     public DOMRpcResult toRpcResult(final NetconfMessage rpcReply, final SchemaPath rpc) {
         final Document document = rpcReply.getDocument();
         final AnyXmlNode result;
-        if(BaseRpcSchemalessTransformer.isOkPresent(document)) {
+        if (BaseRpcSchemalessTransformer.isOkPresent(document)) {
             result =  null;
         } else {
             result = Builders.anyXmlBuilder()
@@ -102,10 +103,12 @@ public class SchemalessMessageTransformer implements MessageTransformer<NetconfM
     private void wrapPayload(final Document doc) {
         final Element payload = doc.getDocumentElement();
         doc.removeChild(payload);
-        final Element rpcNS = doc.createElementNS(NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getNamespace().toString(),
+        final Element rpcNS =
+                doc.createElementNS(NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getNamespace().toString(),
                 NetconfMessageTransformUtil.NETCONF_RPC_QNAME.getLocalName());
         // set msg id
-        rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR, counter.getNewMessageId(NetconfMessageTransformUtil.MESSAGE_ID_PREFIX));
+        rpcNS.setAttribute(NetconfMessageTransformUtil.MESSAGE_ID_ATTR,
+                counter.getNewMessageId(NetconfMessageTransformUtil.MESSAGE_ID_PREFIX));
         rpcNS.appendChild(payload);
         doc.appendChild(rpcNS);
     }
index 8c51218ef96e0ec1ddd368855156d5b04c1bf335..d12a97c8bd4979d7a2f87942f39d5e54d7d11d20 100644 (file)
@@ -74,20 +74,23 @@ public final class NetconfBaseOps {
         Preconditions.checkNotNull(callback);
         Preconditions.checkNotNull(datastore);
 
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(datastore));
+        final ListenableFuture<DOMRpcResult> future =
+                rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(datastore));
         Futures.addCallback(future, callback);
         return future;
     }
 
     public ListenableFuture<DOMRpcResult> lockCandidate(final FutureCallback<DOMRpcResult> callback) {
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_CANDIDATE_QNAME));
+        final ListenableFuture<DOMRpcResult> future =
+                rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_CANDIDATE_QNAME));
         Futures.addCallback(future, callback);
         return future;
     }
 
 
     public ListenableFuture<DOMRpcResult> lockRunning(final FutureCallback<DOMRpcResult> callback) {
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_RUNNING_QNAME));
+        final ListenableFuture<DOMRpcResult> future =
+                rpc.invokeRpc(toPath(NETCONF_LOCK_QNAME), getLockContent(NETCONF_RUNNING_QNAME));
         Futures.addCallback(future, callback);
         return future;
     }
@@ -96,19 +99,22 @@ public final class NetconfBaseOps {
         Preconditions.checkNotNull(callback);
         Preconditions.checkNotNull(datastore);
 
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(datastore));
+        final ListenableFuture<DOMRpcResult> future =
+                rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(datastore));
         Futures.addCallback(future, callback);
         return future;
     }
 
     public ListenableFuture<DOMRpcResult> unlockRunning(final FutureCallback<DOMRpcResult> callback) {
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_RUNNING_QNAME));
+        final ListenableFuture<DOMRpcResult> future =
+                rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_RUNNING_QNAME));
         Futures.addCallback(future, callback);
         return future;
     }
 
     public ListenableFuture<DOMRpcResult> unlockCandidate(final FutureCallback<DOMRpcResult> callback) {
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_CANDIDATE_QNAME));
+        final ListenableFuture<DOMRpcResult> future =
+                rpc.invokeRpc(toPath(NETCONF_UNLOCK_QNAME), getUnLockContent(NETCONF_CANDIDATE_QNAME));
         Futures.addCallback(future, callback);
         return future;
     }
@@ -124,7 +130,8 @@ public final class NetconfBaseOps {
     public ListenableFuture<DOMRpcResult> commit(final FutureCallback<DOMRpcResult> callback) {
         Preconditions.checkNotNull(callback);
 
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+            toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
         Futures.addCallback(future, callback);
         return future;
     }
@@ -133,7 +140,8 @@ public final class NetconfBaseOps {
         Preconditions.checkNotNull(callback);
         Preconditions.checkNotNull(datastore);
 
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME), getValidateContent(datastore));
+        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+                toPath(NetconfMessageTransformUtil.NETCONF_VALIDATE_QNAME), getValidateContent(datastore));
         Futures.addCallback(future, callback);
         return future;
     }
@@ -147,12 +155,14 @@ public final class NetconfBaseOps {
         return validate(callback, NETCONF_RUNNING_QNAME);
     }
 
-    public ListenableFuture<DOMRpcResult> copyConfig(final FutureCallback<DOMRpcResult> callback, final QName source, final QName target) {
+    public ListenableFuture<DOMRpcResult> copyConfig(final FutureCallback<DOMRpcResult> callback,
+                                                     final QName source, final QName target) {
         Preconditions.checkNotNull(callback);
         Preconditions.checkNotNull(source);
         Preconditions.checkNotNull(target);
 
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME), getCopyConfigContent(source, target));
+        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(
+                toPath(NetconfMessageTransformUtil.NETCONF_COPY_CONFIG_QNAME), getCopyConfigContent(source, target));
         Futures.addCallback(future, callback);
         return future;
     }
@@ -161,7 +171,8 @@ public final class NetconfBaseOps {
         return copyConfig(callback, NETCONF_RUNNING_QNAME, NETCONF_CANDIDATE_QNAME);
     }
 
-    public ListenableFuture<DOMRpcResult> getConfig(final FutureCallback<DOMRpcResult> callback, final QName datastore, final Optional<YangInstanceIdentifier> filterPath) {
+    public ListenableFuture<DOMRpcResult> getConfig(final FutureCallback<DOMRpcResult> callback, final QName datastore,
+                                                    final Optional<YangInstanceIdentifier> filterPath) {
         Preconditions.checkNotNull(callback);
         Preconditions.checkNotNull(datastore);
 
@@ -179,8 +190,8 @@ public final class NetconfBaseOps {
         return future;
     }
 
-    public ListenableFuture<Optional<NormalizedNode<?, ?>>> getConfigRunningData(final FutureCallback<DOMRpcResult> callback,
-                                                                                 final Optional<YangInstanceIdentifier> filterPath) {
+    public ListenableFuture<Optional<NormalizedNode<?, ?>>> getConfigRunningData(
+            final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
         final ListenableFuture<DOMRpcResult> configRunning = getConfigRunning(callback, filterPath);
         return extractData(filterPath, configRunning);
     }
@@ -191,32 +202,38 @@ public final class NetconfBaseOps {
         return extractData(filterPath, configRunning);
     }
 
-    private ListenableFuture<Optional<NormalizedNode<?, ?>>> extractData(final Optional<YangInstanceIdentifier> path,
-                                                                         final ListenableFuture<DOMRpcResult> configRunning) {
+    private ListenableFuture<Optional<NormalizedNode<?, ?>>> extractData(
+            final Optional<YangInstanceIdentifier> path, final ListenableFuture<DOMRpcResult> configRunning) {
         return Futures.transform(configRunning, (Function<DOMRpcResult, Optional<NormalizedNode<?, ?>>>) result -> {
-            Preconditions.checkArgument(result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors());
+            Preconditions.checkArgument(
+                    result.getErrors().isEmpty(), "Unable to read data: %s, errors: %s", path, result.getErrors());
             final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataNode =
-                    ((ContainerNode) result.getResult()).getChild(NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get();
+                    ((ContainerNode) result.getResult()).getChild(
+                            NetconfMessageTransformUtil.toId(NetconfMessageTransformUtil.NETCONF_DATA_QNAME)).get();
             return transformer.selectFromDataStructure(dataNode, path.get());
         });
     }
 
-    public ListenableFuture<DOMRpcResult> getConfigRunning(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+    public ListenableFuture<DOMRpcResult> getConfigRunning(final FutureCallback<DOMRpcResult> callback,
+                                                           final Optional<YangInstanceIdentifier> filterPath) {
         return getConfig(callback, NETCONF_RUNNING_QNAME, filterPath);
     }
 
-    public ListenableFuture<DOMRpcResult> getConfigCandidate(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+    public ListenableFuture<DOMRpcResult> getConfigCandidate(final FutureCallback<DOMRpcResult> callback,
+                                                             final Optional<YangInstanceIdentifier> filterPath) {
         return getConfig(callback, NETCONF_CANDIDATE_QNAME, filterPath);
     }
 
-    public ListenableFuture<DOMRpcResult> get(final FutureCallback<DOMRpcResult> callback, final Optional<YangInstanceIdentifier> filterPath) {
+    public ListenableFuture<DOMRpcResult> get(final FutureCallback<DOMRpcResult> callback,
+                                              final Optional<YangInstanceIdentifier> filterPath) {
         Preconditions.checkNotNull(callback);
 
         final ListenableFuture<DOMRpcResult> future;
 
-        future = isFilterPresent(filterPath) ?
-                rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext))) :
-                rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT);
+        future = isFilterPresent(filterPath)
+                ? rpc.invokeRpc(toPath(NETCONF_GET_QNAME),
+                NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, toFilterStructure(filterPath.get(), schemaContext)))
+                : rpc.invokeRpc(toPath(NETCONF_GET_QNAME), NetconfMessageTransformUtil.GET_RPC_CONTENT);
 
         Futures.addCallback(future, callback);
         return future;
@@ -226,40 +243,55 @@ public final class NetconfBaseOps {
         return filterPath.isPresent() && !filterPath.get().isEmpty();
     }
 
-    public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final ModifyAction modifyAction, final boolean rollback) {
+    public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback,
+                                                              final DataContainerChild<?, ?> editStructure,
+                                                              final ModifyAction modifyAction, final boolean rollback) {
         return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.of(modifyAction), rollback);
     }
 
-    public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final boolean rollback) {
+    public ListenableFuture<DOMRpcResult> editConfigCandidate(final FutureCallback<? super DOMRpcResult> callback,
+                                                              final DataContainerChild<?, ?> editStructure,
+                                                              final boolean rollback) {
         return editConfig(callback, NETCONF_CANDIDATE_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
     }
 
-    public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final ModifyAction modifyAction, final boolean rollback) {
+    public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
+                                                            final DataContainerChild<?, ?> editStructure,
+                                                            final ModifyAction modifyAction, final boolean rollback) {
         return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.of(modifyAction), rollback);
     }
 
-    public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback, final DataContainerChild<?, ?> editStructure, final boolean rollback) {
+    public ListenableFuture<DOMRpcResult> editConfigRunning(final FutureCallback<? super DOMRpcResult> callback,
+                                                            final DataContainerChild<?, ?> editStructure,
+                                                            final boolean rollback) {
         return editConfig(callback, NETCONF_RUNNING_QNAME, editStructure, Optional.<ModifyAction>absent(), rollback);
     }
 
-    public ListenableFuture<DOMRpcResult> editConfig(final FutureCallback<? super DOMRpcResult> callback, final QName datastore, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> modifyAction, final boolean rollback) {
+    public ListenableFuture<DOMRpcResult> editConfig(
+            final FutureCallback<? super DOMRpcResult> callback, final QName datastore,
+            final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> modifyAction,
+            final boolean rollback) {
         Preconditions.checkNotNull(editStructure);
         Preconditions.checkNotNull(callback);
         Preconditions.checkNotNull(datastore);
 
-        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_EDIT_CONFIG_QNAME), getEditConfigContent(datastore, editStructure, modifyAction, rollback));
+        final ListenableFuture<DOMRpcResult> future = rpc.invokeRpc(toPath(NETCONF_EDIT_CONFIG_QNAME),
+                getEditConfigContent(datastore, editStructure, modifyAction, rollback));
 
         Futures.addCallback(future, callback);
         return future;
     }
 
-    public DataContainerChild<?, ?> createEditConfigStrcture(final Optional<NormalizedNode<?, ?>> lastChild, final Optional<ModifyAction> operation, final YangInstanceIdentifier dataPath) {
+    public DataContainerChild<?, ?> createEditConfigStrcture(final Optional<NormalizedNode<?, ?>> lastChild,
+                                                             final Optional<ModifyAction> operation,
+                                                             final YangInstanceIdentifier dataPath) {
         final AnyXmlNode configContent = transformer.createEditConfigStructure(lastChild, dataPath, operation);
         return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(configContent).build();
     }
 
-    private static ContainerNode getEditConfigContent(final QName datastore,
-            final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final boolean rollback) {
+    private static ContainerNode getEditConfigContent(
+            final QName datastore, final DataContainerChild<?, ?> editStructure,
+            final Optional<ModifyAction> defaultOperation, final boolean rollback) {
         final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> editBuilder =
                 Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_EDIT_CONFIG_QNAME));
 
@@ -267,14 +299,16 @@ public final class NetconfBaseOps {
         editBuilder.withChild(getTargetNode(datastore));
 
         // Default operation
-        if(defaultOperation.isPresent()) {
+        if (defaultOperation.isPresent()) {
             final String opString = defaultOperation.get().name().toLowerCase();
-            editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME)).withValue(opString).build());
+            editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME))
+                    .withValue(opString).build());
         }
 
         // Error option
-        if(rollback) {
-            editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_ERROR_OPTION_QNAME)).withValue(ROLLBACK_ON_ERROR_OPTION).build());
+        if (rollback) {
+            editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_ERROR_OPTION_QNAME))
+                    .withValue(ROLLBACK_ON_ERROR_OPTION).build());
         }
 
         // Edit content
index 2b1476f8220394f953d25f76814e09f858ce48d6..07fa3467f5fe5f5ee8b041d9395575fa5a62a263 100644 (file)
@@ -72,7 +72,8 @@ public class NetconfMessageTransformUtil {
     public static final String MESSAGE_ID_PREFIX = "m";
     public static final String MESSAGE_ID_ATTR = "message-id";
 
-    public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
+    public static final QName CREATE_SUBSCRIPTION_RPC_QNAME =
+            QName.create(CreateSubscriptionInput.QNAME, "create-subscription").intern();
     private static final String SUBTREE = "subtree";
 
     // Blank document used for creation of new DOM nodes
@@ -81,18 +82,26 @@ public class NetconfMessageTransformUtil {
 
     private NetconfMessageTransformUtil() {}
 
-    public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
+    public static final QName IETF_NETCONF_MONITORING =
+            QName.create(NetconfState.QNAME, "ietf-netconf-monitoring").intern();
     public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data").intern();
     public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema").intern();
-    public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format").intern();
-    public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location").intern();
-    public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
-    public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version").intern();
-    public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
-
-    public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
-
-    public static final QName NETCONF_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
+    public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT =
+            QName.create(IETF_NETCONF_MONITORING, "format").intern();
+    public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION =
+            QName.create(IETF_NETCONF_MONITORING, "location").intern();
+    public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER =
+            QName.create(IETF_NETCONF_MONITORING, "identifier").intern();
+    public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION =
+            QName.create(IETF_NETCONF_MONITORING, "version").intern();
+    public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE =
+            QName.create(IETF_NETCONF_MONITORING, "namespace").intern();
+
+    public static final QName IETF_NETCONF_NOTIFICATIONS =
+            QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications").intern();
+
+    public static final QName NETCONF_QNAME =
+            QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "netconf").intern();
     public static final URI NETCONF_URI = NETCONF_QNAME.getNamespace();
 
     public static final QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data").intern();
@@ -108,7 +117,8 @@ public class NetconfMessageTransformUtil {
     public static final QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate").intern();
     public static final QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config").intern();
     public static final QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation").intern();
-    public static final QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
+    public static final QName NETCONF_DEFAULT_OPERATION_QNAME =
+            QName.create(NETCONF_OPERATION_QNAME, "default-operation").intern();
     public static final QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config").intern();
     public static final QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
     public static final QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
@@ -152,25 +162,32 @@ public class NetconfMessageTransformUtil {
     public static final DataContainerChild<?, ?> EMPTY_FILTER;
 
     static {
-        final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
+        final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
+                Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
 
-        final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
-        element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
+        final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
+                Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
+        element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(),
+                NETCONF_TYPE_QNAME.getLocalName(), "subtree");
 
         anyXmlBuilder.withValue(new DOMSource(element));
 
         EMPTY_FILTER = anyXmlBuilder.build();
     }
 
-    public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
-        final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
+    public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier,
+                                                             final SchemaContext ctx) {
+        final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
+                Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
         anyXmlBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
 
         final NormalizedNode<?, ?> filterContent = ImmutableNodes.fromInstanceId(ctx, identifier);
 
-        final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(), Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
-        element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(), "subtree");
+        final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_FILTER_QNAME.getLocalName(),
+                Optional.of(NETCONF_FILTER_QNAME.getNamespace().toString()));
+        element.setAttributeNS(NETCONF_FILTER_QNAME.getNamespace().toString(), NETCONF_TYPE_QNAME.getLocalName(),
+                "subtree");
 
         try {
             NetconfUtil.writeNormalizedNode(filterContent, new DOMResult(element), SchemaPath.ROOT, ctx);
@@ -187,13 +204,13 @@ public class NetconfMessageTransformUtil {
         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
 
-        if(inputMsgId.equals(outputMsgId) == false) {
-            final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
-                    .put( "actual-message-id", outputMsgId )
-                    .put( "expected-message-id", inputMsgId )
+        if (inputMsgId.equals(outputMsgId) == false) {
+            final Map<String, String> errorInfo = ImmutableMap.<String, String>builder()
+                    .put("actual-message-id", outputMsgId)
+                    .put("expected-message-id", inputMsgId)
                     .build();
 
-            throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
+            throw new NetconfDocumentedException("Response message contained unknown \"message-id\"",
                     null, NetconfDocumentedException.ErrorType.PROTOCOL,
                     NetconfDocumentedException.ErrorTag.BAD_ATTRIBUTE,
                     NetconfDocumentedException.ErrorSeverity.ERROR, errorInfo);
@@ -201,33 +218,32 @@ public class NetconfMessageTransformUtil {
     }
 
     public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
-        if(NetconfMessageUtil.isErrorMessage(output)) {
+        if (NetconfMessageUtil.isErrorMessage(output)) {
             throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
         }
     }
 
-    public static RpcError toRpcError( final NetconfDocumentedException ex ) {
+    public static RpcError toRpcError(final NetconfDocumentedException ex) {
         final StringBuilder infoBuilder = new StringBuilder();
         final Map<String, String> errorInfo = ex.getErrorInfo();
-        if(errorInfo != null) {
-            for( final Entry<String,String> e: errorInfo.entrySet() ) {
-                infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
-                .append( "</" ).append( e.getKey() ).append( '>' );
+        if (errorInfo != null) {
+            for (final Entry<String, String> e : errorInfo.entrySet()) {
+                infoBuilder.append('<').append(e.getKey()).append('>').append(e.getValue())
+                        .append("</").append(e.getKey()).append('>');
 
             }
         }
 
-        final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
-        return severity == ErrorSeverity.ERROR ?
-                RpcResultBuilder.newError(
-                        toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
-                        ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
-                            RpcResultBuilder.newWarning(
-                                    toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
-                                    ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
+        final ErrorSeverity severity = toRpcErrorSeverity(ex.getErrorSeverity());
+        return severity == ErrorSeverity.ERROR
+                ? RpcResultBuilder.newError(toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
+                        ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause())
+                : RpcResultBuilder.newWarning(
+                        toRpcErrorType(ex.getErrorType()), ex.getErrorTag().getTagValue(),
+                        ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause());
     }
 
-    private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
+    private static ErrorSeverity toRpcErrorSeverity(final NetconfDocumentedException.ErrorSeverity severity) {
         switch (severity) {
             case WARNING:
                 return RpcError.ErrorSeverity.WARNING;
@@ -239,13 +255,13 @@ public class NetconfMessageTransformUtil {
     private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
         switch (type) {
             case PROTOCOL:
-            return RpcError.ErrorType.PROTOCOL;
+                return RpcError.ErrorType.PROTOCOL;
             case RPC:
-            return RpcError.ErrorType.RPC;
+                return RpcError.ErrorType.RPC;
             case TRANSPORT:
-            return RpcError.ErrorType.TRANSPORT;
-        default:
-            return RpcError.ErrorType.APPLICATION;
+                return RpcError.ErrorType.TRANSPORT;
+            default:
+                return RpcError.ErrorType.APPLICATION;
         }
     }
 
@@ -279,22 +295,27 @@ public class NetconfMessageTransformUtil {
         return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(ImmutableList.copyOf(node)).build();
     }
 
-    public static AnyXmlNode createEditConfigAnyxml(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
-                                                                     final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
+    public static AnyXmlNode createEditConfigAnyxml(
+            final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+            final Optional<NormalizedNode<?, ?>> lastChildOverride) {
         final NormalizedNode<?, ?> configContent;
 
         if (dataPath.isEmpty()) {
-            Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
+            Preconditions.checkArgument(lastChildOverride.isPresent(),
+                    "Data has to be present when creating structure for top level element");
             Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
-                    "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
+                    "Data has to be either container or a list node when creating structure for top level element, "
+                            + "but was: %s", lastChildOverride.get());
             configContent = lastChildOverride.get();
         } else {
-            final Entry<QName, ModifyAction> modifyOperation =
-                    operation.isPresent() ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
-            configContent = ImmutableNodes.fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
+            final Entry<QName, ModifyAction> modifyOperation = operation.isPresent()
+                    ? new AbstractMap.SimpleEntry<>(NETCONF_OPERATION_QNAME, operation.get()) : null;
+            configContent = ImmutableNodes
+                    .fromInstanceId(ctx, dataPath, lastChildOverride, Optional.fromNullable(modifyOperation));
         }
 
-        final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(), Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
+        final Element element = XmlUtil.createElement(BLANK_DOCUMENT, NETCONF_CONFIG_QNAME.getLocalName(),
+                Optional.of(NETCONF_CONFIG_QNAME.getNamespace().toString()));
         try {
             NetconfUtil.writeNormalizedNode(configContent, new DOMResult(element), SchemaPath.ROOT, ctx);
         } catch (IOException | XMLStreamException e) {
@@ -305,8 +326,9 @@ public class NetconfMessageTransformUtil {
         return Builders.anyXmlBuilder().withNodeIdentifier(toId(NETCONF_CONFIG_QNAME)).withValue(value).build();
     }
 
-    public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
-                                                                     final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
+    public static DataContainerChild<?, ?> createEditConfigStructure(
+            final SchemaContext ctx, final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+            final Optional<NormalizedNode<?, ?>> lastChildOverride) {
         return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME))
                 .withChild(createEditConfigAnyxml(ctx, dataPath, operation, lastChildOverride)).build();
     }
@@ -318,8 +340,8 @@ public class NetconfMessageTransformUtil {
     public static Map.Entry<Date, XmlElement> stripNotification(final NetconfMessage message) {
         final XmlElement xmlElement = XmlElement.fromDomDocument(message.getDocument());
         final List<XmlElement> childElements = xmlElement.getChildElements();
-        Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format.\nExpected 2 childElements," +
-                " actual childElements size is %s", message, childElements.size());
+        Preconditions.checkArgument(childElements.size() == 2, "Unable to parse notification %s, unexpected format."
+                + "\nExpected 2 childElements, actual childElements size is %s", message, childElements.size());
 
         final XmlElement eventTimeElement;
         final XmlElement notificationElement;
@@ -327,8 +349,7 @@ public class NetconfMessageTransformUtil {
         if (childElements.get(0).getName().equals(EVENT_TIME)) {
             eventTimeElement = childElements.get(0);
             notificationElement = childElements.get(1);
-        }
-        else if(childElements.get(1).getName().equals(EVENT_TIME)) {
+        } else if (childElements.get(1).getName().equals(EVENT_TIME)) {
             eventTimeElement = childElements.get(1);
             notificationElement = childElements.get(0);
         } else {
@@ -342,7 +363,8 @@ public class NetconfMessageTransformUtil {
         } catch (final DocumentedException e) {
             throw new IllegalArgumentException("Notification payload does not contain " + EVENT_TIME + " " + message);
         } catch (final DateTimeParseException e) {
-            LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement, NetconfNotification.UNKNOWN_EVENT_TIME, e);
+            LOG.warn("Unable to parse event time from {}. Setting time to {}", eventTimeElement,
+                    NetconfNotification.UNKNOWN_EVENT_TIME, e);
             return new AbstractMap.SimpleEntry<>(NetconfNotification.UNKNOWN_EVENT_TIME, notificationElement);
         }
     }
@@ -359,13 +381,15 @@ public class NetconfMessageTransformUtil {
         return new DOMResult(elementNS);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public static void writeNormalizedRpc(final ContainerNode normalized, final DOMResult result,
-                                          final SchemaPath schemaPath, final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
+                                          final SchemaPath schemaPath,
+                                          final SchemaContext baseNetconfCtx) throws IOException, XMLStreamException {
         final XMLStreamWriter writer = NetconfUtil.XML_FACTORY.createXMLStreamWriter(result);
         try {
-            try (final NormalizedNodeStreamWriter normalizedNodeStreamWriter =
+            try (NormalizedNodeStreamWriter normalizedNodeStreamWriter =
                     XMLStreamNormalizedNodeStreamWriter.create(writer, baseNetconfCtx, schemaPath)) {
-                try (final SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
+                try (SchemaOrderedNormalizedNodeWriter normalizedNodeWriter =
                         new SchemaOrderedNormalizedNodeWriter(normalizedNodeStreamWriter, baseNetconfCtx, schemaPath)) {
                     final Collection<DataContainerChild<?, ?>> value = normalized.getValue();
                     normalizedNodeWriter.write(value);
@@ -376,7 +400,7 @@ public class NetconfMessageTransformUtil {
             try {
                 writer.close();
             } catch (final Exception e) {
-               LOG.warn("Unable to close resource properly", e);
+                LOG.warn("Unable to close resource properly", e);
             }
         }
     }
index 2e0349dcf56c3ea488ee71dc4c428ef0fc29294c..e5eaab1d7d92944350067eb6eef3026d489426bc 100644 (file)
@@ -15,7 +15,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Simple Netconf rpc logging callback
+ * Simple Netconf RPC logging callback.
  */
 public class NetconfRpcFutureCallback implements FutureCallback<DOMRpcResult> {
     private static final Logger LOG  = LoggerFactory.getLogger(NetconfRpcFutureCallback.class);
@@ -30,7 +30,7 @@ public class NetconfRpcFutureCallback implements FutureCallback<DOMRpcResult> {
 
     @Override
     public void onSuccess(final DOMRpcResult result) {
-        if(result.getErrors().isEmpty()) {
+        if (result.getErrors().isEmpty()) {
             LOG.trace("{}: {} invoked successfully", id, type);
         } else {
             onUnsuccess(result);
@@ -42,7 +42,7 @@ public class NetconfRpcFutureCallback implements FutureCallback<DOMRpcResult> {
     }
 
     @Override
-    public void onFailure(final Throwable t) {
-        LOG.warn("{}: {} failed.", id, type, t);
+    public void onFailure(final Throwable throwable) {
+        LOG.warn("{}: {} failed.", id, type, throwable);
     }
 }
index 1572e203f7cee05c93c7561830dfed3c29d40ee1..5ccab6ba66e760762fe361020bbe772e32ec9f54 100644 (file)
@@ -28,14 +28,16 @@ class NetconfRpcStructureTransformer implements RpcStructureTransformer {
     }
 
     @Override
-    public Optional<NormalizedNode<?, ?>> selectFromDataStructure(final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
-                                                                  final YangInstanceIdentifier path) {
+    public Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+            final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
+            final YangInstanceIdentifier path) {
         return NormalizedNodes.findNode(data, path.getPathArguments());
     }
 
     @Override
     public AnyXmlNode createEditConfigStructure(final Optional<NormalizedNode<?, ?>> data,
-                                                final YangInstanceIdentifier dataPath, Optional<ModifyAction> operation) {
+                                                final YangInstanceIdentifier dataPath,
+                                                Optional<ModifyAction> operation) {
         return NetconfMessageTransformUtil.createEditConfigAnyxml(schemaContext, dataPath, operation, data);
     }
 
index 829bac68473053434c9c8df55dcb5330e94903af..c54da2a25a032f8a7a3a7455b9235a70527311ec 100644 (file)
@@ -29,26 +29,28 @@ import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.UsesNode;
 
 /**
- * Simple proxy for container like schema nodes, where user provides a collection of children schema nodes
+ * Simple proxy for container like schema nodes, where user provides a collection of children schema nodes.
  */
 public final class NodeContainerProxy implements ContainerSchemaNode {
 
     private final Map<QName, DataSchemaNode> childNodes;
-    private final QName qName;
+    private final QName qualifiedName;
     private final Set<AugmentationSchema> availableAugmentations;
 
-    public NodeContainerProxy(final QName qName, final Map<QName, DataSchemaNode> childNodes, final Set<AugmentationSchema> availableAugmentations) {
+    public NodeContainerProxy(final QName qualifiedName, final Map<QName, DataSchemaNode> childNodes,
+                              final Set<AugmentationSchema> availableAugmentations) {
         this.availableAugmentations = availableAugmentations;
         this.childNodes = Preconditions.checkNotNull(childNodes, "childNodes");
-        this.qName = qName;
+        this.qualifiedName = qualifiedName;
     }
 
-    public NodeContainerProxy(final QName qName, final Collection<DataSchemaNode> childNodes) {
-        this(qName, asMap(childNodes), Collections.<AugmentationSchema>emptySet());
+    public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes) {
+        this(qualifiedName, asMap(childNodes), Collections.<AugmentationSchema>emptySet());
     }
 
-    public NodeContainerProxy(final QName qName, final Collection<DataSchemaNode> childNodes, final Set<AugmentationSchema> availableAugmentations) {
-        this(qName, asMap(childNodes), availableAugmentations);
+    public NodeContainerProxy(final QName qualifiedName, final Collection<DataSchemaNode> childNodes,
+                              final Set<AugmentationSchema> availableAugmentations) {
+        this(qualifiedName, asMap(childNodes), availableAugmentations);
     }
 
     private static Map<QName, DataSchemaNode> asMap(final Collection<DataSchemaNode> childNodes) {
@@ -76,8 +78,8 @@ public final class NodeContainerProxy implements ContainerSchemaNode {
     }
 
     @Override
-    public DataSchemaNode getDataChildByName(final QName qName) {
-        return childNodes.get(qName);
+    public DataSchemaNode getDataChildByName(final QName qualifiedName) {
+        return childNodes.get(qualifiedName);
     }
 
     @Override
@@ -117,7 +119,7 @@ public final class NodeContainerProxy implements ContainerSchemaNode {
 
     @Override
     public QName getQName() {
-        return qName;
+        return qualifiedName;
     }
 
     @Override
index ef5009b931ae91e7d5bb064cde8a19ad385b5345..90e9c8b06e594a2e369eb64227da7e62304914d5 100644 (file)
@@ -44,6 +44,6 @@ interface RpcStructureTransformer {
      * @param path path to select
      * @return selected data
      */
-    Optional<NormalizedNode<?, ?>> selectFromDataStructure(DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
-                                                           YangInstanceIdentifier path);
+    Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+            DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data, YangInstanceIdentifier path);
 }
index 3342bf58737c19d5741ab6c663569629338524ab..099d2f2dde991c7f7150d1cf57954e735ea48eba 100644 (file)
@@ -43,13 +43,15 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
      * @return selected data
      */
     @Override
-    public Optional<NormalizedNode<?, ?>> selectFromDataStructure(final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
-                                                                  final YangInstanceIdentifier path) {
+    public Optional<NormalizedNode<?, ?>> selectFromDataStructure(
+            final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> data,
+            final YangInstanceIdentifier path) {
         Preconditions.checkArgument(data instanceof AnyXmlNode);
         final List<XmlElement> xmlElements = selectMatchingNodes(getSourceElement(((AnyXmlNode)data).getValue()), path);
         final Document result = XmlUtil.newDocument();
         final QName dataQName = NetconfMessageTransformUtil.NETCONF_DATA_QNAME;
-        final Element dataElement = result.createElementNS(dataQName.getNamespace().toString(), dataQName.getLocalName());
+        final Element dataElement =
+                result.createElementNS(dataQName.getNamespace().toString(), dataQName.getLocalName());
         result.appendChild(dataElement);
         for (XmlElement xmlElement : xmlElements) {
             dataElement.appendChild(result.importNode(xmlElement.getDomElement(), true));
@@ -71,7 +73,8 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
      */
     @Override
     public AnyXmlNode createEditConfigStructure(final Optional<NormalizedNode<?, ?>> data,
-                                                final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation) {
+                                                final YangInstanceIdentifier dataPath,
+                                                final Optional<ModifyAction> operation) {
         Preconditions.checkArgument(data.isPresent());
         Preconditions.checkArgument(data.get() instanceof AnyXmlNode);
 
@@ -91,7 +94,8 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
         } else {
             final List<YangInstanceIdentifier.PathArgument> pathArguments = dataPath.getPathArguments();
             //last will be appended later
-            final List<YangInstanceIdentifier.PathArgument> pathWithoutLast = pathArguments.subList(0, pathArguments.size() - 1);
+            final List<YangInstanceIdentifier.PathArgument> pathWithoutLast =
+                    pathArguments.subList(0, pathArguments.size() - 1);
             parentXmlStructure = instanceIdToXmlStructure(pathWithoutLast, configElement);
         }
         if (operation.isPresent()) {
@@ -115,7 +119,8 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
     public DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier path) {
         final Document document = XmlUtil.newDocument();
         final QName filterQname = NetconfMessageTransformUtil.NETCONF_FILTER_QNAME;
-        final Element filter = document.createElementNS(filterQname.getNamespace().toString(), filterQname.getLocalName());
+        final Element filter =
+                document.createElementNS(filterQname.getNamespace().toString(), filterQname.getLocalName());
         final Attr a = document.createAttributeNS(filterQname.getNamespace().toString(), "type");
         a.setTextContent("subtree");
         filter.setAttributeNode(a);
@@ -135,8 +140,8 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
         final XmlElement dataElement = XmlElement.fromDomElement(dataNode);
         final YangInstanceIdentifier.PathArgument lastPathArgument = dataPath.getLastPathArgument();
         final QName nodeType = lastPathArgument.getNodeType();
-        if (!nodeType.getNamespace().toString().equals(dataNode.getNamespaceURI()) ||
-               !nodeType.getLocalName().equals(dataElement.getName())) {
+        if (!nodeType.getNamespace().toString().equals(dataNode.getNamespaceURI())
+                || !nodeType.getLocalName().equals(dataElement.getName())) {
             throw new IllegalStateException(
                     String.format("Can't write data '%s' to path %s", dataNode.getTagName(), dataPath));
         }
@@ -151,9 +156,10 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
         final YangInstanceIdentifier.NodeIdentifierWithPredicates keyedId =
                 (YangInstanceIdentifier.NodeIdentifierWithPredicates) lastPathArgument;
         final Map<QName, Object> keyValues = keyedId.getKeyValues();
-        for (QName qName : keyValues.keySet()) {
+        for (QName qualifiedName : keyValues.keySet()) {
             final List<XmlElement> key =
-                    dataElement.getChildElementsWithinNamespace(qName.getLocalName(), qName.getNamespace().toString());
+                    dataElement.getChildElementsWithinNamespace(qualifiedName.getLocalName(),
+                            qualifiedName.getNamespace().toString());
             if (key.isEmpty()) {
                 throw new IllegalStateException("No key present in xml");
             }
@@ -166,7 +172,7 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
             } catch (DocumentedException e) {
                 throw new IllegalStateException("Key value not present in key element");
             }
-            if (!keyValues.get(qName).equals(textContent)) {
+            if (!keyValues.get(qualifiedName).equals(textContent)) {
                 throw new IllegalStateException("Key value in path not equal to key value in xml");
             }
         }
@@ -191,9 +197,11 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer {
             parent.appendChild(element);
             //if path argument is list id, add also keys to resulting xml
             if (pathArgument instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
-                YangInstanceIdentifier.NodeIdentifierWithPredicates listNode = (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
+                YangInstanceIdentifier.NodeIdentifierWithPredicates listNode =
+                        (YangInstanceIdentifier.NodeIdentifierWithPredicates) pathArgument;
                 for (Map.Entry<QName, Object> key : listNode.getKeyValues().entrySet()) {
-                    final Element keyElement = doc.createElementNS(key.getKey().getNamespace().toString(), key.getKey().getLocalName());
+                    final Element keyElement =
+                            doc.createElementNS(key.getKey().getNamespace().toString(), key.getKey().getLocalName());
                     keyElement.setTextContent(key.getValue().toString());
                     element.appendChild(keyElement);
                 }
index 52c606455f2af54b0cf57635cc7b9045cd4fd2a8..555c6a3f10394cb5965af8a22f0df7379acf96b2 100644 (file)
@@ -15,11 +15,11 @@ import java.util.concurrent.atomic.AtomicInteger;
 public class MessageCounter {
     final AtomicInteger messageId = new AtomicInteger(0);
 
-    private static final String messageIdBlueprint = "%s-%s";
+    private static final String MESSAGE_ID_BLUEPRINT = "%s-%s";
 
     public String getNewMessageId(final String prefix) {
         Preconditions.checkArgument(Strings.isNullOrEmpty(prefix) == false, "Null or empty prefix");
-        return String.format(messageIdBlueprint, prefix, getNewMessageId());
+        return String.format(MESSAGE_ID_BLUEPRINT, prefix, getNewMessageId());
     }
 
     public String getNewMessageId() {
index d98232787ed652da628b54f941bef536adbfc2f3..c52e55e7f5070e6b83987cc402e7ce301ccbd650 100644 (file)
@@ -33,7 +33,8 @@ public final class RemoteDeviceId {
     private final InstanceIdentifier<Node> bindingPath;
     private final NodeKey key;
     private final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier topologyPath;
-    private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> topologyBindingPath;
+    private final InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+            .network.topology.rev131021.network.topology.topology.Node> topologyBindingPath;
     private InetSocketAddress address;
     private Host host;
 
@@ -65,30 +66,41 @@ public final class RemoteDeviceId {
     private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPath(final String name) {
         final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
                 org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
-        builder.node(Nodes.QNAME).node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name);
+        builder.node(Nodes.QNAME).node(Node.QNAME)
+                .nodeWithKey(Node.QNAME, QName.create(Node.QNAME.getNamespace(), Node.QNAME.getRevision(), "id"), name);
 
         return builder.build();
     }
 
-    private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) {
-        final InstanceIdentifier<NetworkTopology> networkTopology = InstanceIdentifier.builder(NetworkTopology.class).build();
-        final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
+    private static InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network
+            .topology.rev131021.network.topology.topology.Node> createBindingPathForTopology(final NodeKey key) {
+        final InstanceIdentifier<NetworkTopology> networkTopology =
+                InstanceIdentifier.builder(NetworkTopology.class).build();
+        final KeyedInstanceIdentifier<Topology, TopologyKey> topology = networkTopology
+                .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())));
         return topology
-                .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.class,
-                        new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey(
-                                new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId(key.getId().getValue())));
+                .child(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+                        .network.topology.rev131021.network.topology.topology.Node.class,
+                        new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network
+                                .topology.topology.NodeKey(new org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+                                .network.topology.rev131021.NodeId(key.getId().getValue())));
     }
 
-    private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(final String name) {
+    private static org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier createBIPathForTopology(
+            final String name) {
         final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder builder =
                 org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.builder();
         builder
                 .node(NetworkTopology.QNAME)
                 .node(Topology.QNAME)
-                .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), TopologyNetconf.QNAME.getLocalName())
-                .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME)
-                .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME,
-                        QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name);
+                .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"),
+                        TopologyNetconf.QNAME.getLocalName())
+                .node(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+                        .network.topology.rev131021.network.topology.topology.Node.QNAME)
+                .nodeWithKey(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+                        .network.topology.rev131021.network.topology.topology.Node.QNAME,
+                        QName.create(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+                                .network.topology.rev131021.network.topology.topology.Node.QNAME, "node-id"), name);
         return builder.build();
     }
 
@@ -112,7 +124,8 @@ public final class RemoteDeviceId {
         return key;
     }
 
-    public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() {
+    public InstanceIdentifier<org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang
+            .network.topology.rev131021.network.topology.topology.Node> getTopologyBindingPath() {
         return topologyBindingPath;
     }
 
@@ -130,19 +143,19 @@ public final class RemoteDeviceId {
 
     @Override
     public String toString() {
-        return "RemoteDevice{" + name +'}';
+        return "RemoteDevice{" + name + '}';
     }
 
     @Override
-    public boolean equals(final Object o) {
-        if (this == o) {
+    public boolean equals(final Object obj) {
+        if (this == obj) {
             return true;
         }
-        if (!(o instanceof RemoteDeviceId)) {
+        if (!(obj instanceof RemoteDeviceId)) {
             return false;
         }
 
-        final RemoteDeviceId that = (RemoteDeviceId) o;
+        final RemoteDeviceId that = (RemoteDeviceId) obj;
 
         if (!name.equals(that.name)) {
             return false;
index 2f58669f7e629ef9361c3412766440edfee1676d..318df85c8deb21cf681b24ad742928f145373764 100644 (file)
@@ -26,6 +26,7 @@ import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import com.google.common.util.concurrent.Futures;
+import java.io.IOException;
 import java.io.InputStream;
 import java.net.InetSocketAddress;
 import java.util.ArrayList;
@@ -75,40 +76,46 @@ import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
 import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
+import org.xml.sax.SAXException;
 
+@SuppressWarnings("checkstyle:IllegalCatch")
 public class NetconfDeviceTest {
 
-    private static final NetconfMessage notification;
+    private static final NetconfMessage NOTIFICATION;
 
-    private static final ContainerNode compositeNode;
+    private static final ContainerNode COMPOSITE_NODE;
 
     static {
         try {
-            compositeNode = mockClass(ContainerNode.class);
+            COMPOSITE_NODE = mockClass(ContainerNode.class);
         } catch (final Exception e) {
             throw new RuntimeException(e);
         }
         try {
-            notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
-        } catch (Exception e) {
+            NOTIFICATION = new NetconfMessage(XmlUtil
+                    .readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
+        } catch (SAXException | IOException e) {
             throw new ExceptionInInitializerError(e);
         }
     }
 
-    private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
+    private static final DOMRpcResult RPC_RESULT = new DefaultDOMRpcResult(COMPOSITE_NODE);
 
     public static final String TEST_NAMESPACE = "test:namespace";
     public static final String TEST_MODULE = "test-module";
     public static final String TEST_REVISION = "2013-07-22";
     public static final SourceIdentifier TEST_SID =
             RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
-    public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION;
+    public static final String TEST_CAPABILITY =
+            TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION;
 
     public static final SourceIdentifier TEST_SID2 =
             RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
-    public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&amp;revision=" + TEST_REVISION;
+    public static final String TEST_CAPABILITY2 =
+            TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&amp;revision=" + TEST_REVISION;
 
-    private static final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id) -> NetconfStateSchemas.EMPTY;
+    private static final NetconfDeviceSchemasResolver STATE_SCHEMAS_RESOLVER =
+        (deviceRpc, remoteSessionCapabilities, id) -> NetconfStateSchemas.EMPTY;
 
     @Test
     public void testNetconfDeviceFlawedModelFailedResolution() throws Exception {
@@ -133,12 +140,13 @@ public class NetconfDeviceTest {
             final Module first = Iterables.getFirst(schema.getModules(), null);
             final QName qName = QName.create(first.getQNameModule(), first.getName());
             final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
-            final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
+            final NetconfStateSchemas.RemoteYangSchema source2 =
+                    new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
             return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
         };
 
-        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
-                = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+                .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
 
         final NetconfDevice device = new NetconfDeviceBuilder()
                 .setReconnectOnSchemasChange(true)
@@ -148,10 +156,12 @@ public class NetconfDeviceTest {
                 .setSalFacade(facade)
                 .build();
         // Monitoring supported
-        final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
+        final NetconfSessionPreferences sessionCaps =
+                getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
         device.onRemoteSessionUp(sessionCaps, listener);
 
-        Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+        Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
         Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
     }
 
@@ -173,8 +183,8 @@ public class NetconfDeviceTest {
                 schemaResolutionException))
                 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
 
-        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
-                = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+                .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, STATE_SCHEMAS_RESOLVER);
         final NetconfDevice device = new NetconfDeviceBuilder()
                 .setReconnectOnSchemasChange(true)
                 .setSchemaResourcesDTO(schemaResourcesDTO)
@@ -202,8 +212,10 @@ public class NetconfDeviceTest {
         final SchemaRepository schemaRepository = getSchemaRepository();
 
         // Make fallback attempt to fail due to empty resolved sources
-        final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
-        doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException)).when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
+        final MissingSchemaSourceException schemaResolutionException =
+                new MissingSchemaSourceException("fail first", TEST_SID);
+        doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException))
+                .when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
         doAnswer(invocation -> {
             if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
                 return Futures.immediateFailedCheckedFuture(schemaResolutionException);
@@ -216,12 +228,13 @@ public class NetconfDeviceTest {
             final Module first = Iterables.getFirst(schema.getModules(), null);
             final QName qName = QName.create(first.getQNameModule(), first.getName());
             final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
-            final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
+            final NetconfStateSchemas.RemoteYangSchema source2 =
+                    new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
             return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
         };
 
-        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
-                = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
+                .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
 
         final NetconfDevice device = new NetconfDeviceBuilder()
                 .setReconnectOnSchemasChange(true)
@@ -231,10 +244,12 @@ public class NetconfDeviceTest {
                 .setSalFacade(facade)
                 .build();
         // Monitoring supported
-        final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
+        final NetconfSessionPreferences sessionCaps =
+                getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
         device.onRemoteSessionUp(sessionCaps, listener);
 
-        Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+        Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
         Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
     }
 
@@ -242,14 +257,17 @@ public class NetconfDeviceTest {
         final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
         final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
         doNothing().when(mockReg).close();
-        doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
+        doReturn(mockReg).when(mock).registerSchemaSource(
+                any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class),
+                any(PotentialSchemaSource.class));
         return mock;
     }
 
     private static SchemaRepository getSchemaRepository() {
         final SchemaRepository mock = mock(SchemaRepository.class);
         final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
-        doReturn(Futures.immediateCheckedFuture(mockRep)).when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
+        doReturn(Futures.immediateCheckedFuture(mockRep))
+                .when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
         return mock;
     }
 
@@ -258,8 +276,8 @@ public class NetconfDeviceTest {
         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
         final NetconfDeviceCommunicator listener = getListener();
 
-        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
-                = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), stateSchemasResolver);
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+                getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), STATE_SCHEMAS_RESOLVER);
         final NetconfDevice device = new NetconfDeviceBuilder()
                 .setReconnectOnSchemasChange(true)
                 .setSchemaResourcesDTO(schemaResourcesDTO)
@@ -268,8 +286,8 @@ public class NetconfDeviceTest {
                 .setSalFacade(facade)
                 .build();
 
-        device.onNotification(notification);
-        device.onNotification(notification);
+        device.onNotification(NOTIFICATION);
+        device.onNotification(NOTIFICATION);
 
         verify(facade, times(0)).onNotification(any(DOMNotification.class));
 
@@ -278,11 +296,12 @@ public class NetconfDeviceTest {
 
         final DOMRpcService deviceRpc = mock(DOMRpcService.class);
 
-        device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
+        device.handleSalInitializationSuccess(
+                NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
 
         verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
 
-        device.onNotification(notification);
+        device.onNotification(NOTIFICATION);
         verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
     }
 
@@ -293,8 +312,8 @@ public class NetconfDeviceTest {
 
         final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
 
-        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
-                = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+                getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
         final NetconfDevice device = new NetconfDeviceBuilder()
                 .setReconnectOnSchemasChange(true)
                 .setSchemaResourcesDTO(schemaResourcesDTO)
@@ -307,7 +326,8 @@ public class NetconfDeviceTest {
         device.onRemoteSessionUp(sessionCaps, listener);
 
         verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
-        verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+        verify(facade, timeout(5000)).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
 
         device.onRemoteSessionDown();
         verify(facade, timeout(5000)).onDeviceDisconnected();
@@ -315,7 +335,8 @@ public class NetconfDeviceTest {
         device.onRemoteSessionUp(sessionCaps, listener);
 
         verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
-        verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+        verify(facade, timeout(5000).times(2)).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
     }
 
     @Test
@@ -325,8 +346,8 @@ public class NetconfDeviceTest {
 
         final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
 
-        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
-                = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, stateSchemasResolver);
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
+                getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
         final NetconfDevice device = new NetconfDeviceBuilder()
                 .setReconnectOnSchemasChange(true)
                 .setSchemaResourcesDTO(schemaResourcesDTO)
@@ -340,21 +361,27 @@ public class NetconfDeviceTest {
                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
         Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
         moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
-        moduleBasedCaps.put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
+        moduleBasedCaps
+                .put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
 
         netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
 
         ArgumentCaptor argument = ArgumentCaptor.forClass(NetconfSessionPreferences.class);
-        verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
-        NetconfDeviceCapabilities netconfDeviceCaps = ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
-
-        netconfDeviceCaps.getResolvedCapabilities().forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
-                moduleBasedCaps.get(QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
+        verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(
+                any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
+        NetconfDeviceCapabilities netconfDeviceCaps =
+                ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
+
+        netconfDeviceCaps.getResolvedCapabilities()
+                .forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
+                        moduleBasedCaps.get(
+                                QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
     }
 
     private static SchemaContextFactory getSchemaFactory() throws Exception {
         final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
-        doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
+        doReturn(Futures.immediateCheckedFuture(getSchema()))
+                .when(schemaFactory).createSchemaContext(any(Collection.class));
         return schemaFactory;
     }
 
@@ -366,8 +393,10 @@ public class NetconfDeviceTest {
     }
 
     private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
-        final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
-        doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+        final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
+                mockCloseableClass(RemoteDeviceHandler.class);
+        doNothing().when(remoteDeviceHandler).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
         doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
         return remoteDeviceHandler;
@@ -396,18 +425,19 @@ public class NetconfDeviceTest {
 
     public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
         final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
-        doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
-        doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
-        doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
+        doReturn(NOTIFICATION).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
+        doReturn(RPC_RESULT).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
+        doReturn(COMPOSITE_NODE).when(messageTransformer).toNotification(any(NetconfMessage.class));
         return messageTransformer;
     }
 
-    public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
+    public NetconfSessionPreferences getSessionCaps(final boolean addMonitor,
+                                                    final Collection<String> additionalCapabilities) {
         final ArrayList<String> capabilities = Lists.newArrayList(
                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
 
-        if(addMonitor) {
+        if (addMonitor) {
             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
         }
 
@@ -419,7 +449,8 @@ public class NetconfDeviceTest {
 
     public NetconfDeviceCommunicator getListener() throws Exception {
         final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
-//        doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
+//        doReturn(Futures.immediateFuture(rpcResult))
+//                .when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
         return remoteDeviceCommunicator;
     }
 }
index 92d31ab734f630c5e1d517deb5124c364bfaa9dc..fd2ea869c72a2a0db4dec51d226ecf29f5d46d92 100644 (file)
@@ -58,16 +58,21 @@ import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.Dom
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 public class NetconfStateSchemasTest {
 
-    private static final NetconfSessionPreferences CAPS = NetconfSessionPreferences.fromStrings(Collections.singleton("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04"));
+    private static final Logger LOG = LoggerFactory.getLogger(NetconfStateSchemasTest.class);
+
+    private static final NetconfSessionPreferences CAPS = NetconfSessionPreferences.fromStrings(Collections.singleton(
+        "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04"));
     private final RemoteDeviceId deviceId = new RemoteDeviceId("device", new InetSocketAddress(99));
+    private final int numberOfSchemas = 73;
+    private final int numberOfLegalSchemas = numberOfSchemas - 3;
     private ContainerNode compositeNodeSchemas;
-    private final int NUMBER_OF_SCHEMAS = 73;
-    private final int NUMBER_OF_LEGAL_SCHEMAS = NUMBER_OF_SCHEMAS - 3;
 
     @Mock
     private DOMRpcService rpc;
@@ -79,9 +84,13 @@ public class NetconfStateSchemasTest {
         final DataSchemaNode schemasNode =
                 ((ContainerSchemaNode) schemaContext
                         .getDataChildByName(NetconfState.QNAME)).getDataChildByName(Schemas.QNAME);
-        final Document schemasXml = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconf-state.schemas.payload.xml"));
-        final ToNormalizedNodeParser<Element, ContainerNode, ContainerSchemaNode> containerNodeParser = DomToNormalizedNodeParserFactory.getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, false).getContainerNodeParser();
-        compositeNodeSchemas = containerNodeParser.parse(Collections.singleton(schemasXml.getDocumentElement()), (ContainerSchemaNode) schemasNode);
+        final Document schemasXml =
+                XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconf-state.schemas.payload.xml"));
+        final ToNormalizedNodeParser<Element, ContainerNode, ContainerSchemaNode> containerNodeParser =
+                DomToNormalizedNodeParserFactory
+                    .getInstance(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, schemaContext, false).getContainerNodeParser();
+        compositeNodeSchemas = containerNodeParser
+                .parse(Collections.singleton(schemasXml.getDocumentElement()), (ContainerSchemaNode) schemasNode);
 
     }
 
@@ -90,7 +99,7 @@ public class NetconfStateSchemasTest {
         final NetconfStateSchemas schemas = NetconfStateSchemas.create(deviceId, compositeNodeSchemas);
 
         final Set<QName> availableYangSchemasQNames = schemas.getAvailableYangSchemasQNames();
-        assertEquals(NUMBER_OF_LEGAL_SCHEMAS, availableYangSchemasQNames.size());
+        assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
 
         assertThat(availableYangSchemasQNames,
                 hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
@@ -103,17 +112,20 @@ public class NetconfStateSchemasTest {
                 .withChild(compositeNodeSchemas)
                 .build();
         final ContainerNode data = Builders.containerBuilder()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
+                .withNodeIdentifier(new YangInstanceIdentifier
+                        .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME))
                 .withChild(netconfState)
                 .build();
         final ContainerNode rpcReply = Builders.containerBuilder()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
+                .withNodeIdentifier(new YangInstanceIdentifier
+                        .NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME))
                 .withChild(data)
                 .build();
-        when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcReply)));
+        when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
+                .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcReply)));
         final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
         final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
-        assertEquals(NUMBER_OF_LEGAL_SCHEMAS, availableYangSchemasQNames.size());
+        assertEquals(numberOfLegalSchemas, availableYangSchemasQNames.size());
 
         assertThat(availableYangSchemasQNames,
                 hasItem(QName.create("urn:TBD:params:xml:ns:yang:network-topology", "2013-07-12", "network-topology")));
@@ -140,12 +152,14 @@ public class NetconfStateSchemasTest {
     @Test
     public void testCreateRpcError() throws Exception {
         final RpcError rpcError = RpcResultBuilder.newError(RpcError.ErrorType.RPC, "fail", "fail");
-        when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)));
+        when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any()))
+                .thenReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(rpcError)));
         final NetconfStateSchemas stateSchemas = NetconfStateSchemas.create(rpc, CAPS, deviceId);
         final Set<QName> availableYangSchemasQNames = stateSchemas.getAvailableYangSchemasQNames();
         Assert.assertTrue(availableYangSchemasQNames.isEmpty());
     }
 
+    @SuppressWarnings("checkstyle:IllegalThrows")
     @Test(expected = RuntimeException.class)
     public void testCreateInterrupted() throws Throwable {
         //NetconfStateSchemas.create calls Thread.currentThread().interrupt(), so it must run in its own thread
@@ -157,7 +171,7 @@ public class NetconfStateSchemasTest {
                 when(rpc.invokeRpc(eq(toPath(NETCONF_GET_QNAME)), any())).thenReturn(checkedFuture);
                 NetconfStateSchemas.create(rpc, CAPS, deviceId);
             } catch (final InterruptedException | ExecutionException e) {
-                e.printStackTrace();
+                LOG.info("Operation failed.", e);
             }
 
         });
@@ -170,9 +184,12 @@ public class NetconfStateSchemasTest {
 
     @Test
     public void testRemoteYangSchemaEquals() throws Exception {
-        final NetconfStateSchemas.RemoteYangSchema schema1 = new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
-        final NetconfStateSchemas.RemoteYangSchema schema2 = new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
-        final NetconfStateSchemas.RemoteYangSchema schema3 = new NetconfStateSchemas.RemoteYangSchema(Schemas.QNAME);
+        final NetconfStateSchemas.RemoteYangSchema schema1 =
+                new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
+        final NetconfStateSchemas.RemoteYangSchema schema2 =
+                new NetconfStateSchemas.RemoteYangSchema(NetconfState.QNAME);
+        final NetconfStateSchemas.RemoteYangSchema schema3 =
+                new NetconfStateSchemas.RemoteYangSchema(Schemas.QNAME);
         Assert.assertEquals(schema1, schema2);
         Assert.assertEquals(schema2, schema1);
         Assert.assertNotEquals(schema1, schema3);
index f2c85eade3e25c522239f53d26f2a90cb1c3250e..20502f45e982088b2f74d0cb588c5273ee204e64 100644 (file)
@@ -47,7 +47,8 @@ public class NetconfToNotificationTest {
         userNotification = new NetconfMessage(doc);
     }
 
-    static SchemaContext getNotificationSchemaContext(final Class<?> loadClass, final boolean getExceptionTest) throws Exception {
+    static SchemaContext getNotificationSchemaContext(final Class<?> loadClass,
+                                                      final boolean getExceptionTest) throws Exception {
         final List<InputStream> modelsToParse = new ArrayList<>();
 
         if (getExceptionTest) {
index 15c6c7316c788411b7d94457a0c0d818348e9f6b..10cb4e3236f4ca49a6f8da2de2b172432b87ad01 100644 (file)
@@ -37,25 +37,28 @@ import org.w3c.dom.Document;
 
 public class NetconfToRpcRequestTest {
 
-    private final static String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
-    private final static String REVISION = "2014-07-14";
-    private final static QName INPUT_QNAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "input");
-    private final static QName STREAM_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "stream-name");
-    private final static QName SUBSCRIBE_RPC_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "subscribe");
-
-    private final static String CONFIG_TEST_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:rpc:config:defs";
-    private final static String CONFIG_TEST_REVISION = "2014-07-21";
-    private final static QName EDIT_CONFIG_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "edit-config");
-    private final static QName GET_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get");
-    private final static QName GET_CONFIG_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get-config");
+    private static final String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
+    private static final String REVISION = "2014-07-14";
+    private static final QName INPUT_QNAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "input");
+    private static final QName STREAM_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "stream-name");
+    private static final QName SUBSCRIBE_RPC_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "subscribe");
+
+    private static final String CONFIG_TEST_NAMESPACE =
+            "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:rpc:config:defs";
+    private static final String CONFIG_TEST_REVISION = "2014-07-21";
+    private static final QName EDIT_CONFIG_QNAME =
+            QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "edit-config");
+    private static final QName GET_QNAME = QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get");
+    private static final QName GET_CONFIG_QNAME =
+            QName.create(CONFIG_TEST_NAMESPACE, CONFIG_TEST_REVISION, "get-config");
 
     static SchemaContext cfgCtx;
     static NetconfMessageTransformer messageTransformer;
 
     @BeforeClass
     public static void setup() throws Exception {
-        List<InputStream> modelsToParse = Collections
-            .singletonList(NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
+        List<InputStream> modelsToParse = Collections.singletonList(
+                NetconfToRpcRequestTest.class.getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
         final Set<Module> notifModules = YangParserTestUtils.parseYangStreams(modelsToParse).getModules();
         assertTrue(!notifModules.isEmpty());
 
@@ -72,7 +75,8 @@ public class NetconfToRpcRequestTest {
 
     @Test
     public void testUserDefinedRpcCall() throws Exception {
-        final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> rootBuilder = Builders.containerBuilder();
+        final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> rootBuilder =
+                Builders.containerBuilder();
         rootBuilder.withNodeIdentifier(toId(SUBSCRIBE_RPC_NAME));
 
         rootBuilder.withChild(buildLeaf(STREAM_NAME, "NETCONF"));
@@ -97,11 +101,11 @@ public class NetconfToRpcRequestTest {
     @Test(expected = IllegalArgumentException.class)
     public void testRpcResponse() throws Exception {
         final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
-                "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-5\">\n" +
-                "<data xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">" +
-                "module schema" +
-                "</data>\n" +
-                "</rpc-reply>\n"
+                "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-5\">\n"
+                        + "<data xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">"
+                        + "module schema"
+                        + "</data>\n"
+                        + "</rpc-reply>\n"
         ));
 
         messageTransformer.toRpcResult(response, toPath(EDIT_CONFIG_QNAME));
index c336033190f8d59a13a0853760d9fd9e78dd1fd2..07bed0593d53b5e9059eae8897a7d7a71cd8ef75 100644 (file)
@@ -55,7 +55,8 @@ public class SchemalessNetconfDeviceTest {
         final NetconfMessage netconfMessage = mock(NetconfMessage.class);
 
         device.onRemoteSessionUp(sessionCaps, listener);
-        verify(facade).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+        verify(facade).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
 
         device.onNotification(netconfMessage);
         verify(facade).onNotification(any(DOMNotification.class));
@@ -69,14 +70,17 @@ public class SchemalessNetconfDeviceTest {
 
     @SuppressWarnings("unchecked")
     private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
-        final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
-        doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+        final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
+                mockCloseableClass(RemoteDeviceHandler.class);
+        doNothing().when(remoteDeviceHandler).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
         doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
         return remoteDeviceHandler;
     }
 
-    private static <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
+    private static <T extends AutoCloseable> T mockCloseableClass(
+            final Class<T> remoteDeviceHandlerClass) throws Exception {
         final T mock = mockClass(remoteDeviceHandlerClass);
         doNothing().when(mock).close();
         return mock;
@@ -88,12 +92,13 @@ public class SchemalessNetconfDeviceTest {
         return mock;
     }
 
-    private static NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
+    private static NetconfSessionPreferences getSessionCaps(final boolean addMonitor,
+                                                            final Collection<String> additionalCapabilities) {
         final ArrayList<String> capabilities = Lists.newArrayList(
                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
 
-        if(addMonitor) {
+        if (addMonitor) {
             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
         }
 
index d97320fbc4429cb5278524c636ccb2080753423a..da24dd0e5107c3cc693b3124ba37ff45da5ca5ba 100644 (file)
@@ -68,11 +68,15 @@ import org.opendaylight.yangtools.util.xml.UntrustedXML;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 public class NetconfDeviceCommunicatorTest {
 
+    private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicatorTest.class);
+
     @Mock
     NetconfClientSession mockSession;
 
@@ -83,9 +87,10 @@ public class NetconfDeviceCommunicatorTest {
 
     @Before
     public void setUp() throws Exception {
-        MockitoAnnotations.initMocks( this );
+        MockitoAnnotations.initMocks(this);
 
-        communicator = new NetconfDeviceCommunicator( new RemoteDeviceId( "test", InetSocketAddress.createUnresolved("localhost", 22)), mockDevice, 10);
+        communicator = new NetconfDeviceCommunicator(
+                new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), mockDevice, 10);
     }
 
     void setupSession() {
@@ -96,25 +101,26 @@ public class NetconfDeviceCommunicatorTest {
     }
 
     private ListenableFuture<RpcResult<NetconfMessage>> sendRequest() throws Exception {
-        return sendRequest( UUID.randomUUID().toString(), true );
+        return sendRequest(UUID.randomUUID().toString(), true);
     }
 
     @SuppressWarnings("unchecked")
-    private ListenableFuture<RpcResult<NetconfMessage>> sendRequest( final String messageID, final boolean doLastTest ) throws Exception {
+    private ListenableFuture<RpcResult<NetconfMessage>> sendRequest(final String messageID,
+                                                                    final boolean doLastTest) throws Exception {
         Document doc = UntrustedXML.newDocumentBuilder().newDocument();
-        Element element = doc.createElement( "request" );
-        element.setAttribute( "message-id", messageID );
-        doc.appendChild( element );
-        NetconfMessage message = new NetconfMessage( doc );
+        Element element = doc.createElement("request");
+        element.setAttribute("message-id", messageID);
+        doc.appendChild(element);
+        NetconfMessage message = new NetconfMessage(doc);
 
-        ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
-        doReturn( mockChannelFuture ).when( mockChannelFuture )
-            .addListener( any( (GenericFutureListener.class ) ) );
-        doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+        ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+        doReturn(mockChannelFuture).when(mockChannelFuture)
+                .addListener(any((GenericFutureListener.class)));
+        doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
 
         ListenableFuture<RpcResult<NetconfMessage>> resultFuture =
-                                      communicator.sendRequest( message, QName.create( "mock rpc" ) );
-        if(doLastTest) {
+                communicator.sendRequest(message, QName.create("mock rpc"));
+        if (doLastTest) {
             assertNotNull("ListenableFuture is null", resultFuture);
         }
         return resultFuture;
@@ -124,53 +130,53 @@ public class NetconfDeviceCommunicatorTest {
     public void testOnSessionUp() {
         String testCapability = "urn:opendaylight:params:xml:ns:test?module=test-module&revision=2014-06-02";
         Collection<String> serverCapabilities =
-                Sets.newHashSet( NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
-                                 NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
-                                 testCapability );
-        doReturn( serverCapabilities ).when( mockSession ).getServerCapabilities();
-
-        ArgumentCaptor<NetconfSessionPreferences> NetconfSessionPreferences =
-                                              ArgumentCaptor.forClass( NetconfSessionPreferences.class );
-        doNothing().when( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
-
-        communicator.onSessionUp( mockSession );
-
-        verify( mockSession ).getServerCapabilities();
-        verify( mockDevice ).onRemoteSessionUp( NetconfSessionPreferences.capture(), eq( communicator ) );
-
-        NetconfSessionPreferences actualCapabilites = NetconfSessionPreferences.getValue();
-        assertEquals( "containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
-                NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()) );
-        assertEquals( "containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability) );
-        assertEquals( "getModuleBasedCaps", Sets.newHashSet(
-                            QName.create( "urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module" )),
-                      actualCapabilites.getModuleBasedCaps());
-        assertEquals( "isRollbackSupported", true, actualCapabilites.isRollbackSupported() );
-        assertEquals( "isMonitoringSupported", true, actualCapabilites.isMonitoringSupported() );
+                Sets.newHashSet(NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString(),
+                        NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString(),
+                        testCapability);
+        doReturn(serverCapabilities).when(mockSession).getServerCapabilities();
+
+        ArgumentCaptor<NetconfSessionPreferences> netconfSessionPreferences =
+                ArgumentCaptor.forClass(NetconfSessionPreferences.class);
+        doNothing().when(mockDevice).onRemoteSessionUp(netconfSessionPreferences.capture(), eq(communicator));
+
+        communicator.onSessionUp(mockSession);
+
+        verify(mockSession).getServerCapabilities();
+        verify(mockDevice).onRemoteSessionUp(netconfSessionPreferences.capture(), eq(communicator));
+
+        NetconfSessionPreferences actualCapabilites = netconfSessionPreferences.getValue();
+        assertEquals("containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
+                NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()));
+        assertEquals("containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability));
+        assertEquals("getModuleBasedCaps", Sets.newHashSet(
+                QName.create("urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module")),
+                actualCapabilites.getModuleBasedCaps());
+        assertEquals("isRollbackSupported", true, actualCapabilites.isRollbackSupported());
+        assertEquals("isMonitoringSupported", true, actualCapabilites.isMonitoringSupported());
     }
 
     @SuppressWarnings("unchecked")
-    @Test(timeout=5000)
+    @Test(timeout = 5000)
     public void testOnSessionDown() throws Exception {
         setupSession();
 
         ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
+        final ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest();
 
-        doNothing().when( mockDevice ).onRemoteSessionDown();
+        doNothing().when(mockDevice).onRemoteSessionDown();
 
-        communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
+        communicator.onSessionDown(mockSession, new Exception("mock ex"));
 
-        verifyErrorRpcResult( resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
-        verifyErrorRpcResult( resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed" );
+        verifyErrorRpcResult(resultFuture1.get(), RpcError.ErrorType.TRANSPORT, "operation-failed");
+        verifyErrorRpcResult(resultFuture2.get(), RpcError.ErrorType.TRANSPORT, "operation-failed");
 
-        verify( mockDevice ).onRemoteSessionDown();
+        verify(mockDevice).onRemoteSessionDown();
 
-        reset( mockDevice );
+        reset(mockDevice);
 
-        communicator.onSessionDown( mockSession, new Exception( "mock ex" ) );
+        communicator.onSessionDown(mockSession, new Exception("mock ex"));
 
-        verify( mockDevice, never() ).onRemoteSessionDown();
+        verify(mockDevice, never()).onRemoteSessionDown();
     }
 
     @Test
@@ -179,71 +185,86 @@ public class NetconfDeviceCommunicatorTest {
 
         ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest();
 
-        doNothing().when( mockDevice ).onRemoteSessionDown();
+        doNothing().when(mockDevice).onRemoteSessionDown();
 
         String reasonText = "testing terminate";
-        NetconfTerminationReason reason = new NetconfTerminationReason( reasonText );
-        communicator.onSessionTerminated( mockSession, reason );
+        NetconfTerminationReason reason = new NetconfTerminationReason(reasonText);
+        communicator.onSessionTerminated(mockSession, reason);
 
-        RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.TRANSPORT,
-                                                  "operation-failed" );
-        assertEquals( "RpcError message", reasonText, rpcError.getMessage() );
+        RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.TRANSPORT,
+                "operation-failed");
+        assertEquals("RpcError message", reasonText, rpcError.getMessage());
 
-        verify( mockDevice ).onRemoteSessionDown();
+        verify(mockDevice).onRemoteSessionDown();
     }
 
     @Test
     public void testClose() throws Exception {
         communicator.close();
-        verify( mockDevice, never() ).onRemoteSessionDown();
+        verify(mockDevice, never()).onRemoteSessionDown();
     }
 
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     @Test
     public void testSendRequest() throws Exception {
         setupSession();
 
         NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
-        QName rpc = QName.create( "mock rpc" );
+        QName rpc = QName.create("mock rpc");
 
         ArgumentCaptor<GenericFutureListener> futureListener =
-                                            ArgumentCaptor.forClass( GenericFutureListener.class );
+                ArgumentCaptor.forClass(GenericFutureListener.class);
 
-        ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
-        doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
-        doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+        ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+        doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
+        doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
 
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
 
-        verify( mockSession ).sendMessage( same( message ) );
+        verify(mockSession).sendMessage(same(message));
 
-        assertNotNull( "ListenableFuture is null", resultFuture );
+        assertNotNull("ListenableFuture is null", resultFuture);
 
-        verify( mockChannelFuture ).addListener( futureListener.capture() );
-        Future<Void> operationFuture = mock( Future.class );
-        doReturn( true ).when( operationFuture ).isSuccess();
-        doReturn( true ).when( operationFuture ).isDone();
-        futureListener.getValue().operationComplete( operationFuture );
+        verify(mockChannelFuture).addListener(futureListener.capture());
+        Future<Void> operationFuture = mock(Future.class);
+        doReturn(true).when(operationFuture).isSuccess();
+        doReturn(true).when(operationFuture).isDone();
+        futureListener.getValue().operationComplete(operationFuture);
 
         try {
-            resultFuture.get( 1, TimeUnit.MILLISECONDS ); // verify it's not cancelled or has an error set
-        }
-        catch( TimeoutException e ) {} // expected
+            resultFuture.get(1, TimeUnit.MILLISECONDS); // verify it's not cancelled or has an error set
+        } catch (TimeoutException e) {
+            LOG.info("Operation failed due timeout.");
+        } // expected
     }
 
     @Test
     public void testSendRequestWithNoSession() throws Exception {
         NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
-        QName rpc = QName.create( "mock rpc" );
+        QName rpc = QName.create("mock rpc");
 
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
 
-        assertNotNull( "ListenableFuture is null", resultFuture );
+        assertNotNull("ListenableFuture is null", resultFuture);
 
         // Should have an immediate result
-        RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
+        RpcResult<NetconfMessage> rpcResult = resultFuture.get(3, TimeUnit.MILLISECONDS);
+
+        verifyErrorRpcResult(rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed");
+    }
 
-        verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
+    private static NetconfMessage createSuccessResponseMessage(final String messageID)
+            throws ParserConfigurationException {
+        Document doc = UntrustedXML.newDocumentBuilder().newDocument();
+        Element rpcReply =
+                doc.createElementNS(URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
+        rpcReply.setAttribute("message-id", messageID);
+        Element element = doc.createElementNS("ns", "data");
+        element.setTextContent(messageID);
+        rpcReply.appendChild(element);
+        doc.appendChild(rpcReply);
+
+        return new NetconfMessage(doc);
     }
 
     @SuppressWarnings({ "rawtypes", "unchecked" })
@@ -252,45 +273,33 @@ public class NetconfDeviceCommunicatorTest {
         setupSession();
 
         NetconfMessage message = new NetconfMessage(UntrustedXML.newDocumentBuilder().newDocument());
-        QName rpc = QName.create( "mock rpc" );
+        QName rpc = QName.create("mock rpc");
 
         ArgumentCaptor<GenericFutureListener> futureListener =
-                                            ArgumentCaptor.forClass( GenericFutureListener.class );
+                ArgumentCaptor.forClass(GenericFutureListener.class);
 
-        ChannelFuture mockChannelFuture = mock( ChannelFuture.class );
-        doReturn( mockChannelFuture ).when( mockChannelFuture ).addListener( futureListener.capture() );
-        doReturn( mockChannelFuture ).when( mockSession ).sendMessage( same( message ) );
+        ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
+        doReturn(mockChannelFuture).when(mockChannelFuture).addListener(futureListener.capture());
+        doReturn(mockChannelFuture).when(mockSession).sendMessage(same(message));
 
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest( message, rpc );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = communicator.sendRequest(message, rpc);
 
-        assertNotNull( "ListenableFuture is null", resultFuture );
+        assertNotNull("ListenableFuture is null", resultFuture);
 
-        verify( mockChannelFuture ).addListener( futureListener.capture() );
+        verify(mockChannelFuture).addListener(futureListener.capture());
 
-        Future<Void> operationFuture = mock( Future.class );
-        doReturn( false ).when( operationFuture ).isSuccess();
-        doReturn( true ).when( operationFuture ).isDone();
-        doReturn( new Exception( "mock error" ) ).when( operationFuture ).cause();
-        futureListener.getValue().operationComplete( operationFuture );
+        Future<Void> operationFuture = mock(Future.class);
+        doReturn(false).when(operationFuture).isSuccess();
+        doReturn(true).when(operationFuture).isDone();
+        doReturn(new Exception("mock error")).when(operationFuture).cause();
+        futureListener.getValue().operationComplete(operationFuture);
 
         // Should have an immediate result
-        RpcResult<NetconfMessage> rpcResult = resultFuture.get( 3, TimeUnit.MILLISECONDS );
-
-        RpcError rpcError = verifyErrorRpcResult( rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed" );
-        assertEquals( "RpcError message contains \"mock error\"", true,
-                    rpcError.getMessage().contains( "mock error" ) );
-    }
+        RpcResult<NetconfMessage> rpcResult = resultFuture.get(3, TimeUnit.MILLISECONDS);
 
-    private static NetconfMessage createSuccessResponseMessage( final String messageID ) throws ParserConfigurationException {
-        Document doc = UntrustedXML.newDocumentBuilder().newDocument();
-        Element rpcReply = doc.createElementNS( URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlMappingConstants.RPC_REPLY_KEY);
-        rpcReply.setAttribute( "message-id", messageID );
-        Element element = doc.createElementNS( "ns", "data" );
-        element.setTextContent( messageID );
-        rpcReply.appendChild( element );
-        doc.appendChild( rpcReply );
-
-        return new NetconfMessage( doc );
+        RpcError rpcError = verifyErrorRpcResult(rpcResult, RpcError.ErrorType.TRANSPORT, "operation-failed");
+        assertEquals("RpcError message contains \"mock error\"", true,
+                rpcError.getMessage().contains("mock error"));
     }
 
     //Test scenario verifying whether missing message is handled
@@ -300,18 +309,18 @@ public class NetconfDeviceCommunicatorTest {
         setupSession();
 
         String messageID1 = UUID.randomUUID().toString();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest(messageID1, true);
 
         String messageID2 = UUID.randomUUID().toString();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest(messageID2, true);
 
         String messageID3 = UUID.randomUUID().toString();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture3 = sendRequest( messageID3, true );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture3 = sendRequest(messageID3, true);
 
         //response messages 1,2 are omitted
-        communicator.onMessage( mockSession, createSuccessResponseMessage( messageID3 ) );
+        communicator.onMessage(mockSession, createSuccessResponseMessage(messageID3));
 
-        verifyResponseMessage( resultFuture3.get(), messageID3 );
+        verifyResponseMessage(resultFuture3.get(), messageID3);
     }
 
     @Test
@@ -319,16 +328,16 @@ public class NetconfDeviceCommunicatorTest {
         setupSession();
 
         String messageID1 = UUID.randomUUID().toString();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest( messageID1, true );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture1 = sendRequest(messageID1, true);
 
         String messageID2 = UUID.randomUUID().toString();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest( messageID2, true );
+        final ListenableFuture<RpcResult<NetconfMessage>> resultFuture2 = sendRequest(messageID2, true);
 
-        communicator.onMessage( mockSession, createSuccessResponseMessage( messageID1 ) );
-        communicator.onMessage( mockSession, createSuccessResponseMessage( messageID2 ) );
+        communicator.onMessage(mockSession, createSuccessResponseMessage(messageID1));
+        communicator.onMessage(mockSession, createSuccessResponseMessage(messageID2));
 
-        verifyResponseMessage( resultFuture1.get(), messageID1 );
-        verifyResponseMessage( resultFuture2.get(), messageID2 );
+        verifyResponseMessage(resultFuture1.get(), messageID1);
+        verifyResponseMessage(resultFuture2.get(), messageID2);
     }
 
     @Test
@@ -336,30 +345,32 @@ public class NetconfDeviceCommunicatorTest {
         setupSession();
 
         String messageID = UUID.randomUUID().toString();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(messageID, true);
 
-        communicator.onMessage( mockSession, createErrorResponseMessage( messageID ) );
+        communicator.onMessage(mockSession, createErrorResponseMessage(messageID));
 
-        RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.RPC,
-                                                  "missing-attribute" );
-        assertEquals( "RpcError message", "Missing attribute", rpcError.getMessage() );
+        RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.RPC,
+                "missing-attribute");
+        assertEquals("RpcError message", "Missing attribute", rpcError.getMessage());
 
         String errorInfo = rpcError.getInfo();
-        assertNotNull( "RpcError info is null", errorInfo );
-        assertEquals( "Error info contains \"foo\"", true,
-                      errorInfo.contains( "<bad-attribute>foo</bad-attribute>" ) );
-        assertEquals( "Error info contains \"bar\"", true,
-                      errorInfo.contains( "<bad-element>bar</bad-element>" ) );
+        assertNotNull("RpcError info is null", errorInfo);
+        assertEquals("Error info contains \"foo\"", true,
+                errorInfo.contains("<bad-attribute>foo</bad-attribute>"));
+        assertEquals("Error info contains \"bar\"", true,
+                errorInfo.contains("<bad-element>bar</bad-element>"));
     }
 
     /**
-     * Test whether reconnect is scheduled properly
+     * Test whether reconnect is scheduled properly.
      */
     @Test
     public void testNetconfDeviceReconnectInCommunicator() throws Exception {
-        final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device = mock(RemoteDevice.class);
+        final RemoteDevice<NetconfSessionPreferences, NetconfMessage, NetconfDeviceCommunicator> device =
+                mock(RemoteDevice.class);
 
-        final TimedReconnectStrategy timedReconnectStrategy = new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
+        final TimedReconnectStrategy timedReconnectStrategy =
+                new TimedReconnectStrategy(GlobalEventExecutor.INSTANCE, 10000, 0, 1.0, null, 100L, null);
         final ReconnectStrategy reconnectStrategy = spy(new ReconnectStrategy() {
             @Override
             public int getConnectTimeout() throws Exception {
@@ -380,7 +391,8 @@ public class NetconfDeviceCommunicatorTest {
         final EventLoopGroup group = new NioEventLoopGroup();
         final Timer time = new HashedWheelTimer();
         try {
-            final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
+            final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(
+                    new RemoteDeviceId("test", InetSocketAddress.createUnresolved("localhost", 22)), device, 10);
             final NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create()
                     .withAddress(new InetSocketAddress("localhost", 65000))
                     .withReconnectStrategy(reconnectStrategy)
@@ -393,7 +405,8 @@ public class NetconfDeviceCommunicatorTest {
 
             listener.initializeRemoteConnection(new NetconfClientDispatcherImpl(group, group, time), cfg);
 
-            verify(reconnectStrategy, timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
+            verify(reconnectStrategy,
+                    timeout((int) TimeUnit.MINUTES.toMillis(3)).times(101)).scheduleReconnect(any(Throwable.class));
         } finally {
             time.stop();
             group.shutdownGracefully();
@@ -405,21 +418,21 @@ public class NetconfDeviceCommunicatorTest {
         setupSession();
 
         String messageID = UUID.randomUUID().toString();
-        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest( messageID, true );
+        ListenableFuture<RpcResult<NetconfMessage>> resultFuture = sendRequest(messageID, true);
 
-        communicator.onMessage( mockSession, createSuccessResponseMessage( UUID.randomUUID().toString() ) );
+        communicator.onMessage(mockSession, createSuccessResponseMessage(UUID.randomUUID().toString()));
 
-        RpcError rpcError = verifyErrorRpcResult( resultFuture.get(), RpcError.ErrorType.PROTOCOL,
-                                                  "bad-attribute" );
-        assertEquals( "RpcError message non-empty", true,
-                      !Strings.isNullOrEmpty( rpcError.getMessage() ) );
+        RpcError rpcError = verifyErrorRpcResult(resultFuture.get(), RpcError.ErrorType.PROTOCOL,
+                "bad-attribute");
+        assertEquals("RpcError message non-empty", true,
+                !Strings.isNullOrEmpty(rpcError.getMessage()));
 
         String errorInfo = rpcError.getInfo();
-        assertNotNull( "RpcError info is null", errorInfo );
-        assertEquals( "Error info contains \"actual-message-id\"", true,
-                      errorInfo.contains( "actual-message-id" ) );
-        assertEquals( "Error info contains \"expected-message-id\"", true,
-                      errorInfo.contains( "expected-message-id" ) );
+        assertNotNull("RpcError info is null", errorInfo);
+        assertEquals("Error info contains \"actual-message-id\"", true,
+                errorInfo.contains("actual-message-id"));
+        assertEquals("Error info contains \"expected-message-id\"", true,
+                errorInfo.contains("expected-message-id"));
     }
 
     @Test
@@ -443,32 +456,31 @@ public class NetconfDeviceCommunicatorTest {
         assertNotNull("ListenableFuture is null", resultFuture);
     }
 
-    private static NetconfMessage createErrorResponseMessage( final String messageID ) throws Exception {
-        String xmlStr =
-            "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"" +
-            "           message-id=\"" + messageID + "\">" +
-            "  <rpc-error>" +
-            "    <error-type>rpc</error-type>" +
-            "    <error-tag>missing-attribute</error-tag>" +
-            "    <error-severity>error</error-severity>" +
-            "    <error-message>Missing attribute</error-message>" +
-            "    <error-info>" +
-            "      <bad-attribute>foo</bad-attribute>" +
-            "      <bad-element>bar</bad-element>" +
-            "    </error-info>" +
-            "  </rpc-error>" +
-            "</rpc-reply>";
-
-        ByteArrayInputStream bis = new ByteArrayInputStream( xmlStr.getBytes() );
+    private static NetconfMessage createErrorResponseMessage(final String messageID) throws Exception {
+        String xmlStr = "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""
+                + "           message-id=\"" + messageID + "\">"
+                + "  <rpc-error>"
+                + "    <error-type>rpc</error-type>"
+                + "    <error-tag>missing-attribute</error-tag>"
+                + "    <error-severity>error</error-severity>"
+                + "    <error-message>Missing attribute</error-message>"
+                + "    <error-info>"
+                + "      <bad-attribute>foo</bad-attribute>"
+                + "      <bad-element>bar</bad-element>"
+                + "    </error-info>"
+                + "  </rpc-error>"
+                + "</rpc-reply>";
+
+        ByteArrayInputStream bis = new ByteArrayInputStream(xmlStr.getBytes());
         Document doc = UntrustedXML.newDocumentBuilder().parse(bis);
-        return new NetconfMessage( doc );
+        return new NetconfMessage(doc);
     }
 
-    private static void verifyResponseMessage( final RpcResult<NetconfMessage> rpcResult, final String dataText ) {
-        assertNotNull( "RpcResult is null", rpcResult );
-        assertEquals( "isSuccessful", true, rpcResult.isSuccessful() );
+    private static void verifyResponseMessage(final RpcResult<NetconfMessage> rpcResult, final String dataText) {
+        assertNotNull("RpcResult is null", rpcResult);
+        assertEquals("isSuccessful", true, rpcResult.isSuccessful());
         NetconfMessage messageResult = rpcResult.getResult();
-        assertNotNull( "getResult", messageResult );
+        assertNotNull("getResult", messageResult);
 //        List<SimpleNode<?>> nodes = messageResult.getSimpleNodesByName(
 //                                         QName.create( URI.create( "ns" ), null, "data" ) );
 //        assertNotNull( "getSimpleNodesByName", nodes );
@@ -476,16 +488,16 @@ public class NetconfDeviceCommunicatorTest {
 //        assertEquals( "SimpleNode value", dataText, nodes.iterator().next().getValue() );
     }
 
-    private static RpcError verifyErrorRpcResult( final RpcResult<NetconfMessage> rpcResult,
-                                           final RpcError.ErrorType expErrorType, final String expErrorTag ) {
-        assertNotNull( "RpcResult is null", rpcResult );
-        assertEquals( "isSuccessful", false, rpcResult.isSuccessful() );
-        assertNotNull( "RpcResult errors is null", rpcResult.getErrors() );
-        assertEquals( "Errors size", 1, rpcResult.getErrors().size() );
+    private static RpcError verifyErrorRpcResult(final RpcResult<NetconfMessage> rpcResult,
+                                                 final RpcError.ErrorType expErrorType, final String expErrorTag) {
+        assertNotNull("RpcResult is null", rpcResult);
+        assertEquals("isSuccessful", false, rpcResult.isSuccessful());
+        assertNotNull("RpcResult errors is null", rpcResult.getErrors());
+        assertEquals("Errors size", 1, rpcResult.getErrors().size());
         RpcError rpcError = rpcResult.getErrors().iterator().next();
-        assertEquals( "getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity() );
-        assertEquals( "getErrorType", expErrorType, rpcError.getErrorType() );
-        assertEquals( "getErrorTag", expErrorTag, rpcError.getTag() );
+        assertEquals("getErrorSeverity", RpcError.ErrorSeverity.ERROR, rpcError.getSeverity());
+        assertEquals("getErrorType", expErrorType, rpcError.getErrorType());
+        assertEquals("getErrorTag", expErrorTag, rpcError.getTag());
 
         final String msg = rpcError.getMessage();
         assertNotNull("getMessage is null", msg);
index db07df1e86c6d978c7df6888ae038392edbf0680..a8491df28498cd98af2c00c01b4410969e99b215 100644 (file)
@@ -27,7 +27,8 @@ public class NetconfSessionPreferencesTest {
         final List<String> caps1 = Lists.newArrayList(
                 "namespace:1?module=module1&revision=2012-12-12",
                 "namespace:2?module=module2&amp;revision=2012-12-12",
-                "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
+                "urn:ietf:params:xml:ns:yang:"
+                        + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
                 "urn:ietf:params:netconf:base:1.0",
                 "urn:ietf:params:netconf:capability:rollback-on-error:1.0"
         );
@@ -44,8 +45,8 @@ public class NetconfSessionPreferencesTest {
 
         final NetconfSessionPreferences merged = sessionCaps1.addModuleCaps(sessionCaps2);
         assertCaps(merged, 2, 2 + 1 /*Preserved monitoring*/ + 2 /*already present*/);
-        for (final QName qName : sessionCaps2.getModuleBasedCaps()) {
-            assertThat(merged.getModuleBasedCaps(), hasItem(qName));
+        for (final QName qualifiedName : sessionCaps2.getModuleBasedCaps()) {
+            assertThat(merged.getModuleBasedCaps(), hasItem(qualifiedName));
         }
         assertThat(merged.getModuleBasedCaps(), hasItem(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING));
 
@@ -58,7 +59,8 @@ public class NetconfSessionPreferencesTest {
         final List<String> caps1 = Lists.newArrayList(
                 "namespace:1?module=module1&revision=2012-12-12",
                 "namespace:2?module=module2&amp;revision=2012-12-12",
-                "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
+                "urn:ietf:params:xml:ns:yang:"
+                        + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
                 "urn:ietf:params:netconf:base:1.0",
                 "urn:ietf:params:netconf:capability:rollback-on-error:1.0"
         );
@@ -82,7 +84,8 @@ public class NetconfSessionPreferencesTest {
         final List<String> caps1 = Lists.newArrayList(
                 "namespace:1?module=module1&revision=2012-12-12",
                 "namespace:2?module=module2&amp;revision=2012-12-12",
-                "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
+                "urn:ietf:params:xml:ns:yang:"
+                        + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
                 "urn:ietf:params:netconf:base:1.0",
                 "urn:ietf:params:netconf:capability:rollback-on-error:1.0",
                 "urn:ietf:params:netconf:capability:candidate:1.0"
@@ -103,7 +106,7 @@ public class NetconfSessionPreferencesTest {
 
         final NetconfSessionPreferences merged = sessionCaps1.addNonModuleCaps(sessionCaps2);
 
-        assertCaps(merged, 3+2, 3);
+        assertCaps(merged, 3 + 2, 3);
         for (final String capability : sessionCaps2.getNonModuleCaps()) {
             assertThat(merged.getNonModuleCaps(), hasItem(capability));
         }
@@ -122,7 +125,8 @@ public class NetconfSessionPreferencesTest {
         final List<String> caps1 = Lists.newArrayList(
                 "namespace:1?module=module1&revision=2012-12-12",
                 "namespace:2?module=module2&amp;revision=2012-12-12",
-                "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
+                "urn:ietf:params:xml:ns:yang:"
+                        + "ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
                 "urn:ietf:params:netconf:base:1.0",
                 "urn:ietf:params:netconf:capability:rollback-on-error:1.0",
                 "urn:ietf:params:netconf:capability:candidate:1.0"
index 99ba1d0b34fa94e0cec47ebdc2cd11e9921c2b4c..654c6ab66c1f5155ce7d18daca5953f3a94492d0 100644 (file)
@@ -48,7 +48,8 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 
 public class KeepaliveSalFacadeTest {
 
-    private static final RemoteDeviceId REMOTE_DEVICE_ID = new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
+    private static final RemoteDeviceId REMOTE_DEVICE_ID =
+            new RemoteDeviceId("test", new InetSocketAddress("localhost", 22));
 
     @Mock
     private RemoteDeviceHandler<NetconfSessionPreferences> underlyingSalFacade;
@@ -85,8 +86,8 @@ public class KeepaliveSalFacadeTest {
                 invocationOnMock.callRealMethod();
                 return currentKeepalive;
             }
-        }).when(executorServiceSpy).schedule(Mockito.<Runnable> any(),
-                Mockito.anyLong(), Matchers.<TimeUnit> any());
+        }).when(executorServiceSpy).schedule(Mockito.<Runnable>any(),
+                Mockito.anyLong(), Matchers.<TimeUnit>any());
 
         Mockito.when(currentKeepalive.isDone()).thenReturn(true);
     }
@@ -101,7 +102,8 @@ public class KeepaliveSalFacadeTest {
         final DOMRpcResult result = new DefaultDOMRpcResult(Builders.containerBuilder().withNodeIdentifier(
                 new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME)).build());
 
-        doReturn(Futures.immediateCheckedFuture(result)).when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
+        doReturn(Futures.immediateCheckedFuture(result))
+                .when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
 
         final KeepaliveSalFacade keepaliveSalFacade =
                 new KeepaliveSalFacade(REMOTE_DEVICE_ID, underlyingSalFacade, executorServiceSpy, 1L, 1L);
@@ -182,7 +184,8 @@ public class KeepaliveSalFacadeTest {
                 proxyRpc = (DOMRpcService) invocationOnMock.getArguments()[2];
                 return null;
             }
-        }).when(underlyingSalFacade).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+        }).when(underlyingSalFacade).onDeviceConnected(
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
 
         doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("illegal-state")))
                 .when(deviceRpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
index 95e048e745871057e6f1318083b571bf7b7d5e33..b2274d1ec73b12079dc679782ded2fe766a34807 100644 (file)
@@ -30,9 +30,13 @@ import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.yangtools.concepts.ObjectRegistration;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class MountInstanceTest {
 
+    private static final Logger LOG = LoggerFactory.getLogger(MountInstanceTest.class);
+
     private static SchemaContext SCHEMA_CONTEXT;
 
     @Mock
@@ -53,10 +57,10 @@ public class MountInstanceTest {
     private NetconfDeviceSalProvider.MountInstance mountInstance;
 
     @BeforeClass
-    public static void suiteSetUp() throws Exception{
+    public static void suiteSetUp() throws Exception {
         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
-        moduleInfoBackedContext.addModuleInfos(
-                Lists.newArrayList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
+        moduleInfoBackedContext.addModuleInfos(Lists.newArrayList(org.opendaylight.yang.gen
+                .v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
         SCHEMA_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get();
 
     }
@@ -67,7 +71,8 @@ public class MountInstanceTest {
         when(service.createMountPoint(any(YangInstanceIdentifier.class))).thenReturn(mountPointBuilder);
 
         when(mountPointBuilder.register()).thenReturn(registration);
-        mountInstance = new NetconfDeviceSalProvider.MountInstance(service, new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830)));
+        mountInstance = new NetconfDeviceSalProvider.MountInstance(
+                service, new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830)));
     }
 
 
@@ -88,7 +93,7 @@ public class MountInstanceTest {
         try {
             mountInstance.onTopologyDeviceConnected(SCHEMA_CONTEXT, broker, rpcService, notificationService);
         } catch (final IllegalStateException e) {
-            e.printStackTrace();
+            LOG.warn("Operation failed.", e);
             Assert.fail("Topology registration still present after disconnect ");
         }
     }
index e38cf05ba4c8ca9228dfa4035a85bd10d0e9324c..4c4141fbb033e6f5b1153bfff1d5c3eb9b2e7eae 100644 (file)
@@ -55,12 +55,13 @@ public class NetconfDeviceDataBrokerTest {
         MockitoAnnotations.initMocks(this);
         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
         moduleInfoBackedContext.addModuleInfos(
-                Lists.newArrayList(
-                        $YangModuleInfoImpl.getInstance(),
-                        org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
+                Lists.newArrayList($YangModuleInfoImpl.getInstance(),
+                        org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns
+                                .netconf.base._1._0.rev110601.$YangModuleInfoImpl.getInstance()));
         schemaContext = moduleInfoBackedContext.tryToCreateSchemaContext().get();
         DOMRpcResult result = new DefaultDOMRpcResult();
-        when(rpcService.invokeRpc(any(SchemaPath.class), any(NormalizedNode.class))).thenReturn(Futures.immediateCheckedFuture(result));
+        when(rpcService.invokeRpc(any(SchemaPath.class), any(NormalizedNode.class)))
+                .thenReturn(Futures.immediateCheckedFuture(result));
 
         dataBroker = getDataBroker(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
     }
@@ -81,7 +82,8 @@ public class NetconfDeviceDataBrokerTest {
 
     @Test
     public void testWritableRunningCandidateWriteTransaction() throws Exception {
-        testWriteTransaction(WriteCandidateRunningTx.class, NetconfMessageTransformUtil.NETCONF_RUNNING_WRITABLE_URI.toString(),
+        testWriteTransaction(
+                WriteCandidateRunningTx.class, NetconfMessageTransformUtil.NETCONF_RUNNING_WRITABLE_URI.toString(),
                 NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
     }
 
@@ -102,7 +104,8 @@ public class NetconfDeviceDataBrokerTest {
 
     private NetconfDeviceDataBroker getDataBroker(String... caps) {
         NetconfSessionPreferences prefs = NetconfSessionPreferences.fromStrings(Arrays.asList(caps));
-        final RemoteDeviceId id = new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830));
+        final RemoteDeviceId id =
+                new RemoteDeviceId("device-1", InetSocketAddress.createUnresolved("localhost", 17830));
         return new NetconfDeviceDataBroker(id, schemaContext, rpcService, prefs);
     }
 
index dd7bc5878b7bd428b020141e49c6343e6a77cd8e..f81440f4adbc85ea48a412ab2329e4bf776cb950 100644 (file)
@@ -61,16 +61,18 @@ public class NetconfDeviceRpcTest {
         schema = getSchema();
         NetconfMessageTransformer transformer = new NetconfMessageTransformer(schema, true);
         final NetconfMessage reply = new NetconfMessage(XmlUtil.readXmlToDocument(
-                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
-                        "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n" +
-                        "<data>\n" +
-                        "</data>\n" +
-                        "</rpc-reply>"));
+                "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
+                        + "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"101\">\n"
+                        + "<data>\n"
+                        + "</data>\n"
+                        "</rpc-reply>"));
         RpcResult<NetconfMessage> result = RpcResultBuilder.success(reply).build();
-        doReturn(Futures.immediateFuture(result)).when(communicator).sendRequest(any(NetconfMessage.class), any(QName.class));
+        doReturn(Futures.immediateFuture(result))
+                .when(communicator).sendRequest(any(NetconfMessage.class), any(QName.class));
         rpc = new NetconfDeviceRpc(schema, communicator, transformer);
 
-        path = SchemaPath.create(true, QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config"));
+        path = SchemaPath
+                .create(true, QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config"));
         expectedReply = transformer.toRpcResult(reply, path);
     }
 
@@ -100,8 +102,8 @@ public class NetconfDeviceRpcTest {
     }
 
     private static ContainerNode createNode(String namespace, String date, String localName) {
-        return Builders.containerBuilder()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, date, localName))).build();
+        return Builders.containerBuilder().withNodeIdentifier(
+                new YangInstanceIdentifier.NodeIdentifier(QName.create(namespace, date, localName))).build();
     }
 
     private static SchemaContext getSchema() {
index 4cb0ed7a155d480d31fa51d152ff34e461a78284..89f0ee26422afa6913ee219028d33618896d6404 100644 (file)
@@ -37,7 +37,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest;
 import org.powermock.modules.junit4.PowerMockRunner;
 
 @RunWith(PowerMockRunner.class)
-@PrepareForTest({NetconfDeviceTopologyAdapter.class, NetconfDeviceSalProvider.MountInstance.class, NetconfSessionPreferences.class})
+@PrepareForTest({NetconfDeviceTopologyAdapter.class, NetconfDeviceSalProvider.MountInstance.class,
+        NetconfSessionPreferences.class})
 public class NetconfDeviceSalFacadeTest {
 
     private NetconfDeviceSalFacade deviceFacade;
@@ -49,7 +50,7 @@ public class NetconfDeviceSalFacadeTest {
     private NetconfDeviceSalProvider salProvider;
 
     @Before
-    public void setUp() throws Exception{
+    public void setUp() throws Exception {
         initMocks(this);
         final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
         final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("test", address);
@@ -60,7 +61,8 @@ public class NetconfDeviceSalFacadeTest {
         mountInstance = PowerMockito.mock(NetconfDeviceSalProvider.MountInstance.class);
 
         doReturn(netconfDeviceTopologyAdapter).when(salProvider).getTopologyDatastoreAdapter();
-        doNothing().when(netconfDeviceTopologyAdapter).updateDeviceData(any(Boolean.class), any(NetconfDeviceCapabilities.class));
+        doNothing().when(netconfDeviceTopologyAdapter)
+                .updateDeviceData(any(Boolean.class), any(NetconfDeviceCapabilities.class));
 
         doReturn(mountInstance).when(salProvider).getMountInstance();
         doNothing().when(mountInstance).onTopologyDeviceDisconnected();
@@ -94,13 +96,16 @@ public class NetconfDeviceSalFacadeTest {
     public void testOnDeviceConnected() {
         final SchemaContext schemaContext = mock(SchemaContext.class);
 
-        final NetconfSessionPreferences netconfSessionPreferences = NetconfSessionPreferences.fromStrings(getCapabilities());
+        final NetconfSessionPreferences netconfSessionPreferences =
+                NetconfSessionPreferences.fromStrings(getCapabilities());
 
         final DOMRpcService deviceRpc = mock(DOMRpcService.class);
         deviceFacade.onDeviceConnected(schemaContext, netconfSessionPreferences, deviceRpc);
 
-        verify(mountInstance, times(1)).onTopologyDeviceConnected(eq(schemaContext), any(DOMDataBroker.class), eq(deviceRpc), any(NetconfDeviceNotificationService.class));
-        verify(netconfDeviceTopologyAdapter, times(1)).updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
+        verify(mountInstance, times(1)).onTopologyDeviceConnected(eq(schemaContext),
+                any(DOMDataBroker.class), eq(deviceRpc), any(NetconfDeviceNotificationService.class));
+        verify(netconfDeviceTopologyAdapter,
+                times(1)).updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities());
     }
 
     @Test
@@ -110,7 +115,7 @@ public class NetconfDeviceSalFacadeTest {
         verify(mountInstance).publish(domNotification);
     }
 
-   private static List<String> getCapabilities() {
+    private static List<String> getCapabilities() {
         return Arrays.asList(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
     }
 }
index efb4862cc13da693a2d361ddf5274d20a86cbf38..69ad2a479f5a69a9796b5c10a52a5ffc4109f1d7 100644 (file)
@@ -92,15 +92,17 @@ public class NetconfDeviceTopologyAdapterTest {
 
     private DataBroker dataBroker;
 
-    private ConcurrentDOMDataBroker cDOMDataBroker;
+    private ConcurrentDOMDataBroker concurrentDOMDataBroker;
 
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         doReturn(txChain).when(broker).createTransactionChain(any(TransactionChainListener.class));
         doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
-        doNothing().when(writeTx).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
-        doNothing().when(writeTx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+        doNothing().when(writeTx)
+                .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+        doNothing().when(writeTx)
+                .merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
 
         doReturn(txIdent).when(writeTx).getIdentifier();
 
@@ -118,22 +120,25 @@ public class NetconfDeviceTopologyAdapterTest {
         ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
                 16, 16, "CommitFutures");
 
-        cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
+        concurrentDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
 
         final ClassPool pool = ClassPool.getDefault();
         final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
         final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
-        codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
+        codecRegistry.onBindingRuntimeContextUpdated(
+                BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
 
         final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
-        final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
+        final BindingToNormalizedNodeCodec bindingToNormalized =
+                new BindingToNormalizedNodeCodec(loading, codecRegistry);
         bindingToNormalized.onGlobalContextUpdated(schemaContext);
-        dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
+        dataBroker = new BindingDOMDataBrokerAdapter(concurrentDOMDataBroker, bindingToNormalized);
 
         transactionChain = dataBroker.createTransactionChain(new TransactionChainListener() {
             @Override
-            public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction, Throwable cause) {
+            public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction,
+                                                 Throwable cause) {
 
             }
 
@@ -153,16 +158,20 @@ public class NetconfDeviceTopologyAdapterTest {
         adapter.setDeviceAsFailed(null);
 
         verify(txChain, times(2)).newWriteOnlyTransaction();
-        verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+        verify(writeTx, times(1))
+                .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
         adapter.close();
 
         adapter = new NetconfDeviceTopologyAdapter(id, transactionChain); //not a mock
         adapter.setDeviceAsFailed(null);
 
-        Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
+        Optional<NetconfNode> netconfNode = dataBroker.newReadWriteTransaction().read(LogicalDatastoreType.OPERATIONAL,
+                id.getTopologyBindingPath().augmentation(NetconfNode.class)).checkedGet(5, TimeUnit.SECONDS);
 
         assertEquals("Netconf node should be presented.", true, netconfNode.isPresent());
-        assertEquals("Connection status should be failed.", NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(), netconfNode.get().getConnectionStatus().getName());
+        assertEquals("Connection status should be failed.",
+                NetconfNodeConnectionStatus.ConnectionStatus.UnableToConnect.getName(),
+                netconfNode.get().getConnectionStatus().getName());
 
     }
 
@@ -174,7 +183,8 @@ public class NetconfDeviceTopologyAdapterTest {
         adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
 
         verify(txChain, times(2)).newWriteOnlyTransaction();
-        verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
+        verify(writeTx, times(1))
+                .put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(NetconfNode.class));
         verify(writeTx, times(1)).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(Node.class));
 
     }
@@ -186,35 +196,43 @@ public class NetconfDeviceTopologyAdapterTest {
 
         NetconfDeviceTopologyAdapter adapter = new NetconfDeviceTopologyAdapter(id, transactionChain);
 
-        QName nTestLeafQname = QName.create("urn:TBD:params:xml:ns:yang:network-topology-augment-test", "2016-08-08", "test-id").intern();
+        QName netconfTestLeafQname = QName.create(
+                "urn:TBD:params:xml:ns:yang:network-topology-augment-test", "2016-08-08", "test-id").intern();
 
-        YangInstanceIdentifier pathToAugmentedLeaf = YangInstanceIdentifier.builder().node(NetworkTopology.QNAME).
-                node(Topology.QNAME).nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "topology-netconf").
-                node(Node.QNAME).nodeWithKey(Node.QNAME, QName.create(Node.QNAME, "node-id"), "test").node(nTestLeafQname).build();
+        YangInstanceIdentifier pathToAugmentedLeaf = YangInstanceIdentifier.builder().node(NetworkTopology.QNAME)
+                .node(Topology.QNAME)
+                .nodeWithKey(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "topology-netconf")
+                .node(Node.QNAME)
+                .nodeWithKey(Node.QNAME, QName.create(Node.QNAME, "node-id"), "test")
+                .node(netconfTestLeafQname).build();
 
-        NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId).withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(nTestLeafQname)).build();
+        NormalizedNode<?, ?> augmentNode = ImmutableLeafNodeBuilder.create().withValue(dataTestId)
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(netconfTestLeafQname)).build();
 
-        DOMDataWriteTransaction writeTx =  cDOMDataBroker.newWriteOnlyTransaction();
+        DOMDataWriteTransaction writeTx =  concurrentDOMDataBroker.newWriteOnlyTransaction();
         writeTx.put(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf, augmentNode);
         writeTx.submit();
 
         adapter.updateDeviceData(true, new NetconfDeviceCapabilities());
-        Optional<NormalizedNode<?, ?>> testNode = cDOMDataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
+        Optional<NormalizedNode<?, ?>> testNode = concurrentDOMDataBroker.newReadOnlyTransaction()
+                .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
 
         assertEquals("Augmented node data should be still present after device update.", true, testNode.isPresent());
         assertEquals("Augmented data should be the same as before update node.", dataTestId, testNode.get().getValue());
 
         adapter.setDeviceAsFailed(null);
-        testNode = cDOMDataBroker.newReadOnlyTransaction().read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
+        testNode = concurrentDOMDataBroker.newReadOnlyTransaction()
+                .read(LogicalDatastoreType.OPERATIONAL, pathToAugmentedLeaf).checkedGet(2, TimeUnit.SECONDS);
 
         assertEquals("Augmented node data should be still present after device failed.", true, testNode.isPresent());
-        assertEquals("Augmented data should be the same as before failed device.", dataTestId, testNode.get().getValue());
+        assertEquals("Augmented data should be the same as before failed device.",
+                dataTestId, testNode.get().getValue());
     }
 
     private List<InputStream> getYangSchemas() {
         final List<String> schemaPaths = Arrays.asList("/schemas/network-topology@2013-10-21.yang",
-                "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang", "/schemas/netconf-node-topology.yang",
-                "/schemas/network-topology-augment-test@2016-08-08.yang");
+                "/schemas/ietf-inet-types@2013-07-15.yang", "/schemas/yang-ext.yang",
+                "/schemas/netconf-node-topology.yang", "/schemas/network-topology-augment-test@2016-08-08.yang");
         final List<InputStream> schemas = new ArrayList<>();
 
         for (String schemaPath : schemaPaths) {
@@ -248,7 +266,8 @@ public class NetconfDeviceTopologyAdapterTest {
             }
 
             @Override
-            public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
+            public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+                    final SchemaContextListener listener) {
                 listener.onGlobalContextUpdated(getGlobalContext());
                 return new ListenerRegistration<SchemaContextListener>() {
                     @Override
index 80f97b1ab0819ccc8618b66938ce1d6ae0c49055..8448e9372aa16ec73ab8a88fe859a7d417d56676 100644 (file)
@@ -33,9 +33,13 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 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.SchemaPath;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class SchemalessNetconfDeviceRpcTest {
 
+    private static final Logger LOG = LoggerFactory.getLogger(SchemalessNetconfDeviceRpcTest.class);
+
     @Mock
     private RemoteDeviceCommunicator<NetconfMessage> listener;
 
@@ -58,17 +62,17 @@ public class SchemalessNetconfDeviceRpcTest {
     public void testInvokeRpc() throws Exception {
         final QName qName = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01", "get-config");
         SchemaPath type = SchemaPath.create(true, qName);
-        DOMSource src = new DOMSource(XmlUtil.readXmlToDocument("<get-config xmlns=\"dd\">\n" +
-                "    <source>\n" +
-                "      <running/>\n" +
-                "    </source>\n" +
-                "    <filter type=\"subtree\">\n" +
-                "      <mainroot xmlns=\"urn:dummy:mod-0\">\n" +
-                "        <maincontent/>\n" +
-                "<choiceList></choiceList>\n" +
-                "      </mainroot>\n" +
-                "    </filter>\n" +
-                "  </get-config>"));
+        DOMSource src = new DOMSource(XmlUtil.readXmlToDocument("<get-config xmlns=\"dd\">\n"
+                + "    <source>\n"
+                + "      <running/>\n"
+                + "    </source>\n"
+                + "    <filter type=\"subtree\">\n"
+                + "      <mainroot xmlns=\"urn:dummy:mod-0\">\n"
+                + "        <maincontent/>\n"
+                + "<choiceList></choiceList>\n"
+                + "      </mainroot>\n"
+                + "    </filter>\n"
+                "  </get-config>"));
         NormalizedNode<?, ?> input = Builders.anyXmlBuilder()
                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(qName))
                 .withValue(src)
@@ -76,8 +80,8 @@ public class SchemalessNetconfDeviceRpcTest {
 
         deviceRpc.invokeRpc(type, input);
         ArgumentCaptor<NetconfMessage> msgCaptor = ArgumentCaptor.forClass(NetconfMessage.class);
-        ArgumentCaptor<QName> qNameCaptor = ArgumentCaptor.forClass(QName.class);
-        verify(listener).sendRequest(msgCaptor.capture(), qNameCaptor.capture());
-        System.out.println(XmlUtil.toString(msgCaptor.getValue().getDocument()));
+        ArgumentCaptor<QName> qnameCaptor = ArgumentCaptor.forClass(QName.class);
+        verify(listener).sendRequest(msgCaptor.capture(), qnameCaptor.capture());
+        LOG.info(XmlUtil.toString(msgCaptor.getValue().getDocument()));
     }
 }
index 7d4dd0abaecdecf03333cf144653ea68b62599c2..2f912bd9af9cb401cef3b27e5b315490f9fdb14f 100644 (file)
@@ -78,8 +78,10 @@ public class NetconfDeviceWriteOnlyTxTest {
         final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, mock(SchemaContext.class)),
                 false);
         final MapNode emptyList = ImmutableNodes.mapNodeBuilder(NETCONF_FILTER_QNAME).build();
-        tx.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
-        tx.put(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
+        tx.merge(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier
+                .create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
+        tx.put(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier
+                .create(new YangInstanceIdentifier.NodeIdentifier(NETCONF_FILTER_QNAME)), emptyList);
 
         verify(rpc, atMost(1)).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
     }
@@ -94,10 +96,14 @@ public class NetconfDeviceWriteOnlyTxTest {
         } catch (final TransactionCommitFailedException e) {
             // verify discard changes was sent
             final InOrder inOrder = inOrder(rpc);
-            inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), NetconfBaseOps.getLockContent(NETCONF_CANDIDATE_QNAME));
-            inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
-            inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)), any(NormalizedNode.class));
-            inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME), NetconfBaseOps.getUnLockContent(NETCONF_CANDIDATE_QNAME));
+            inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME),
+                    NetconfBaseOps.getLockContent(NETCONF_CANDIDATE_QNAME));
+            inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+                    NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+            inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME)),
+                    any(NormalizedNode.class));
+            inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME),
+                    NetconfBaseOps.getUnLockContent(NETCONF_CANDIDATE_QNAME));
             return;
         }
 
@@ -106,8 +112,8 @@ public class NetconfDeviceWriteOnlyTxTest {
 
     @Test
     public void testFailedCommit() throws Exception {
-        final CheckedFuture<DefaultDOMRpcResult, Exception> rpcErrorFuture =
-                Futures.immediateCheckedFuture(new DefaultDOMRpcResult(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "a", "m")));
+        final CheckedFuture<DefaultDOMRpcResult, Exception> rpcErrorFuture = Futures.immediateCheckedFuture(
+                new DefaultDOMRpcResult(RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "a", "m")));
 
         doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult(((NormalizedNode<?, ?>) null))))
         .doReturn(rpcErrorFuture).when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
@@ -131,23 +137,27 @@ public class NetconfDeviceWriteOnlyTxTest {
                 .doReturn(Futures.immediateFailedCheckedFuture(new IllegalStateException("Failed tx")))
                 .when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
 
-        final WriteRunningTx tx = new WriteRunningTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext()),
-                false);
+        final WriteRunningTx tx = new WriteRunningTx(
+                id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext()), false);
 
         tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
         tx.submit();
         // verify discard changes was sent
         final InOrder inOrder = inOrder(rpc);
-        inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), NetconfBaseOps.getLockContent(NETCONF_RUNNING_QNAME));
-        inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any(NormalizedNode.class));
-        inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME), NetconfBaseOps.getUnLockContent(NETCONF_RUNNING_QNAME));
+        inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_LOCK_QNAME),
+                NetconfBaseOps.getLockContent(NETCONF_RUNNING_QNAME));
+        inOrder.verify(rpc).invokeRpc(eq(toPath(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)),
+                any(NormalizedNode.class));
+        inOrder.verify(rpc).invokeRpc(toPath(NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME),
+                NetconfBaseOps.getUnLockContent(NETCONF_RUNNING_QNAME));
     }
 
     @Test
     public void testListenerSuccess() throws Exception {
         doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult((NormalizedNode<?, ?>) null)))
                 .when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
-        final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+        final WriteCandidateTx tx = new WriteCandidateTx(
+                id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
         final TxListener listener = mock(TxListener.class);
         tx.addListener(listener);
         tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
@@ -162,7 +172,8 @@ public class NetconfDeviceWriteOnlyTxTest {
     public void testListenerCancellation() throws Exception {
         doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult((NormalizedNode<?, ?>) null)))
                 .when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
-        final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+        final WriteCandidateTx tx = new WriteCandidateTx(
+                id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
         final TxListener listener = mock(TxListener.class);
         tx.addListener(listener);
         tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
@@ -178,7 +189,8 @@ public class NetconfDeviceWriteOnlyTxTest {
         final IllegalStateException cause = new IllegalStateException("Failed tx");
         doReturn(Futures.immediateFailedCheckedFuture(cause))
                 .when(rpc).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
-        final WriteCandidateTx tx = new WriteCandidateTx(id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
+        final WriteCandidateTx tx = new WriteCandidateTx(
+                id, new NetconfBaseOps(rpc, BaseSchema.BASE_NETCONF_CTX.getSchemaContext()), false);
         final TxListener listener = mock(TxListener.class);
         tx.addListener(listener);
         tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
index 8d67fbc78a234d57282fab1c1dea6e87b9d9edcd..dc32b881d720950ea5f75da911593ceecd14d873 100644 (file)
@@ -35,7 +35,7 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 
 public class ReadOnlyTxTest {
 
-    private static final YangInstanceIdentifier path = YangInstanceIdentifier.create();
+    private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.create();
 
     @Mock
     private DOMRpcService rpc;
@@ -54,31 +54,39 @@ public class ReadOnlyTxTest {
     public void testRead() throws Exception {
         final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
 
-        final ReadOnlyTx readOnlyTx = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+        final ReadOnlyTx readOnlyTx =
+                new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
 
         readOnlyTx.read(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create());
-        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
-        readOnlyTx.read(LogicalDatastoreType.OPERATIONAL, path);
-        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
+        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+                NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
+        readOnlyTx.read(LogicalDatastoreType.OPERATIONAL, PATH);
+        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+                NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
     }
 
     @Test
     public void testExists() throws Exception {
         final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
 
-        final ReadOnlyTx readOnlyTx = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+        final ReadOnlyTx readOnlyTx =
+                new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
 
         readOnlyTx.exists(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.create());
-        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
-        readOnlyTx.exists(LogicalDatastoreType.OPERATIONAL, path);
-        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
+        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+                NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME)), any(NormalizedNode.class));
+        readOnlyTx.exists(LogicalDatastoreType.OPERATIONAL, PATH);
+        verify(rpc).invokeRpc(Mockito.eq(NetconfMessageTransformUtil.toPath(
+                NetconfMessageTransformUtil.NETCONF_GET_QNAME)), any(NormalizedNode.class));
     }
 
     @Test
     public void testIdentifier() throws Exception {
         final NetconfBaseOps netconfOps = new NetconfBaseOps(rpc, mock(SchemaContext.class));
-        final ReadOnlyTx tx1 = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
-        final ReadOnlyTx tx2 = new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+        final ReadOnlyTx tx1 =
+                new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
+        final ReadOnlyTx tx2 =
+                new ReadOnlyTx(netconfOps, new RemoteDeviceId("a", new InetSocketAddress("localhost", 196)));
         Assert.assertNotEquals(tx1.getIdentifier(), tx2.getIdentifier());
     }
 }
\ No newline at end of file
index e56b02dd1c3387e538611a940cc63b68c3701b1b..56384cdf32f10e0c93f786ff84bf69641525195d 100644 (file)
@@ -51,7 +51,8 @@ public class TxChainTest {
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         when(broker.newReadOnlyTransaction()).thenReturn(readOnlyTx);
-        when(broker.newWriteOnlyTransaction()).thenReturn(writeOnlyTx1).thenReturn(writeOnlyTx2).thenReturn(writeOnlyTx3);
+        when(broker.newWriteOnlyTransaction()).thenReturn(writeOnlyTx1)
+                .thenReturn(writeOnlyTx2).thenReturn(writeOnlyTx3);
         when(writeOnlyTx1.addListener(any())).thenReturn(registration1);
         when(writeOnlyTx2.addListener(any())).thenReturn(registration2);
         when(writeOnlyTx3.addListener(any())).thenReturn(registration3);
index 961ee8d58279504ff83096417a6c51fd7a6bb11c..fd99a54d76c95ddcc9c7aac533f5778842b6b36d 100644 (file)
@@ -49,7 +49,8 @@ public class WriteCandidateRunningTxTest {
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
+        final SchemaContext schemaContext =
+                YangParserTestUtils.parseYangStreams(getClass().getResourceAsStream("/schemas/test-module.yang"));
         doReturn(Futures.immediateCheckedFuture(new DefaultDOMRpcResult())).when(rpc).invokeRpc(any(), any());
         netconfOps = new NetconfBaseOps(rpc, schemaContext);
         id = new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("0.0.0.0", 17830));
@@ -59,19 +60,25 @@ public class WriteCandidateRunningTxTest {
     public void testSubmit() throws Exception {
         final WriteCandidateRunningTx tx = new WriteCandidateRunningTx(id, netconfOps, true);
         //check, if lock is called
-        final ContainerNode candidateLock = getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
-        final ContainerNode runningLock = getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
+        final ContainerNode candidateLock =
+                getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
+        final ContainerNode runningLock =
+                getLockContent(NETCONF_LOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
         verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), runningLock);
         verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_LOCK_QNAME), candidateLock);
         tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
         tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
         //check, if both edits are called
-        verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+        verify(rpc, times(2)).invokeRpc(
+                eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
         tx.submit().get();
         //check, if unlock is called
-        verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
-        final ContainerNode candidateUnlock = getLockContent(NETCONF_UNLOCK_QNAME, NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
-        final ContainerNode runningUnlock = getLockContent(NETCONF_UNLOCK_QNAME, NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
+        verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+                NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+        final ContainerNode candidateUnlock = getLockContent(NETCONF_UNLOCK_QNAME,
+                NetconfMessageTransformUtil.NETCONF_RUNNING_QNAME);
+        final ContainerNode runningUnlock = getLockContent(NETCONF_UNLOCK_QNAME,
+                NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME);
         verify(rpc).invokeRpc(SchemaPath.create(true, NETCONF_UNLOCK_QNAME), candidateUnlock);
         verify(rpc).invokeRpc(SchemaPath.create(true, NETCONF_UNLOCK_QNAME), runningUnlock);
     }
index ca9bb16c743ae9058b325c9d771a5a8aa1e4c1eb..7370b0da5d3f6bb01cae25f816956f3d51afc1dc 100644 (file)
@@ -56,10 +56,12 @@ public class WriteCandidateTxTest {
         tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
         tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
         //check, if both edits are called
-        verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+        verify(rpc, times(2))
+                .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
         tx.submit().get();
         //check, if unlock is called
-        verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME), NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+        verify(rpc).invokeRpc(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME),
+                NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
         verify(rpc).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)), any());
     }
 
index 1e8293d58297ba1d833dabb54b75915c82dfaf5c..ab53dc4f4d12e870b28df24ac8ab1665b574472d 100644 (file)
@@ -56,10 +56,12 @@ public class WriteRunningTxTest {
         tx.put(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getContainerId(), TxTestUtils.getContainerNode());
         tx.merge(LogicalDatastoreType.CONFIGURATION, TxTestUtils.getLeafId(), TxTestUtils.getLeafNode());
         //check, if no edit-config is called before submit
-        verify(rpc, never()).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+        verify(rpc, never())
+                .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
         tx.submit().get();
         //check, if both edits are called
-        verify(rpc, times(2)).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
+        verify(rpc, times(2))
+                .invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME)), any());
         //check, if unlock is called
         verify(rpc).invokeRpc(eq(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_UNLOCK_QNAME)), any());
     }
index 2b49b10b8f760c60bed8bfdb25ae54d54453502b..c44413ded9ab9d00dced2f880b4bea94d7260a7d 100644 (file)
@@ -59,7 +59,8 @@ public class NetconfRemoteSchemaYangSourceProviderTest {
         CheckedFuture<DOMRpcResult, DOMRpcException> response = Futures.immediateCheckedFuture(value);
         doReturn(response).when(service).invokeRpc(any(SchemaPath.class), any(NormalizedNode.class));
 
-        provider = new NetconfRemoteSchemaYangSourceProvider(new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)), service);
+        provider = new NetconfRemoteSchemaYangSourceProvider(
+                new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)), service);
     }
 
     @Test
@@ -70,7 +71,8 @@ public class NetconfRemoteSchemaYangSourceProviderTest {
         Assert.assertEquals(identifier, source.getIdentifier());
         verify(service).invokeRpc(
                 SchemaPath.create(true, NetconfMessageTransformUtil.GET_SCHEMA_QNAME),
-                NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest(identifier.getName(), Optional.of(identifier.getRevision()))
+                NetconfRemoteSchemaYangSourceProvider
+                        .createGetSchemaRequest(identifier.getName(), Optional.of(identifier.getRevision()))
         );
     }
 
@@ -85,7 +87,8 @@ public class NetconfRemoteSchemaYangSourceProviderTest {
         Element root = xmlDoc.createElement("data");
         root.setTextContent("module test {}");
         final DOMSource v = new DOMSource(root);
-        DataContainerChild<?, ?> child = ImmutableAnyXmlNodeBuilder.create().withNodeIdentifier(childId).withValue(v).build();
+        DataContainerChild<?, ?> child =
+                ImmutableAnyXmlNodeBuilder.create().withNodeIdentifier(childId).withValue(v).build();
         return ImmutableContainerNodeBuilder.create().withNodeIdentifier(id).withChild(child).build();
     }
 
index 5363bd19558bab1477420f0ce9a1ee90043c3303..8f4c320f9750a25f950cf12f33ba5ce643b855d3 100644 (file)
@@ -41,22 +41,22 @@ public class BaseRpcSchemalessTransformerTest {
         XMLUnit.setIgnoreAttributeOrder(true);
     }
 
-    private static final String EXP_RPC = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-            "   <edit-config>\n" +
-            "       <target>\n" +
-            "           <candidate/>\n" +
-            "       </target>\n" +
-            "       <config>\n" +
-            "           <top xmlns=\"http://example.com/schema/1.2/config\">\n" +
-            "               <users xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:operation=\"replace\">\n" +
-            "                   <user>\n" +
-            "                       <name>fred</name>\n" +
-            "                   </user>\n" +
-            "               </users>\n" +
-            "           </top>\n" +
-            "       </config>\n" +
-            "   </edit-config>\n" +
-            "</rpc>\n";
+    private static final String EXP_RPC = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+            + "   <edit-config>\n"
+            + "       <target>\n"
+            + "           <candidate/>\n"
+            + "       </target>\n"
+            + "       <config>\n"
+            + "           <top xmlns=\"http://example.com/schema/1.2/config\">\n"
+            + "               <users xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:operation=\"replace\">\n"
+            + "                   <user>\n"
+            + "                       <name>fred</name>\n"
+            + "                   </user>\n"
+            + "               </users>\n"
+            + "           </top>\n"
+            + "       </config>\n"
+            + "   </edit-config>\n"
+            "</rpc>\n";
 
     BaseRpcSchemalessTransformer transformer;
 
@@ -67,50 +67,61 @@ public class BaseRpcSchemalessTransformerTest {
 
     @Test(expected = UnsupportedOperationException.class)
     public void toNotification() throws Exception {
-        transformer.toNotification(new NetconfMessage(XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"))));
+        transformer.toNotification(new NetconfMessage(
+                XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"))));
     }
 
     @Test
     public void toRpcRequest() throws Exception {
-        final Document doc = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/edit-config/container.xml"));
+        final Document doc =
+                XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/edit-config/container.xml"));
         final AnyXmlNode xml = Builders.anyXmlBuilder()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME))
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(
+                        NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME))
                 .withValue(new DOMSource(doc.getDocumentElement()))
                 .build();
         final ChoiceNode editContent = Builders.choiceBuilder()
                 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(EditContent.QNAME))
                 .withChild(xml)
                 .build();
-        final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME))
-                .withChild(Builders.leafBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build())
+        final ChoiceNode candidate = Builders.choiceBuilder().withNodeIdentifier(
+                new YangInstanceIdentifier.NodeIdentifier(ConfigTarget.QNAME))
+                .withChild(Builders.leafBuilder().withNodeIdentifier(
+                        new YangInstanceIdentifier.NodeIdentifier(Candidate.QNAME)).build())
                 .build();
         final DataContainerChild<?, ?> target = Builders.containerBuilder()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_TARGET_QNAME))
+                .withNodeIdentifier(
+                        new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_TARGET_QNAME))
                 .withChild(candidate)
                 .build();
         final ContainerNode editConfig = Builders.containerBuilder()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME))
+                .withNodeIdentifier(
+                    new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME))
                 .withChild(editContent)
                 .withChild(target)
                 .build();
-        final NetconfMessage msg = transformer.toRpcRequest(SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), editConfig);
+        final NetconfMessage msg = transformer.toRpcRequest(
+                SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), editConfig);
         final Diff diff = XMLUnit.compareXML(EXP_RPC, XmlUtil.toString(msg.getDocument()));
         Assert.assertTrue(diff.toString(), diff.similar());
     }
 
     @Test
     public void toRpcResult() throws Exception {
-        final Document doc = XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
+        final Document doc = XmlUtil.readXmlToDocument(
+                "<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>");
         final InputStream stream = getClass().getResourceAsStream("/schemaless/get-config/container.xml");
         final Element dataElement = XmlUtil.readXmlToElement(stream);
         final Element element = (Element) doc.importNode(dataElement, true);
         doc.getDocumentElement().appendChild(element);
         final NetconfMessage msg = new NetconfMessage(doc);
-        final DOMRpcResult result = transformer.toRpcResult(msg, SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME));
+        final DOMRpcResult result = transformer.toRpcResult(msg,
+                SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_GET_CONFIG_QNAME));
         Assert.assertNotNull(result.getResult());
         final ContainerNode rpcReply = (ContainerNode) result.getResult();
         Assert.assertEquals(NetconfMessageTransformUtil.NETCONF_RPC_REPLY_QNAME, rpcReply.getNodeType());
-        final Optional dataOpt = rpcReply.getChild(new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME));
+        final Optional dataOpt = rpcReply.getChild(
+                new YangInstanceIdentifier.NodeIdentifier(NetconfMessageTransformUtil.NETCONF_DATA_QNAME));
         Assert.assertTrue(dataOpt.isPresent());
         final AnyXmlNode data = (AnyXmlNode) dataOpt.get();
         final Diff diff = XMLUnit.compareXML(dataElement.getOwnerDocument(), (Document) data.getValue().getNode());
index f0e3966718ff4d5583e2c2f15c11c0a12e0fe5c7..a0c90c7293fa5c20c8b136fafa2d03819eaeb20b 100644 (file)
@@ -126,7 +126,8 @@ public class NetconfMessageTransformerTest {
 
     @Test
     public void testDiscardChangesRequest() throws Exception {
-        final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_DISCARD_CHANGES_QNAME), null);
+        final NetconfMessage netconfMessage =
+                netconfMessageTransformer.toRpcRequest(toPath(NETCONF_DISCARD_CHANGES_QNAME), null);
         assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("<discard"));
         assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("<rpc"));
         assertThat(XmlUtil.toString(netconfMessage.getDocument()), CoreMatchers.containsString("message-id"));
@@ -136,70 +137,78 @@ public class NetconfMessageTransformerTest {
     public void tesGetSchemaRequest() throws Exception {
         final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(GET_SCHEMA_QNAME),
                 NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")));
-        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
-                "<format>yang</format>\n" +
-                "<identifier>module</identifier>\n" +
-                "<version>2012-12-12</version>\n" +
-                "</get-schema>\n" +
-                "</rpc>");
+        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<get-schema xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+                + "<format>yang</format>\n"
+                + "<identifier>module</identifier>\n"
+                + "<version>2012-12-12</version>\n"
+                + "</get-schema>\n"
+                "</rpc>");
     }
 
     @Test
     public void tesGetSchemaResponse() throws Exception {
         final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
         final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
-                "<rpc-reply message-id=\"101\"\n" +
-                        "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                        "<data\n" +
-                        "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
-                        "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n" +
-                        "Random YANG SCHEMA\n" +
-                        "</xs:schema>\n" +
-                        "</data>\n" +
-                        "</rpc-reply>"
+                "<rpc-reply message-id=\"101\"\n"
+                        + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                        + "<data\n"
+                        + "xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+                        + "<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n"
+                        + "Random YANG SCHEMA\n"
+                        + "</xs:schema>\n"
+                        + "</data>\n"
+                        "</rpc-reply>"
         ));
-        final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
+        final DOMRpcResult compositeNodeRpcResult =
+                netconfMessageTransformer.toRpcResult(response, toPath(GET_SCHEMA_QNAME));
         assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
         assertNotNull(compositeNodeRpcResult.getResult());
-        final DOMSource schemaContent = ((AnyXmlNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getValue().iterator().next()).getValue();
-        assertThat(((Element) schemaContent.getNode()).getTextContent(), CoreMatchers.containsString("Random YANG SCHEMA"));
+        final DOMSource schemaContent =
+            ((AnyXmlNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getValue().iterator().next()).getValue();
+        assertThat(((Element) schemaContent.getNode()).getTextContent(),
+                CoreMatchers.containsString("Random YANG SCHEMA"));
     }
 
     @Test
     public void testGetConfigResponse() throws Exception {
-        final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" +
-                "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<data>\n" +
-                "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
-                "<schemas>\n" +
-                "<schema>\n" +
-                "<identifier>module</identifier>\n" +
-                "<version>2012-12-12</version>\n" +
-                "<format xmlns:x=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">x:yang</format>\n" +
-                "</schema>\n" +
-                "</schemas>\n" +
-                "</netconf-state>\n" +
-                "</data>\n" +
-                "</rpc-reply>"));
+        final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n"
+                + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<data>\n"
+                + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+                + "<schemas>\n"
+                + "<schema>\n"
+                + "<identifier>module</identifier>\n"
+                + "<version>2012-12-12</version>\n"
+                + "<format xmlns:x=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">x:yang</format>\n"
+                + "</schema>\n"
+                + "</schemas>\n"
+                + "</netconf-state>\n"
+                + "</data>\n"
+                "</rpc-reply>"));
 
         final NetconfMessageTransformer netconfMessageTransformer = getTransformer(getSchema(true));
-        final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
+        final DOMRpcResult compositeNodeRpcResult =
+                netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_GET_CONFIG_QNAME));
         assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
         assertNotNull(compositeNodeRpcResult.getResult());
 
         final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> values = Lists.newArrayList(
-                NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
+                NetconfRemoteSchemaYangSourceProvider
+                        .createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
 
         final Map<QName, Object> keys = Maps.newHashMap();
         for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> value : values) {
             keys.put(value.getNodeType(), value.getValue());
         }
 
-        final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates = new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
-        final MapEntryNode schemaNode = Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
+        final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates =
+                new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
+        final MapEntryNode schemaNode =
+                Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
 
-        final ContainerNode data = (ContainerNode) ((ContainerNode) compositeNodeRpcResult.getResult()).getChild(toId(NETCONF_DATA_QNAME)).get();
+        final ContainerNode data = (ContainerNode) ((ContainerNode) compositeNodeRpcResult
+                .getResult()).getChild(toId(NETCONF_DATA_QNAME)).get();
         final ContainerNode state = (ContainerNode) data.getChild(toId(NetconfState.QNAME)).get();
         final ContainerNode schemas = (ContainerNode) state.getChild(toId(Schemas.QNAME)).get();
         final MapNode schemaParent = (MapNode) schemas.getChild(toId(Schema.QNAME)).get();
@@ -218,59 +227,68 @@ public class NetconfMessageTransformerTest {
         final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_GET_CONFIG_QNAME),
                 NetconfMessageTransformUtil.wrap(NETCONF_GET_CONFIG_QNAME, source, filter));
 
-        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n" +
-                "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
-                "<schemas/>\n" +
-                "</netconf-state>" +
-                "</filter>\n" +
-                "<source>\n" +
-                "<running/>\n" +
-                "</source>\n" +
-                "</get-config>" +
-                "</rpc>");
+        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<get-config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n"
+                + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+                + "<schemas/>\n"
+                + "</netconf-state>"
+                + "</filter>\n"
+                + "<source>\n"
+                + "<running/>\n"
+                + "</source>\n"
+                + "</get-config>"
+                "</rpc>");
     }
 
     @Test
     public void testEditConfigRequest() throws Exception {
         final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> values = Lists.newArrayList(
-            NetconfRemoteSchemaYangSourceProvider.createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
+                NetconfRemoteSchemaYangSourceProvider
+                        .createGetSchemaRequest("module", Optional.of("2012-12-12")).getValue());
 
         final Map<QName, Object> keys = Maps.newHashMap();
         for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> value : values) {
             keys.put(value.getNodeType(), value.getValue());
         }
 
-        final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates = new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
-        final MapEntryNode schemaNode = Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
+        final YangInstanceIdentifier.NodeIdentifierWithPredicates identifierWithPredicates =
+                new YangInstanceIdentifier.NodeIdentifierWithPredicates(Schema.QNAME, keys);
+        final MapEntryNode schemaNode =
+                Builders.mapEntryBuilder().withNodeIdentifier(identifierWithPredicates).withValue(values).build();
 
-        final YangInstanceIdentifier id = YangInstanceIdentifier.builder().node(NetconfState.QNAME).node(Schemas.QNAME).node(Schema.QNAME).nodeWithKey(Schema.QNAME, keys).build();
-        final DataContainerChild<?, ?> editConfigStructure = createEditConfigStructure(BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext(), id, Optional.<ModifyAction>absent(), Optional.<NormalizedNode<?, ?>>fromNullable(schemaNode));
+        final YangInstanceIdentifier id = YangInstanceIdentifier.builder()
+                .node(NetconfState.QNAME).node(Schemas.QNAME).node(Schema.QNAME)
+                .nodeWithKey(Schema.QNAME, keys).build();
+        final DataContainerChild<?, ?> editConfigStructure =
+                createEditConfigStructure(BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext(), id,
+                        Optional.<ModifyAction>absent(), Optional.<NormalizedNode<?, ?>>fromNullable(schemaNode));
 
         final DataContainerChild<?, ?> target = NetconfBaseOps.getTargetNode(NETCONF_CANDIDATE_QNAME);
 
-        final ContainerNode wrap = NetconfMessageTransformUtil.wrap(NETCONF_EDIT_CONFIG_QNAME, editConfigStructure, target);
-        final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_EDIT_CONFIG_QNAME), wrap);
-
-        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<edit-config>\n" +
-                "<target>\n" +
-                "<candidate/>\n" +
-                "</target>\n" +
-                "<config>\n" +
-                "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
-                "<schemas>\n" +
-                "<schema>\n" +
-                "<identifier>module</identifier>\n" +
-                "<version>2012-12-12</version>\n" +
-                "<format>yang</format>\n" +
-                "</schema>\n" +
-                "</schemas>\n" +
-                "</netconf-state>\n" +
-                "</config>\n" +
-                "</edit-config>\n" +
-                "</rpc>");
+        final ContainerNode wrap =
+                NetconfMessageTransformUtil.wrap(NETCONF_EDIT_CONFIG_QNAME, editConfigStructure, target);
+        final NetconfMessage netconfMessage =
+                netconfMessageTransformer.toRpcRequest(toPath(NETCONF_EDIT_CONFIG_QNAME), wrap);
+
+        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<edit-config>\n"
+                + "<target>\n"
+                + "<candidate/>\n"
+                + "</target>\n"
+                + "<config>\n"
+                + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+                + "<schemas>\n"
+                + "<schema>\n"
+                + "<identifier>module</identifier>\n"
+                + "<version>2012-12-12</version>\n"
+                + "<format>yang</format>\n"
+                + "</schema>\n"
+                + "</schemas>\n"
+                + "</netconf-state>\n"
+                + "</config>\n"
+                + "</edit-config>\n"
+                + "</rpc>");
     }
 
     private static void assertSimilarXml(final NetconfMessage netconfMessage, final String xmlContent)
@@ -291,17 +309,17 @@ public class NetconfMessageTransformerTest {
         final NetconfMessage netconfMessage = netconfMessageTransformer.toRpcRequest(toPath(NETCONF_GET_QNAME),
                 NetconfMessageTransformUtil.wrap(NETCONF_GET_QNAME, filter));
 
-        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
-                "<get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n" +
-                "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n" +
-                "<capabilities>\n" +
-                "<capability>a:b:c</capability>\n" +
-                "</capabilities>\n" +
-                "</netconf-state>" +
-                "</filter>\n" +
-                "</get>" +
-                "</rpc>");
+        assertSimilarXml(netconfMessage, "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
+                + "<get xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<filter xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:type=\"subtree\">\n"
+                + "<netconf-state xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring\">\n"
+                + "<capabilities>\n"
+                + "<capability>a:b:c</capability>\n"
+                + "</capabilities>\n"
+                + "</netconf-state>"
+                + "</filter>\n"
+                + "</get>"
+                "</rpc>");
     }
 
     private static NetconfMessageTransformer getTransformer(final SchemaContext schema) {
@@ -313,17 +331,20 @@ public class NetconfMessageTransformerTest {
         final NetconfMessage response = new NetconfMessage(XmlUtil.readXmlToDocument(
                 "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><ok/></rpc-reply>"
         ));
-        final DOMRpcResult compositeNodeRpcResult = netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_COMMIT_QNAME));
+        final DOMRpcResult compositeNodeRpcResult =
+                netconfMessageTransformer.toRpcResult(response, toPath(NETCONF_COMMIT_QNAME));
         assertTrue(compositeNodeRpcResult.getErrors().isEmpty());
         assertNull(compositeNodeRpcResult.getResult());
     }
 
     public SchemaContext getSchema(final boolean addBase) {
         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
-        if(addBase) {
+        if (addBase) {
             moduleInfoBackedContext.addModuleInfos(Collections.singleton($YangModuleInfoImpl.getInstance()));
         }
-        moduleInfoBackedContext.addModuleInfos(Collections.singleton(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.$YangModuleInfoImpl.getInstance()));
+        moduleInfoBackedContext
+                .addModuleInfos(Collections.singleton(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf
+                        .netconf.monitoring.rev101004.$YangModuleInfoImpl.getInstance()));
         return moduleInfoBackedContext.tryToCreateSchemaContext().get();
     }
 }
index 0bb282915d589bb20bde61f5bad5453c335f8d4a..ab99752c77ecfe353c884244adfdc8b2dfda7dd5 100644 (file)
@@ -34,18 +34,20 @@ public class SchemalessMessageTransformerTest {
         XMLUnit.setIgnoreWhitespace(true);
     }
 
-    private static final String EXP_REQUEST = "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-            "<test-rpc xmlns=\"test-ns\">\n" +
-            "<input>aaa</input>\n" +
-            "</test-rpc>\n" +
-            "</rpc>";
-    private static final String EXP_REPLY = "<rpc-reply message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-            "<output xmlns=\"test-ns\">aaa</output>\n" +
-            "</rpc-reply>";
-    private static final String OK_REPLY = "<rpc-reply message-id=\"101\"\n" +
-            "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-            "<ok/>\n" +
-            "</rpc-reply>\n";
+    private static final String EXP_REQUEST =
+            "<rpc message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                    + "<test-rpc xmlns=\"test-ns\">\n"
+                    + "<input>aaa</input>\n"
+                    + "</test-rpc>\n"
+                    + "</rpc>";
+    private static final String EXP_REPLY =
+            "<rpc-reply message-id=\"m-0\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                    + "<output xmlns=\"test-ns\">aaa</output>\n"
+                    + "</rpc-reply>";
+    private static final String OK_REPLY = "<rpc-reply message-id=\"101\"\n"
+            + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+            + "<ok/>\n"
+            + "</rpc-reply>\n";
 
     private SchemalessMessageTransformer transformer;
     private static final QName TEST_RPC = QName.create("test-ns", "2016-10-13", "test-rpc");
@@ -61,8 +63,10 @@ public class SchemalessMessageTransformerTest {
         final Document payload = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/notification-payload.xml"));
         final NetconfMessage netconfMessage = new NetconfMessage(payload);
         final DOMNotification domNotification = transformer.toNotification(netconfMessage);
-        Assert.assertEquals(domNotification.getType().getLastComponent(), SchemalessMessageTransformer.SCHEMALESS_NOTIFICATION_PAYLOAD.getNodeType());
-        final QName qName = QName.create("org:opendaylight:notification:test:ns:yang:user-notification", "user-visited-page");
+        Assert.assertEquals(domNotification.getType().getLastComponent(),
+                SchemalessMessageTransformer.SCHEMALESS_NOTIFICATION_PAYLOAD.getNodeType());
+        final QName qName =
+                QName.create("org:opendaylight:notification:test:ns:yang:user-notification", "user-visited-page");
         final AnyXmlNode dataContainerChild =
                 (AnyXmlNode) domNotification.getBody().getChild(new YangInstanceIdentifier.NodeIdentifier(qName)).get();
         final Diff diff = XMLUnit.compareXML(payload, dataContainerChild.getValue().getNode().getOwnerDocument());
@@ -97,7 +101,8 @@ public class SchemalessMessageTransformerTest {
     @Test
     public void toEmptyRpcResult() throws Exception {
         final Document doc = XmlUtil.readXmlToDocument(OK_REPLY);
-        final DOMRpcResult result = transformer.toRpcResult(new NetconfMessage(doc), SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME));
+        final DOMRpcResult result = transformer.toRpcResult(
+                new NetconfMessage(doc), SchemaPath.create(true, NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME));
         Assert.assertNull(result.getResult());
     }
 
index 697aed3085c6c81f831a3bd05415021a43de0c18..71928d2495d620f9b9bd4b7652ad5410176d897d 100644 (file)
@@ -55,14 +55,20 @@ public class SchemalessRpcStructureTransformerTest {
     private final SchemalessRpcStructureTransformer adapter = new SchemalessRpcStructureTransformer();
     private final String testDataset;
 
-    public SchemalessRpcStructureTransformerTest(YangInstanceIdentifier path, String testDataset, Class<? extends Exception> expectedException) throws IOException, SAXException, URISyntaxException {
+    public SchemalessRpcStructureTransformerTest(
+            YangInstanceIdentifier path, String testDataset,
+            Class<? extends Exception> expectedException) throws IOException, SAXException, URISyntaxException {
         this.path = path;
         this.testDataset = testDataset;
         this.expectedException = expectedException;
-        this.source = new DOMSource(XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/schemaless/data/" + testDataset)).getDocumentElement());
-        this.expectedConfig = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/edit-config/" + testDataset).toURI())));
-        this.expectedFilter = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/filter/" + testDataset).toURI())));
-        this.getConfigData = new String(Files.readAllBytes(Paths.get(getClass().getResource("/schemaless/get-config/" + testDataset).toURI())));
+        this.source = new DOMSource(XmlUtil.readXmlToDocument(getClass()
+                .getResourceAsStream("/schemaless/data/" + testDataset)).getDocumentElement());
+        this.expectedConfig = new String(Files.readAllBytes(
+                Paths.get(getClass().getResource("/schemaless/edit-config/" + testDataset).toURI())));
+        this.expectedFilter = new String(Files.readAllBytes(
+                Paths.get(getClass().getResource("/schemaless/filter/" + testDataset).toURI())));
+        this.getConfigData = new String(Files.readAllBytes(
+                Paths.get(getClass().getResource("/schemaless/get-config/" + testDataset).toURI())));
     }
 
     @Parameterized.Parameters
@@ -80,7 +86,8 @@ public class SchemalessRpcStructureTransformerTest {
                 {YangInstanceIdentifier.builder()
                         .node(createNodeId("top"))
                         .node(createNodeId("users"))
-                        .node(createListNodeId("user", ImmutableMap.of(QName.create(NAMESPACE, "key1"), "k1", QName.create(NAMESPACE, "key2"), "k2")))
+                        .node(createListNodeId("user", ImmutableMap.of(QName.create(NAMESPACE, "key1"), "k1",
+                                QName.create(NAMESPACE, "key2"), "k2")))
                         .build(), "keyed-list-compound-key.xml", null},
                 {YangInstanceIdentifier.builder()
                         .node(createNodeId("top"))
@@ -98,14 +105,15 @@ public class SchemalessRpcStructureTransformerTest {
 
     @Test
     public void testCreateEditConfigStructure() throws Exception {
-        if(expectedException != null) {
+        if (expectedException != null) {
             thrown.expect(expectedException);
         }
         AnyXmlNode data = Builders.anyXmlBuilder()
                 .withNodeIdentifier(createNodeId(path.getLastPathArgument().getNodeType().getLocalName()))
                 .withValue(source)
                 .build();
-        final AnyXmlNode anyXmlNode = adapter.createEditConfigStructure(Optional.of(data), path, Optional.of(ModifyAction.REPLACE));
+        final AnyXmlNode anyXmlNode =
+                adapter.createEditConfigStructure(Optional.of(data), path, Optional.of(ModifyAction.REPLACE));
         final String s = XmlUtil.toString((Element) anyXmlNode.getValue().getNode());
         Diff diff = new Diff(expectedConfig, s);
         Assert.assertTrue(String.format("Input %s: %s", testDataset, diff.toString()), diff.similar());
@@ -137,11 +145,14 @@ public class SchemalessRpcStructureTransformerTest {
         return new YangInstanceIdentifier.NodeIdentifier(QName.create(NAMESPACE, name));
     }
 
-    private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(String nodeName, String keyName, String id) {
-        return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), QName.create(NAMESPACE, keyName), id);
+    private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(
+            String nodeName, String keyName, String id) {
+        return new YangInstanceIdentifier
+                .NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), QName.create(NAMESPACE, keyName), id);
     }
 
-    private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(String nodeName, Map<QName, Object> keys) {
+    private static YangInstanceIdentifier.NodeIdentifierWithPredicates createListNodeId(
+            String nodeName, Map<QName, Object> keys) {
         return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(NAMESPACE, nodeName), keys);
     }
 }