Merge "Bug 8153: Enforce check-style rules for netconf - aaa-authn-odl-plugin"
authorTomas Cere <tcere@cisco.com>
Thu, 27 Apr 2017 13:58:55 +0000 (13:58 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Thu, 27 Apr 2017 13:58:55 +0000 (13:58 +0000)
111 files changed:
netconf/mdsal-netconf-monitoring/pom.xml
netconf/mdsal-netconf-monitoring/src/main/java/org/opendaylight/controller/config/yang/netconf/mdsal/monitoring/MdsalMonitoringMapperFactory.java
netconf/mdsal-netconf-monitoring/src/main/java/org/opendaylight/controller/config/yang/netconf/mdsal/monitoring/MonitoringToMdsalWriter.java
netconf/mdsal-netconf-monitoring/src/test/java/org/opendaylight/controller/config/yang/netconf/mdsal/monitoring/MonitoringToMdsalWriterTest.java
netconf/netconf-artifacts/pom.xml
netconf/netconf-client/pom.xml
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientDispatcher.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientDispatcherImpl.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSession.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiator.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorFactory.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SshClientChannelInitializer.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/TcpClientChannelInitializer.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfiguration.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfigurationBuilder.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfReconnectingClientConfiguration.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfReconnectingClientConfigurationBuilder.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientConfigurationTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientDispatcherImplTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorFactoryTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiatorTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/NetconfReconnectingClientConfigurationTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListenerTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/SshClientChannelInitializerTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/TcpClientChannelInitializerTest.java
netconf/netconf-client/src/test/java/org/opendaylight/netconf/client/TestingNetconfClient.java
netconf/netconf-netty-util/pom.xml
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractChannelInitializer.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSession.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/BufferedWriter.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregator.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXICodec.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIToMessageDecoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfMessageToEXIEncoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfMessageToXMLEncoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParameters.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessage.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/AuthenticationHandler.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/authentication/LoginPassword.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerReader.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerWriter.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiatorTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/TestingNetconfSession.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoderTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfChunkAggregatorTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXIHandlersTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfHelloMessageToXMLEncoderTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToHelloMessageDecoderTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/NetconfXMLToMessageDecoderTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/EXIParametersTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/exi/NetconfStartExiMessageTest.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandlerTest.java
netconf/netconf-ssh/pom.xml
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyClientHandler.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/AuthProviderTracker.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClient.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServer.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServerHandler.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyClientHandler.java [new file with mode: 0644]
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServer.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServerHandler.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java
netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java
netconf/netconf-topology-singleton/src/main/resources/org/opendaylight/blueprint/netconf-topology-singleton.xml
netconf/netconf-topology-singleton/src/main/yang/netconf-clustered-topology-config.yang [new file with mode: 0644]
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfNodeActorTest.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManagerTest.java
netconf/netconf-util/pom.xml
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/NetconfUtil.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperation.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperation.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/FramingMechanism.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageUtil.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SendErrorExceptionUtil.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtil.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfiguration.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolver.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/XMLNetconfUtil.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/CloseableUtilTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/NetconfUtilTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperationTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperationTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractSingletonNetconfOperationTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/NetconfMessageUtilTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterNotificationTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterRpcTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtilTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/NetconfXmlUnitRecursiveQualifier.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolverTest.java
netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/XMLNetconfUtilTest.java
restconf/restconf-artifacts/pom.xml

index 1fe1a025f2994beb535343b082f6652b6754a4ff..5bc776a9468097f7fb393d0deb528dc0577a86c4 100644 (file)
     </dependency>
   </dependencies>
 
+  <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 0fe866d847e993942e566cafacfe8d207d685017..a163dd7540abf65659985e541ee594da24b3f83e 100644 (file)
@@ -27,9 +27,10 @@ public class MdsalMonitoringMapperFactory implements NetconfOperationServiceFact
 
     private static final Set<Capability> CAPABILITIES = Collections.emptySet();
 
-    public MdsalMonitoringMapperFactory(final NetconfOperationServiceFactoryListener netconfOperationServiceFactoryListener,
-                                        final NetconfMonitoringService netconfMonitoringService,
-                                        final MonitoringToMdsalWriter monitoringToMdsalWriter) {
+    public MdsalMonitoringMapperFactory(
+            final NetconfOperationServiceFactoryListener netconfOperationServiceFactoryListener,
+            final NetconfMonitoringService netconfMonitoringService,
+            final MonitoringToMdsalWriter monitoringToMdsalWriter) {
 
         this.netconfOperationServiceFactoryListener = netconfOperationServiceFactoryListener;
         this.monitoringToMdsalWriter = monitoringToMdsalWriter;
@@ -56,9 +57,9 @@ public class MdsalMonitoringMapperFactory implements NetconfOperationServiceFact
 
     @Override
     public Set<Capability> getCapabilities() {
-        // TODO
-        // No capabilities exposed to prevent clashes with schemas from mdsal-netconf-connector (it exposes all the schemas)
-        // If the schemas exposed by mdsal-netconf-connector are filtered, this class would expose monitoring related models
+        // TODO No capabilities exposed to prevent clashes with schemas from mdsal-netconf-connector (it exposes
+        // all the schemas). If the schemas exposed by mdsal-netconf-connector are filtered, this class would expose
+        // monitoring related models.
         return CAPABILITIES;
     }
 
@@ -68,7 +69,7 @@ public class MdsalMonitoringMapperFactory implements NetconfOperationServiceFact
     }
 
     /**
-     * Invoke using blueprint
+     * Invoked using blueprint.
      */
     @Override
     public void close() {
index 3e487b4db6045c248891122be3a8336c6fe826f9..30e2655924086de8b934c3e1833a77effffbbbed 100644 (file)
@@ -52,11 +52,12 @@ public final class MonitoringToMdsalWriter implements AutoCloseable, NetconfMoni
     }
 
     /**
-     * Invoke using blueprint
+     * Invoked using blueprint.
      */
     @Override
     public void close() {
-        runTransaction((tx) -> tx.delete(LogicalDatastoreType.OPERATIONAL, InstanceIdentifier.create(NetconfState.class)));
+        runTransaction((tx) -> tx.delete(LogicalDatastoreType.OPERATIONAL,
+                InstanceIdentifier.create(NetconfState.class)));
     }
 
     @Override
@@ -80,7 +81,8 @@ public final class MonitoringToMdsalWriter implements AutoCloseable, NetconfMoni
 
     @Override
     public void onCapabilitiesChanged(Capabilities capabilities) {
-        runTransaction((tx) -> tx.put(LogicalDatastoreType.OPERATIONAL, CAPABILITIES_INSTANCE_IDENTIFIER, capabilities));
+        runTransaction((tx) -> tx.put(LogicalDatastoreType.OPERATIONAL, CAPABILITIES_INSTANCE_IDENTIFIER,
+                capabilities));
     }
 
     @Override
@@ -89,7 +91,7 @@ public final class MonitoringToMdsalWriter implements AutoCloseable, NetconfMoni
     }
 
     /**
-     * Invoke using blueprint
+     * Invoked using blueprint.
      */
     public void start() {
         serverMonitoringDependency.registerCapabilitiesListener(this);
@@ -107,8 +109,8 @@ public final class MonitoringToMdsalWriter implements AutoCloseable, NetconfMoni
             }
 
             @Override
-            public void onFailure(Throwable t) {
-                LOG.warn("Unable to update netconf state", t);
+            public void onFailure(Throwable throwable) {
+                LOG.warn("Unable to update netconf state", throwable);
             }
         });
     }
index 10256b86f92c774651433ba1c2a6a087ebc95d93..05b6bd15f9054aeee639fb7fd62c090014bbbb81 100644 (file)
@@ -39,7 +39,8 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 public class MonitoringToMdsalWriterTest {
 
-    private static final InstanceIdentifier<NetconfState> INSTANCE_IDENTIFIER = InstanceIdentifier.create(NetconfState.class);
+    private static final InstanceIdentifier<NetconfState> INSTANCE_IDENTIFIER =
+            InstanceIdentifier.create(NetconfState.class);
 
     @Mock
     private NetconfMonitoringService monitoring;
@@ -77,7 +78,8 @@ public class MonitoringToMdsalWriterTest {
 
     @Test
     public void testOnCapabilityChanged() throws Exception {
-        final InstanceIdentifier<Capabilities> capabilitiesId = InstanceIdentifier.create(NetconfState.class).child(Capabilities.class);
+        final InstanceIdentifier<Capabilities> capabilitiesId =
+                InstanceIdentifier.create(NetconfState.class).child(Capabilities.class);
         writer.start();
         final Capabilities capabilities = new CapabilitiesBuilder().build();
         writer.onCapabilitiesChanged(capabilities);
@@ -88,7 +90,8 @@ public class MonitoringToMdsalWriterTest {
 
     @Test
     public void testOnSchemasChanged() throws Exception {
-        final InstanceIdentifier<Schemas> schemasId = InstanceIdentifier.create(NetconfState.class).child(Schemas.class);
+        final InstanceIdentifier<Schemas> schemasId =
+                InstanceIdentifier.create(NetconfState.class).child(Schemas.class);
         writer.start();
         final Schemas schemas = new SchemasBuilder().build();
         writer.onSchemasChanged(schemas);
@@ -102,7 +105,10 @@ public class MonitoringToMdsalWriterTest {
         Session session = new SessionBuilder()
                 .setSessionId(1L)
                 .build();
-        final InstanceIdentifier<Session> id = InstanceIdentifier.create(NetconfState.class).child(Sessions.class).child(Session.class, session.getKey());
+        final InstanceIdentifier<Session> id =
+                InstanceIdentifier.create(NetconfState.class)
+                        .child(Sessions.class)
+                        .child(Session.class, session.getKey());
         writer.start();
         writer.onSessionStarted(session);
         InOrder inOrder = inOrder(writeTransaction);
@@ -115,7 +121,10 @@ public class MonitoringToMdsalWriterTest {
         Session session = new SessionBuilder()
                 .setSessionId(1L)
                 .build();
-        final InstanceIdentifier<Session> id = InstanceIdentifier.create(NetconfState.class).child(Sessions.class).child(Session.class, session.getKey());
+        final InstanceIdentifier<Session> id =
+                InstanceIdentifier.create(NetconfState.class)
+                        .child(Sessions.class)
+                        .child(Session.class, session.getKey());
         writer.start();
         writer.onSessionEnded(session);
         InOrder inOrder = inOrder(writeTransaction);
@@ -134,8 +143,14 @@ public class MonitoringToMdsalWriterTest {
         List<Session> sessions = new ArrayList<>();
         sessions.add(session1);
         sessions.add(session2);
-        final InstanceIdentifier<Session> id1 = InstanceIdentifier.create(NetconfState.class).child(Sessions.class).child(Session.class, session1.getKey());
-        final InstanceIdentifier<Session> id2 = InstanceIdentifier.create(NetconfState.class).child(Sessions.class).child(Session.class, session2.getKey());
+        final InstanceIdentifier<Session> id1 =
+                InstanceIdentifier.create(NetconfState.class)
+                        .child(Sessions.class)
+                        .child(Session.class, session1.getKey());
+        final InstanceIdentifier<Session> id2 =
+                InstanceIdentifier.create(NetconfState.class)
+                        .child(Sessions.class)
+                        .child(Session.class, session2.getKey());
         writer.start();
         writer.onSessionsUpdated(sessions);
         InOrder inOrder = inOrder(writeTransaction);
index 681740033764a370ff72bd0e01dac99764ac8464..7019ffbf36bff31aad1472dfe10f8a7e0fc3c7a5 100644 (file)
                 <version>${project.version}</version>
                 <classifier>features</classifier>
                 <type>xml</type>
-                <scope>runtime</scope>
             </dependency>
 
             <dependency>
                 <groupId>${project.groupId}</groupId>
                 <artifactId>features-netconf</artifactId>
                 <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+
+            <!-- netconf features -->
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>features4-netconf</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-aaa-netconf-plugin</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-aaa-netconf-plugin-no-cluster</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-config-netconf-connector</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-all</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-api</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-client</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-impl</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-mapping-api</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-mdsal</artifactId>
+                <version>1.6.0-SNAPSHOT</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-monitoring</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-netty-util</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-notifications-api</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-notifications-impl</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
                 <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-ssh</artifactId>
+                <version>${project.version}</version>
                 <type>xml</type>
-                <scope>runtime</scope>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-tcp</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-util</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+
+            <!-- netconf-connector features -->
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>features4-netconf-connector</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-message-bus</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
             </dependency>
             <dependency>
                 <groupId>${project.groupId}</groupId>
                 <artifactId>odl-netconf-clustered-topology</artifactId>
                 <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-connector</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-connector-all</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-connector-ssh</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
                 <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-callhome-ssh</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-console</artifactId>
+                <version>${project.version}</version>
                 <type>xml</type>
-                <scope>runtime</scope>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-netconf-topology</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+
+            <!-- yanglib features -->
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>features4-yanglib</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-yanglib</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
             </dependency>
         </dependencies>
     </dependencyManagement>
index 6c4f3edae121c3de76b3eadd7f8d7bca7587f3ab..072eeac5b638c931e279caa9a31ad3ba467fd137 100644 (file)
           </execution>
         </executions>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index 38f7155d292656bc1d30908fddbd6c1f962bd2f5..66fdff674dff563dbac1dad9464e5f81ad45fa1c 100644 (file)
@@ -14,10 +14,10 @@ import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfigurati
 public interface NetconfClientDispatcher {
 
     /**
+     * Create netconf client. Network communication has to be set up based on network protocol specified in
+     * clientConfiguration
      *
-     * Create netconf client. Network communication has to be set up based on network protocol specified in clientConfiguration
-     *
-     * @param clientConfiguration
+     * @param clientConfiguration Configuration of client
      * @return netconf client based on provided configuration
      */
     Future<NetconfClientSession> createClient(NetconfClientConfiguration clientConfiguration);
index 38635b1ec350bd071a83b92e759e488105c09179..6abce42b43239d0c0d645964d11450c8abcb2c7a 100644 (file)
@@ -25,7 +25,8 @@ public class NetconfClientDispatcherImpl extends AbstractDispatcher<NetconfClien
 
     private final Timer timer;
 
-    public NetconfClientDispatcherImpl(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup, final Timer timer) {
+    public NetconfClientDispatcherImpl(final EventLoopGroup bossGroup, final EventLoopGroup workerGroup,
+                                       final Timer timer) {
         super(bossGroup, workerGroup);
         this.timer = timer;
     }
@@ -37,55 +38,63 @@ public class NetconfClientDispatcherImpl extends AbstractDispatcher<NetconfClien
     @Override
     public Future<NetconfClientSession> createClient(final NetconfClientConfiguration clientConfiguration) {
         switch (clientConfiguration.getProtocol()) {
-        case TCP:
-            return createTcpClient(clientConfiguration);
-        case SSH:
-            return createSshClient(clientConfiguration);
+            case TCP:
+                return createTcpClient(clientConfiguration);
+            case SSH:
+                return createSshClient(clientConfiguration);
+            default:
+                throw new IllegalArgumentException("Unknown client protocol " + clientConfiguration.getProtocol());
         }
-        throw new IllegalArgumentException("Unknown client protocol " + clientConfiguration.getProtocol());
     }
 
     @Override
     public Future<Void> createReconnectingClient(final NetconfReconnectingClientConfiguration clientConfiguration) {
         switch (clientConfiguration.getProtocol()) {
-        case TCP:
-            return createReconnectingTcpClient(clientConfiguration);
-        case SSH:
-            return createReconnectingSshClient(clientConfiguration);
+            case TCP:
+                return createReconnectingTcpClient(clientConfiguration);
+            case SSH:
+                return createReconnectingSshClient(clientConfiguration);
+            default:
+                throw new IllegalArgumentException("Unknown client protocol " + clientConfiguration.getProtocol());
         }
-        throw new IllegalArgumentException("Unknown client protocol " + clientConfiguration.getProtocol());
     }
 
     private Future<NetconfClientSession> createTcpClient(final NetconfClientConfiguration currentConfiguration) {
         LOG.debug("Creating TCP client with configuration: {}", currentConfiguration);
         return super.createClient(currentConfiguration.getAddress(), currentConfiguration.getReconnectStrategy(),
-                (ch, promise) -> new TcpClientChannelInitializer(getNegotiatorFactory(currentConfiguration), currentConfiguration
-                                .getSessionListener()).initialize(ch, promise));
+            (ch, promise) -> new TcpClientChannelInitializer(getNegotiatorFactory(currentConfiguration),
+                        currentConfiguration
+                        .getSessionListener()).initialize(ch, promise));
     }
 
-    private Future<Void> createReconnectingTcpClient(final NetconfReconnectingClientConfiguration currentConfiguration) {
+    private Future<Void> createReconnectingTcpClient(
+            final NetconfReconnectingClientConfiguration currentConfiguration) {
         LOG.debug("Creating reconnecting TCP client with configuration: {}", currentConfiguration);
-        final TcpClientChannelInitializer init = new TcpClientChannelInitializer(getNegotiatorFactory(currentConfiguration),
+        final TcpClientChannelInitializer init =
+                new TcpClientChannelInitializer(getNegotiatorFactory(currentConfiguration),
                 currentConfiguration.getSessionListener());
 
-        return super.createReconnectingClient(currentConfiguration.getAddress(), currentConfiguration.getConnectStrategyFactory(),
+        return super.createReconnectingClient(currentConfiguration.getAddress(), currentConfiguration
+                .getConnectStrategyFactory(),
                 currentConfiguration.getReconnectStrategy(), init::initialize);
     }
 
     private Future<NetconfClientSession> createSshClient(final NetconfClientConfiguration currentConfiguration) {
         LOG.debug("Creating SSH client with configuration: {}", currentConfiguration);
         return super.createClient(currentConfiguration.getAddress(), currentConfiguration.getReconnectStrategy(),
-                (ch, sessionPromise) -> new SshClientChannelInitializer(currentConfiguration.getAuthHandler(),
+            (ch, sessionPromise) -> new SshClientChannelInitializer(currentConfiguration.getAuthHandler(),
                         getNegotiatorFactory(currentConfiguration), currentConfiguration.getSessionListener())
                         .initialize(ch, sessionPromise));
     }
 
-    private Future<Void> createReconnectingSshClient(final NetconfReconnectingClientConfiguration currentConfiguration) {
+    private Future<Void> createReconnectingSshClient(
+            final NetconfReconnectingClientConfiguration currentConfiguration) {
         LOG.debug("Creating reconnecting SSH client with configuration: {}", currentConfiguration);
         final SshClientChannelInitializer init = new SshClientChannelInitializer(currentConfiguration.getAuthHandler(),
                 getNegotiatorFactory(currentConfiguration), currentConfiguration.getSessionListener());
 
-        return super.createReconnectingClient(currentConfiguration.getAddress(), currentConfiguration.getConnectStrategyFactory(), currentConfiguration.getReconnectStrategy(),
+        return super.createReconnectingClient(currentConfiguration.getAddress(), currentConfiguration
+                .getConnectStrategyFactory(), currentConfiguration.getReconnectStrategy(),
                 init::initialize);
     }
 
index e27f72b5c927ccb8d70d80e1de9ba7de1204780a..86415ecfdfa9fa450db3051ec5214acb5164a2e6 100644 (file)
@@ -27,13 +27,13 @@ public class NetconfClientSession extends AbstractNetconfSession<NetconfClientSe
     /**
      * Construct a new session.
      *
-     * @param sessionListener
-     * @param channel
-     * @param sessionId
-     * @param capabilities set of advertised capabilities. Expected to be immutable.
+     * @param sessionListener    Netconf client session listener.
+     * @param channel    Channel.
+     * @param sessionId    Session Id.
+     * @param capabilities    Set of advertised capabilities. Expected to be immutable.
      */
-    public NetconfClientSession(final NetconfClientSessionListener sessionListener, final Channel channel, final long sessionId,
-            final Collection<String> capabilities) {
+    public NetconfClientSession(final NetconfClientSessionListener sessionListener, final Channel channel,
+                                final long sessionId, final Collection<String> capabilities) {
         super(sessionListener, channel, sessionId);
         this.capabilities = capabilities;
         LOG.debug("Client Session {} created", this);
@@ -49,7 +49,8 @@ public class NetconfClientSession extends AbstractNetconfSession<NetconfClientSe
     }
 
     @Override
-    protected void addExiHandlers(final ByteToMessageDecoder decoder, final MessageToByteEncoder<NetconfMessage> encoder) {
+    protected void addExiHandlers(final ByteToMessageDecoder decoder,
+                                  final MessageToByteEncoder<NetconfMessage> encoder) {
         // TODO used only in negotiator, client supports only auto start-exi
         replaceMessageDecoder(decoder);
         replaceMessageEncoder(encoder);
index 55d92d6df6e33bc25ea471067bce24976d6db529..608450225f52d84d71cff3d1443b739905edaa5d 100644 (file)
@@ -40,14 +40,14 @@ import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
 public class NetconfClientSessionNegotiator extends
-        AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession, NetconfClientSessionListener>
-{
+        AbstractNetconfSessionNegotiator<NetconfClientSessionPreferences, NetconfClientSession,
+                NetconfClientSessionListener> {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfClientSessionNegotiator.class);
 
-    private static final XPathExpression sessionIdXPath = XMLNetconfUtil
+    private static final XPathExpression SESSION_ID_X_PATH = XMLNetconfUtil
             .compileXPath("/netconf:hello/netconf:session-id");
 
-    private static final XPathExpression sessionIdXPathNoNamespace = XMLNetconfUtil
+    private static final XPathExpression SESSION_ID_X_PATH_NO_NAMESPACE = XMLNetconfUtil
             .compileXPath("/hello/session-id");
 
     private static final String EXI_1_0_CAPABILITY_MARKER = "exi:1.0";
@@ -84,7 +84,7 @@ public class NetconfClientSessionNegotiator extends
     /**
      * Initiates exi communication by sending start-exi message and waiting for positive/negative response.
      *
-     * @param startExiMessage
+     * @param startExiMessage Exi message for initilization of exi communication.
      */
     void tryToInitiateExi(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
         channel.pipeline().addAfter(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
@@ -93,9 +93,10 @@ public class NetconfClientSessionNegotiator extends
 
         session.sendMessage(startExiMessage).addListener(new ChannelFutureListener() {
             @Override
-            public void operationComplete(final ChannelFuture f) {
-                if (!f.isSuccess()) {
-                    LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, this, f.cause());
+            public void operationComplete(final ChannelFuture channelFuture) {
+                if (!channelFuture.isSuccess()) {
+                    LOG.warn("Failed to send start-exi message {} on session {}", startExiMessage, this,
+                            channelFuture.cause());
                     channel.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
                 } else {
                     LOG.trace("Start-exi message {} sent to socket on session {}", startExiMessage, this);
@@ -120,11 +121,12 @@ public class NetconfClientSessionNegotiator extends
     }
 
     private static long extractSessionId(final Document doc) {
-        String textContent = getSessionIdWithXPath(doc, sessionIdXPath);
+        String textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH);
         if (Strings.isNullOrEmpty(textContent)) {
-            textContent = getSessionIdWithXPath(doc, sessionIdXPathNoNamespace);
+            textContent = getSessionIdWithXPath(doc, SESSION_ID_X_PATH_NO_NAMESPACE);
             if (Strings.isNullOrEmpty(textContent)) {
-                throw new IllegalStateException("Session id not received from server, hello message: " + XmlUtil.toString(doc));
+                throw new IllegalStateException("Session id not received from server, hello message: " + XmlUtil
+                        .toString(doc));
             }
         }
 
@@ -142,7 +144,8 @@ public class NetconfClientSessionNegotiator extends
         final long sessionId = extractSessionId(message.getDocument());
 
         // Copy here is important: it disconnects the strings from the document
-        Set<String> capabilities = ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message.getDocument()));
+        Set<String> capabilities = ImmutableSet.copyOf(NetconfMessageUtil.extractCapabilitiesFromHello(message
+                .getDocument()));
 
         capabilities = INTERNER.intern(capabilities);
 
@@ -150,7 +153,7 @@ public class NetconfClientSessionNegotiator extends
     }
 
     /**
-     * Handler to process response for start-exi message
+     * Handler to process response for start-exi message.
      */
     private final class ExiConfirmationInboundHandler extends ChannelInboundHandlerAdapter {
         private static final String EXI_CONFIRMED_HANDLER = "exiConfirmedHandler";
@@ -158,11 +161,13 @@ public class NetconfClientSessionNegotiator extends
         private final NetconfClientSession session;
         private final NetconfStartExiMessage startExiMessage;
 
-        ExiConfirmationInboundHandler(final NetconfClientSession session, final NetconfStartExiMessage startExiMessage) {
+        ExiConfirmationInboundHandler(final NetconfClientSession session,
+                                      final NetconfStartExiMessage startExiMessage) {
             this.session = session;
             this.startExiMessage = startExiMessage;
         }
 
+        @SuppressWarnings("checkstyle:IllegalCatch")
         @Override
         public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
             ctx.pipeline().remove(ExiConfirmationInboundHandler.EXI_CONFIRMED_HANDLER);
@@ -176,20 +181,22 @@ public class NetconfClientSessionNegotiator extends
                     session.startExiCommunication(startExiMessage);
                 } catch (RuntimeException e) {
                     // Unable to add exi, continue without exi
-                    LOG.warn("Unable to start exi communication, Communication will continue without exi on session {}", session, e);
+                    LOG.warn("Unable to start exi communication, Communication will continue without exi on session "
+                            + "{}", session, e);
                 }
 
                 // Error response
-            } else if(NetconfMessageUtil.isErrorMessage(netconfMessage)) {
+            } else if (NetconfMessageUtil.isErrorMessage(netconfMessage)) {
                 LOG.warn(
                         "Error response to start-exi message {}, Communication will continue without exi on session {}",
                         netconfMessage, session);
 
                 // Unexpected response to start-exi, throwing message away, continue without exi
             } else {
-                LOG.warn("Unexpected response to start-exi message, should be ok, was {}, " +
-                         "Communication will continue without exi and response message will be thrown away on session {}",
-                         netconfMessage, session);
+                LOG.warn("Unexpected response to start-exi message, should be ok, was {}, "
+                        + "Communication will continue without exi "
+                        + "and response message will be thrown away on session {}",
+                        netconfMessage, session);
             }
 
             negotiationSuccessful(session);
index a49ac1a26d794651d754f1551350e74fcad43750..b1767f9fddd383335d400869e35c54820a2c1e07 100644 (file)
@@ -31,7 +31,8 @@ import org.openexi.proc.common.EXIOptionsException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfMessage, NetconfClientSession, NetconfClientSessionListener> {
+public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfMessage,
+        NetconfClientSession, NetconfClientSessionListener> {
 
     public static final Set<String> EXI_CLIENT_CAPABILITIES = ImmutableSet.of(
             XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
@@ -95,7 +96,8 @@ public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorF
 
     public NetconfClientSessionNegotiatorFactory(final Timer timer,
                                                  final Optional<NetconfHelloMessageAdditionalHeader> additionalHeader,
-                                                 final long connectionTimeoutMillis, final EXIOptions exiOptions, final Set<String> capabilities) {
+                                                 final long connectionTimeoutMillis, final EXIOptions exiOptions,
+                                                 final Set<String> capabilities) {
         this.timer = Preconditions.checkNotNull(timer);
         this.additionalHeader = additionalHeader;
         this.connectionTimeoutMillis = connectionTimeoutMillis;
@@ -104,21 +106,22 @@ public class NetconfClientSessionNegotiatorFactory implements SessionNegotiatorF
     }
 
     @Override
-    public SessionNegotiator<NetconfClientSession> getSessionNegotiator(final SessionListenerFactory<NetconfClientSessionListener> sessionListenerFactory,
-                                                                        final Channel channel,
-            final Promise<NetconfClientSession> promise) {
+    public SessionNegotiator<NetconfClientSession> getSessionNegotiator(
+            final SessionListenerFactory<NetconfClientSessionListener> sessionListenerFactory,
+            final Channel channel, final Promise<NetconfClientSession> promise) {
 
         NetconfMessage startExiMessage = NetconfStartExiMessage.create(options, START_EXI_MESSAGE_ID);
         NetconfHelloMessage helloMessage = null;
         try {
             helloMessage = NetconfHelloMessage.createClientHello(clientCapabilities, additionalHeader);
         } catch (NetconfDocumentedException e) {
-            LOG.error("Unable to create client hello message with capabilities {} and additional handler {}", clientCapabilities,additionalHeader);
+            LOG.error("Unable to create client hello message with capabilities {} and additional handler {}",
+                    clientCapabilities, additionalHeader);
             throw new IllegalStateException(e);
         }
 
         NetconfClientSessionPreferences proposal = new NetconfClientSessionPreferences(helloMessage, startExiMessage);
         return new NetconfClientSessionNegotiator(proposal, promise, channel, timer,
-                sessionListenerFactory.getSessionListener(),connectionTimeoutMillis);
+                sessionListenerFactory.getSessionListener(), connectionTimeoutMillis);
     }
 }
index 040d60c14acff0ff80b80a0f69d06b0bf7f1716c..654210a4a0e1685b032cdf3cb60fb10c9bd3a1d8 100644 (file)
@@ -25,7 +25,7 @@ public class SimpleNetconfClientSessionListener implements NetconfClientSessionL
         private final Promise<NetconfMessage> promise;
         private final NetconfMessage request;
 
-        public RequestEntry(Promise<NetconfMessage> future, NetconfMessage request) {
+        RequestEntry(Promise<NetconfMessage> future, NetconfMessage request) {
             this.promise = Preconditions.checkNotNull(future);
             this.request = Preconditions.checkNotNull(request);
         }
@@ -71,14 +71,14 @@ public class SimpleNetconfClientSessionListener implements NetconfClientSessionL
     }
 
     @Override
-    public final void onSessionDown(NetconfClientSession clientSession, Exception e) {
-        LOG.debug("Client Session {} went down unexpectedly", clientSession, e);
-        tearDown(e);
+    public final void onSessionDown(NetconfClientSession clientSession, Exception exception) {
+        LOG.debug("Client Session {} went down unexpectedly", clientSession, exception);
+        tearDown(exception);
     }
 
     @Override
     public final void onSessionTerminated(NetconfClientSession clientSession,
-            NetconfTerminationReason netconfTerminationReason) {
+                                          NetconfTerminationReason netconfTerminationReason) {
         LOG.debug("Client Session {} terminated, reason: {}", clientSession,
                 netconfTerminationReason.getErrorMessage());
         tearDown(new RuntimeException(netconfTerminationReason.getErrorMessage()));
index 65a433fe16d03dce4a4b024cbf0a98526e5631eb..9adf79cef1d404860ce8bc5cbfd2f5c00b67f3aa 100644 (file)
@@ -20,9 +20,9 @@ final class SshClientChannelInitializer extends AbstractChannelInitializer<Netco
     private final NetconfClientSessionNegotiatorFactory negotiatorFactory;
     private final NetconfClientSessionListener sessionListener;
 
-    public SshClientChannelInitializer(final AuthenticationHandler authHandler,
-                                       final NetconfClientSessionNegotiatorFactory negotiatorFactory,
-                                       final NetconfClientSessionListener sessionListener) {
+    SshClientChannelInitializer(final AuthenticationHandler authHandler,
+                                final NetconfClientSessionNegotiatorFactory negotiatorFactory,
+                                final NetconfClientSessionListener sessionListener) {
         this.authenticationHandler = authHandler;
         this.negotiatorFactory = negotiatorFactory;
         this.sessionListener = sessionListener;
@@ -33,7 +33,7 @@ final class SshClientChannelInitializer extends AbstractChannelInitializer<Netco
         try {
             // ssh handler has to be the first handler in pipeline
             ch.pipeline().addFirst(AsyncSshHandler.createForNetconfSubsystem(authenticationHandler, promise));
-            super.initialize(ch,promise);
+            super.initialize(ch, promise);
         } catch (final IOException e) {
             throw new RuntimeException(e);
         }
@@ -42,7 +42,7 @@ final class SshClientChannelInitializer extends AbstractChannelInitializer<Netco
     @Override
     protected void initializeSessionNegotiator(final Channel ch,
                                                final Promise<NetconfClientSession> promise) {
-        ch.pipeline().addAfter(NETCONF_MESSAGE_DECODER,  AbstractChannelInitializer.NETCONF_SESSION_NEGOTIATOR,
+        ch.pipeline().addAfter(NETCONF_MESSAGE_DECODER, AbstractChannelInitializer.NETCONF_SESSION_NEGOTIATOR,
                 negotiatorFactory.getSessionNegotiator(() -> sessionListener, ch, promise));
     }
 }
index 84f4bf9f3238c54a91f75cb500ce0c1f79756222..2cf0e1a5cd32e04aaabf297a695e786946f8723b 100644 (file)
@@ -41,7 +41,8 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer<NetconfClie
             GenericFutureListener<Future<NetconfClientSession>> negotiationFutureListener;
 
             @Override
-            public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress,
+            public void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
+                                final SocketAddress localAddress,
                                 final ChannelPromise channelPromise) throws Exception {
                 connectPromise = channelPromise;
                 ChannelPromise tcpConnectFuture = new DefaultChannelPromise(ch);
@@ -53,7 +54,7 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer<NetconfClie
                 };
 
                 tcpConnectFuture.addListener(future -> {
-                    if(future.isSuccess()) {
+                    if (future.isSuccess()) {
                         //complete connection promise with netconf negotiation future
                         negotiationFuture.addListener(negotiationFutureListener);
                     } else {
@@ -65,14 +66,15 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer<NetconfClie
 
             @Override
             public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
-                // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
-                if(connectPromise.isSuccess()) {
+                // If we have already succeeded and the session was dropped after, we need to fire inactive to notify
+                // reconnect logic
+                if (connectPromise.isSuccess()) {
                     ctx.fireChannelInactive();
                 }
 
                 //If connection promise is not already set, it means negotiation failed
                 //we must set connection promise to failure
-                if(!connectPromise.isDone()) {
+                if (!connectPromise.isDone()) {
                     connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
                 }
 
index 59a8d1f446169b123b2065bd32504233666eca62..d1d6e40176abc79407c0f4466dde96b18e7380d0 100644 (file)
@@ -16,9 +16,13 @@ import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader
 import org.opendaylight.netconf.client.NetconfClientSessionListener;
 import org.opendaylight.netconf.nettyutil.handler.ssh.authentication.AuthenticationHandler;
 import org.opendaylight.protocol.framework.ReconnectStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class NetconfClientConfiguration {
 
+    private static final Logger LOG = LoggerFactory.getLogger(NetconfClientConfiguration.class);
+
     private final NetconfClientProtocol clientProtocol;
     private final InetSocketAddress address;
     private final Long connectionTimeoutMillis;
@@ -30,7 +34,11 @@ public class NetconfClientConfiguration {
 
     private final AuthenticationHandler authHandler;
 
-    NetconfClientConfiguration(final NetconfClientProtocol protocol, final InetSocketAddress address, final Long connectionTimeoutMillis, final NetconfHelloMessageAdditionalHeader additionalHeader, final NetconfClientSessionListener sessionListener, final ReconnectStrategy reconnectStrategy, final AuthenticationHandler authHandler) {
+    NetconfClientConfiguration(final NetconfClientProtocol protocol, final InetSocketAddress address,
+                               final Long connectionTimeoutMillis,
+                               final NetconfHelloMessageAdditionalHeader additionalHeader,
+                               final NetconfClientSessionListener sessionListener,
+                               final ReconnectStrategy reconnectStrategy, final AuthenticationHandler authHandler) {
         this.address = address;
         this.connectionTimeoutMillis = connectionTimeoutMillis;
         this.additionalHeader = additionalHeader;
@@ -69,14 +77,17 @@ public class NetconfClientConfiguration {
         return clientProtocol;
     }
 
+    @SuppressWarnings("checkstyle:FallThrough")
     private void validateConfiguration() {
         Preconditions.checkNotNull(clientProtocol, " ");
         switch (clientProtocol) {
-        case SSH:
-            validateSshConfiguration();
-            // Fall through intentional (ssh validation is a superset of tcp validation)
-        case TCP:
-            validateTcpConfiguration();
+            case SSH:
+                validateSshConfiguration();
+                // Fall through intentional (ssh validation is a superset of tcp validation)
+            case TCP:
+                validateTcpConfiguration();
+            default:
+                LOG.warn("Unexpected protocol: {} in netconf client configuration.", clientProtocol);
         }
     }
 
@@ -108,7 +119,7 @@ public class NetconfClientConfiguration {
                 .add("authHandler", authHandler);
     }
 
-    public static enum NetconfClientProtocol {
+    public enum NetconfClientProtocol {
         TCP, SSH
     }
 }
\ No newline at end of file
index d1f2b42d4ec51e5247ebfe25affe5fbe6085898a..8047d60f1cca6cdc9101b9a782d117349992e137 100644 (file)
@@ -16,7 +16,8 @@ import org.opendaylight.protocol.framework.ReconnectStrategy;
 public class NetconfClientConfigurationBuilder {
 
     public static final int DEFAULT_CONNECTION_TIMEOUT_MILLIS = 5000;
-    public static final NetconfClientConfiguration.NetconfClientProtocol DEFAULT_CLIENT_PROTOCOL = NetconfClientConfiguration.NetconfClientProtocol.TCP;
+    public static final NetconfClientConfiguration.NetconfClientProtocol DEFAULT_CLIENT_PROTOCOL =
+            NetconfClientConfiguration.NetconfClientProtocol.TCP;
 
     private InetSocketAddress address;
     private long connectionTimeoutMillis = DEFAULT_CONNECTION_TIMEOUT_MILLIS;
@@ -43,12 +44,14 @@ public class NetconfClientConfigurationBuilder {
         return this;
     }
 
-    public NetconfClientConfigurationBuilder withProtocol(final NetconfClientConfiguration.NetconfClientProtocol clientProtocol) {
+    public NetconfClientConfigurationBuilder withProtocol(
+            final NetconfClientConfiguration.NetconfClientProtocol clientProtocol) {
         this.clientProtocol = clientProtocol;
         return this;
     }
 
-    public NetconfClientConfigurationBuilder withAdditionalHeader(final NetconfHelloMessageAdditionalHeader additionalHeader) {
+    public NetconfClientConfigurationBuilder withAdditionalHeader(
+            final NetconfHelloMessageAdditionalHeader additionalHeader) {
         this.additionalHeader = additionalHeader;
         return this;
     }
@@ -97,6 +100,7 @@ public class NetconfClientConfigurationBuilder {
     }
 
     public NetconfClientConfiguration build() {
-        return new NetconfClientConfiguration(clientProtocol, address, connectionTimeoutMillis, additionalHeader, sessionListener, reconnectStrategy, authHandler);
+        return new NetconfClientConfiguration(clientProtocol, address, connectionTimeoutMillis, additionalHeader,
+                sessionListener, reconnectStrategy, authHandler);
     }
 }
index dcb9ec310dd623813779820c306801e38a22d044..a2512687e4ad569a35adc5bfd5f91472edc62797 100644 (file)
@@ -21,9 +21,12 @@ public final class NetconfReconnectingClientConfiguration extends NetconfClientC
     private final ReconnectStrategyFactory connectStrategyFactory;
 
     NetconfReconnectingClientConfiguration(final NetconfClientProtocol clientProtocol, final InetSocketAddress address,
-            final Long connectionTimeoutMillis, final NetconfHelloMessageAdditionalHeader additionalHeader,
-            final NetconfClientSessionListener sessionListener, final ReconnectStrategy reconnectStrategy,
-            final ReconnectStrategyFactory connectStrategyFactory, final AuthenticationHandler authHandler) {
+                                           final Long connectionTimeoutMillis,
+                                           final NetconfHelloMessageAdditionalHeader additionalHeader,
+                                           final NetconfClientSessionListener sessionListener,
+                                           final ReconnectStrategy reconnectStrategy,
+                                           final ReconnectStrategyFactory connectStrategyFactory,
+                                           final AuthenticationHandler authHandler) {
         super(clientProtocol, address, connectionTimeoutMillis, additionalHeader, sessionListener, reconnectStrategy,
                 authHandler);
         this.connectStrategyFactory = connectStrategyFactory;
index dfa334c5b36b069fe81bc861caed083987532703..4597dca75eb2cc4ba0e5c07a919af1e6e485392f 100644 (file)
@@ -26,14 +26,17 @@ public class NetconfReconnectingClientConfigurationBuilder extends NetconfClient
     }
 
 
-    public NetconfReconnectingClientConfigurationBuilder withConnectStrategyFactory(final ReconnectStrategyFactory connectStrategyFactory) {
+    public NetconfReconnectingClientConfigurationBuilder withConnectStrategyFactory(
+            final ReconnectStrategyFactory connectStrategyFactory) {
         this.connectStrategyFactory = connectStrategyFactory;
         return this;
     }
 
     @Override
     public NetconfReconnectingClientConfiguration build() {
-        return new NetconfReconnectingClientConfiguration(getProtocol(), getAddress(), getConnectionTimeoutMillis(), getAdditionalHeader(), getSessionListener(), getReconnectStrategy(), connectStrategyFactory, getAuthHandler());
+        return new NetconfReconnectingClientConfiguration(getProtocol(), getAddress(), getConnectionTimeoutMillis(),
+                getAdditionalHeader(), getSessionListener(), getReconnectStrategy(), connectStrategyFactory,
+                getAuthHandler());
     }
 
     // Override setter methods to return subtype
@@ -44,22 +47,27 @@ public class NetconfReconnectingClientConfigurationBuilder extends NetconfClient
     }
 
     @Override
-    public NetconfReconnectingClientConfigurationBuilder withConnectionTimeoutMillis(final long connectionTimeoutMillis) {
-        return (NetconfReconnectingClientConfigurationBuilder) super.withConnectionTimeoutMillis(connectionTimeoutMillis);
+    public NetconfReconnectingClientConfigurationBuilder withConnectionTimeoutMillis(
+            final long connectionTimeoutMillis) {
+        return (NetconfReconnectingClientConfigurationBuilder)
+                super.withConnectionTimeoutMillis(connectionTimeoutMillis);
     }
 
     @Override
-    public NetconfReconnectingClientConfigurationBuilder withAdditionalHeader(final NetconfHelloMessageAdditionalHeader additionalHeader) {
+    public NetconfReconnectingClientConfigurationBuilder withAdditionalHeader(
+            final NetconfHelloMessageAdditionalHeader additionalHeader) {
         return (NetconfReconnectingClientConfigurationBuilder) super.withAdditionalHeader(additionalHeader);
     }
 
     @Override
-    public NetconfReconnectingClientConfigurationBuilder withSessionListener(final NetconfClientSessionListener sessionListener) {
+    public NetconfReconnectingClientConfigurationBuilder withSessionListener(
+            final NetconfClientSessionListener sessionListener) {
         return (NetconfReconnectingClientConfigurationBuilder) super.withSessionListener(sessionListener);
     }
 
     @Override
-    public NetconfReconnectingClientConfigurationBuilder withReconnectStrategy(final ReconnectStrategy reconnectStrategy) {
+    public NetconfReconnectingClientConfigurationBuilder withReconnectStrategy(
+            final ReconnectStrategy reconnectStrategy) {
         return (NetconfReconnectingClientConfigurationBuilder) super.withReconnectStrategy(reconnectStrategy);
     }
 
@@ -69,7 +77,8 @@ public class NetconfReconnectingClientConfigurationBuilder extends NetconfClient
     }
 
     @Override
-    public NetconfReconnectingClientConfigurationBuilder withProtocol(NetconfClientConfiguration.NetconfClientProtocol clientProtocol) {
+    public NetconfReconnectingClientConfigurationBuilder withProtocol(
+            NetconfClientConfiguration.NetconfClientProtocol clientProtocol) {
         return (NetconfReconnectingClientConfigurationBuilder) super.withProtocol(clientProtocol);
     }
 }
index 0d4f0addf90408a3cb7f09d3300af953d75833c7..e5aec5d402da77928491b2bb0a6b9b9ac8052070 100644 (file)
@@ -23,19 +23,20 @@ public class NetconfClientConfigurationTest {
     @Test
     public void testNetconfClientConfiguration() throws Exception {
         Long timeout = 200L;
-        NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader("a", "host", "port", "trans", "id");
+        NetconfHelloMessageAdditionalHeader header =
+                new NetconfHelloMessageAdditionalHeader("a", "host", "port", "trans", "id");
         NetconfClientSessionListener listener = new SimpleNetconfClientSessionListener();
         InetSocketAddress address = InetSocketAddress.createUnresolved("host", 830);
         ReconnectStrategy strategy = Mockito.mock(ReconnectStrategy.class);
         AuthenticationHandler handler = Mockito.mock(AuthenticationHandler.class);
-        NetconfClientConfiguration cfg = NetconfClientConfigurationBuilder.create().
-                withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH).
-                withAddress(address).
-                withConnectionTimeoutMillis(timeout).
-                withReconnectStrategy(strategy).
-                withAdditionalHeader(header).
-                withSessionListener(listener).
-                withAuthHandler(handler).build();
+        NetconfClientConfiguration cfg = NetconfClientConfigurationBuilder.create()
+                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
+                .withAddress(address)
+                .withConnectionTimeoutMillis(timeout)
+                .withReconnectStrategy(strategy)
+                .withAdditionalHeader(header)
+                .withSessionListener(listener)
+                .withAuthHandler(handler).build();
 
         Assert.assertEquals(timeout, cfg.getConnectionTimeoutMillis());
         Assert.assertEquals(Optional.fromNullable(header), cfg.getAdditionalHeader());
index c2c1289555e0d136e96581b4413b166fcf2dd4cb..82bbe001381154707cb111422ff8190791508092 100644 (file)
@@ -49,7 +49,8 @@ public class NetconfClientDispatcherImplTest {
         doReturn(thr).when(chf).cause();
 
         Long timeout = 200L;
-        NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader("a", "host", "port", "trans", "id");
+        NetconfHelloMessageAdditionalHeader header =
+                new NetconfHelloMessageAdditionalHeader("a", "host", "port", "trans", "id");
         NetconfClientSessionListener listener = new SimpleNetconfClientSessionListener();
         InetSocketAddress address = InetSocketAddress.createUnresolved("host", 830);
         ReconnectStrategyFactory reconnectStrategyFactory = Mockito.mock(ReconnectStrategyFactory.class);
@@ -62,32 +63,32 @@ public class NetconfClientDispatcherImplTest {
         doReturn("").when(reconnectStrategyFactory).toString();
         doReturn(reconnect).when(reconnectStrategyFactory).createReconnectStrategy();
 
-        NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create().
-                withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH).
-                withAddress(address).
-                withConnectionTimeoutMillis(timeout).
-                withReconnectStrategy(reconnect).
-                withAdditionalHeader(header).
-                withSessionListener(listener).
-                withConnectStrategyFactory(reconnectStrategyFactory).
-                withAuthHandler(handler).build();
+        NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create()
+                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
+                .withAddress(address)
+                .withConnectionTimeoutMillis(timeout)
+                .withReconnectStrategy(reconnect)
+                .withAdditionalHeader(header)
+                .withSessionListener(listener)
+                .withConnectStrategyFactory(reconnectStrategyFactory)
+                .withAuthHandler(handler).build();
 
-        NetconfReconnectingClientConfiguration cfg2 = NetconfReconnectingClientConfigurationBuilder.create().
-                withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP).
-                withAddress(address).
-                withConnectionTimeoutMillis(timeout).
-                withReconnectStrategy(reconnect).
-                withAdditionalHeader(header).
-                withSessionListener(listener).
-                withConnectStrategyFactory(reconnectStrategyFactory).
-                withAuthHandler(handler).build();
+        NetconfReconnectingClientConfiguration cfg2 = NetconfReconnectingClientConfigurationBuilder.create()
+                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP)
+                .withAddress(address)
+                .withConnectionTimeoutMillis(timeout)
+                .withReconnectStrategy(reconnect)
+                .withAdditionalHeader(header)
+                .withSessionListener(listener)
+                .withConnectStrategyFactory(reconnectStrategyFactory)
+                .withAuthHandler(handler).build();
 
         NetconfClientDispatcherImpl dispatcher = new NetconfClientDispatcherImpl(bossGroup, workerGroup, timer);
         Future<NetconfClientSession> sshSession = dispatcher.createClient(cfg);
         Future<NetconfClientSession> tcpSession = dispatcher.createClient(cfg2);
 
         Future<Void> sshReconn = dispatcher.createReconnectingClient(cfg);
-        Future<Void> tcpReconn = dispatcher.createReconnectingClient(cfg2);
+        final Future<Void> tcpReconn = dispatcher.createReconnectingClient(cfg2);
 
         assertNotNull(sshSession);
         assertNotNull(tcpSession);
index 3c24b7b5f8da7cd75b9a6433fce5ec227d2060cf..718c67b7989106cd2fe2220a5c836812d243ac08 100644 (file)
@@ -35,7 +35,8 @@ public class NetconfClientSessionNegotiatorFactoryTest {
         NetconfClientSessionNegotiatorFactory negotiatorFactory = new NetconfClientSessionNegotiatorFactory(timer,
                 Optional.<NetconfHelloMessageAdditionalHeader>absent(), 200L);
 
-        SessionNegotiator<?> sessionNegotiator = negotiatorFactory.getSessionNegotiator(listenerFactory, channel, promise);
+        SessionNegotiator<?> sessionNegotiator = negotiatorFactory.getSessionNegotiator(listenerFactory, channel,
+                promise);
         assertNotNull(sessionNegotiator);
     }
 }
index 9632d176af12e0345cdda287a79293503928436a..8ca1d8c8115098cf447a467eaba49f867acca0a6 100644 (file)
@@ -66,7 +66,8 @@ public class NetconfClientSessionNegotiatorTest {
 
     @Before
     public void setUp() throws Exception {
-        helloMessage = NetconfHelloMessage.createClientHello(Sets.newSet("exi:1.0"), Optional.<NetconfHelloMessageAdditionalHeader>absent());
+        helloMessage = NetconfHelloMessage.createClientHello(Sets.newSet("exi:1.0"), Optional
+                .<NetconfHelloMessageAdditionalHeader>absent());
         pipeline = mockChannelPipeline();
         future = mockChannelFuture();
         channel = mockChannel();
@@ -107,8 +108,10 @@ public class NetconfClientSessionNegotiatorTest {
         doReturn(handler).when(pipeline).replace(anyString(), anyString(), any(ChunkedFramingMechanismEncoder.class));
 
         NetconfXMLToHelloMessageDecoder messageDecoder = new NetconfXMLToHelloMessageDecoder();
-        doReturn(messageDecoder).when(pipeline).replace(anyString(), anyString(), any(NetconfXMLToMessageDecoder.class));
-        doReturn(pipeline).when(pipeline).replace(any(ChannelHandler.class), anyString(), any(NetconfClientSession.class));
+        doReturn(messageDecoder).when(pipeline).replace(anyString(), anyString(), any(NetconfXMLToMessageDecoder
+                .class));
+        doReturn(pipeline).when(pipeline).replace(any(ChannelHandler.class), anyString(), any(NetconfClientSession
+                .class));
         return pipeline;
     }
 
@@ -126,8 +129,9 @@ public class NetconfClientSessionNegotiatorTest {
         }).when(eventLoop).execute(any(Runnable.class));
     }
 
-    private NetconfClientSessionNegotiator createNetconfClientSessionNegotiator(final Promise<NetconfClientSession> promise,
-                                                                                final NetconfMessage startExi) {
+    private NetconfClientSessionNegotiator createNetconfClientSessionNegotiator(
+            final Promise<NetconfClientSession> promise,
+            final NetconfMessage startExi) {
         ChannelProgressivePromise progressivePromise = mock(ChannelProgressivePromise.class);
         NetconfClientSessionPreferences preferences = new NetconfClientSessionPreferences(helloMessage, startExi);
         doReturn(progressivePromise).when(promise).setFailure(any(Throwable.class));
@@ -203,13 +207,16 @@ public class NetconfClientSessionNegotiatorTest {
         NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class);
         NetconfClientSessionNegotiator negotiator = createNetconfClientSessionNegotiator(promise, null);
 
-        Set<String> set =  createCapabilities("/helloMessage3.xml");
+        Set<String> set = createCapabilities("/helloMessage3.xml");
 
-        final Set<String> cachedS1 = (Set<String>) negotiator.getSession(sessionListener,channel,createHelloMsg("/helloMessage1.xml")).getServerCapabilities();
+        final Set<String> cachedS1 = (Set<String>) negotiator.getSession(sessionListener, channel,
+                createHelloMsg("/helloMessage1.xml")).getServerCapabilities();
 
         //helloMessage2 and helloMessage3 are the same with different order
-        final Set<String> cachedS2 = (Set<String>) negotiator.getSession(sessionListener,channel,createHelloMsg("/helloMessage2.xml")).getServerCapabilities();
-        final Set<String> cachedS3 = (Set<String>) negotiator.getSession(sessionListener,channel,createHelloMsg("/helloMessage3.xml")).getServerCapabilities();
+        final Set<String> cachedS2 = (Set<String>) negotiator.getSession(sessionListener, channel,
+                createHelloMsg("/helloMessage2.xml")).getServerCapabilities();
+        final Set<String> cachedS3 = (Set<String>) negotiator.getSession(sessionListener, channel,
+                createHelloMsg("/helloMessage3.xml")).getServerCapabilities();
 
         assertEquals(cachedS3, set);
         assertNotEquals(cachedS1, set);
index 6ec737d01699f3b7749c2cdd79529470f1504cd9..d6e480014c5b74a4f5576bc9ce36e9c01772ed29 100644 (file)
@@ -25,22 +25,23 @@ public class NetconfReconnectingClientConfigurationTest {
     @Test
     public void testNetconfReconnectingClientConfiguration() throws Exception {
         Long timeout = 200L;
-        NetconfHelloMessageAdditionalHeader header = new NetconfHelloMessageAdditionalHeader("a", "host", "port", "trans", "id");
+        NetconfHelloMessageAdditionalHeader header =
+                new NetconfHelloMessageAdditionalHeader("a", "host", "port", "trans", "id");
         NetconfClientSessionListener listener = new SimpleNetconfClientSessionListener();
         InetSocketAddress address = InetSocketAddress.createUnresolved("host", 830);
         ReconnectStrategyFactory strategy = Mockito.mock(ReconnectStrategyFactory.class);
         AuthenticationHandler handler = Mockito.mock(AuthenticationHandler.class);
         ReconnectStrategy reconnect = Mockito.mock(ReconnectStrategy.class);
 
-        NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create().
-                withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH).
-                withAddress(address).
-                withConnectionTimeoutMillis(timeout).
-                withReconnectStrategy(reconnect).
-                withAdditionalHeader(header).
-                withSessionListener(listener).
-                withConnectStrategyFactory(strategy).
-                withAuthHandler(handler).build();
+        NetconfReconnectingClientConfiguration cfg = NetconfReconnectingClientConfigurationBuilder.create()
+                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH)
+                .withAddress(address)
+                .withConnectionTimeoutMillis(timeout)
+                .withReconnectStrategy(reconnect)
+                .withAdditionalHeader(header)
+                .withSessionListener(listener)
+                .withConnectStrategyFactory(strategy)
+                .withAuthHandler(handler).build();
 
         Assert.assertEquals(timeout, cfg.getConnectionTimeoutMillis());
         Assert.assertEquals(Optional.fromNullable(header), cfg.getAdditionalHeader());
index 6d0fb5b44e66798b812c64e6db32b1fbef05050e..1dde3d4dfa64f6f7b4151d807ec722557dd52c28 100644 (file)
@@ -73,7 +73,7 @@ public class SimpleNetconfClientSessionListenerTest {
     @Test
     public void testSessionDown() throws Exception {
         SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
-        Future<NetconfMessage> promise = simpleListener.sendRequest(message);
+        final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
         simpleListener.onSessionUp(clientSession);
         verify(channel, times(1)).writeAndFlush(anyObject());
 
@@ -84,7 +84,7 @@ public class SimpleNetconfClientSessionListenerTest {
     @Test
     public void testSendRequest() throws Exception {
         SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
-        Future<NetconfMessage> promise = simpleListener.sendRequest(message);
+        final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
         simpleListener.onSessionUp(clientSession);
         verify(channel, times(1)).writeAndFlush(anyObject());
 
@@ -95,7 +95,7 @@ public class SimpleNetconfClientSessionListenerTest {
     @Test
     public void testOnMessage() throws Exception {
         SimpleNetconfClientSessionListener simpleListener = new SimpleNetconfClientSessionListener();
-        Future<NetconfMessage> promise = simpleListener.sendRequest(message);
+        final Future<NetconfMessage> promise = simpleListener.sendRequest(message);
         simpleListener.onSessionUp(clientSession);
         verify(channel, times(1)).writeAndFlush(anyObject());
 
index 288e0662eae15a5b3d21dffdd5dfcf5d98d670ac..2bfe717403472ff663743d8daefe805ff7652ece 100644 (file)
@@ -34,7 +34,8 @@ public class SshClientChannelInitializerTest {
 
         SessionNegotiator<?> sessionNegotiator = mock(SessionNegotiator.class);
         doReturn("").when(sessionNegotiator).toString();
-        doReturn(sessionNegotiator).when(negotiatorFactory).getSessionNegotiator(any(SessionListenerFactory.class), any(Channel.class), any(Promise.class));
+        doReturn(sessionNegotiator).when(negotiatorFactory).getSessionNegotiator(any(SessionListenerFactory.class),
+                any(Channel.class), any(Promise.class));
         ChannelPipeline pipeline = mock(ChannelPipeline.class);
         doReturn(pipeline).when(pipeline).addAfter(anyString(), anyString(), any(ChannelHandler.class));
         Channel channel = mock(Channel.class);
@@ -46,8 +47,8 @@ public class SshClientChannelInitializerTest {
         Promise<NetconfClientSession> promise = mock(Promise.class);
         doReturn("").when(promise).toString();
 
-        SshClientChannelInitializer initializer = new SshClientChannelInitializer(authenticationHandler, negotiatorFactory,
-                sessionListener);
+        SshClientChannelInitializer initializer = new SshClientChannelInitializer(authenticationHandler,
+                negotiatorFactory, sessionListener);
         initializer.initialize(channel, promise);
         verify(pipeline, times(1)).addFirst(any(ChannelHandler.class));
     }
index 04b284bc54c8991d20387b175cb772bf62fbbdc5..7ff2f174739261f415749dd9105e30e5d9e5cb4c 100644 (file)
@@ -29,9 +29,10 @@ public class TcpClientChannelInitializerTest {
         NetconfClientSessionNegotiatorFactory factory = mock(NetconfClientSessionNegotiatorFactory.class);
         SessionNegotiator<?> sessionNegotiator = mock(SessionNegotiator.class);
         doReturn("").when(sessionNegotiator).toString();
-        doReturn(sessionNegotiator).when(factory).getSessionNegotiator(any(SessionListenerFactory.class), any(Channel.class), any(Promise.class));
+        doReturn(sessionNegotiator).when(factory).getSessionNegotiator(any(SessionListenerFactory.class),
+                any(Channel.class), any(Promise.class));
         NetconfClientSessionListener listener = mock(NetconfClientSessionListener.class);
-        TcpClientChannelInitializer initializer = new TcpClientChannelInitializer(factory, listener);
+        final TcpClientChannelInitializer initializer = new TcpClientChannelInitializer(factory, listener);
         ChannelPipeline pipeline = mock(ChannelPipeline.class);
         doReturn(pipeline).when(pipeline).addAfter(anyString(), anyString(), any(ChannelHandler.class));
         Channel channel = mock(Channel.class);
index dabe11a3ed9606b42daf45cbde69075cd0787437..10f7ae893d8aa6e4d9e1dc8d69703b20863700a7 100644 (file)
@@ -35,7 +35,7 @@ import org.opendaylight.protocol.framework.NeverReconnectStrategy;
 
 
 /**
- * Synchronous netconf client suitable for testing
+ * Synchronous netconf client suitable for testing.
  */
 public class TestingNetconfClient implements Closeable {
 
@@ -47,7 +47,8 @@ public class TestingNetconfClient implements Closeable {
     private final long sessionId;
 
     public TestingNetconfClient(String clientLabel,
-                                NetconfClientDispatcher netconfClientDispatcher, final NetconfClientConfiguration config) throws InterruptedException {
+                                NetconfClientDispatcher netconfClientDispatcher,
+                                final NetconfClientConfiguration config) throws InterruptedException {
         this.label = clientLabel;
         sessionListener = config.getSessionListener();
         Future<NetconfClientSession> clientFuture = netconfClientDispatcher.createClient(config);
@@ -66,7 +67,7 @@ public class TestingNetconfClient implements Closeable {
     }
 
     public Future<NetconfMessage> sendRequest(NetconfMessage message) {
-        return ((SimpleNetconfClientSessionListener)sessionListener).sendRequest(message);
+        return ((SimpleNetconfClientSessionListener) sessionListener).sendRequest(message);
     }
 
     public NetconfMessage sendMessage(NetconfMessage message, int attemptMsDelay) throws ExecutionException,
@@ -105,13 +106,16 @@ public class TestingNetconfClient implements Closeable {
     public static void main(String[] args) throws Exception {
         HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();
         NioEventLoopGroup nettyGroup = new NioEventLoopGroup();
-        NetconfClientDispatcherImpl netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup, hashedWheelTimer);
+        NetconfClientDispatcherImpl netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyGroup, nettyGroup,
+                hashedWheelTimer);
         LoginPassword authHandler = new LoginPassword("admin", "admin");
-        TestingNetconfClient client = new TestingNetconfClient("client", netconfClientDispatcher, getClientConfig("127.0.0.1", 1830, true, Optional.of(authHandler)));
+        TestingNetconfClient client = new TestingNetconfClient("client", netconfClientDispatcher,
+                getClientConfig("127.0.0.1", 1830, true, Optional.of(authHandler)));
         System.console().writer().println(client.getCapabilities());
     }
 
-    private static NetconfClientConfiguration getClientConfig(String host ,int port, boolean ssh, Optional<? extends AuthenticationHandler> maybeAuthHandler) throws UnknownHostException {
+    private static NetconfClientConfiguration getClientConfig(String host, int port, boolean ssh, Optional<? extends
+            AuthenticationHandler> maybeAuthHandler) throws UnknownHostException {
         InetSocketAddress netconfAddress = new InetSocketAddress(InetAddress.getByName(host), port);
         final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
         b.withAddress(netconfAddress);
index be792df880ca4bbdc7910e2c02adb789b4a4ad5c..d3689608eb58bb7420245cac69703ce0fbeed4f0 100644 (file)
           </execution>
         </executions>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index 6bc9d70f1a11813e027b876c852575593497bddc..c967e8f317a03667634f65d3854e2228bea0e882 100644 (file)
@@ -28,7 +28,8 @@ public abstract class AbstractChannelInitializer<S extends NetconfSession> {
     public void initialize(Channel ch, Promise<S> promise) {
         ch.pipeline().addLast(NETCONF_MESSAGE_AGGREGATOR, new NetconfEOMAggregator());
         initializeMessageDecoder(ch);
-        ch.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER, FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM));
+        ch.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER,
+                FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM));
         initializeMessageEncoder(ch);
 
         initializeSessionNegotiator(ch, promise);
index e4c03ed50f43b518622957e179715e87f8f36814..b1c1203c4f1dc5cb295e7ce9c4845c2ab422b90b 100644 (file)
@@ -32,7 +32,8 @@ import org.openexi.sax.TransmogrifierException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public abstract class AbstractNetconfSession<S extends NetconfSession, L extends NetconfSessionListener<S>> extends AbstractProtocolSession<NetconfMessage> implements NetconfSession, NetconfExiSession {
+public abstract class AbstractNetconfSession<S extends NetconfSession,L extends NetconfSessionListener<S>>
+        extends AbstractProtocolSession<NetconfMessage> implements NetconfSession, NetconfExiSession {
     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSession.class);
     private final L sessionListener;
     private final long sessionId;
@@ -104,7 +105,8 @@ public abstract class AbstractNetconfSession<S extends NetconfSession, L extends
         LOG.debug("Session {} end of input detected while session was in state {}", toString(), isUp() ? "up"
                 : "initialized");
         if (isUp()) {
-            this.sessionListener.onSessionDown(thisInstance(), new IOException("End of input detected. Close the session."));
+            this.sessionListener.onSessionDown(thisInstance(),
+                    new IOException("End of input detected. Close the session."));
         }
     }
 
index b3d35dc3c0d05bd8811505b4c450948052c9f0ff..2f30023f541f94914fac34bac68d8852f383cb68 100644 (file)
@@ -41,7 +41,8 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.NodeList;
 
-public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences, S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
+public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionPreferences,
+        S extends AbstractNetconfSession<S, L>, L extends NetconfSessionListener<S>>
     extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
 
     private static final Logger LOG = LoggerFactory.getLogger(AbstractNetconfSessionNegotiator.class);
@@ -54,7 +55,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
     private Timeout timeout;
 
     /**
-     * Possible states for Finite State Machine
+     * Possible states for Finite State Machine.
      */
     protected enum State {
         IDLE, OPEN_WAIT, FAILED, ESTABLISHED
@@ -65,8 +66,9 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
     private final Timer timer;
     private final long connectionTimeoutMillis;
 
-    protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise, final Channel channel, final Timer timer,
-            final L sessionListener, final long connectionTimeoutMillis) {
+    protected AbstractNetconfSessionNegotiator(final P sessionPreferences, final Promise<S> promise,
+                                               final Channel channel, final Timer timer,
+                                               final L sessionListener, final long connectionTimeoutMillis) {
         super(promise, channel);
         this.sessionPreferences = sessionPreferences;
         this.promise = promise;
@@ -95,7 +97,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
 
     private static Optional<SslHandler> getSslHandler(final Channel channel) {
         final SslHandler sslHandler = channel.pipeline().get(SslHandler.class);
-        return sslHandler == null ? Optional.<SslHandler> absent() : Optional.of(sslHandler);
+        return sslHandler == null ? Optional.<SslHandler>absent() : Optional.of(sslHandler);
     }
 
     public P getSessionPreferences() {
@@ -130,7 +132,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
                             channel.close().addListener(new GenericFutureListener<ChannelFuture>() {
                                 @Override
                                 public void operationComplete(final ChannelFuture future) throws Exception {
-                                    if(future.isSuccess()) {
+                                    if (future.isSuccess()) {
                                         LOG.debug("Channel {} closed: success", future.channel());
                                     } else {
                                         LOG.warn("Channel {} closed: fail", future.channel());
@@ -138,7 +140,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
                                 }
                             });
                         }
-                    } else if(channel.isOpen()) {
+                    } else if (channel.isOpen()) {
                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
                     }
                 }
@@ -152,12 +154,13 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
     }
 
     private void cancelTimeout() {
-        if(timeout!=null) {
+        if (timeout != null) {
             timeout.cancel();
         }
     }
 
-    protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException {
+    protected final S getSessionForHelloMessage(final NetconfHelloMessage netconfMessage)
+            throws NetconfDocumentedException {
         Preconditions.checkNotNull(netconfMessage, "netconfMessage");
 
         final Document doc = netconfMessage.getDocument();
@@ -171,7 +174,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
     }
 
     /**
-     * Insert chunk framing handlers into the pipeline
+     * Insert chunk framing handlers into the pipeline.
      */
     private void insertChunkFramingToPipeline() {
         replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_FRAME_ENCODER,
@@ -188,11 +191,13 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
     /**
      * Remove special inbound handler for hello message. Insert regular netconf xml message (en|de)coders.
      *
+     * <p>
      * Inbound hello message handler should be kept until negotiation is successful
      * It caches any non-hello messages while negotiation is still in progress
      */
     protected final void replaceHelloMessageInboundHandler(final S session) {
-        ChannelHandler helloMessageHandler = replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
+        ChannelHandler helloMessageHandler = replaceChannelHandler(channel,
+                AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, new NetconfXMLToMessageDecoder());
 
         Preconditions.checkState(helloMessageHandler instanceof NetconfXMLToHelloMessageDecoder,
                 "Pipeline handlers misplaced on session: %s, pipeline: %s", session, channel.pipeline());
@@ -200,7 +205,8 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
                 ((NetconfXMLToHelloMessageDecoder) helloMessageHandler).getPostHelloNetconfMessages();
 
         // Process messages received during negotiation
-        // The hello message handler does not have to be synchronized, since it is always call from the same thread by netty
+        // The hello message handler does not have to be synchronized,
+        // since it is always call from the same thread by netty.
         // It means, we are now using the thread now
         for (NetconfMessage message : netconfMessagesFromNegotiation) {
             session.handleMessage(message);
@@ -211,19 +217,22 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
      * Remove special outbound handler for hello message. Insert regular netconf xml message (en|de)coders.
      */
     private void replaceHelloMessageOutboundHandler() {
-        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new NetconfMessageToXMLEncoder());
+        replaceChannelHandler(channel, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
+                new NetconfMessageToXMLEncoder());
     }
 
-    private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey, final ChannelHandler decoder) {
+    private static ChannelHandler replaceChannelHandler(final Channel channel, final String handlerKey,
+                                                        final ChannelHandler decoder) {
         return channel.pipeline().replace(handlerKey, handlerKey, decoder);
     }
 
-    protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message) throws NetconfDocumentedException;
+    protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message)
+            throws NetconfDocumentedException;
 
     private synchronized void changeState(final State newState) {
         LOG.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
-        Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s for chanel %s", state,
-                newState, channel);
+        Preconditions.checkState(isStateChangePermitted(state, newState),
+                "Cannot change state from %s to %s for chanel %s", state, newState, channel);
         this.state = newState;
     }
 
@@ -252,7 +261,7 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
     }
 
     /**
-     * Handler to catch exceptions in pipeline during negotiation
+     * Handler to catch exceptions in pipeline during negotiation.
      */
     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
         @Override
index 78e5ad06c7718b2086884bbc72702854a1f53325..7f3dd3854fdf23df5cefbeab7165b277f999b212 100644 (file)
@@ -8,7 +8,6 @@
 
 package org.opendaylight.netconf.nettyutil.handler;
 
-
 import com.google.common.base.Preconditions;
 import java.io.IOException;
 import java.io.Writer;
@@ -16,10 +15,12 @@ import javax.annotation.concurrent.NotThreadSafe;
 
 /**
  * Custom BufferedWriter optimized for netconf pipeline implemented instead of default BufferedWriter provided by jdk.
+ *
  * <p>
  * The line separator instance field in java.io.BufferedWriter is
  * assigned using AccessController and takes considerable amount of time especially
  * if lots of BufferedWriters are created in the system.
+ *
  * <p>
  * This implementation should only be used if newLine method is not required
  * such as netconf message to XML encoders.
@@ -31,7 +32,7 @@ public final class BufferedWriter extends Writer {
     private static final int DEFAULT_CHAR_BUFFER_SIZE = 8192;
 
     private final Writer writer;
-    private final char buffer[];
+    private final char[] buffer;
     private final int bufferSize;
 
     private int nextChar = 0;
@@ -49,24 +50,27 @@ public final class BufferedWriter extends Writer {
     }
 
     private void flushBuffer() throws IOException {
-        if (nextChar == 0)
+        if (nextChar == 0) {
             return;
+        }
         writer.write(buffer, 0, nextChar);
         nextChar = 0;
     }
 
     @Override
-    public void write(final int c) throws IOException {
-        if (nextChar >= bufferSize)
+    public void write(final int character) throws IOException {
+        if (nextChar >= bufferSize) {
             flushBuffer();
-        buffer[nextChar++] = (char) c;
+        }
+        buffer[nextChar++] = (char) character;
     }
 
     @Override
     public void write(final char[] buffer, final int offset, final int length) throws IOException {
-        if ((offset < 0) || (offset > buffer.length) || (length < 0) ||
-                ((offset + length) > buffer.length) || ((offset + length) < 0)) {
-            throw new IndexOutOfBoundsException(String.format("Buffer size: %d, Offset: %d, Length: %d", buffer.length, offset, length));
+        if ((offset < 0) || (offset > buffer.length)
+                || (length < 0) || ((offset + length) > buffer.length) || ((offset + length) < 0)) {
+            throw new IndexOutOfBoundsException(
+                    String.format("Buffer size: %d, Offset: %d, Length: %d", buffer.length, offset, length));
         } else if (length == 0) {
             return;
         }
@@ -77,29 +81,31 @@ public final class BufferedWriter extends Writer {
             return;
         }
 
-        int b = offset;
+        int bufferOffset = offset;
         final int t = offset + length;
-        while (b < t) {
-            final int d = Math.min(bufferSize - nextChar, t - b);
-            System.arraycopy(buffer, b, this.buffer, nextChar, d);
-            b += d;
+        while (bufferOffset < t) {
+            final int d = Math.min(bufferSize - nextChar, t - bufferOffset);
+            System.arraycopy(buffer, bufferOffset, this.buffer, nextChar, d);
+            bufferOffset += d;
             nextChar += d;
-            if (nextChar >= bufferSize)
+            if (nextChar >= bufferSize) {
                 flushBuffer();
+            }
         }
     }
 
     @Override
     public void write(final String string, final int offset, final int length) throws IOException {
-        int b = offset;
+        int bufferOffset = offset;
         final int t = offset + length;
-        while (b < t) {
-            final int d = Math.min(bufferSize - nextChar, t - b);
-            string.getChars(b, b + d, buffer, nextChar);
-            b += d;
+        while (bufferOffset < t) {
+            final int d = Math.min(bufferSize - nextChar, t - bufferOffset);
+            string.getChars(bufferOffset, bufferOffset + d, buffer, nextChar);
+            bufferOffset += d;
             nextChar += d;
-            if (nextChar >= bufferSize)
+            if (nextChar >= bufferSize) {
                 flushBuffer();
+            }
         }
     }
 
index 8c9a2b35c973267b7336b1713ed9aa29c71e2c29..1d7a3cd5adad2b8b0218e91b1970fb999558b69d 100644 (file)
@@ -27,7 +27,8 @@ public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf
     }
 
     public ChunkedFramingMechanismEncoder(final int chunkSize) {
-        Preconditions.checkArgument(chunkSize >= MIN_CHUNK_SIZE && chunkSize <= MAX_CHUNK_SIZE, "Unsupported chunk size %s", chunkSize);
+        Preconditions.checkArgument(chunkSize >= MIN_CHUNK_SIZE && chunkSize <= MAX_CHUNK_SIZE,
+                "Unsupported chunk size %s", chunkSize);
         this.chunkSize = chunkSize;
     }
 
index 08eba8e0f2fccec13e9d709e9b8f3ccf559d6188..144b4f5b4c22187b71004a7e1ade5a5bce9b1cab 100644 (file)
@@ -18,12 +18,12 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class NetconfChunkAggregator extends ByteToMessageDecoder {
-    private final static Logger LOG = LoggerFactory.getLogger(NetconfChunkAggregator.class);
+    private static final Logger LOG = LoggerFactory.getLogger(NetconfChunkAggregator.class);
     private static final String GOT_PARAM_WHILE_WAITING_FOR_PARAM = "Got byte {} while waiting for {}";
     private static final String GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM = "Got byte {} while waiting for {}-{}";
     public static final int DEFAULT_MAXIMUM_CHUNK_SIZE = 16 * 1024 * 1024;
 
-    private static enum State {
+    private enum State {
         HEADER_ONE, // \n
         HEADER_TWO, // #
         HEADER_LENGTH_FIRST, // [1-9]
@@ -40,16 +40,16 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
     private long chunkSize;
     private CompositeByteBuf chunk;
 
-    private static void checkNewLine(final byte b,final String errorMessage) {
-        if (b != '\n') {
-            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, b, (byte)'\n');
+    private static void checkNewLine(final byte byteToCheck, final String errorMessage) {
+        if (byteToCheck != '\n') {
+            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, byteToCheck, (byte)'\n');
             throw new IllegalStateException(errorMessage);
         }
     }
 
-    private static void checkHash(final byte b,final String errorMessage) {
-        if (b != '#') {
-            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, b, (byte)'#');
+    private static void checkHash(final byte byteToCheck, final String errorMessage) {
+        if (byteToCheck != '#') {
+            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM, byteToCheck, (byte)'#');
             throw new IllegalStateException(errorMessage);
         }
     }
@@ -62,118 +62,115 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
     }
 
     @Override
-    protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IllegalStateException {
+    protected void decode(final ChannelHandlerContext ctx,
+                          final ByteBuf in, final List<Object> out) throws IllegalStateException {
         while (in.isReadable()) {
             switch (state) {
-            case HEADER_ONE:
-            {
-                final byte b = in.readByte();
-                checkNewLine(b, "Malformed chunk header encountered (byte 0)");
-
-                state = State.HEADER_TWO;
-
-                initChunk();
-                break;
-            }
-            case HEADER_TWO:
-            {
-                final byte b = in.readByte();
-                checkHash(b, "Malformed chunk header encountered (byte 1)");
-
-                state = State.HEADER_LENGTH_FIRST;
-                break;
-            }
-            case HEADER_LENGTH_FIRST:
-            {
-                final byte b = in.readByte();
-                chunkSize = processHeaderLengthFirst(b);
-                state = State.HEADER_LENGTH_OTHER;
-                break;
-            }
-            case HEADER_LENGTH_OTHER:
-            {
-                final byte b = in.readByte();
-                if (b == '\n') {
-                    state = State.DATA;
+                case HEADER_ONE:
+                {
+                    final byte b = in.readByte();
+                    checkNewLine(b, "Malformed chunk header encountered (byte 0)");
+                    state = State.HEADER_TWO;
+                    initChunk();
                     break;
                 }
-
-                if (b < '0' || b > '9') {
-                    LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'0', (byte)'9');
-                    throw new IllegalStateException("Invalid chunk size encountered");
+                case HEADER_TWO:
+                {
+                    final byte b = in.readByte();
+                    checkHash(b, "Malformed chunk header encountered (byte 1)");
+                    state = State.HEADER_LENGTH_FIRST;
+                    break;
                 }
-
-                chunkSize *= 10;
-                chunkSize += b - '0';
-                checkChunkSize();
-                break;
-            }
-            case DATA:
-                /*
-                 * FIXME: this gathers all data into one big chunk before passing
-                 *        it on. Make sure the pipeline can work with partial data
-                 *        and then change this piece to pass the data on as it
-                 *        comes through.
-                 */
-                if (in.readableBytes() < chunkSize) {
-                    LOG.debug("Buffer has {} bytes, need {} to complete chunk", in.readableBytes(), chunkSize);
-                    in.discardReadBytes();
-                    return;
+                case HEADER_LENGTH_FIRST:
+                {
+                    final byte b = in.readByte();
+                    chunkSize = processHeaderLengthFirst(b);
+                    state = State.HEADER_LENGTH_OTHER;
+                    break;
+                }
+                case HEADER_LENGTH_OTHER:
+                {
+                    final byte b = in.readByte();
+                    if (b == '\n') {
+                        state = State.DATA;
+                        break;
+                    }
+                    if (b < '0' || b > '9') {
+                        LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'0', (byte)'9');
+                        throw new IllegalStateException("Invalid chunk size encountered");
+                    }
+                    chunkSize *= 10;
+                    chunkSize += b - '0';
+                    checkChunkSize();
+                    break;
+                }
+                case DATA:
+                    /*
+                     * FIXME: this gathers all data into one big chunk before passing
+                     *        it on. Make sure the pipeline can work with partial data
+                     *        and then change this piece to pass the data on as it
+                     *        comes through.
+                     */
+                    if (in.readableBytes() < chunkSize) {
+                        LOG.debug("Buffer has {} bytes, need {} to complete chunk", in.readableBytes(), chunkSize);
+                        in.discardReadBytes();
+                        return;
+                    }
+                    aggregateChunks(in.readBytes((int) chunkSize));
+                    state = State.FOOTER_ONE;
+                    break;
+                case FOOTER_ONE:
+                {
+                    final byte b = in.readByte();
+                    checkNewLine(b,"Malformed chunk footer encountered (byte 0)");
+                    state = State.FOOTER_TWO;
+                    chunkSize = 0;
+                    break;
+                }
+                case FOOTER_TWO:
+                {
+                    final byte b = in.readByte();
+                    checkHash(b,"Malformed chunk footer encountered (byte 1)");
+                    state = State.FOOTER_THREE;
+                    break;
+                }
+                case FOOTER_THREE:
+                {
+                    final byte b = in.readByte();
+                    // In this state, either header-of-new-chunk or message-end is expected
+                    // Depends on the next character
+                    extractNewChunkOrMessageEnd(b);
+                    break;
+                }
+                case FOOTER_FOUR:
+                {
+                    final byte b = in.readByte();
+                    checkNewLine(b,"Malformed chunk footer encountered (byte 3)");
+                    state = State.HEADER_ONE;
+                    out.add(chunk);
+                    chunk = null;
+                    break;
+                }
+                default :
+                {
+                    LOG.info("Unknown state.");
                 }
-                aggregateChunks(in.readBytes((int) chunkSize));
-                state = State.FOOTER_ONE;
-                break;
-            case FOOTER_ONE:
-            {
-                final byte b = in.readByte();
-                checkNewLine(b,"Malformed chunk footer encountered (byte 0)");
-                state = State.FOOTER_TWO;
-                chunkSize = 0;
-                break;
-            }
-            case FOOTER_TWO:
-            {
-                final byte b = in.readByte();
-                checkHash(b,"Malformed chunk footer encountered (byte 1)");
-                state = State.FOOTER_THREE;
-                break;
-            }
-            case FOOTER_THREE:
-            {
-                final byte b = in.readByte();
-
-                // In this state, either header-of-new-chunk or message-end is expected
-                // Depends on the next character
-
-                extractNewChunkOrMessageEnd(b);
-
-                break;
-            }
-            case FOOTER_FOUR:
-            {
-                final byte b = in.readByte();
-                checkNewLine(b,"Malformed chunk footer encountered (byte 3)");
-                state = State.HEADER_ONE;
-                out.add(chunk);
-                chunk = null;
-                break;
-            }
             }
         }
 
         in.discardReadBytes();
     }
 
-    private void extractNewChunkOrMessageEnd(final byte b) {
-        if (isHeaderLengthFirst(b)) {
+    private void extractNewChunkOrMessageEnd(final byte byteToCheck) {
+        if (isHeaderLengthFirst(byteToCheck)) {
             // Extract header length#1 from new chunk
-            chunkSize = processHeaderLengthFirst(b);
+            chunkSize = processHeaderLengthFirst(byteToCheck);
             // Proceed with next chunk processing
             state = State.HEADER_LENGTH_OTHER;
-        } else if (b == '#') {
+        } else if (byteToCheck == '#') {
             state = State.FOOTER_FOUR;
         } else {
-            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte) '#', (byte) '1', (byte) '9');
+            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, byteToCheck, (byte) '#', (byte) '1', (byte) '9');
             throw new IllegalStateException("Malformed chunk footer encountered (byte 2)");
         }
     }
@@ -189,16 +186,16 @@ public class NetconfChunkAggregator extends ByteToMessageDecoder {
         chunk.writerIndex(chunk.writerIndex() + newChunk.readableBytes());
     }
 
-    private static int processHeaderLengthFirst(final byte b) {
-        if (!isHeaderLengthFirst(b)) {
-            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, b, (byte)'1', (byte)'9');
+    private static int processHeaderLengthFirst(final byte byteToCheck) {
+        if (!isHeaderLengthFirst(byteToCheck)) {
+            LOG.debug(GOT_PARAM_WHILE_WAITING_FOR_PARAM_PARAM, byteToCheck, (byte)'1', (byte)'9');
             throw new IllegalStateException("Invalid chunk size encountered (byte 0)");
         }
 
-        return b - '0';
+        return byteToCheck - '0';
     }
 
-    private static boolean isHeaderLengthFirst(final byte b) {
-        return b >= '1' && b <= '9';
+    private static boolean isHeaderLengthFirst(final byte byteToCheck) {
+        return byteToCheck >= '1' && byteToCheck <= '9';
     }
 }
index 1186a5c4d09b20a043a3d8dd3cb9d6f105974ac7..235b5378c26736ea5c02b49621b22650e55b0920 100644 (file)
@@ -45,12 +45,13 @@ public final class NetconfEXICodec {
      * Since we have a limited number of options we can have, instantiating a weak cache
      * will allow us to reuse instances where possible.
      */
-    private static final LoadingCache<Short, GrammarCache> GRAMMAR_CACHES = CacheBuilder.newBuilder().weakValues().build(new CacheLoader<Short, GrammarCache>() {
-        @Override
-        public GrammarCache load(final Short key) {
-            return new GrammarCache(key);
-        }
-    });
+    private static final LoadingCache<Short, GrammarCache> GRAMMAR_CACHES =
+            CacheBuilder.newBuilder().weakValues().build(new CacheLoader<Short, GrammarCache>() {
+                @Override
+                public GrammarCache load(final Short key) {
+                    return new GrammarCache(key);
+                }
+            });
 
     /**
      * Grammar cache acts as a template and is duplicated by the Transmogrifier and the Reader
index 6d2508757a4e3138c5f3effe1cb7a2e08c757dd3..99d791642a5f9bf1ff5a1d560d2a79b7afb126a1 100644 (file)
@@ -37,10 +37,12 @@ public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfEXIToMessageDecoder.class);
     private static final SAXTransformerFactory FACTORY;
+
     static {
         final TransformerFactory f = SAXTransformerFactory.newInstance();
         if (!f.getFeature(SAXTransformerFactory.FEATURE)) {
-            throw new TransformerFactoryConfigurationError(String.format("Factory %s is not a SAXTransformerFactory", f));
+            throw new TransformerFactoryConfigurationError(
+                    String.format("Factory %s is not a SAXTransformerFactory", f));
         }
 
         FACTORY = (SAXTransformerFactory)f;
@@ -64,7 +66,8 @@ public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder {
     }
 
     @Override
-    protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws EXIOptionsException, IOException, SAXException, TransformerConfigurationException  {
+    protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
+            throws EXIOptionsException, IOException, SAXException, TransformerConfigurationException  {
         /*
          * Note that we could loop here and process all the messages, but we can't do that.
          * The reason is <stop-exi> operation, which has the contract of immediately stopping
@@ -88,7 +91,7 @@ public final class NetconfEXIToMessageDecoder extends ByteToMessageDecoder {
         final DOMResult domResult = new DOMResult(documentBuilder.newDocument());
         handler.setResult(domResult);
 
-        try (final InputStream is = new ByteBufInputStream(in)) {
+        try (InputStream is = new ByteBufInputStream(in)) {
             // Performs internal reset before doing anything
             reader.parse(new InputSource(is));
         }
index 0d50a2f74bed28041f331e8f6625045f6d17bfa2..fac1b2ba4db393aab8a2a2876369c99d46da1c96 100644 (file)
@@ -25,25 +25,28 @@ import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader
  * {@link NetconfHelloMessage}
  * . Used by netconf clients to send information about the user, ip address,
  * protocol etc.
+ *
  * <p>
  * Hello message with header example:
+ *
  * <p>
  *
  * <pre>
  * {@code
  * [tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]
- * <hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
- * <capabilities>
- * <capability>urn:ietf:params:netconf:base:1.0</capability>
- * </capabilities>
- * </hello>
+ * < hello xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+ * < capabilities>
+ * < capability>urn:ietf:params:netconf:base:1.0< /capability>
+ * < /capabilities>
+ * < /hello>
  * }
  * </pre>
  */
 public final class NetconfHelloMessageToXMLEncoder extends NetconfMessageToXMLEncoder {
     @Override
     @VisibleForTesting
-    public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out) throws IOException, TransformerException {
+    public void encode(ChannelHandlerContext ctx, NetconfMessage msg, ByteBuf out)
+            throws IOException, TransformerException {
         Preconditions.checkState(msg instanceof NetconfHelloMessage, "Netconf message of type %s expected, was %s",
                 NetconfHelloMessage.class, msg.getClass());
         Optional<NetconfHelloMessageAdditionalHeader> headerOptional = ((NetconfHelloMessage) msg)
index a9500ece2880970342e1ab88baf5897f89bbf6d9..e874ab3a4062db96b41f16f76d6dbce91e3c7c0e 100644 (file)
@@ -39,15 +39,17 @@ public final class NetconfMessageToEXIEncoder extends MessageToByteEncoder<Netco
         this.transmogrifier = Preconditions.checkNotNull(transmogrifier);
     }
 
-    public static NetconfMessageToEXIEncoder create(final NetconfEXICodec codec) throws EXIOptionsException, TransmogrifierException {
+    public static NetconfMessageToEXIEncoder create(final NetconfEXICodec codec)
+            throws EXIOptionsException, TransmogrifierException {
         return new NetconfMessageToEXIEncoder(codec.getTransmogrifier());
     }
 
     @Override
-    protected void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws EXIOptionsException, IOException, TransformerException, TransmogrifierException {
+    protected void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out)
+            throws EXIOptionsException, IOException, TransformerException, TransmogrifierException {
         LOG.trace("Sent to encode : {}", msg);
 
-        try (final OutputStream os = new ByteBufOutputStream(out)) {
+        try (OutputStream os = new ByteBufOutputStream(out)) {
             transmogrifier.setOutputStream(os);
             final ContentHandler handler = transmogrifier.getSAXTransmogrifier();
             final Transformer transformer = ThreadLocalTransformers.getDefaultTransformer();
index 608f1998296f33a0bbb70b4cdf856d4b3b88d096..f033e0efe3406eb1f03edbdf323502e1018dbcfd 100644 (file)
@@ -40,7 +40,8 @@ public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMess
 
     @Override
     @VisibleForTesting
-    public void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out) throws IOException, TransformerException {
+    public void encode(final ChannelHandlerContext ctx, final NetconfMessage msg, final ByteBuf out)
+            throws IOException, TransformerException {
         LOG.trace("Sent to encode : {}", msg);
 
         if (clientId.isPresent()) {
@@ -53,7 +54,8 @@ public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMess
 
             // Using custom BufferedWriter that does not provide newLine method as performance improvement
             // see javadoc for BufferedWriter
-            StreamResult result = new StreamResult(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)));
+            StreamResult result =
+                    new StreamResult(new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8)));
             DOMSource source = new DOMSource(msg.getDocument());
             ThreadLocalTransformers.getPrettyTransformer().transform(source, result);
         }
index 5353381748e610f2cd3e90076b6fd3a082833a79..5d69d401118e3bf9da1716dbc6e8725461508955 100644 (file)
@@ -34,9 +34,7 @@ import org.xml.sax.SAXException;
 /**
  * Customized NetconfXMLToMessageDecoder that reads additional header with
  * session metadata from
- * {@link NetconfHelloMessage}
- *
- *
+ * {@link NetconfHelloMessage}*
  * This handler should be replaced in pipeline by regular message handler as last step of negotiation.
  * It serves as a message barrier and halts all non-hello netconf messages.
  * Netconf messages after hello should be processed once the negotiation succeeded.
@@ -61,7 +59,8 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder
 
     @Override
     @VisibleForTesting
-    public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IOException, SAXException, NetconfDocumentedException {
+    public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
+            throws IOException, SAXException, NetconfDocumentedException {
         if (in.readableBytes() == 0) {
             LOG.debug("No more content in incoming buffer.");
             return;
@@ -109,9 +108,10 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder
         }
     }
 
-    private static NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc) throws NetconfDocumentedException {
+    private static NetconfMessage getNetconfMessage(final String additionalHeader, final Document doc)
+            throws NetconfDocumentedException {
         NetconfMessage msg = new NetconfMessage(doc);
-        if(NetconfHelloMessage.isHelloMessage(msg)) {
+        if (NetconfHelloMessage.isHelloMessage(msg)) {
             if (additionalHeader != null) {
                 return new NetconfHelloMessage(doc, NetconfHelloMessageAdditionalHeader.fromString(additionalHeader));
             } else {
@@ -145,15 +145,15 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder
                 return -1;
             }
         }
-        int j = 0;
+        int index = 0;
         for (int i = 0; i < bytes.length; i++) {
-            if (bytes[i] == sequence[j]) {
-                j++;
-                if (j == sequence.length) {
-                    return i - j + 1;
+            if (bytes[i] == sequence[index]) {
+                index++;
+                if (index == sequence.length) {
+                    return i - index + 1;
                 }
             } else {
-                j = 0;
+                index = 0;
             }
         }
         return -1;
@@ -161,20 +161,20 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder
 
     private static void logMessage(final byte[] bytes) {
         if (LOG.isDebugEnabled()) {
-            String s = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
-            LOG.debug("Parsing message \n{}", s);
+            String string = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString();
+            LOG.debug("Parsing message \n{}", string);
         }
     }
 
     private static boolean startsWithAdditionalHeader(final byte[] bytes) {
         for (byte[] possibleStart : POSSIBLE_STARTS) {
-            int i = 0;
+            int index = 0;
             for (byte b : possibleStart) {
-                if(bytes[i++] != b) {
+                if (bytes[index++] != b) {
                     break;
                 }
 
-                if(i == possibleStart.length) {
+                if (index == possibleStart.length) {
                     return true;
                 }
             }
@@ -188,7 +188,9 @@ public final class NetconfXMLToHelloMessageDecoder extends ByteToMessageDecoder
     }
 
     /**
-     * @return Collection of NetconfMessages that were not hello, but were received during negotiation
+     * Get netconf messages received during negotiation.
+     *
+     * @return Collection of NetconfMessages that were not hello, but were received during negotiation.
      */
     public Iterable<NetconfMessage> getPostHelloNetconfMessages() {
         return nonHelloMessages;
index fcb92f0e14dca2ded4e4ebd2002fc9f5371da5af..68dba39d63bccae8f2e18280116e722e317d9258 100644 (file)
@@ -25,7 +25,8 @@ public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder {
     private static final Logger LOG = LoggerFactory.getLogger(NetconfXMLToMessageDecoder.class);
 
     @Override
-    public void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) throws IOException, SAXException {
+    public void decode(final ChannelHandlerContext ctx, final ByteBuf in,
+                       final List<Object> out) throws IOException, SAXException {
         if (in.isReadable()) {
             if (LOG.isTraceEnabled()) {
                 LOG.trace("Received to decode: {}", ByteBufUtil.hexDump(in));
@@ -77,10 +78,10 @@ public final class NetconfXMLToMessageDecoder extends ByteToMessageDecoder {
      * Check whether a byte is whitespace/control character. Considered whitespace characters: <br/>
      * SPACE, \t, \n, \v, \r, \f
      *
-     * @param b byte to check
+     * @param byteToCheck byte to check
      * @return true if the byte is a whitespace/control character
      */
-    private static boolean isWhitespace(final byte b) {
-        return b <= 0x0d && b >= 0x09 || b == 0x20;
+    private static boolean isWhitespace(final byte byteToCheck) {
+        return byteToCheck <= 0x0d && byteToCheck >= 0x09 || byteToCheck == 0x20;
     }
 }
index 8ba28731481cf0fc8dee499e6e876054871e0def..f63a1e0ae1812a48a856f37ef4d0a822896c5ea5 100644 (file)
@@ -38,7 +38,7 @@ public final class EXIParameters {
         this.options = Preconditions.checkNotNull(options);
     }
 
-
+    @SuppressWarnings("checkstyle:FallThrough")
     public static EXIParameters fromXmlElement(final XmlElement root) throws EXIOptionsException {
         final EXIOptions options =  new EXIOptions();
         final NodeList alignmentElements = root.getElementsByTagName(EXI_PARAMETER_ALIGNMENT);
@@ -47,20 +47,21 @@ public final class EXIParameters {
             final String alignmentTextContent = alignmentElement.getTextContent().trim();
 
             switch (alignmentTextContent) {
-            case EXI_PARAMETER_BYTE_ALIGNED:
-                options.setAlignmentType(AlignmentType.byteAligned);
-                break;
-            case EXI_PARAMETER_COMPRESSED:
-                options.setAlignmentType(AlignmentType.compress);
-                break;
-            case EXI_PARAMETER_PRE_COMPRESSION:
-                options.setAlignmentType(AlignmentType.preCompress);
-                break;
-            default:
-                LOG.warn("Unexpected value in alignmentTextContent: {} , using default value", alignmentTextContent);
-            case EXI_PARAMETER_BIT_PACKED:
-                options.setAlignmentType(AlignmentType.bitPacked);
-                break;
+                case EXI_PARAMETER_BYTE_ALIGNED:
+                    options.setAlignmentType(AlignmentType.byteAligned);
+                    break;
+                case EXI_PARAMETER_COMPRESSED:
+                    options.setAlignmentType(AlignmentType.compress);
+                    break;
+                case EXI_PARAMETER_PRE_COMPRESSION:
+                    options.setAlignmentType(AlignmentType.preCompress);
+                    break;
+                default:
+                    LOG.warn("Unexpected value in alignmentTextContent: {} , using default value",
+                            alignmentTextContent);
+                case EXI_PARAMETER_BIT_PACKED:
+                    options.setAlignmentType(AlignmentType.bitPacked);
+                    break;
             }
         } else {
             options.setAlignmentType(AlignmentType.bitPacked);
index f3711ae388c795e5d20396c51968627651ae03f0..3f81a5175e4689ab993c3920b3095cfcefeb9008 100644 (file)
@@ -33,6 +33,7 @@ public final class NetconfStartExiMessage extends NetconfMessage {
     public static final String PIS_KEY = "pis";
     public static final String PREFIXES_KEY = "prefixes";
     private static final Logger LOG = LoggerFactory.getLogger(NetconfStartExiMessage.class);
+
     private NetconfStartExiMessage(final Document doc) {
         super(doc);
     }
@@ -75,37 +76,40 @@ public final class NetconfStartExiMessage extends NetconfMessage {
         }
     }
 
+    @SuppressWarnings("checkstyle:FallThrough")
     private static void addAlignment(final EXIOptions exiOptions, final Document doc, final Element startExiElement) {
         final Element alignmentElement = doc.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0,
                 ALIGNMENT_KEY);
 
         String alignmentString;
         switch (exiOptions.getAlignmentType()) {
-        case byteAligned: {
-            alignmentString = EXIParameters.EXI_PARAMETER_BYTE_ALIGNED;
-            break;
-        }
-        case compress: {
-            alignmentString = EXIParameters.EXI_PARAMETER_COMPRESSED;
-            break;
-        }
-        case preCompress: {
-            alignmentString = EXIParameters.EXI_PARAMETER_PRE_COMPRESSION;
-            break;
-        }
-        default:
-            LOG.warn("Unexpected value in EXI alignment type: {} , using default value", exiOptions.getAlignmentType());
-        case bitPacked: {
-            alignmentString = EXIParameters.EXI_PARAMETER_BIT_PACKED;
-            break;
-        }
+            case byteAligned: {
+                alignmentString = EXIParameters.EXI_PARAMETER_BYTE_ALIGNED;
+                break;
+            }
+            case compress: {
+                alignmentString = EXIParameters.EXI_PARAMETER_COMPRESSED;
+                break;
+            }
+            case preCompress: {
+                alignmentString = EXIParameters.EXI_PARAMETER_PRE_COMPRESSION;
+                break;
+            }
+            default:
+                LOG.warn("Unexpected value in EXI alignment type: {} , using default value",
+                        exiOptions.getAlignmentType());
+            case bitPacked: {
+                alignmentString = EXIParameters.EXI_PARAMETER_BIT_PACKED;
+                break;
+            }
         }
 
         alignmentElement.setTextContent(alignmentString);
         startExiElement.appendChild(alignmentElement);
     }
 
-    private static void createFidelityElement(final Document doc, final List<Element> fidelityElements, final boolean fidelity, final String fidelityName) {
+    private static void createFidelityElement(final Document doc, final List<Element> fidelityElements,
+                                              final boolean fidelity, final String fidelityName) {
 
         if (fidelity) {
             fidelityElements.add(doc.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0,
index c6c417f7d0afdd3a52c4fdc7aeb5212fce8c30ef..aed43347d863ee9269911ed4cb66fb7b49535b78 100644 (file)
@@ -18,5 +18,6 @@ public abstract class AuthenticationHandler {
 
     public abstract String getUsername();
 
-    public abstract org.apache.sshd.client.future.AuthFuture authenticate(final ClientSession session) throws IOException;
+    public abstract org.apache.sshd.client.future.AuthFuture authenticate(ClientSession session)
+            throws IOException;
 }
index 6219f91b2d9998a6c2d2027a457f615f14de69cb..46cb2c717b314cb64548c553354087bf5df2f082 100644 (file)
@@ -14,7 +14,7 @@ import org.apache.sshd.client.future.AuthFuture;
 
 /**
  * Class Providing username/password authentication option to
- * {@link org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler}
+ * {@link org.opendaylight.netconf.nettyutil.handler.ssh.client.AsyncSshHandler}.
  */
 public class LoginPassword extends AuthenticationHandler {
     private final String username;
index cb642c1a9954cba715cbb381431f9467c3c731c3..8f6e2baa6304583b456901717bf48e4ec3988e7e 100644 (file)
@@ -44,6 +44,7 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
     private static final long DEFAULT_TIMEOUT = -1L;
 
     public static final SshClient DEFAULT_CLIENT;
+
     static {
         final Map<String, String> props = new HashMap<>();
         props.put(SshClient.AUTH_TIMEOUT, Long.toString(DEFAULT_TIMEOUT));
@@ -77,29 +78,31 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
     }
 
     /**
+     * Constructor of {@code AsyncSshHandler}.
      *
-     * @param authenticationHandler
-     * @param sshClient started SshClient
-     * @throws IOException
+     * @param authenticationHandler authentication handler
+     * @param sshClient             started SshClient
+     * @throws IOException          if the I/O operation fails
      */
-    public AsyncSshHandler(final AuthenticationHandler authenticationHandler, final SshClient sshClient) throws IOException {
+    public AsyncSshHandler(final AuthenticationHandler authenticationHandler,
+                           final SshClient sshClient) throws IOException {
         this.authenticationHandler = Preconditions.checkNotNull(authenticationHandler);
         this.sshClient = Preconditions.checkNotNull(sshClient);
     }
 
-    public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler) throws IOException {
+    public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler)
+            throws IOException {
         return new AsyncSshHandler(authenticationHandler, DEFAULT_CLIENT);
     }
 
     /**
+     * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful
+     * netconf negotiation.
      *
-     * Create AsyncSshHandler for netconf subsystem. Negotiation future has to be set to success after successful netconf
-     * negotiation.
-     *
-     * @param authenticationHandler
-     * @param negotiationFuture
-     * @return
-     * @throws IOException
+     * @param authenticationHandler authentication handler
+     * @param negotiationFuture     negotiation future
+     * @return                      {@code AsyncSshHandler}
+     * @throws IOException          if the I/O operation fails
      */
     public static AsyncSshHandler createForNetconfSubsystem(final AuthenticationHandler authenticationHandler,
             final Future<?> negotiationFuture) throws IOException {
@@ -135,9 +138,8 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
                         handleSshAuthenticated(session, ctx);
                     } else {
                         // Exception does not have to be set in the future, add simple exception in such case
-                        final Throwable exception = future.getException() == null ?
-                                new IllegalStateException("Authentication failed") :
-                                future.getException();
+                        final Throwable exception = future.getException() == null
+                                ? new IllegalStateException("Authentication failed") : future.getException();
                         handleSshSetupFailure(ctx, exception);
                     }
                 }
@@ -149,14 +151,15 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
 
     private synchronized void handleSshAuthenticated(final ClientSession session, final ChannelHandlerContext ctx) {
         try {
-            LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(), session.getServerVersion());
+            LOG.debug("SSH session authenticated on channel: {}, server version: {}", ctx.channel(),
+                    session.getServerVersion());
 
             channel = session.createSubsystemChannel(SUBSYSTEM);
             channel.setStreaming(ClientChannel.Streaming.Async);
             channel.open().addListener(new SshFutureListener<OpenFuture>() {
                 @Override
                 public void operationComplete(final OpenFuture future) {
-                    if(future.isOpened()) {
+                    if (future.isOpened()) {
                         handleSshChanelOpened(ctx);
                     } else {
                         handleSshSetupFailure(ctx, future.getException());
@@ -173,7 +176,7 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
     private synchronized void handleSshChanelOpened(final ChannelHandlerContext ctx) {
         LOG.trace("SSH subsystem channel opened successfully on channel: {}", ctx.channel());
 
-        if(negotiationFuture == null) {
+        if (negotiationFuture == null) {
             connectPromise.setSuccess();
         }
 
@@ -191,19 +194,20 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
             }
         }, channel.toString(), channel.getAsyncOut());
 
-        // if readAsyncListener receives immediate close, it will close this handler and closing this handler sets channel variable to null
-        if(channel != null) {
+        // if readAsyncListener receives immediate close,
+        // it will close this handler and closing this handler sets channel variable to null
+        if (channel != null) {
             sshWriteAsyncHandler = new AsyncSshHandlerWriter(channel.getAsyncIn());
             ctx.fireChannelActive();
         }
     }
 
-    private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable e) {
-        LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), e);
+    private synchronized void handleSshSetupFailure(final ChannelHandlerContext ctx, final Throwable error) {
+        LOG.warn("Unable to setup SSH connection on channel: {}", ctx.channel(), error);
 
         // If the promise is not yet done, we have failed with initial connect and set connectPromise to failure
-        if(!connectPromise.isDone()) {
-            connectPromise.setFailure(e);
+        if (!connectPromise.isDone()) {
+            connectPromise.setFailure(error);
         }
 
         disconnect(ctx, ctx.newPromise());
@@ -215,11 +219,12 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
     }
 
     @Override
-    public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
+    public synchronized void connect(final ChannelHandlerContext ctx, final SocketAddress remoteAddress,
+                                     final SocketAddress localAddress, final ChannelPromise promise) throws Exception {
         LOG.debug("SSH session connecting on channel {}. promise: {} ", ctx.channel(), connectPromise);
         this.connectPromise = promise;
 
-        if(negotiationFuture != null) {
+        if (negotiationFuture != null) {
 
             negotiationFutureListener = new GenericFutureListener<Future<?>>() {
                 @Override
@@ -240,36 +245,39 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
         disconnect(ctx, promise);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public synchronized void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) {
-        LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}", ctx.channel(), connectPromise);
+        LOG.trace("Closing SSH session on channel: {} with connect promise in state: {}",
+                ctx.channel(),connectPromise);
 
-        // If we have already succeeded and the session was dropped after, we need to fire inactive to notify reconnect logic
-        if(connectPromise.isSuccess()) {
+        // If we have already succeeded and the session was dropped after,
+        // we need to fire inactive to notify reconnect logic
+        if (connectPromise.isSuccess()) {
             ctx.fireChannelInactive();
         }
 
-        if(sshWriteAsyncHandler != null) {
+        if (sshWriteAsyncHandler != null) {
             sshWriteAsyncHandler.close();
         }
 
-        if(sshReadAsyncListener != null) {
+        if (sshReadAsyncListener != null) {
             sshReadAsyncListener.close();
         }
 
         //If connection promise is not already set, it means negotiation failed
         //we must set connection promise to failure
-        if(!connectPromise.isDone()) {
+        if (!connectPromise.isDone()) {
             connectPromise.setFailure(new IllegalStateException("Negotiation failed"));
         }
 
         //Remove listener from negotiation future, we don't want notifications
         //from negotiation anymore
-        if(negotiationFuture != null) {
+        if (negotiationFuture != null) {
             negotiationFuture.removeListener(negotiationFutureListener);
         }
 
-        if(session!= null && !session.isClosed() && !session.isClosing()) {
+        if (session != null && !session.isClosed() && !session.isClosing()) {
             session.close(false).addListener(new SshFutureListener<CloseFuture>() {
                 @Override
                 public void operationComplete(final CloseFuture future) {
@@ -281,9 +289,11 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
             });
         }
 
-        // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs to cleanup its resources
-        // e.g. Socket that it tries to open in its constructor (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
-        // TODO better solution would be to implement custom ChannelFactory + Channel that will use mina SSH lib internally: port this to custom channel implementation
+        // Super disconnect is necessary in this case since we are using NioSocketChannel and it needs
+        // to cleanup its resources e.g. Socket that it tries to open in its constructor
+        // (https://bugs.opendaylight.org/show_bug.cgi?id=2430)
+        // TODO better solution would be to implement custom ChannelFactory + Channel
+        // that will use mina SSH lib internally: port this to custom channel implementation
         try {
             // Disconnect has to be closed after inactive channel event was fired, because it interferes with it
             super.disconnect(ctx, ctx.newPromise());
index b54eb4616907c60ca45de6ff292e6826bfb8fc25..c79b71308ace4d270c15d93564f91cd1877ec880 100644 (file)
@@ -35,7 +35,8 @@ public final class AsyncSshHandlerReader implements SshFutureListener<IoReadFutu
     private Buffer buf;
     private IoReadFuture currentReadFuture;
 
-    public AsyncSshHandlerReader(final AutoCloseable connectionClosedCallback, final ReadMsgHandler readHandler, final String channelId, final IoInputStream asyncOut) {
+    public AsyncSshHandlerReader(final AutoCloseable connectionClosedCallback, final ReadMsgHandler readHandler,
+                                 final String channelId, final IoInputStream asyncOut) {
         this.connectionClosedCallback = connectionClosedCallback;
         this.readHandler = readHandler;
         this.channelId = channelId;
@@ -46,14 +47,14 @@ public final class AsyncSshHandlerReader implements SshFutureListener<IoReadFutu
 
     @Override
     public synchronized void operationComplete(final IoReadFuture future) {
-        if(future.getException() != null) {
+        if (future.getException() != null) {
 
             //if asyncout is already set to null by close method, do nothing
-            if(asyncOut == null) {
+            if (asyncOut == null) {
                 return;
             }
 
-            if(asyncOut.isClosed() || asyncOut.isClosing()) {
+            if (asyncOut.isClosed() || asyncOut.isClosing()) {
                 // Ssh dropped
                 LOG.debug("Ssh session dropped on channel: {}", channelId, future.getException());
             } else {
@@ -65,8 +66,9 @@ public final class AsyncSshHandlerReader implements SshFutureListener<IoReadFutu
 
         if (future.getRead() > 0) {
             final ByteBuf msg = Unpooled.wrappedBuffer(buf.array(), 0, future.getRead());
-            if(LOG.isTraceEnabled()) {
-                LOG.trace("Reading message on channel: {}, message: {}", channelId, AsyncSshHandlerWriter.byteBufToString(msg));
+            if (LOG.isTraceEnabled()) {
+                LOG.trace("Reading message on channel: {}, message: {}",
+                        channelId, AsyncSshHandlerWriter.byteBufToString(msg));
             }
             readHandler.onMessageRead(msg);
 
@@ -77,6 +79,7 @@ public final class AsyncSshHandlerReader implements SshFutureListener<IoReadFutu
         }
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     private void invokeDisconnect() {
         try {
             connectionClosedCallback.close();
@@ -89,7 +92,7 @@ public final class AsyncSshHandlerReader implements SshFutureListener<IoReadFutu
     @Override
     public synchronized void close() {
         // Remove self as listener on close to prevent reading from closed input
-        if(currentReadFuture != null) {
+        if (currentReadFuture != null) {
             currentReadFuture.removeListener(this);
             currentReadFuture = null;
         }
index e9a1d75c55e33c897ad29241dc9ce0792655972d..e333da2b7610ab6b210e4c158b5e9b2f2cbcf2e7 100644 (file)
@@ -37,8 +37,8 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
     // TODO implement Limiting mechanism for pending writes
     // But there is a possible issue with limiting:
     // 1. What to do when queue is full ? Immediate Fail for every request ?
-    // 2. At this level we might be dealing with Chunks of messages(not whole messages) and unexpected behavior might occur
-    // when we send/queue 1 chunk and fail the other chunks
+    // 2. At this level we might be dealing with Chunks of messages(not whole messages)
+    // and unexpected behavior might occur when we send/queue 1 chunk and fail the other chunks
 
     private volatile IoOutputStream asyncIn;
 
@@ -78,7 +78,8 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
 
     //sending message with pending
     //if resending message not succesfull, then attribute wasPending is true
-    private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise, final ByteBuf byteBufMsg, final boolean wasPending) {
+    private void writeWithPendingDetection(final ChannelHandlerContext ctx, final ChannelPromise promise,
+                                           final ByteBuf byteBufMsg, final boolean wasPending) {
         try {
 
             if (LOG.isTraceEnabled()) {
@@ -94,15 +95,17 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
                     // while the pending write was in progress from the write callback
                     synchronized (asyncIn) {
                         if (LOG.isTraceEnabled()) {
-                            LOG.trace("Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
-                                    ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg));
+                            LOG.trace(
+                                "Ssh write request finished on channel: {} with result: {}: and ex:{}, message: {}",
+                                ctx.channel(), future.isWritten(), future.getException(), byteBufToString(byteBufMsg));
                         }
 
                         // Notify success or failure
                         if (future.isWritten()) {
                             promise.setSuccess();
                         } else {
-                            LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(), byteBufToString(byteBufMsg), future.getException());
+                            LOG.warn("Ssh write request failed on channel: {} for message: {}", ctx.channel(),
+                                    byteBufToString(byteBufMsg), future.getException());
                             promise.setFailure(future.getException());
                         }
 
@@ -117,14 +120,15 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
                     }
 
                     // Check pending queue and schedule next
-                    // At this time we are guaranteed that we are not in pending state anymore so the next request should succeed
+                    // At this time we are guaranteed that we are not in pending state anymore
+                    // so the next request should succeed
                     writePendingIfAny();
                 }
             });
 
         } catch (final WritePendingException e) {
 
-            if(wasPending == false){
+            if (wasPending == false) {
                 queueRequest(ctx, byteBufMsg, promise);
             }
         }
@@ -139,7 +143,8 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
             final PendingWriteRequest pendingWrite = pending.peek();
             final ByteBuf msg = pendingWrite.msg;
             if (LOG.isTraceEnabled()) {
-                LOG.trace("Writing pending request on channel: {}, message: {}", pendingWrite.ctx.channel(), byteBufToString(msg));
+                LOG.trace("Writing pending request on channel: {}, message: {}",
+                        pendingWrite.ctx.channel(), byteBufToString(msg));
             }
 
             writeWithPendingDetection(pendingWrite.ctx, pendingWrite.promise, msg, true);
@@ -160,7 +165,8 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
         }
         new PendingWriteRequest(ctx, msg, promise).pend(pending);
 //        } catch (final Exception ex) {
-//            LOG.warn("Unable to queue write request on channel: {}. Setting fail for the request: {}", ctx.channel(), ex, byteBufToString(msg));
+//            LOG.warn("Unable to queue write request on channel: {}. Setting fail for the request: {}",
+//                    ctx.channel(), ex, byteBufToString(msg));
 //            msg.release();
 //            promise.setFailure(ex);
 //        }
@@ -184,7 +190,7 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
         private final ByteBuf msg;
         private final ChannelPromise promise;
 
-        public PendingWriteRequest(final ChannelHandlerContext ctx, final ByteBuf msg, final ChannelPromise promise) {
+        PendingWriteRequest(final ChannelHandlerContext ctx, final ByteBuf msg, final ChannelPromise promise) {
             this.ctx = ctx;
             // Reset reader index, last write (failed) attempt moved index to the end
             msg.resetReaderIndex();
@@ -196,8 +202,8 @@ public final class AsyncSshHandlerWriter implements AutoCloseable {
             // Preconditions.checkState(pending.size() < MAX_PENDING_WRITES,
             // "Too much pending writes(%s) on channel: %s, remote window is not getting read or is too small",
             // pending.size(), ctx.channel());
-            Preconditions.checkState(pending.offer(this), "Cannot pend another request write (pending count: %s) on channel: %s",
-                    pending.size(), ctx.channel());
+            Preconditions.checkState(pending.offer(this),
+                "Cannot pend another request write (pending count: %s) on channel: %s", pending.size(), ctx.channel());
         }
     }
 }
index 4da5b2c89029da8735896912d37f7d79504a0c9f..af64d2901576d1d1cc993b475e36c407eed300c3 100644 (file)
@@ -75,12 +75,15 @@ public class AbstractNetconfSessionNegotiatorTest {
         MockitoAnnotations.initMocks(this);
         channel = new EmbeddedChannel();
         xmlToHello = new NetconfXMLToHelloMessageDecoder();
-        channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, new ChannelInboundHandlerAdapter());
+        channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
+                new ChannelInboundHandlerAdapter());
         channel.pipeline().addLast(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, xmlToHello);
-        channel.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER, FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM));
+        channel.pipeline().addLast(NETCONF_MESSAGE_FRAME_ENCODER,
+                FramingMechanismHandlerFactory.createHandler(FramingMechanism.EOM));
         channel.pipeline().addLast(NETCONF_MESSAGE_AGGREGATOR, new NetconfEOMAggregator());
         hello = NetconfHelloMessage.createClientHello(Collections.emptySet(), Optional.absent());
-        helloBase11 = NetconfHelloMessage.createClientHello(Collections.singleton(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1), Optional.absent());
+        helloBase11 = NetconfHelloMessage.createClientHello(Collections
+                .singleton(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1), Optional.absent());
         prefs = new NetconfSessionPreferences(helloBase11);
         doReturn(promise).when(promise).setFailure(any());
         doReturn(promise).when(promise).setSuccess(any());
@@ -136,7 +139,8 @@ public class AbstractNetconfSessionNegotiatorTest {
         final AbstractNetconfSession session = negotiator.getSessionForHelloMessage(helloBase11);
         Assert.assertNotNull(session);
         Assert.assertTrue(channel.pipeline().get(NETCONF_MESSAGE_AGGREGATOR) instanceof NetconfChunkAggregator);
-        Assert.assertTrue(channel.pipeline().get(NETCONF_MESSAGE_FRAME_ENCODER) instanceof ChunkedFramingMechanismEncoder);
+        Assert.assertTrue(channel.pipeline().get(NETCONF_MESSAGE_FRAME_ENCODER)
+                instanceof ChunkedFramingMechanismEncoder);
     }
 
     @Test
@@ -177,7 +181,7 @@ public class AbstractNetconfSessionNegotiatorTest {
 
         @Override
         protected TestingNetconfSession getSession(final NetconfSessionListener sessionListener, final Channel channel,
-                                                   final NetconfHelloMessage message) throws NetconfDocumentedException {
+                                               final NetconfHelloMessage message) throws NetconfDocumentedException {
             return new TestingNetconfSession(sessionListener, channel, 0L);
         }
 
index 8edfca9296bb7df336415822dc5622e6fd5af912..7dda1cdac8dcf67d2a3ee269e5e283fb84d92ec9 100644 (file)
@@ -66,7 +66,8 @@ public class AbstractNetconfSessionTest {
         doNothing().when(listener).onMessage(any(TestingNetconfSession.class), any(NetconfMessage.class));
         doNothing().when(listener).onSessionUp(any(TestingNetconfSession.class));
         doNothing().when(listener).onSessionDown(any(TestingNetconfSession.class), any(Exception.class));
-        doNothing().when(listener).onSessionTerminated(any(TestingNetconfSession.class), any(NetconfTerminationReason.class));
+        doNothing().when(listener).onSessionTerminated(any(TestingNetconfSession.class),
+                any(NetconfTerminationReason.class));
 
         doReturn(writeFuture).when(writeFuture).addListener(any(GenericFutureListener.class));
 
@@ -88,7 +89,8 @@ public class AbstractNetconfSessionTest {
             }
         }).when(eventLoop).execute(any(Runnable.class));
 
-        clientHello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(), Optional.<NetconfHelloMessageAdditionalHeader>absent());
+        clientHello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(),
+                Optional.<NetconfHelloMessageAdditionalHeader>absent());
     }
 
     @Test
@@ -122,14 +124,17 @@ public class AbstractNetconfSessionTest {
         doReturn("handler").when(mock).toString();
 
         testingNetconfSession.replaceMessageDecoder(mock);
-        verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, mock);
+        verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_DECODER,
+                AbstractChannelInitializer.NETCONF_MESSAGE_DECODER, mock);
         testingNetconfSession.replaceMessageEncoder(mock);
-        verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock);
+        verify(pipeline).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
+                AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock);
         testingNetconfSession.replaceMessageEncoderAfterNextMessage(mock);
         verifyNoMoreInteractions(pipeline);
 
         testingNetconfSession.sendMessage(clientHello);
-        verify(pipeline, times(2)).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock);
+        verify(pipeline, times(2)).replace(AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER,
+                AbstractChannelInitializer.NETCONF_MESSAGE_ENCODER, mock);
     }
 
     @Test
@@ -154,7 +159,8 @@ public class AbstractNetconfSessionTest {
     @Test
     public void testSendMessage() throws Exception {
         final TestingNetconfSession testingNetconfSession = new TestingNetconfSession(listener, channel, 1L);
-        final NetconfHelloMessage clientHello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(), Optional.<NetconfHelloMessageAdditionalHeader>absent());
+        final NetconfHelloMessage clientHello = NetconfHelloMessage.createClientHello(Collections.<String>emptySet(),
+                Optional.<NetconfHelloMessageAdditionalHeader>absent());
         testingNetconfSession.sendMessage(clientHello);
         verify(channel).writeAndFlush(clientHello);
     }
index b7a1c6c741a456aff47b8a35a4956ac002c9ad49..cb8733ee05194224659e1b045fe2061becf3056a 100644 (file)
@@ -14,9 +14,11 @@ import io.netty.handler.codec.MessageToByteEncoder;
 import org.opendaylight.netconf.api.NetconfMessage;
 import org.opendaylight.netconf.api.NetconfSessionListener;
 
-class TestingNetconfSession extends AbstractNetconfSession<TestingNetconfSession, NetconfSessionListener<TestingNetconfSession>> {
+class TestingNetconfSession
+        extends AbstractNetconfSession<TestingNetconfSession, NetconfSessionListener<TestingNetconfSession>> {
 
-    TestingNetconfSession(final NetconfSessionListener<TestingNetconfSession> sessionListener, final Channel channel, final long sessionId) {
+    TestingNetconfSession(final NetconfSessionListener<TestingNetconfSession> sessionListener,
+                          final Channel channel, final long sessionId) {
         super(sessionListener, channel, sessionId);
     }
 
@@ -26,7 +28,8 @@ class TestingNetconfSession extends AbstractNetconfSession<TestingNetconfSession
     }
 
     @Override
-    protected void addExiHandlers(final ByteToMessageDecoder decoder, final MessageToByteEncoder<NetconfMessage> encoder) {
+    protected void addExiHandlers(final ByteToMessageDecoder decoder,
+                                  final MessageToByteEncoder<NetconfMessage> encoder) {
     }
 
     @Override
index c8837dfd95c5d54e20d951bfc5f300c6b5c59a8b..bb95ff1b0223e8390d22769f7b8eb2649270735b 100644 (file)
@@ -55,10 +55,10 @@ public class ChunkedFramingMechanismEncoderTest {
 
         byte[] buf = new byte[destination.readableBytes()];
         destination.readBytes(buf);
-        String s = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(buf)).toString();
+        String string = StandardCharsets.US_ASCII.decode(ByteBuffer.wrap(buf)).toString();
 
-        assertTrue(s.startsWith("\n#256\na"));
-        assertTrue(s.endsWith("\n#20\naaaaaaaaaaaaaaaaaaaa\n##\n"));
+        assertTrue(string.startsWith("\n#256\na"));
+        assertTrue(string.endsWith("\n#20\naaaaaaaaaaaaaaaaaaaa\n##\n"));
     }
 
     private static byte[] getByteArray(final int size) {
index 321b34ccf77bfc0602e40141f6c13df860cdd6af..a9a67f19c43e0474006b1b92e6ee328fea10b352 100644 (file)
@@ -19,20 +19,20 @@ import org.junit.Test;
 
 public class NetconfChunkAggregatorTest {
 
-    private static final String CHUNKED_MESSAGE = "\n#4\n" +
-            "<rpc" +
-            "\n#18\n" +
-            " message-id=\"102\"\n" +
-            "\n#79\n" +
-            "     xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-            "  <close-session/>\n" +
-            "</rpc>" +
-            "\n##\n";
-
-    public static final String EXPECTED_MESSAGE = "<rpc message-id=\"102\"\n" +
-            "     xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-            "  <close-session/>\n" +
-            "</rpc>";
+    private static final String CHUNKED_MESSAGE = "\n#4\n"
+            + "<rpc"
+            + "\n#18\n"
+            + " message-id=\"102\"\n"
+            + "\n#79\n"
+            + "     xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+            + "  <close-session/>\n"
+            + "</rpc>"
+            "\n##\n";
+
+    public static final String EXPECTED_MESSAGE = "<rpc message-id=\"102\"\n"
+            + "     xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+            + "  <close-session/>\n"
+            "</rpc>";
 
     private static final String CHUNKED_MESSAGE_ONE = "\n#101\n" + EXPECTED_MESSAGE + "\n##\n";
 
index f80b4dacf1df1f6f11e91e2a122edc54181b7f81..b1b6e6d56ab3fea5a3554c7e3614cf034371c383 100644 (file)
@@ -48,7 +48,8 @@ public class NetconfEXIHandlersTest {
         this.msgAsExi = msgToExi(msgAsString, codec);
     }
 
-    private static byte[] msgToExi(final String msgAsString, final NetconfEXICodec codec) throws EXIOptionsException, TransmogrifierException, IOException {
+    private static byte[] msgToExi(final String msgAsString,final NetconfEXICodec codec)
+            throws EXIOptionsException, TransmogrifierException, IOException {
         final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         final Transmogrifier transmogrifier = codec.getTransmogrifier();
         transmogrifier.setOutputStream(byteArrayOutputStream);
index 7eaceff6697ccc31fe8d37f8dcaa0cefb9580560..794ce8dad2d014ac66996a954229ddddd69bf52c 100644 (file)
@@ -36,7 +36,8 @@ public class NetconfHelloMessageToXMLEncoderTest {
 
     @Test
     public void testEncode() throws Exception {
-        final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"),
+        final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument(
+                "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"),
                 NetconfHelloMessageAdditionalHeader.fromString("[tomas;10.0.0.0:10000;tcp;client;]"));
         final ByteBuf destination = Unpooled.buffer();
         new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, destination);
@@ -48,7 +49,8 @@ public class NetconfHelloMessageToXMLEncoderTest {
 
     @Test
     public void testEncodeNoHeader() throws Exception {
-        final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
+        final NetconfMessage msg = new NetconfHelloMessage(XmlUtil.readXmlToDocument(
+                "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
         final ByteBuf destination = Unpooled.buffer();
         new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, destination);
 
@@ -59,7 +61,8 @@ public class NetconfHelloMessageToXMLEncoderTest {
 
     @Test(expected = IllegalStateException.class)
     public void testEncodeNotHello() throws Exception {
-        final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
+        final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument(
+                "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>"));
         new NetconfHelloMessageToXMLEncoder().encode(ctx, msg, null);
     }
 }
\ No newline at end of file
index 9ee511ace0356178c4719baaf76bbfba9784cb0a..fc20f9585d4a8f7e1c0702bbe1f5e564bd7985e4 100644 (file)
@@ -28,7 +28,8 @@ public class NetconfXMLToHelloMessageDecoderTest {
     @Test
     public void testDecodeWithHeader() throws Exception {
         final ByteBuf src = Unpooled.wrappedBuffer(String.format("%s\n%s",
-                "[tomas;10.0.0.0:10000;tcp;client;]", "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>").getBytes());
+                "[tomas;10.0.0.0:10000;tcp;client;]",
+                "<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>").getBytes());
         final List<Object> out = Lists.newArrayList();
         new NetconfXMLToHelloMessageDecoder().decode(null, src, out);
 
@@ -36,13 +37,16 @@ public class NetconfXMLToHelloMessageDecoderTest {
         assertThat(out.get(0), CoreMatchers.instanceOf(NetconfHelloMessage.class));
         final NetconfHelloMessage hello = (NetconfHelloMessage) out.get(0);
         assertTrue(hello.getAdditionalHeader().isPresent());
-        assertEquals("[tomas;10.0.0.0:10000;tcp;client;]" + System.lineSeparator(), hello.getAdditionalHeader().get().toFormattedString());
-        assertThat(XmlUtil.toString(hello.getDocument()), CoreMatchers.containsString("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""));
+        assertEquals("[tomas;10.0.0.0:10000;tcp;client;]" + System.lineSeparator(),
+                hello.getAdditionalHeader().get().toFormattedString());
+        assertThat(XmlUtil.toString(hello.getDocument()),
+                CoreMatchers.containsString("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\""));
     }
 
     @Test
     public void testDecodeNoHeader() throws Exception {
-        final ByteBuf src = Unpooled.wrappedBuffer("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
+        final ByteBuf src =
+                Unpooled.wrappedBuffer("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
         final List<Object> out = Lists.newArrayList();
         new NetconfXMLToHelloMessageDecoder().decode(null, src, out);
 
@@ -54,9 +58,12 @@ public class NetconfXMLToHelloMessageDecoderTest {
 
     @Test
     public void testDecodeCaching() throws Exception {
-        final ByteBuf msg1 = Unpooled.wrappedBuffer("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
-        final ByteBuf msg2 = Unpooled.wrappedBuffer("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
-        final ByteBuf src = Unpooled.wrappedBuffer("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
+        final ByteBuf msg1 =
+                Unpooled.wrappedBuffer("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
+        final ByteBuf msg2 =
+                Unpooled.wrappedBuffer("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
+        final ByteBuf src =
+                Unpooled.wrappedBuffer("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
         final List<Object> out = Lists.newArrayList();
         final NetconfXMLToHelloMessageDecoder decoder = new NetconfXMLToHelloMessageDecoder();
         decoder.decode(null, src, out);
@@ -70,7 +77,8 @@ public class NetconfXMLToHelloMessageDecoderTest {
 
     @Test(expected = IllegalStateException.class)
     public void testDecodeNotHelloReceived() throws Exception {
-        final ByteBuf msg1 = Unpooled.wrappedBuffer("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
+        final ByteBuf msg1 =
+                Unpooled.wrappedBuffer("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"/>".getBytes());
         final List<Object> out = Lists.newArrayList();
         NetconfXMLToHelloMessageDecoder decoder = new NetconfXMLToHelloMessageDecoder();
         decoder.decode(null, msg1, out);
index 37b7b2a9cd0609a00a4f3cdbdf0da06fef4f5699..ea5bd62df6c6991ab5455486f52475bb658519f5 100644 (file)
@@ -39,7 +39,8 @@ public class NetconfXMLToMessageDecoderTest {
          * A leading LF is the case reported in BUG-2838.
          */
         final ArrayList<Object> out = Lists.newArrayList();
-        new NetconfXMLToMessageDecoder().decode(null, Unpooled.wrappedBuffer("\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><msg/>".getBytes()), out);
+        new NetconfXMLToMessageDecoder().decode(null,
+                Unpooled.wrappedBuffer("\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><msg/>".getBytes()), out);
         assertEquals(1, out.size());
     }
 
@@ -51,11 +52,12 @@ public class NetconfXMLToMessageDecoderTest {
          * (eg CSR1000V running IOS 15.4(1)S)
          */
         final ArrayList<Object> out = Lists.newArrayList();
-        new NetconfXMLToMessageDecoder().decode(null, Unpooled.wrappedBuffer("\r\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><msg/>".getBytes()), out);
+        new NetconfXMLToMessageDecoder().decode(null,
+                Unpooled.wrappedBuffer("\r\n<?xml version=\"1.0\" encoding=\"UTF-8\"?><msg/>".getBytes()), out);
         assertEquals(1, out.size());
     }
 
-    @Test(expected=SAXParseException.class)
+    @Test(expected = SAXParseException.class)
     public void testDecodeGibberish() throws Exception {
         /* Test that we reject inputs where we cannot find the xml start '<' character */
         final ArrayList<Object> out = Lists.newArrayList();
@@ -78,7 +80,7 @@ public class NetconfXMLToMessageDecoderTest {
          */
 
         final ArrayList<Object> out = Lists.newArrayList();
-        byte whitespaces[] = {' ', '\t', '\n', '\r', '\f', 0x0b /* vertical tab */};
+        byte[] whitespaces = {' ', '\t', '\n', '\r', '\f', 0x0b /* vertical tab */};
         new NetconfXMLToMessageDecoder().decode(
                 null,
                 Unpooled.copiedBuffer(
index 9879d61e6c33142956f8f18b93b3a0b6800d266e..f14e0995b0a466620fe59d51a42f134e144731cc 100644 (file)
@@ -25,22 +25,22 @@ public class EXIParametersTest {
     @Parameterized.Parameters
     public static Iterable<Object[]> data() throws Exception {
         final String noChangeXml =
-                "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n" +
-                "<alignment>bit-packed</alignment>\n" +
-                "</start-exi>\n";
+                "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n"
+                + "<alignment>bit-packed</alignment>\n"
+                "</start-exi>\n";
 
 
         final String fullOptionsXml =
-                "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n" +
-                "<alignment>byte-aligned</alignment>\n" +
-                "<fidelity>\n" +
-                "<comments/>\n" +
-                "<dtd/>\n" +
-                "<lexical-values/>\n" +
-                "<pis/>\n" +
-                "<prefixes/>\n" +
-                "</fidelity>\n" +
-                "</start-exi>\n";
+                "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n"
+                + "<alignment>byte-aligned</alignment>\n"
+                + "<fidelity>\n"
+                + "<comments/>\n"
+                + "<dtd/>\n"
+                + "<lexical-values/>\n"
+                + "<pis/>\n"
+                + "<prefixes/>\n"
+                + "</fidelity>\n"
+                "</start-exi>\n";
 
         final EXIOptions fullOptions = new EXIOptions();
         fullOptions.setAlignmentType(AlignmentType.byteAligned);
index 24e93d97380d4866a3908a659e89f249405dda1c..d7ccba6f3b6490f9720873d8fddc80501541aabe 100644 (file)
@@ -24,25 +24,27 @@ public class NetconfStartExiMessageTest {
 
     @Parameterized.Parameters
     public static Iterable<Object[]> data() throws Exception {
-        final String noChangeXml = "<rpc xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:message-id=\"id\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n" +
-                "<alignment>bit-packed</alignment>\n" +
-                "</start-exi>\n" +
-                "</rpc>";
+        final String noChangeXml = "<rpc xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" "
+                + "ns0:message-id=\"id\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n"
+                + "<alignment>bit-packed</alignment>\n"
+                + "</start-exi>\n"
+                + "</rpc>";
 
 
-        final String fullOptionsXml = "<rpc xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" ns0:message-id=\"id\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n" +
-                "<alignment>byte-aligned</alignment>\n" +
-                "<fidelity>\n" +
-                "<comments/>\n" +
-                "<dtd/>\n" +
-                "<lexical-values/>\n" +
-                "<pis/>\n" +
-                "<prefixes/>\n" +
-                "</fidelity>\n" +
-                "</start-exi>\n" +
-                "</rpc>";
+        final String fullOptionsXml = "<rpc xmlns:ns0=\"urn:ietf:params:xml:ns:netconf:base:1.0\" "
+                + "ns0:message-id=\"id\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<start-exi xmlns=\"urn:ietf:params:xml:ns:netconf:exi:1.0\">\n"
+                + "<alignment>byte-aligned</alignment>\n"
+                + "<fidelity>\n"
+                + "<comments/>\n"
+                + "<dtd/>\n"
+                + "<lexical-values/>\n"
+                + "<pis/>\n"
+                + "<prefixes/>\n"
+                + "</fidelity>\n"
+                + "</start-exi>\n"
+                + "</rpc>";
 
         final EXIOptions fullOptions = new EXIOptions();
         fullOptions.setAlignmentType(AlignmentType.byteAligned);
index 4f11465dd2e66bc4e138b3f63d8a93fe7effd616..f1806b43cef396659dea16e04f50aa9d6c19d8ed 100644 (file)
@@ -221,7 +221,8 @@ public class AsyncSshHandlerTest {
             @Override
             public void onSuccess(final SshFutureListener<IoReadFuture> result) {
                 doReturn(new IllegalStateException()).when(mockedReadFuture).getException();
-                doReturn(mockedReadFuture).when(mockedReadFuture).removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
+                doReturn(mockedReadFuture).when(mockedReadFuture)
+                        .removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
                 doReturn(true).when(asyncOut).isClosing();
                 doReturn(true).when(asyncOut).isClosed();
                 result.operationComplete(mockedReadFuture);
@@ -251,7 +252,8 @@ public class AsyncSshHandlerTest {
             @Override
             public void onSuccess(final SshFutureListener<IoReadFuture> result) {
                 doReturn(new IllegalStateException()).when(mockedReadFuture).getException();
-                doReturn(mockedReadFuture).when(mockedReadFuture).removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
+                doReturn(mockedReadFuture).when(mockedReadFuture)
+                        .removeListener(Matchers.<SshFutureListener<IoReadFuture>>any());
                 result.operationComplete(mockedReadFuture);
             }
         });
@@ -340,11 +342,14 @@ public class AsyncSshHandlerTest {
 
         final ChannelPromise firstWritePromise = getMockedPromise();
 
-        // intercept listener for first write, so we can invoke successful write later thus simulate pending of the first write
-        final ListenableFuture<SshFutureListener<IoWriteFuture>> firstWriteListenerFuture = stubAddListener(ioWriteFuture);
+        // intercept listener for first write,
+        // so we can invoke successful write later thus simulate pending of the first write
+        final ListenableFuture<SshFutureListener<IoWriteFuture>> firstWriteListenerFuture =
+                stubAddListener(ioWriteFuture);
         asyncSshHandler.write(ctx, Unpooled.copiedBuffer(new byte[]{0,1,2,3,4,5}), firstWritePromise);
         final SshFutureListener<IoWriteFuture> firstWriteListener = firstWriteListenerFuture.get();
-        // intercept second listener, this is the listener for pending write for the pending write to know when pending state ended
+        // intercept second listener,
+        // this is the listener for pending write for the pending write to know when pending state ended
         final ListenableFuture<SshFutureListener<IoWriteFuture>> pendingListener = stubAddListener(ioWriteFuture);
 
         final ChannelPromise secondWritePromise = getMockedPromise();
@@ -386,8 +391,10 @@ public class AsyncSshHandlerTest {
 
         final ChannelPromise firstWritePromise = getMockedPromise();
 
-        // intercept listener for first write, so we can invoke successful write later thus simulate pending of the first write
-        final ListenableFuture<SshFutureListener<IoWriteFuture>> firstWriteListenerFuture = stubAddListener(ioWriteFuture);
+        // intercept listener for first write,
+        // so we can invoke successful write later thus simulate pending of the first write
+        final ListenableFuture<SshFutureListener<IoWriteFuture>> firstWriteListenerFuture =
+                stubAddListener(ioWriteFuture);
         asyncSshHandler.write(ctx, Unpooled.copiedBuffer(new byte[]{0,1,2,3,4,5}), firstWritePromise);
 
         final ChannelPromise secondWritePromise = getMockedPromise();
@@ -464,7 +471,8 @@ public class AsyncSshHandlerTest {
         return sshSession;
     }
 
-    private ChannelSubsystem getMockedSubsystemChannel(final IoInputStream asyncOut, final IoOutputStream asyncIn) throws IOException {
+    private ChannelSubsystem getMockedSubsystemChannel(final IoInputStream asyncOut,
+                                                       final IoOutputStream asyncIn) throws IOException {
         final ChannelSubsystem subsystemChannel = mock(ChannelSubsystem.class);
         doReturn("subsystemChannel").when(subsystemChannel).toString();
 
@@ -597,14 +605,15 @@ public class AsyncSshHandlerTest {
         return spy(new DefaultChannelPromise(channel));
     }
 
-    private static abstract class SuccessFutureListener<T extends SshFuture<T>> implements FutureCallback<SshFutureListener<T>> {
+    private abstract static class SuccessFutureListener<T extends SshFuture<T>>
+            implements FutureCallback<SshFutureListener<T>> {
 
         @Override
-        public abstract void onSuccess(final SshFutureListener<T> result);
+        public abstract void onSuccess(SshFutureListener<T> result);
 
         @Override
-        public void onFailure(final Throwable t) {
-            throw new RuntimeException(t);
+        public void onFailure(final Throwable throwable) {
+            throw new RuntimeException(throwable);
         }
     }
 }
index 64caf33c6959481253324fa1e2b7b17761ae99b5..66f87fb69936f7d661035649f73e38275e02a168 100644 (file)
           <groupId>org.opendaylight.yangtools</groupId>
           <artifactId>yang-maven-plugin</artifactId>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index fca99e0b3c0e1f906abe237ecd1b87080d6c6e13..300e19f594368cd7d224fe7da4aa23dde88a81e0 100644 (file)
@@ -44,7 +44,8 @@ public class NetconfNorthboundSshServer {
         sshProxyServer = new SshProxyServer(Executors.newScheduledThreadPool(1), workerGroup, eventExecutor);
 
         final InetSocketAddress inetAddress = getInetAddress(bindingAddress, portNumber);
-        final SshProxyServerConfigurationBuilder sshProxyServerConfigurationBuilder = new SshProxyServerConfigurationBuilder();
+        final SshProxyServerConfigurationBuilder sshProxyServerConfigurationBuilder =
+                new SshProxyServerConfigurationBuilder();
         sshProxyServerConfigurationBuilder.setBindingAddress(inetAddress);
         sshProxyServerConfigurationBuilder.setLocalAddress(localAddress);
         sshProxyServerConfigurationBuilder.setAuthenticator(authProvider);
@@ -68,8 +69,9 @@ public class NetconfNorthboundSshServer {
 
     private InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) {
         try {
-            IpAddress ipAddress= IpAddressBuilder.getDefaultInstance(bindingAddress);
-            final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
+            IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress);
+            final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null
+                    ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue());
             return new InetSocketAddress(inetAd, Integer.valueOf(portNumber));
         } catch (final UnknownHostException e) {
             throw new IllegalArgumentException("Unable to bind netconf endpoint to address " + bindingAddress, e);
index 69dd6bc6f946a88b7a1203602dec8465e20739ae..b5a6355d2990c6c26926b6a3fae1280af89dce85 100644 (file)
@@ -39,6 +39,7 @@ import org.slf4j.LoggerFactory;
  * This command handles all netconf related rpc and forwards to delegate server.
  * Uses netty to make a local connection to delegate server.
  *
+ * <p>
  * Command is Apache Mina SSH terminology for objects handling ssh data.
  */
 public class RemoteNetconfCommand implements AsyncCommand, SessionAware {
@@ -105,24 +106,26 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware {
         final Bootstrap clientBootstrap = new Bootstrap();
         clientBootstrap.group(clientEventGroup).channel(LocalChannel.class);
 
-        clientBootstrap
-                .handler(new ChannelInitializer<LocalChannel>() {
-                    @Override
-                    public void initChannel(final LocalChannel ch) throws Exception {
-                        ch.pipeline().addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback));
-                    }
-                });
+        clientBootstrap.handler(new ChannelInitializer<LocalChannel>() {
+            @Override
+            public void initChannel(final LocalChannel ch) throws Exception {
+                ch.pipeline()
+                        .addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback));
+            }
+        });
         clientChannelFuture = clientBootstrap.connect(localAddress);
         clientChannelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
 
             @Override
             public void operationComplete(final ChannelFuture future) throws Exception {
-                if(future.isSuccess()) {
+                if (future.isSuccess()) {
                     clientChannel = clientChannelFuture.channel();
                 } else {
-                    LOG.warn("Unable to establish internal connection to netconf server for client: {}", getClientAddress());
+                    LOG.warn("Unable to establish internal connection to netconf server for client: {}",
+                            getClientAddress());
                     Preconditions.checkNotNull(callback, "Exit callback must be set");
-                    callback.onExit(1, "Unable to establish internal connection to netconf server for client: "+ getClientAddress());
+                    callback.onExit(1, "Unable to establish internal connection to netconf server for client: "
+                            + getClientAddress());
                 }
             }
         });
@@ -134,13 +137,14 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware {
                 getClientAddress(), clientChannel);
 
         clientChannelFuture.cancel(true);
-        if(clientChannel != null) {
+        if (clientChannel != null) {
             clientChannel.close().addListener(new GenericFutureListener<ChannelFuture>() {
 
                 @Override
                 public void operationComplete(final ChannelFuture future) throws Exception {
                     if (future.isSuccess() == false) {
-                        LOG.warn("Unable to release internal connection to netconf server on channel: {}", clientChannel);
+                        LOG.warn("Unable to release internal connection to netconf server on channel: {}",
+                                clientChannel);
                     }
                 }
             });
@@ -156,7 +160,7 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware {
         final SocketAddress remoteAddress = session.getIoSession().getRemoteAddress();
         String hostName = "";
         String port = "";
-        if(remoteAddress instanceof InetSocketAddress) {
+        if (remoteAddress instanceof InetSocketAddress) {
             hostName = ((InetSocketAddress) remoteAddress).getAddress().getHostAddress();
             port = Integer.toString(((InetSocketAddress) remoteAddress).getPort());
         }
index 66a337433878ab6f692c9de5c8a1ba23248bff93..2a198383a693c91b90b6f3faa7462d64772a2ac9 100644 (file)
@@ -22,7 +22,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * Netty handler that reads SSH from remote client and writes to delegate server and reads from delegate server and writes to remote client
+ * Netty handler that reads SSH from remote client and writes to delegate server
+ * and reads from delegate server and writes to remote client.
  */
 final class SshProxyClientHandler extends ChannelInboundHandlerAdapter {
 
@@ -37,9 +38,9 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter {
     private final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader;
     private final ExitCallback callback;
 
-    public SshProxyClientHandler(final IoInputStream in, final IoOutputStream out,
-                                 final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader,
-                                 final ExitCallback callback) {
+    SshProxyClientHandler(final IoInputStream in, final IoOutputStream out,
+                          final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader,
+                          final ExitCallback callback) {
         this.in = in;
         this.out = out;
         this.netconfHelloMessageAdditionalHeader = netconfHelloMessageAdditionalHeader;
@@ -64,9 +65,10 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter {
         }, new AsyncSshHandlerReader.ReadMsgHandler() {
             @Override
             public void onMessageRead(final ByteBuf msg) {
-                if(LOG.isTraceEnabled()) {
+                if (LOG.isTraceEnabled()) {
                     LOG.trace("Forwarding message for client: {} on channel: {}, message: {}",
-                            netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(), AsyncSshHandlerWriter.byteBufToString(msg));
+                            netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(),
+                            AsyncSshHandlerWriter.byteBufToString(msg));
                 }
                 // Just forward to delegate
                 ctx.writeAndFlush(msg);
@@ -90,8 +92,8 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter {
     public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
         LOG.debug("Internal connection to netconf server was dropped for client: {} on channel: ",
                 netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel());
-        callback.onExit(1, "Internal connection to netconf server was dropped for client: " +
-                netconfHelloMessageAdditionalHeader.getAddress() + " on channel: " + ctx.channel());
+        callback.onExit(1, "Internal connection to netconf server was dropped for client: "
+                netconfHelloMessageAdditionalHeader.getAddress() + " on channel: " + ctx.channel());
         super.channelInactive(ctx);
     }
 
index 9fa4bb33ab5592691bb2c08c028aaca116fdea53..ab8e22228b63efca2194e2fefdff455b09b98ab1 100644 (file)
@@ -52,10 +52,12 @@ public class SshProxyServer implements AutoCloseable {
     private final EventLoopGroup clientGroup;
     private final IoServiceFactoryFactory nioServiceWithPoolFactoryFactory;
 
-    public SshProxyServer(final ScheduledExecutorService minaTimerExecutor, final EventLoopGroup clientGroup, final ExecutorService nioExecutor) {
+    public SshProxyServer(final ScheduledExecutorService minaTimerExecutor,
+                          final EventLoopGroup clientGroup, final ExecutorService nioExecutor) {
         this.minaTimerExecutor = minaTimerExecutor;
         this.clientGroup = clientGroup;
-        this.nioServiceWithPoolFactoryFactory = new NioServiceWithPoolFactory.NioServiceWithPoolFactoryFactory(nioExecutor);
+        this.nioServiceWithPoolFactoryFactory =
+                new NioServiceWithPoolFactory.NioServiceWithPoolFactoryFactory(nioExecutor);
         this.sshServer = SshServer.setUpDefaultServer();
     }
 
@@ -86,7 +88,8 @@ public class SshProxyServer implements AutoCloseable {
         sshServer.setProperties(getProperties(sshProxyServerConfiguration));
 
         final RemoteNetconfCommand.NetconfCommandFactory netconfCommandFactory =
-                new RemoteNetconfCommand.NetconfCommandFactory(clientGroup, sshProxyServerConfiguration.getLocalAddress());
+                new RemoteNetconfCommand.NetconfCommandFactory(clientGroup,
+                        sshProxyServerConfiguration.getLocalAddress());
         sshServer.setSubsystemFactories(ImmutableList.of(netconfCommandFactory));
         sshServer.start();
     }
@@ -112,14 +115,15 @@ public class SshProxyServer implements AutoCloseable {
     }
 
     /**
-     * Based on Nio2ServiceFactory with one addition: injectable executor
+     * Based on Nio2ServiceFactory with one addition: injectable executor.
      */
-    private static final class NioServiceWithPoolFactory extends CloseableUtils.AbstractCloseable implements IoServiceFactory {
+    private static final class NioServiceWithPoolFactory
+            extends CloseableUtils.AbstractCloseable implements IoServiceFactory {
 
         private final FactoryManager manager;
         private final AsynchronousChannelGroup group;
 
-        public NioServiceWithPoolFactory(final FactoryManager manager, final ExecutorService executor) {
+        NioServiceWithPoolFactory(final FactoryManager manager, final ExecutorService executor) {
             this.manager = manager;
             try {
                 group = AsynchronousChannelGroup.withThreadPool(executor);
@@ -138,6 +142,7 @@ public class SshProxyServer implements AutoCloseable {
             return new Nio2Acceptor(manager, handler, group);
         }
 
+        @SuppressWarnings("checkstyle:IllegalCatch")
         @Override
         protected void doCloseImmediately() {
             try {
index 55b54862d2e2abcea38ba1bc61ba3a00f1e3dfc0..9fe57a40b692105fcaa2568dba7446c160ad5dd6 100644 (file)
@@ -21,7 +21,8 @@ public final class SshProxyServerConfiguration {
     private final KeyPairProvider keyPairProvider;
     private final int idleTimeout;
 
-    SshProxyServerConfiguration(final InetSocketAddress bindingAddress, final LocalAddress localAddress, final AuthProvider authenticator, final KeyPairProvider keyPairProvider, final int idleTimeout) {
+    SshProxyServerConfiguration(final InetSocketAddress bindingAddress, final LocalAddress localAddress,
+                    final AuthProvider authenticator, final KeyPairProvider keyPairProvider, final int idleTimeout) {
         this.bindingAddress = Preconditions.checkNotNull(bindingAddress);
         this.localAddress = Preconditions.checkNotNull(localAddress);
         this.authenticator = Preconditions.checkNotNull(authenticator);
index 14b00b462d93c6942f413fc4551f16e7cf832117..5b7948ed6fde4a803e10e2a96c2cbafd19d9224a 100644 (file)
@@ -46,7 +46,8 @@ public final class SshProxyServerConfigurationBuilder {
     }
 
     public SshProxyServerConfiguration createSshProxyServerConfiguration() {
-        return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, keyPairProvider, idleTimeout);
+        return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator,
+                keyPairProvider, idleTimeout);
     }
 
     public static SshProxyServerConfigurationBuilder create() {
index 51be1bc3eae126e1e1204d2ef626fcb3433366cc..124e7e7ac16948c80331e3cb0fd8e32a309a86d6 100644 (file)
@@ -24,7 +24,7 @@ final class AuthProviderTracker implements ServiceTrackerCustomizer<AuthProvider
     private final ServiceTracker<AuthProvider, AuthProvider> listenerTracker;
     private volatile AuthProvider authProvider;
 
-    public AuthProviderTracker(final BundleContext bundleContext) {
+    AuthProviderTracker(final BundleContext bundleContext) {
         this.bundleContext = bundleContext;
         listenerTracker = new ServiceTracker<>(bundleContext, AuthProvider.class, this);
         listenerTracker.open();
index fddbc7389b3ec85ac70bc6a237fcd777bd80a170..f31f7b95b1ed93cb0d81e202ee5b5ab99f5f54da 100644 (file)
@@ -46,8 +46,8 @@ public class NetconfSSHActivator implements BundleActivator {
     public void start(final BundleContext bundleContext) throws IOException, InvalidSyntaxException {
         minaTimerExecutor = Executors.newScheduledThreadPool(POOL_SIZE, new ThreadFactory() {
             @Override
-            public Thread newThread(final Runnable r) {
-                return new Thread(r, "netconf-ssh-server-mina-timers");
+            public Thread newThread(final Runnable runnable) {
+                return new Thread(runnable, "netconf-ssh-server-mina-timers");
             }
         });
         clientGroup = new NioEventLoopGroup();
@@ -61,19 +61,19 @@ public class NetconfSSHActivator implements BundleActivator {
             server.close();
         }
 
-        if(authProviderTracker != null) {
+        if (authProviderTracker != null) {
             authProviderTracker.stop();
         }
 
-        if(nioExecutor!=null) {
+        if (nioExecutor != null) {
             nioExecutor.shutdownNow();
         }
 
-        if(clientGroup != null) {
+        if (clientGroup != null) {
             clientGroup.shutdownGracefully();
         }
 
-        if(minaTimerExecutor != null) {
+        if (minaTimerExecutor != null) {
             minaTimerExecutor.shutdownNow();
         }
     }
index c8584a7ed8cb608aa34279aba1e866ea37fe34c4..2cdd97c9f90994a47472439a9320ad151a3a92b6 100644 (file)
@@ -45,23 +45,24 @@ public class EchoClient extends Thread {
         this.channelInitializer = channelInitializer;
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public void run() {
         // Configure the client.
         EventLoopGroup group = new NioEventLoopGroup();
         try {
-            Bootstrap b = new Bootstrap();
+            Bootstrap bootstrap = new Bootstrap();
 
-            b.group(group)
+            bootstrap.group(group)
                     .channel(LocalChannel.class)
                     .handler(channelInitializer);
 
             // Start the client.
             LocalAddress localAddress = new LocalAddress("foo");
-            ChannelFuture f = b.connect(localAddress).sync();
+            ChannelFuture future = bootstrap.connect(localAddress).sync();
 
             // Wait until the connection is closed.
-            f.channel().closeFuture().sync();
+            future.channel().closeFuture().sync();
         } catch (Exception e) {
             LOG.error("Error in client", e);
             throw new RuntimeException("Error in client", e);
index 5d571a5caad660d9c21db1db0f407c2f76e99ce7..2a94d38161e9763322e5b77b80f0f2174c9cad4f 100644 (file)
@@ -31,7 +31,9 @@ public class EchoClientHandler extends ChannelInboundHandlerAdapter implements C
     private ChannelHandlerContext ctx;
     private final StringBuilder fromServer = new StringBuilder();
 
-    public static enum State {CONNECTING, CONNECTED, FAILED_TO_CONNECT, CONNECTION_CLOSED}
+    public enum State {
+        CONNECTING, CONNECTED, FAILED_TO_CONNECT, CONNECTION_CLOSED
+    }
 
 
     private State state = State.CONNECTING;
index a6f9e6cb66595bd0616c35774684571fe683a11b..c660ffd02b0f0643b4a4e088fdaa07c797f589f5 100644 (file)
@@ -31,13 +31,14 @@ import org.slf4j.LoggerFactory;
 public class EchoServer implements Runnable {
     private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class);
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public void run() {
         // Configure the server.
         EventLoopGroup bossGroup = new NioEventLoopGroup(1);
         EventLoopGroup workerGroup = new NioEventLoopGroup();
         try {
-            ServerBootstrap b = new ServerBootstrap();
-            b.group(bossGroup, workerGroup)
+            ServerBootstrap bootstrap = new ServerBootstrap();
+            bootstrap.group(bossGroup, workerGroup)
                     .channel(LocalServerChannel.class)
                     .option(ChannelOption.SO_BACKLOG, 100)
                     .handler(new LoggingHandler(LogLevel.INFO))
@@ -50,10 +51,10 @@ public class EchoServer implements Runnable {
 
             // Start the server.
             LocalAddress localAddress = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
-            ChannelFuture f = b.bind(localAddress).sync();
+            ChannelFuture future = bootstrap.bind(localAddress).sync();
 
             // Wait until the server socket is closed.
-            f.channel().closeFuture().sync();
+            future.channel().closeFuture().sync();
         } catch (Exception e) {
             throw new RuntimeException(e);
         } finally {
index 38634280ffd8ca5f506c01c0abffab5c5e84e464..632d207ea7e76a61438027089432be8503a90cb6 100644 (file)
@@ -26,6 +26,7 @@ public class EchoServerHandler extends ChannelInboundHandlerAdapter {
     private static final Logger LOG = LoggerFactory.getLogger(EchoServerHandler.class);
     private String fromLastNewLine = "";
     private final Splitter splitter = Splitter.onPattern("\r?\n");
+
     @Override
     public void channelActive(ChannelHandlerContext ctx) throws Exception {
         LOG.debug("sleep start");
diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyClientHandler.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyClientHandler.java
new file mode 100644 (file)
index 0000000..dd1daed
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.netconf.netty;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+import java.nio.charset.StandardCharsets;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ProxyClientHandler extends ChannelInboundHandlerAdapter {
+    private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class);
+
+    private final ChannelHandlerContext remoteCtx;
+
+
+    ProxyClientHandler(ChannelHandlerContext remoteCtx) {
+        this.remoteCtx = remoteCtx;
+    }
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) {
+        LOG.info("client active");
+    }
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) {
+        ByteBuf bb = (ByteBuf) msg;
+        LOG.info(">{}", bb.toString(StandardCharsets.UTF_8));
+        remoteCtx.write(msg);
+    }
+
+    @Override
+    public void channelReadComplete(ChannelHandlerContext ctx) {
+        LOG.debug("Flushing server ctx");
+        remoteCtx.flush();
+    }
+
+    @Override
+    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
+        // Close the connection when an exception is raised.
+        LOG.warn("Unexpected exception from downstream", cause);
+        ctx.close();
+    }
+
+    // called both when local or remote connection dies
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) {
+        LOG.debug("channelInactive() called, closing remote client ctx");
+        remoteCtx.close();
+    }
+}
index ee34f8fd2f1ad2acbf4a746f1794bc140513563d..3b693512ea659ec1ae227f3a8f6cec8b903989fa 100644 (file)
@@ -30,6 +30,7 @@ public class ProxyServer implements Runnable {
         this.proxyHandlerFactory = proxyHandlerFactory;
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public void run() {
         // Configure the server.
         final EventLoopGroup bossGroup = new NioEventLoopGroup();
@@ -50,10 +51,10 @@ public class ProxyServer implements Runnable {
 
             // Start the server.
             InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080);
-            ChannelFuture f = serverBootstrap.bind(address).sync();
+            ChannelFuture future = serverBootstrap.bind(address).sync();
 
             // Wait until the server socket is closed.
-            f.channel().closeFuture().sync();
+            future.channel().closeFuture().sync();
         } catch (Exception e) {
             throw new RuntimeException(e);
         } finally {
@@ -62,7 +63,8 @@ public class ProxyServer implements Runnable {
             workerGroup.shutdownGracefully();
         }
     }
-    public static interface ProxyHandlerFactory {
+
+    public interface ProxyHandlerFactory {
         ChannelHandler create(EventLoopGroup bossGroup, LocalAddress localAddress);
     }
 
index dc879c233229f0755dd138f12a1eba034f26767b..c70efcdb34eea40e787f9d3e9e5b5c19776aeed2 100644 (file)
@@ -9,7 +9,6 @@
 package org.opendaylight.netconf.netty;
 
 import io.netty.bootstrap.Bootstrap;
-import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
@@ -19,7 +18,6 @@ import io.netty.channel.ChannelInitializer;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.local.LocalAddress;
 import io.netty.channel.local.LocalChannel;
-import java.nio.charset.StandardCharsets;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -77,45 +75,3 @@ public class ProxyServerHandler extends ChannelInboundHandlerAdapter {
     }
 }
 
-class ProxyClientHandler extends ChannelInboundHandlerAdapter {
-    private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class);
-
-    private final ChannelHandlerContext remoteCtx;
-
-
-    public ProxyClientHandler(ChannelHandlerContext remoteCtx) {
-        this.remoteCtx = remoteCtx;
-    }
-
-    @Override
-    public void channelActive(ChannelHandlerContext ctx) {
-        LOG.info("client active");
-    }
-
-    @Override
-    public void channelRead(ChannelHandlerContext ctx, Object msg) {
-        ByteBuf bb = (ByteBuf) msg;
-        LOG.info(">{}", bb.toString(StandardCharsets.UTF_8));
-        remoteCtx.write(msg);
-    }
-
-    @Override
-    public void channelReadComplete(ChannelHandlerContext ctx) {
-        LOG.debug("Flushing server ctx");
-        remoteCtx.flush();
-    }
-
-    @Override
-    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
-        // Close the connection when an exception is raised.
-        LOG.warn("Unexpected exception from downstream", cause);
-        ctx.close();
-    }
-
-    // called both when local or remote connection dies
-    @Override
-    public void channelInactive(ChannelHandlerContext ctx) {
-        LOG.debug("channelInactive() called, closing remote client ctx");
-        remoteCtx.close();
-    }
-}
index 759b96210bdd068c05f1a6309b223c3d026e40ab..3b1a6950280d2722df43f36ff9ca3148b3c3dee9 100644 (file)
@@ -73,18 +73,21 @@ public class SSHTest {
 
         final InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10831);
         final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerEx, nettyGroup, nioExec);
-        sshProxyServer.bind(
-                new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() {
-                    @Override
-                    public boolean authenticated(final String username, final String password) {
-                        return true;
-                    }
-                }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
+        sshProxyServer.bind(new SshProxyServerConfigurationBuilder()
+                .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS)
+                .setAuthenticator(new AuthProvider() {
+                        @Override
+                        public boolean authenticated(final String username, final String password) {
+                            return true;
+                        }
+                })
+                .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString()))
+                .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
 
         final EchoClientHandler echoClientHandler = connectClient(addr);
 
         Stopwatch stopwatch = Stopwatch.createStarted();
-        while(echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
+        while (echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) {
             Thread.sleep(500);
         }
         assertTrue(echoClientHandler.isConnected());
@@ -131,7 +134,7 @@ public class SSHTest {
         final InetSocketAddress address = new InetSocketAddress(12345);
         final EchoClientHandler echoClientHandler = connectClient(address);
         final Stopwatch stopwatch = Stopwatch.createStarted();
-        while(echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) {
+        while (echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) {
             Thread.sleep(100);
         }
         assertFalse(echoClientHandler.isConnected());
index 1257e4b7e923f4bed84ac260b7f3e883c5d7db05..7af4598997cc6254906f387fa7d809f8c0092ee0 100644 (file)
@@ -72,13 +72,16 @@ public class SSHServerTest {
 
         final InetSocketAddress addr = InetSocketAddress.createUnresolved(HOST, PORT);
         server = new SshProxyServer(minaTimerEx, clientGroup, nioExec);
-        server.bind(
-                new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() {
+        server.bind(new SshProxyServerConfigurationBuilder()
+                .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS)
+                .setAuthenticator(new AuthProvider() {
                     @Override
                     public boolean authenticated(final String username, final String password) {
                         return true;
                     }
-                }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
+                })
+                .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString()))
+                .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration());
         LOG.info("SSH server started on {}", PORT);
     }
 
index 734461ac9c00c14abd980958f119dd5095f8405d..0ca6325f6293308ff8a11582173d713c4b33770a 100644 (file)
@@ -41,6 +41,7 @@ import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySet
 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup.NetconfTopologySetupBuilder;
 import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopologyBuilder;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
@@ -83,9 +84,9 @@ public class NetconfTopologyManager
                                   final ClusterSingletonServiceProvider clusterSingletonServiceProvider,
                                   final BindingAwareBroker bindingAwareBroker,
                                   final ScheduledThreadPool keepaliveExecutor, final ThreadPool processingExecutor,
-                                  final Broker domBroker, final ActorSystemProvider actorSystemProvider, final EventExecutor eventExecutor,
-                                  final NetconfClientDispatcher clientDispatcher, final String topologyId,
-                                  final int writeTxIdleTimeout) {
+                                  final Broker domBroker, final ActorSystemProvider actorSystemProvider,
+                                  final EventExecutor eventExecutor, final NetconfClientDispatcher clientDispatcher,
+                                  final String topologyId, final Config config) {
         this.dataBroker = Preconditions.checkNotNull(dataBroker);
         this.rpcProviderRegistry = Preconditions.checkNotNull(rpcProviderRegistry);
         this.clusterSingletonServiceProvider = Preconditions.checkNotNull(clusterSingletonServiceProvider);
@@ -97,7 +98,7 @@ public class NetconfTopologyManager
         this.eventExecutor = Preconditions.checkNotNull(eventExecutor);
         this.clientDispatcher = Preconditions.checkNotNull(clientDispatcher);
         this.topologyId = Preconditions.checkNotNull(topologyId);
-        this.writeTxIdleTimeout = Duration.apply(writeTxIdleTimeout, TimeUnit.SECONDS);
+        this.writeTxIdleTimeout = Duration.apply(config.getWriteTransactionIdleTimeout(), TimeUnit.SECONDS);
     }
 
     // Blueprint init method
index 8dd5e39d1e57078d92a656173a8b2038bc5fa09c..fbd0422b692c66129f336dbb0f38bd8440ef31fe 100644 (file)
@@ -17,6 +17,7 @@ import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import java.io.IOException;
 import java.util.List;
+import java.util.stream.Collectors;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
@@ -59,6 +60,7 @@ import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceFilter;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
+import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -81,6 +83,7 @@ public class NetconfNodeActor extends UntypedActor {
     private DOMDataBroker deviceDataBroker;
     //readTxActor can be shared
     private ActorRef readTxActor;
+    private List<SchemaSourceRegistration<YangTextSchemaSource>> registeredSchemas;
 
     public static Props props(final NetconfTopologySetup setup,
                               final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
@@ -162,6 +165,11 @@ public class NetconfNodeActor extends UntypedActor {
         }
     }
 
+    @Override
+    public void postStop() throws Exception {
+        super.postStop();
+        closeSchemaSourceRegistrations();
+    }
 
     private void sendYangTextSchemaSourceProxy(final SourceIdentifier sourceIdentifier, final ActorRef sender) {
         final CheckedFuture<YangTextSchemaSource, SchemaSourceException> yangTextSchemaSource =
@@ -216,6 +224,7 @@ public class NetconfNodeActor extends UntypedActor {
         if (this.slaveSalManager != null) {
             slaveSalManager.close();
         }
+        closeSchemaSourceRegistrations();
         slaveSalManager = new SlaveSalFacade(id, setup.getDomBroker(), setup.getActorSystem(), actorResponseWaitTime);
 
         final CheckedFuture<SchemaContext, SchemaResolutionException> remoteSchemaContext =
@@ -247,9 +256,11 @@ public class NetconfNodeActor extends UntypedActor {
         final RemoteSchemaProvider remoteProvider = new RemoteSchemaProvider(remoteYangTextSourceProvider,
                 getContext().dispatcher());
 
-        sourceIdentifiers.forEach(sourceId ->
-                schemaRegistry.registerSchemaSource(remoteProvider, PotentialSchemaSource.create(sourceId,
-                        YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())));
+        registeredSchemas = sourceIdentifiers.stream()
+                .map(sourceId ->
+                        schemaRegistry.registerSchemaSource(remoteProvider, PotentialSchemaSource.create(sourceId,
+                                YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue())))
+                .collect(Collectors.toList());
 
         final SchemaContextFactory schemaContextFactory
                 = schemaRepository.createSchemaContextFactory(SchemaSourceFilter.ALWAYS_ACCEPT);
@@ -257,4 +268,11 @@ public class NetconfNodeActor extends UntypedActor {
         return schemaContextFactory.createSchemaContext(sourceIdentifiers);
     }
 
+    private void closeSchemaSourceRegistrations() {
+        if (registeredSchemas != null) {
+            registeredSchemas.forEach(SchemaSourceRegistration::close);
+            registeredSchemas = null;
+        }
+    }
+
 }
index 0997ea5af2daa94ee7114a4079f7564946ac94f1..977018f62c57d8689f0f81042e76e3814062137d 100644 (file)
@@ -35,6 +35,10 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
     <reference id="clientDispatcherDependency"
                interface="org.opendaylight.netconf.client.NetconfClientDispatcher"
                odl:type="netconf-client-dispatcher"/>
+    <odl:clustered-app-config
+            id="singletonConfig"
+            binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config"
+    />
 
     <bean id="netconfTopologyManager"
           class="org.opendaylight.netconf.topology.singleton.impl.NetconfTopologyManager"
@@ -50,7 +54,7 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
         <argument ref="eventExecutor"/>
         <argument ref="clientDispatcherDependency"/>
         <argument value="topology-netconf"/>
-        <argument value="0"/>
+        <argument ref="singletonConfig"/>
     </bean>
     <service ref="netconfTopologyManager"
              interface="org.opendaylight.netconf.topology.singleton.api.NetconfTopologySingletonService"/>
diff --git a/netconf/netconf-topology-singleton/src/main/yang/netconf-clustered-topology-config.yang b/netconf/netconf-topology-singleton/src/main/yang/netconf-clustered-topology-config.yang
new file mode 100644 (file)
index 0000000..b8cf643
--- /dev/null
@@ -0,0 +1,22 @@
+module netconf-clustered-topology-config {
+    yang-version 1;
+    namespace "urn:opendaylight:netconf:topology:singleton:config";
+    prefix nctc;
+
+    description
+      "Configuration for Netconf Clustered Topology";
+
+    revision "2017-04-19" {
+        description
+            "Initial revision.";
+    }
+
+    container config {
+        leaf write-transaction-idle-timeout {
+            type uint16;
+            default 0;
+            description "Idle time in seconds after which write transaction is cancelled
+            automatically. If 0, automatic cancellation is turned off.";
+        }
+    }
+}
\ No newline at end of file
index b17b8daa704c46575f5ce05141020f9043942782..02e4440dc2a67ab8ed8528f47afca50c3fa1f027 100644 (file)
@@ -12,8 +12,11 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.argThat;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
 import static org.mockito.MockitoAnnotations.initMocks;
 import static org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils.DEFAULT_SCHEMA_REPOSITORY;
 
@@ -27,9 +30,11 @@ import akka.testkit.TestActorRef;
 import akka.util.Timeout;
 import com.google.common.base.MoreObjects;
 import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.SettableFuture;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -43,6 +48,7 @@ import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
+import org.mockito.ArgumentMatcher;
 import org.mockito.Mock;
 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
@@ -50,6 +56,7 @@ import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
+import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
 import org.opendaylight.netconf.topology.singleton.impl.utils.ClusteringRpcException;
@@ -66,13 +73,19 @@ 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.ImmutableNodes;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
+import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
+import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
+import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
 import scala.concurrent.Await;
 import scala.concurrent.Future;
 import scala.concurrent.duration.Duration;
@@ -175,6 +188,39 @@ public class NetconfNodeActorTest {
 
     }
 
+    @Test
+    public void testReceiveRegisterMountpoint() throws Exception {
+        final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
+        doReturn(mock(Broker.class)).when(setup).getDomBroker();
+        final RevisionSourceIdentifier yang1 = RevisionSourceIdentifier.create("yang1");
+        final RevisionSourceIdentifier yang2 = RevisionSourceIdentifier.create("yang2");
+        final SchemaSourceRegistry registry = mock(SchemaSourceRegistry.class);
+        final SchemaRepository schemaRepository = mock(SchemaRepository.class);
+        final SchemaSourceRegistration regYang1 = mock(SchemaSourceRegistration.class);
+        final SchemaSourceRegistration regYang2 = mock(SchemaSourceRegistration.class);
+        doReturn(regYang1).when(registry).registerSchemaSource(any(), withSourceId(yang1));
+        doReturn(regYang2).when(registry).registerSchemaSource(any(), withSourceId(yang2));
+        final SchemaContextFactory schemaContextFactory = mock(SchemaContextFactory.class);
+        doReturn(schemaContextFactory).when(schemaRepository).createSchemaContextFactory(any());
+        final SettableFuture<SchemaContext> schemaContextFuture = SettableFuture.create();
+        final CheckedFuture<SchemaContext, SchemaResolutionException> checkedFuture =
+                Futures.makeChecked(schemaContextFuture, e -> new SchemaResolutionException("fail", e));
+        doReturn(checkedFuture).when(schemaContextFactory).createSchemaContext(any());
+        final ActorRef slaveRef =
+                system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, registry, schemaRepository, TIMEOUT));
+        final List<SourceIdentifier> sources = ImmutableList.of(yang1, yang2);
+        slaveRef.tell(new RegisterMountPoint(sources), masterRef);
+
+        verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang1));
+        verify(registry, timeout(1000)).registerSchemaSource(any(), withSourceId(yang2));
+        //stop actor
+        final Future<Boolean> stopFuture = Patterns.gracefulStop(slaveRef, TIMEOUT.duration());
+        Await.result(stopFuture, TIMEOUT.duration());
+        //provider should be deregistered
+        verify(regYang1).close();
+        verify(regYang2).close();
+    }
+
     @Test
     public void testYangTextSchemaSourceRequestMessage() throws Exception {
         final SchemaRepository schemaRepository = mock(SchemaRepository.class);
@@ -325,6 +371,16 @@ public class NetconfNodeActorTest {
 
     }
 
+    private PotentialSchemaSource<?> withSourceId(final SourceIdentifier identifier) {
+        return argThat(new ArgumentMatcher<PotentialSchemaSource>() {
+            @Override
+            public boolean matches(final Object argument) {
+                final PotentialSchemaSource potentialSchemaSource = (PotentialSchemaSource) argument;
+                return identifier.equals(potentialSchemaSource.getSourceIdentifier());
+            }
+        });
+    }
+
     private String convertStreamToString(final java.io.InputStream is) {
         final java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
         return s.hasNext() ? s.next() : "";
index 99ef75f2a4a488b304269a0c1a061bf09b1d8a17..060ed0e987c964b666864add576c872dafc26773 100644 (file)
@@ -53,6 +53,8 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
 import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder;
@@ -84,9 +86,10 @@ public class NetconfTopologyManagerTest {
         final EventExecutor eventExecutor = mock(EventExecutor.class);
         final NetconfClientDispatcher clientDispatcher = mock(NetconfClientDispatcher.class);
 
+        final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build();
         netconfTopologyManager = new NetconfTopologyManager(dataBroker, rpcProviderRegistry,
                 clusterSingletonServiceProvider, bindingAwareBroker, keepaliveExecutor, processingExecutor, domBroker,
-                actorSystemProvider, eventExecutor, clientDispatcher, topologyId, 0);
+                actorSystemProvider, eventExecutor, clientDispatcher, topologyId, config);
     }
 
     @Test
index 6e8c024d15d44133d8700f77d62b915af650da29..9e30e953200fdcf6872aee20f659fb4ec9ec889a 100644 (file)
           </execution>
         </executions>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index cff8b2a890c5f6d8e547da3f817bb9936f759792..1067da9d91a619dfad978dd8b3b44945e551b57e 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.netconf.util;
 
 public class CloseableUtil {
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public static void closeAll(Iterable<? extends AutoCloseable> autoCloseables) throws Exception {
         Exception lastException = null;
         for (AutoCloseable autoCloseable : autoCloseables) {
index 0e8b9aeec4592b0f98dc5a4d719db0e44933c7c4..d81e5c9be72c37df19bcb7c69b3c240c41308991 100644 (file)
@@ -52,18 +52,22 @@ public final class NetconfUtil {
                 + XmlUtil.toString(response));
     }
 
-    public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext context)
+    @SuppressWarnings("checkstyle:IllegalCatch")
+    public static void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result,
+                                           final SchemaPath schemaPath, final SchemaContext context)
             throws IOException, XMLStreamException {
         final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result);
         try (
-             final NormalizedNodeStreamWriter normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
-             final NormalizedNodeWriter normalizedNodeWriter =  NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
+             NormalizedNodeStreamWriter normalizedNodeStreamWriter =
+                     XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
+             NormalizedNodeWriter normalizedNodeWriter =
+                     NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter)
         ) {
             normalizedNodeWriter.write(normalized);
             normalizedNodeWriter.flush();
         } finally {
             try {
-                if(writer != null) {
+                if (writer != null) {
                     writer.close();
                 }
             } catch (final Exception e) {
index 32d6d79cc2cf65b330e72c7deb6f52c100df3a90..e66e59f3e7ebddacf65820a8d4daf088f2eb3a95 100644 (file)
@@ -23,8 +23,9 @@ public abstract class AbstractLastNetconfOperation extends AbstractNetconfOperat
     @Override
     protected Element handle(final Document document, final XmlElement operationElement,
                              final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
-        if (!subsequentOperation.isExecutionTermination()){
-            throw new DocumentedException(String.format("No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation),
+        if (!subsequentOperation.isExecutionTermination()) {
+            throw new DocumentedException(String.format(
+                    "No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation),
                     DocumentedException.ErrorType.APPLICATION,
                     DocumentedException.ErrorTag.MALFORMED_MESSAGE,
                     DocumentedException.ErrorSeverity.ERROR);
@@ -38,5 +39,6 @@ public abstract class AbstractLastNetconfOperation extends AbstractNetconfOperat
         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
     }
 
-    protected abstract Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException;
+    protected abstract Element handleWithNoSubsequentOperations(Document document,
+                                                                XmlElement operationElement) throws DocumentedException;
 }
index 6a4d2ae50422d45c373aae858409b63021dca6e9..4d988112eae8ad078b426e781015cc46eb6ae7fe 100644 (file)
@@ -41,8 +41,16 @@ public abstract class AbstractNetconfOperation implements NetconfOperation {
         return canHandle(operationNameAndNamespace.getOperationName(), operationNameAndNamespace.getNamespace());
     }
 
+    protected HandlingPriority canHandle(final String operationName, final String operationNamespace) {
+        return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace())
+                ? getHandlingPriority()
+                : HandlingPriority.CANNOT_HANDLE;
+    }
+
     public static final class OperationNameAndNamespace {
-        private final String operationName, namespace;
+        private final String operationName;
+        private final String namespace;
+
         private final XmlElement operationElement;
 
         public OperationNameAndNamespace(final Document message) throws DocumentedException {
@@ -64,6 +72,7 @@ public abstract class AbstractNetconfOperation implements NetconfOperation {
         public XmlElement getOperationElement() {
             return operationElement;
         }
+
     }
 
     protected static XmlElement getRequestElementWithCheck(final Document message) throws DocumentedException {
@@ -71,12 +80,6 @@ public abstract class AbstractNetconfOperation implements NetconfOperation {
                 XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
     }
 
-    protected HandlingPriority canHandle(final String operationName, final String operationNamespace) {
-        return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace())
-                ? getHandlingPriority()
-                : HandlingPriority.CANNOT_HANDLE;
-    }
-
     protected HandlingPriority getHandlingPriority() {
         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
     }
@@ -99,14 +102,16 @@ public abstract class AbstractNetconfOperation implements NetconfOperation {
         Map<String, Attr> attributes = requestElement.getAttributes();
 
         Element response = handle(document, operationElement, subsequentOperation);
-        Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+        Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY,
+                Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
 
-        if(XmlElement.fromDomElement(response).hasNamespace()) {
+        if (XmlElement.fromDomElement(response).hasNamespace()) {
             rpcReply.appendChild(response);
         } else {
-            Element responseNS = XmlUtil.createElement(document, response.getNodeName(), Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+            Element responseNS = XmlUtil.createElement(document, response.getNodeName(),
+                    Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
             NodeList list = response.getChildNodes();
-            while(list.getLength()!=0) {
+            while (list.getLength() != 0) {
                 responseNS.appendChild(list.item(0));
             }
             rpcReply.appendChild(responseNS);
@@ -119,7 +124,8 @@ public abstract class AbstractNetconfOperation implements NetconfOperation {
         return document;
     }
 
-    protected abstract Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation)
+    protected abstract Element handle(Document document, XmlElement message,
+                                      NetconfOperationChainedExecution subsequentOperation)
             throws DocumentedException;
 
     @Override
@@ -127,7 +133,7 @@ public abstract class AbstractNetconfOperation implements NetconfOperation {
         final StringBuffer sb = new StringBuffer(getClass().getName());
         try {
             sb.append("{name=").append(getOperationName());
-        } catch(UnsupportedOperationException e) {
+        } catch (UnsupportedOperationException e) {
             // no problem
         }
         sb.append(", namespace=").append(getOperationNamespace());
index b85a0ad3a869b119d5aa6e28420d2eb51edd2b7b..ae7d7472e94217191d0b8303ed4f5707a96c32ae 100644 (file)
@@ -13,11 +13,15 @@ package org.opendaylight.netconf.util.messages;
  */
 public enum FramingMechanism {
     /**
+     * Chunked framing mechanism.
+     *
      * @see <a href="http://tools.ietf.org/html/rfc6242#section-4.2">Chunked
      *      framing mechanism</a>
      */
     CHUNK,
     /**
+     * End-of-Message framing mechanism.
+     *
      * @see <a
      *      href="http://tools.ietf.org/html/rfc6242#section-4.3">End-of-message
      *      framing mechanism</a>
index 021ba009fac88a9980b7da6a5ede96043d5e29fd..995f6a47d02716492469f8953f0b3844513c6cd2 100644 (file)
@@ -38,7 +38,7 @@ public final class NetconfMessageUtil {
     }
 
     public static boolean isOKMessage(XmlElement xmlElement) throws NetconfDocumentedException {
-        if(xmlElement.getChildElements().size() != 1) {
+        if (xmlElement.getChildElements().size() != 1) {
             return false;
         }
         try {
@@ -57,7 +57,7 @@ public final class NetconfMessageUtil {
     }
 
     public static boolean isErrorMessage(XmlElement xmlElement) throws NetconfDocumentedException {
-        if(xmlElement.getChildElements().size() != 1) {
+        if (xmlElement.getChildElements().size() != 1) {
             return false;
         }
         try {
index 8b72bb836b90d61d78419dd659572c8c7e5bbf38..4768fad00ecea66354528281f700e8ff74f3afe5 100644 (file)
@@ -34,15 +34,15 @@ public final class SendErrorExceptionUtil {
             final DocumentedException sendErrorException) {
         LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException);
         final Document errorDocument = createDocument(sendErrorException);
-        ChannelFuture f = session.sendMessage(new NetconfMessage(errorDocument));
-        f.addListener(new SendErrorVerifyingListener(sendErrorException));
+        ChannelFuture channelFuture = session.sendMessage(new NetconfMessage(errorDocument));
+        channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException));
     }
 
     public static void sendErrorMessage(final Channel channel, final DocumentedException sendErrorException) {
         LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException);
         final Document errorDocument = createDocument(sendErrorException);
-        ChannelFuture f = channel.writeAndFlush(new NetconfMessage(errorDocument));
-        f.addListener(new SendErrorVerifyingListener(sendErrorException));
+        ChannelFuture channelFuture = channel.writeAndFlush(new NetconfMessage(errorDocument));
+        channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException));
     }
 
     public static void sendErrorMessage(final NetconfSession session, final DocumentedException sendErrorException,
@@ -53,20 +53,21 @@ public final class SendErrorExceptionUtil {
         }
 
         tryToCopyAttributes(incommingMessage.getDocument(), errorDocument, sendErrorException);
-        ChannelFuture f = session.sendMessage(new NetconfMessage(errorDocument));
-        f.addListener(new SendErrorVerifyingListener(sendErrorException));
+        ChannelFuture channelFuture = session.sendMessage(new NetconfMessage(errorDocument));
+        channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException));
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     private static void tryToCopyAttributes(final Document incommingDocument, final Document errorDocument,
             final DocumentedException sendErrorException) {
         try {
             final Element incommingRpc = incommingDocument.getDocumentElement();
-            Preconditions.checkState(incommingRpc.getTagName().equals(XmlNetconfConstants.RPC_KEY), "Missing %s element",
-                    XmlNetconfConstants.RPC_KEY);
+            Preconditions.checkState(incommingRpc.getTagName().equals(XmlNetconfConstants.RPC_KEY),
+                    "Missing %s element", XmlNetconfConstants.RPC_KEY);
 
             final Element rpcReply = errorDocument.getDocumentElement();
-            Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY), "Missing %s element",
-                    XmlMappingConstants.RPC_REPLY_KEY);
+            Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY),
+                    "Missing %s element", XmlMappingConstants.RPC_REPLY_KEY);
 
             final NamedNodeMap incomingAttributes = incommingRpc.getAttributes();
             for (int i = 0; i < incomingAttributes.getLength(); i++) {
@@ -93,7 +94,7 @@ public final class SendErrorExceptionUtil {
     private static final class SendErrorVerifyingListener implements ChannelFutureListener {
         private final DocumentedException sendErrorException;
 
-        public SendErrorVerifyingListener(final DocumentedException sendErrorException) {
+        SendErrorVerifyingListener(final DocumentedException sendErrorException) {
             this.sendErrorException = sendErrorException;
         }
 
index aa570952d6798bd021a679dbb21506097f88e88a..96e19b9378b73d4693157f3b71e3e52378953af2 100644 (file)
@@ -28,15 +28,17 @@ import org.w3c.dom.Node;
 public class SubtreeFilter {
     private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class);
 
-    public static Document applyRpcSubtreeFilter(Document requestDocument, Document rpcReply) throws DocumentedException {
+    public static Document applyRpcSubtreeFilter(Document requestDocument,
+                                                 Document rpcReply) throws DocumentedException {
         OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(requestDocument);
-        if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace()) &&
-                XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName()) ||
-                XmlNetconfConstants.GET_CONFIG.equals(operationNameAndNamespace.getOperationName())) {
+        if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace())
+                && XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName())
+                || XmlNetconfConstants.GET_CONFIG.equals(operationNameAndNamespace.getOperationName())) {
             // process subtree filtering here, in case registered netconf operations do
             // not implement filtering.
-            Optional<XmlElement> maybeFilter = operationNameAndNamespace.getOperationElement().getOnlyChildElementOptionally(
-                    XmlNetconfConstants.FILTER, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+            Optional<XmlElement> maybeFilter = operationNameAndNamespace.getOperationElement()
+                    .getOnlyChildElementOptionally(XmlNetconfConstants.FILTER,
+                            XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
             if (!maybeFilter.isPresent()) {
                 return rpcReply;
             }
@@ -57,9 +59,10 @@ public class SubtreeFilter {
      * @param filter filter
      * @param notification notification
      * @return document containing filtered notification content
-     * @throws DocumentedException
+     * @throws DocumentedException if operation fails
      */
-    public static Optional<Document> applySubtreeNotificationFilter(XmlElement filter, Document notification) throws DocumentedException {
+    public static Optional<Document> applySubtreeNotificationFilter(XmlElement filter,
+                                                                    Document notification) throws DocumentedException {
         removeEventTimeNode(notification);
         if (isSupported(filter)) {
             return Optional.fromNullable(filteredNotification(filter, notification));
@@ -68,14 +71,15 @@ public class SubtreeFilter {
     }
 
     private static void removeEventTimeNode(Document document) {
-        final Node eventTimeNode = document.getDocumentElement().getElementsByTagNameNS(
-                XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0, XmlNetconfConstants.EVENT_TIME).item(0);
+        final Node eventTimeNode = document.getDocumentElement().getElementsByTagNameNS(XmlNetconfConstants
+                .URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0, XmlNetconfConstants.EVENT_TIME).item(0);
         document.getDocumentElement().removeChild(eventTimeNode);
     }
 
     private static boolean isSupported(XmlElement filter) {
-        return "subtree".equals(filter.getAttribute("type"))||
-                "subtree".equals(filter.getAttribute("type", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+        return "subtree".equals(filter.getAttribute("type"))
+                || "subtree".equals(filter.getAttribute("type",
+                XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
     }
 
     private static Document extractNotificationContent(Document notification) throws DocumentedException {
@@ -86,14 +90,15 @@ public class SubtreeFilter {
         return notification;
     }
 
-    private static Document filteredNotification(XmlElement filter, Document originalNotification) throws DocumentedException {
+    private static Document filteredNotification(XmlElement filter,
+                                                 Document originalNotification) throws DocumentedException {
         Document result = XmlUtil.newDocument();
         XmlElement dataSrc = XmlElement.fromDomDocument(originalNotification);
         Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false);
         for (XmlElement filterChild : filter.getChildElements()) {
             addSubtree2(filterChild, dataSrc.getOnlyChildElement(), XmlElement.fromDomElement(dataDst));
         }
-        if(dataDst.getFirstChild() != null) {
+        if (dataDst.getFirstChild() != null) {
             result.appendChild(dataDst.getFirstChild());
             return result;
         } else {
@@ -107,7 +112,8 @@ public class SubtreeFilter {
         Element rpcReply = originalReplyDocument.getDocumentElement();
         Node rpcReplyDst = result.importNode(rpcReply, false);
         result.appendChild(rpcReplyDst);
-        XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+        XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data",
+                XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
         Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false);
         rpcReplyDst.appendChild(dataDst);
         addSubtree(filter, dataSrc, XmlElement.fromDomElement(dataDst));
@@ -123,7 +129,8 @@ public class SubtreeFilter {
         }
     }
 
-    private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, XmlElement dstParent) throws DocumentedException {
+    private static MatchingResult addSubtree2(XmlElement filter, XmlElement src,
+                                              XmlElement dstParent) throws DocumentedException {
         Document document = dstParent.getDomElement().getOwnerDocument();
         MatchingResult matches = matches(src, filter);
         if (matches != MatchingResult.NO_MATCH && matches != MatchingResult.CONTENT_MISMATCH) {
@@ -137,7 +144,8 @@ public class SubtreeFilter {
                 int numberOfTextMatchingChildren = 0;
                 for (XmlElement srcChild : src.getChildElements()) {
                     for (XmlElement filterChild : filter.getChildElements()) {
-                        MatchingResult childMatch = addSubtree2(filterChild, srcChild, XmlElement.fromDomElement(copied));
+                        MatchingResult childMatch =
+                                addSubtree2(filterChild, srcChild, XmlElement.fromDomElement(copied));
                         if (childMatch == MatchingResult.CONTENT_MISMATCH) {
                             return MatchingResult.NO_MATCH;
                         }
@@ -166,8 +174,8 @@ public class SubtreeFilter {
      * If filter node has no children and has text content, it also must match.
      */
     private static MatchingResult matches(XmlElement src, XmlElement filter) throws DocumentedException {
-        boolean tagMatch = src.getName().equals(filter.getName()) &&
-                src.getNamespaceOptionally().equals(filter.getNamespaceOptionally());
+        boolean tagMatch = src.getName().equals(filter.getName())
+                && src.getNamespaceOptionally().equals(filter.getNamespaceOptionally());
         MatchingResult result = null;
         if (tagMatch) {
             // match text content
@@ -183,7 +191,7 @@ public class SubtreeFilter {
             if (result == null) {
                 for (Attr attr : filter.getAttributes().values()) {
                     // ignore namespace declarations
-                    if (XmlUtil.XMLNS_URI.equals(attr.getNamespaceURI()) == false ) {
+                    if (XmlUtil.XMLNS_URI.equals(attr.getNamespaceURI()) == false) {
                         // find attr with matching localName(),  namespaceURI(),  == value() in src
                         String found = src.getAttribute(attr.getLocalName(), attr.getNamespaceURI());
                         if (attr.getValue().equals(found) && result != MatchingResult.NO_MATCH) {
@@ -205,7 +213,8 @@ public class SubtreeFilter {
         return result;
     }
 
-    private static boolean prefixedContentMatches(final XmlElement filter, final XmlElement src) throws DocumentedException {
+    private static boolean prefixedContentMatches(final XmlElement filter,
+                                                  final XmlElement src) throws DocumentedException {
         final Map.Entry<String, String> prefixToNamespaceOfFilter;
         final Map.Entry<String, String> prefixToNamespaceOfSrc;
         try {
@@ -226,8 +235,10 @@ public class SubtreeFilter {
             return false;
         }
 
-        final String unprefixedFilterContent = filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1);
-        final String unprefixedSrcContnet = src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1);
+        final String unprefixedFilterContent =
+                filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1);
+        final String unprefixedSrcContnet =
+                src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1);
         // Finally compare unprefixed content
         return unprefixedFilterContent.equals(unprefixedSrcContnet);
     }
index cd74911138a86e5e09b508588d334458632a0a3c..64537f336fc96ce49408a02633c0d761cf813cec 100644 (file)
@@ -9,7 +9,6 @@
 package org.opendaylight.netconf.util.osgi;
 
 import java.util.Collection;
-import java.util.Optional;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.InvalidSyntaxException;
 import org.osgi.framework.ServiceReference;
@@ -30,11 +29,11 @@ public final class NetconfConfigUtil {
         final Collection<ServiceReference<ManagedService>> serviceReferences
                 = bundleContext.getServiceReferences(ManagedService.class, null);
         for (final ServiceReference<ManagedService> serviceReference : serviceReferences) {
-                ManagedService service = bundleContext.getService(serviceReference);
-                if (service instanceof NetconfConfiguration){
-                    LOG.debug("Netconf configuration service found");
-                    return (NetconfConfiguration) service;
-                }
+            ManagedService service = bundleContext.getService(serviceReference);
+            if (service instanceof NetconfConfiguration) {
+                LOG.debug("Netconf configuration service found");
+                return (NetconfConfiguration) service;
+            }
         }
 
         throw new IllegalStateException("Netconf configuration service not found");
index f84d5a195426cf9a82b42391c2d5f5022f518b2d..c67675a91062780df065aedbf9f898abbf7df199 100644 (file)
@@ -55,9 +55,11 @@ public class NetconfConfiguration implements ManagedService {
             LOG.debug("CSS netconf server configuration cannot be updated as passed dictionary is null");
             return;
         }
-        final InetSocketAddress sshServerAddress = new InetSocketAddress((String) dictionaryConfig.get(SSH_ADDRESS_PROP),
-                Integer.parseInt((String) dictionaryConfig.get(SSH_PORT_PROP)));
-        final InetSocketAddress tcpServerAddress = new InetSocketAddress((String) dictionaryConfig.get(TCP_ADDRESS_PROP),
+        final InetSocketAddress sshServerAddress =
+                new InetSocketAddress((String) dictionaryConfig.get(SSH_ADDRESS_PROP),
+                        Integer.parseInt((String) dictionaryConfig.get(SSH_PORT_PROP)));
+        final InetSocketAddress tcpServerAddress =
+                new InetSocketAddress((String) dictionaryConfig.get(TCP_ADDRESS_PROP),
                 Integer.parseInt((String) dictionaryConfig.get(TCP_PORT_PROP)));
 
         netconfConfiguration = new NetconfConfigurationHolder(tcpServerAddress,
@@ -67,11 +69,11 @@ public class NetconfConfiguration implements ManagedService {
         LOG.debug("CSS netconf server configuration was updated: {}", dictionaryConfig.toString());
     }
 
-    public InetSocketAddress getSshServerAddress(){
+    public InetSocketAddress getSshServerAddress() {
         return netconfConfiguration.getSshServerAddress();
     }
 
-    public InetSocketAddress getTcpServerAddress(){
+    public InetSocketAddress getTcpServerAddress() {
         return netconfConfiguration.getTcpServerAddress();
     }
 
index 9c95ed58ac8a14fbb850aaeb9376069330ed4ed8..a705ea647a1074f4a49f976b75bfa04b03d96eb8 100644 (file)
@@ -27,11 +27,11 @@ public class HardcodedNamespaceResolver implements NamespaceContext {
     }
 
     /**
-     * This method returns the uri for all prefixes needed. Wherever possible it
-     * uses XMLConstants.
+     * Returns the URI for all prefixes needed. Wherever possible it
+     * uses {@code XMLConstants}.
      *
-     * @param prefix
-     * @return uri
+     * @param prefix    prefix
+     * @return uri      uniform resource identifier
      */
     @Override
     public String getNamespaceURI(String prefix) {
index ebe7bd023bec82a2593af64be23fc6ef71eb57c2..b3c3da5c2630ac6b75d313797ce5d9ab3319cadd 100644 (file)
@@ -24,13 +24,13 @@ public final class XMLNetconfUtil {
         throw new UnsupportedOperationException("Utility class");
     }
 
-    public static XPathExpression compileXPath(final String xPath) {
-        final XPath xpath = FACTORY.newXPath();
-        xpath.setNamespaceContext(NS_CONTEXT);
+    public static XPathExpression compileXPath(final String xpath) {
+        final XPath newXPath = FACTORY.newXPath();
+        newXPath.setNamespaceContext(NS_CONTEXT);
         try {
-            return xpath.compile(xPath);
+            return newXPath.compile(xpath);
         } catch (final XPathExpressionException e) {
-            throw new IllegalStateException("Error while compiling xpath expression " + xPath, e);
+            throw new IllegalStateException("Error while compiling xpath expression " + xpath, e);
         }
     }
 
index 786395d9b1798e6be2d69bd325a5fb7c01149045..907b2b45058c8dd0352e22d5251ee265dda7e3e7 100644 (file)
@@ -18,6 +18,7 @@ import org.junit.Test;
 
 public class CloseableUtilTest {
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Test
     public void testCloseAllFail() throws Exception {
         final AutoCloseable failingCloseable = new AutoCloseable() {
index 5a7941ad7af0f33fd9b9751fd41fdf8ab05f8e84..38f5bd039f516d99bd59e825426ee081e6d90ced 100644 (file)
@@ -44,8 +44,9 @@ public class NetconfUtilTest {
 
     @Test
     public void testConflictingVersionDetection() throws Exception {
-        final Document document = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml"));
-        try{
+        final Document document = XmlUtil.readXmlToDocument(getClass()
+                .getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml"));
+        try {
             NetconfUtil.checkIsMessageOk(document);
             fail();
         } catch (final IllegalStateException e) {
@@ -63,7 +64,8 @@ public class NetconfUtilTest {
                 .withValue("admin")
                 .build();
         final MapEntryNode session1 = Builders.mapEntryBuilder()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifierWithPredicates(Session.QNAME, QName.create(Session.QNAME, "session-id"), 1L))
+                .withNodeIdentifier(new YangInstanceIdentifier
+                        .NodeIdentifierWithPredicates(Session.QNAME, QName.create(Session.QNAME, "session-id"), 1L))
                 .withChild(username)
                 .build();
         final MapNode sessionList = Builders.mapBuilder()
index 1426505c5d06533f7c7b010241192d37116e8d3a..f9de09342a4c71b0315ca1dc8d779892914be4af 100644 (file)
@@ -33,7 +33,8 @@ public class AbstractLastNetconfOperationTest {
         }
 
         @Override
-        protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{
+        protected Element handleWithNoSubsequentOperations(Document document,
+                                                           XmlElement operationElement) throws DocumentedException {
             handleWithNoSubsequentOperationsRun = true;
             return null;
         }
index 81ccae28f48b22632d7d9817788687dd324d5827..75b870f7f66313b8a5fbd10543062c2402471555 100644 (file)
@@ -43,7 +43,8 @@ public class AbstractNetconfOperationTest {
         }
 
         @Override
-        protected Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException{
+        protected Element handle(Document document, XmlElement message,
+                                 NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
             this.handleRun = true;
             try {
                 return XmlUtil.readXmlToElement("<element/>");
index dc48b8b62464b1070a56ebfc9061df190c961a3b..9ba35770e4ee67e1ec002ce509c9f262dbf1739b 100644 (file)
@@ -25,7 +25,8 @@ public class AbstractSingletonNetconfOperationTest {
         }
 
         @Override
-        protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{
+        protected Element handleWithNoSubsequentOperations(Document document,
+                                                           XmlElement operationElement) throws DocumentedException {
             return null;
         }
 
index ad307fe360cedd2ac71544a3557d232436ddbbc2..53d2c585ef6f26a06a8b269917cb24b3f3c47789 100644 (file)
@@ -24,12 +24,14 @@ public class NetconfMessageUtilTest {
         assertTrue(NetconfMessageUtil.isOKMessage(new NetconfMessage(okMessage)));
         assertFalse(NetconfMessageUtil.isErrorMessage(new NetconfMessage(okMessage)));
 
-        Document errorMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/communicationError/testClientSendsRpcReply_expectedResponse.xml");
+        Document errorMessage = XmlFileLoader
+                .xmlFileToDocument("netconfMessages/communicationError/testClientSendsRpcReply_expectedResponse.xml");
         assertTrue(NetconfMessageUtil.isErrorMessage(new NetconfMessage(errorMessage)));
         assertFalse(NetconfMessageUtil.isOKMessage(new NetconfMessage(errorMessage)));
 
         Document helloMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/client_hello.xml");
-        Collection<String> caps = NetconfMessageUtil.extractCapabilitiesFromHello(new NetconfMessage(helloMessage).getDocument());
+        Collection<String> caps =
+                NetconfMessageUtil.extractCapabilitiesFromHello(new NetconfMessage(helloMessage).getDocument());
         assertTrue(caps.contains("urn:ietf:params:netconf:base:1.0"));
         assertTrue(caps.contains("urn:ietf:params:netconf:base:1.1"));
     }
index ac7d83ce374938dd0ebde0bfbb1d1703c52f589c..96f179a112290f4ae74fcbab97c76abc2bc3931e 100644 (file)
@@ -50,7 +50,7 @@ public class SubtreeFilterNotificationTest {
     }
 
     @Before
-    public void setUp(){
+    public void setUp() {
         XMLUnit.setIgnoreWhitespace(true);
     }
 
@@ -59,8 +59,9 @@ public class SubtreeFilterNotificationTest {
         XmlElement filter = XmlElement.fromDomDocument(getDocument("filter.xml"));
         Document preFilterDocument = getDocument("pre-filter.xml");
         Document postFilterDocument = getDocument("post-filter.xml");
-        Optional<Document> actualPostFilterDocumentOpt = SubtreeFilter.applySubtreeNotificationFilter(filter, preFilterDocument);
-        if(actualPostFilterDocumentOpt.isPresent()) {
+        Optional<Document> actualPostFilterDocumentOpt =
+                SubtreeFilter.applySubtreeNotificationFilter(filter, preFilterDocument);
+        if (actualPostFilterDocumentOpt.isPresent()) {
             Document actualPostFilterDocument = actualPostFilterDocumentOpt.get();
             LOG.info("Actual document: {}", XmlUtil.toString(actualPostFilterDocument));
             Diff diff = XMLUnit.compareXML(postFilterDocument, actualPostFilterDocument);
@@ -71,7 +72,7 @@ public class SubtreeFilterNotificationTest {
     }
 
     public Document getDocument(String fileName) throws SAXException, IOException {
-        return XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/subtree/notification/" + directoryIndex + "/" +
-                fileName));
+        return XmlUtil.readXmlToDocument(getClass().getResourceAsStream(
+                "/subtree/notification/" + directoryIndex + "/" + fileName));
     }
 }
index e486c75f2e0d8d6abc8f3e29ec4f420c212de433..d5b4a24a842f87d3342eaf6dfefacab67663cd50 100644 (file)
@@ -47,7 +47,7 @@ public class SubtreeFilterRpcTest {
     }
 
     @Before
-    public void setUp(){
+    public void setUp() {
         XMLUnit.setIgnoreWhitespace(true);
     }
 
@@ -64,7 +64,7 @@ public class SubtreeFilterRpcTest {
     }
 
     public Document getDocument(String fileName) throws SAXException, IOException {
-        return XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/subtree/rpc/" + directoryIndex + "/" +
-                fileName));
+        return XmlUtil.readXmlToDocument(
+                getClass().getResourceAsStream("/subtree/rpc/" + directoryIndex + "/" + fileName));
     }
 }
index e777bb05f6f97cee52ac72f64c92149340cbecf5..64bf74fec5387cb2f2a7a1cb1e6413765a09c21f 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.netconf.util.osgi;
 
+import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
@@ -66,7 +67,7 @@ public class NetconfConfigUtilTest {
             NetconfConfigUtil.getNetconfConfigurationService(context);
             Assert.fail(IllegalStateException.class + "exception expected");
         } catch (IllegalStateException e) {
-
+            assertTrue(e.getMessage().startsWith("Netconf configuration service not found"));
         }
     }
 
index 494b96ec4351318e11c8ff9e0d3a6f39320516cf..4e55591271fbede48ceae2ad8aa97711a6ce8787 100644 (file)
@@ -16,7 +16,7 @@ import org.w3c.dom.NodeList;
 
 /**
  * Custom xmlunit qualifier that doesn't care about order when deeper in the recursion
- * defaults to comparing element name and text content
+ * defaults to comparing element name and text content.
  */
 public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier {
 
@@ -36,6 +36,7 @@ public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier {
         return compareNodes(currentControl, currentTest);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     private boolean compareNodes(Node currentControl, Node currentTest) {
         try {
 
@@ -54,8 +55,8 @@ public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier {
                 return !(currentControl.hasChildNodes() || currentTest.hasChildNodes());
             }
 
-            return (countNodesWithoutConsecutiveTextNodes(controlNodes) == countNodesWithoutConsecutiveTextNodes(testNodes))
-                    && checkChildren(controlNodes, testNodes);
+            return (countNodesWithoutConsecutiveTextNodes(controlNodes)
+                    == countNodesWithoutConsecutiveTextNodes(testNodes)) && checkChildren(controlNodes, testNodes);
 
         } catch (Exception e) {
             return false;
@@ -106,16 +107,16 @@ public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier {
         return builder.toString();
     }
 
-    private static int countNodesWithoutConsecutiveTextNodes(NodeList l) {
+    private static int countNodesWithoutConsecutiveTextNodes(NodeList nodeList) {
         int count = 0;
         boolean lastNodeWasText = false;
-        final int length = l.getLength();
+        final int length = nodeList.getLength();
         for (int i = 0; i < length; i++) {
-            Node n = l.item(i);
-            if (!lastNodeWasText || n.getNodeType() != Node.TEXT_NODE) {
+            Node node = nodeList.item(i);
+            if (!lastNodeWasText || node.getNodeType() != Node.TEXT_NODE) {
                 count++;
             }
-            lastNodeWasText = n.getNodeType() == Node.TEXT_NODE;
+            lastNodeWasText = node.getNodeType() == Node.TEXT_NODE;
         }
         return count;
     }
index e8941445ed1743e48b3970b4451ffa3540da355e..9ce2be2013e3c5e7ad11d7ceb0d8a5717ae5fa12 100644 (file)
@@ -26,7 +26,8 @@ public class XmlUnitUtil {
 
     private XmlUnitUtil() {}
 
-    public static void assertContainsElementWithText(final Document doc, final String textToFind) throws NodeTestException {
+    public static void assertContainsElementWithText(final Document doc,
+                                                     final String textToFind) throws NodeTestException {
         NodeTest nt = new NodeTest(doc);
         NodeTester tester = new AbstractNodeTester() {
 
@@ -34,7 +35,7 @@ public class XmlUnitUtil {
 
             @Override
             public void testText(Text text) throws NodeTestException {
-                if(!textFound) {
+                if (!textFound) {
                     if (text.getData().equalsIgnoreCase(textToFind)) {
                         textFound = true;
                     }
@@ -58,7 +59,7 @@ public class XmlUnitUtil {
             @Override
             public void testElement(Element element) throws NodeTestException {
                 if (!elementFound) {
-                    if(element.isEqualNode(testElement)) {
+                    if (element.isEqualNode(testElement)) {
                         elementFound = true;
                     }
                 }
@@ -72,7 +73,8 @@ public class XmlUnitUtil {
         assertNodeTestPasses(nt, tester, new short[]{Node.ELEMENT_NODE}, true);
     }
 
-    public static void assertContainsElementWithName(final Document doc, final String elementName) throws NodeTestException {
+    public static void assertContainsElementWithName(final Document doc,
+                                                     final String elementName) throws NodeTestException {
         NodeTest nt = new NodeTest(doc);
         NodeTester tester = new AbstractNodeTester() {
 
index dd646df7141764f9bfc8d85d8ed23b79cd02a01a..c728862068048bfd09b3854132ad3d9874217764 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.netconf.util.xml;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import org.junit.Test;
@@ -18,13 +19,16 @@ public class HardcodedNamespaceResolverTest {
 
     @Test
     public void testResolver() throws Exception {
-        final HardcodedNamespaceResolver hardcodedNamespaceResolver = new HardcodedNamespaceResolver("prefix", "namespace");
+        final HardcodedNamespaceResolver hardcodedNamespaceResolver =
+                new HardcodedNamespaceResolver("prefix", "namespace");
 
         assertEquals("namespace", hardcodedNamespaceResolver.getNamespaceURI("prefix"));
-        try{
+        try {
             hardcodedNamespaceResolver.getNamespaceURI("unknown");
             fail("Unknown namespace lookup should fail");
-        } catch(IllegalStateException e) {}
+        } catch (IllegalStateException e) {
+            assertTrue(e.getMessage().startsWith("Prefix mapping not found for "));
+        }
 
         assertNull(hardcodedNamespaceResolver.getPrefix("any"));
         assertNull(hardcodedNamespaceResolver.getPrefixes("any"));
index f70406bb2cc357e927606043e5562974762e1755..3ca07d4dd438e21e73db8a11837bae2146ae6839 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.netconf.util.xml;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import javax.xml.xpath.XPathConstants;
@@ -25,8 +26,11 @@ public class XMLNetconfUtilTest {
         try {
             XMLNetconfUtil.compileXPath("!@(*&$!");
             fail("Incorrect xpath should fail");
-        } catch (IllegalStateException e) {}
-        final Object value = XmlUtil.evaluateXPath(correctXPath, XmlUtil.readXmlToDocument("<top><innerText>value</innerText></top>"), XPathConstants.NODE);
+        } catch (IllegalStateException e) {
+            assertTrue(e.getMessage().startsWith("Error while compiling xpath expression "));
+        }
+        final Object value = XmlUtil.evaluateXPath(correctXPath,
+                XmlUtil.readXmlToDocument("<top><innerText>value</innerText></top>"), XPathConstants.NODE);
         assertEquals("value", ((Element) value).getTextContent());
     }
 
index 2f52f586851d486a69efec0c329b7406ea617139..207331f61d7455a158565d6bb8b414f65caeca32 100644 (file)
                 <groupId>${project.groupId}</groupId>
                 <artifactId>features-restconf</artifactId>
                 <version>${project.version}</version>
+                <type>xml</type>
                 <classifier>features</classifier>
+            </dependency>
+
+            <!-- restconf features -->
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>features4-restconf</artifactId>
+                <version>${project.version}</version>
                 <type>xml</type>
-                <scope>runtime</scope>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-mdsal-apidocs</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
             </dependency>
             <dependency>
                 <groupId>${project.groupId}</groupId>
                 <artifactId>odl-restconf</artifactId>
                 <version>${project.version}</version>
+                <type>xml</type>
+                <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-restconf-all</artifactId>
+                <version>${project.version}</version>
+                <type>xml</type>
                 <classifier>features</classifier>
+            </dependency>
+            <dependency>
+                <groupId>${project.groupId}</groupId>
+                <artifactId>odl-restconf-noauth</artifactId>
+                <version>${project.version}</version>
                 <type>xml</type>
-                <scope>runtime</scope>
+                <classifier>features</classifier>
             </dependency>
         </dependencies>
     </dependencyManagement>